@adhdev/daemon-standalone 0.9.82-rc.8 → 0.9.82-rc.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +72 -5
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/public/assets/index-C6PWDloP.js +98 -0
- package/public/assets/index-DC6YELcC.css +1 -0
- package/public/assets/{terminal-DCVDkSIp.js → terminal-CfAvHQvJ.js} +1 -1
- package/public/assets/{vendor-piMzuE8Y.js → vendor-CgiI0UIA.js} +29 -29
- package/public/index.html +3 -3
- package/vendor/mcp-server/index.js +31 -5
- package/vendor/mcp-server/index.js.map +1 -1
- package/public/assets/index-UQ7bnB6f.css +0 -1
- package/public/assets/index-rt5QK8HH.js +0 -98
|
@@ -1,98 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-DCVDkSIp.js","assets/vendor-piMzuE8Y.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
var Ou=Object.defineProperty;var Fu=(e,s,r)=>s in e?Ou(e,s,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[s]=r;var Qe=(e,s,r)=>Fu(e,typeof s!="symbol"?s+"":s,r);import{r as i,j as t,M as yo,a as Ku,b as Wu,c as Hu,R as kt,d as kr,t as Uu,e as zu,u as cs,D as Vu,f as Ga,g as qa,i as Gu,h as qu,C as Yu,B as Xu,k as Ju,l as Qu,H as xi,P as bi,m as vo,n as Zu,o as em,p as tm,q as sm,s as es,N as Ya,v as rm}from"./vendor-piMzuE8Y.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))n(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&n(l)}).observe(document,{childList:!0,subtree:!0});function r(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerPolicy&&(o.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?o.credentials="include":a.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(a){if(a.ep)return;a.ep=!0;const o=r(a);fetch(a.href,o)}})();function nm(e={}){const s=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>s&&r.splice(0,r.length-s),a},list(n={}){const a=Math.max(1,Math.floor(n.limit||100));return r.filter(o=>!n.interactionId||o.interactionId===n.interactionId).filter(o=>!n.topic||o.topic===n.topic).filter(o=>!n.kind||o.kind===n.kind).slice(-a).map(o=>({...o,payload:o.payload?{...o.payload}:{}}))},clear(){r.splice(0,r.length)}}}const Ks=nm();function gi(e){const s={};for(const r of e)r.transport&&(s[r.transport]=(s[r.transport]||0)+1);return{count:e.length,ids:e.map(r=>r.id),statuses:e.map(r=>String(r.status||"unknown")),transports:s}}function am(e,s){return typeof e=="string"&&e.trim().length>0&&e!==s}function yi(e){return Array.isArray(e)?[...e]:[]}function Xl(e,s){if(!e)return s??null;const r=Object.prototype.hasOwnProperty.call(e,"messages"),n=Object.prototype.hasOwnProperty.call(e,"activeModal");return s?{...s,...e,messages:r?yi(e.messages):s.messages,activeModal:n?e.activeModal??null:s.activeModal,inputContent:e.inputContent??s.inputContent}:{...e,...r?{messages:yi(e.messages)}:{},...n?{activeModal:e.activeModal??null}:{}}}function mr(e,s){const r=am(e.providerName,e.providerType)?e.providerName:void 0;return{...e,parentId:e.parentId??(s==null?void 0:s.parentSessionId)??null,providerSessionId:e.providerSessionId??(s==null?void 0:s.providerSessionId),providerName:r??(s==null?void 0:s.providerName)??(s==null?void 0:s.cliName)??(s==null?void 0:s.type)??e.providerName??e.providerType,title:e.title??(s==null?void 0:s.title)??r??(s==null?void 0:s.providerName)??e.providerName??e.providerType,workspace:e.workspace??(s==null?void 0:s.workspace)??null,mode:e.mode??(s==null?void 0:s.mode),capabilities:e.capabilities??(s==null?void 0:s.sessionCapabilities)??(s==null?void 0:s.capabilities)??[],cdpConnected:e.cdpConnected??(s==null?void 0:s.cdpConnected),activeChat:Xl(e.activeChat,s==null?void 0:s.activeChat),controlValues:e.controlValues??(s==null?void 0:s.controlValues),providerControls:e.providerControls??(s==null?void 0:s.providerControls),summaryMetadata:e.summaryMetadata??(s==null?void 0:s.summaryMetadata),runtimeWriteOwner:e.runtimeWriteOwner??(s==null?void 0:s.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(s==null?void 0:s.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(s==null?void 0:s.lastMessagePreview),lastMessageRole:e.lastMessageRole??(s==null?void 0:s.lastMessageRole),lastMessageAt:e.lastMessageAt??(s==null?void 0:s.lastMessageAt),lastMessageHash:e.lastMessageHash??(s==null?void 0:s.lastMessageHash),unread:e.unread??(s==null?void 0:s.unread),lastSeenAt:e.lastSeenAt??(s==null?void 0:s.lastSeenAt),inboxBucket:e.inboxBucket??(s==null?void 0:s.inboxBucket),completionMarker:e.completionMarker??(s==null?void 0:s.completionMarker),seenCompletionMarker:e.seenCompletionMarker??(s==null?void 0:s.seenCompletionMarker),surfaceHidden:e.surfaceHidden??(s==null?void 0:s.surfaceHidden),resume:e.resume??(s==null?void 0:s.resume),runtimeKey:e.runtimeKey??(s==null?void 0:s.runtimeKey),runtimeDisplayName:e.runtimeDisplayName??(s==null?void 0:s.runtimeDisplayName),runtimeWorkspaceLabel:e.runtimeWorkspaceLabel??(s==null?void 0:s.runtimeWorkspaceLabel),settings:e.settings??(s==null?void 0:s.settings)}}function Jl(e,s,r){if(!(s!=null&&s.length))return(r==null?void 0:r.preserveMissing)===!1&&Array.isArray(s)?s:e;if(!(e!=null&&e.length))return s;const n=s.map(a=>{const o=e.find(l=>l.id===a.id);return o?mr(a,o):a});if((r==null?void 0:r.preserveMissing)!==!1){const a=new Set(s.map(o=>o.id));for(const o of e)a.has(o.id)||n.push(o)}return n}function vi(e){return!!e&&typeof e=="object"&&"text"in e}function wo(e,s){const r=(s==null?void 0:s.joiner)??" ",n=(s==null?void 0:s.normalizeWhitespace)??!1;let a="";return typeof e=="string"?a=e:Array.isArray(e)?a=e.map(o=>typeof o=="string"?o:vi(o)?String(o.text||""):"").join(r):vi(e)?a=String(e.text||""):a=String(e||""),n?a.replace(/\s+/g," ").trim():a}function Ws(e){return wo(e,{normalizeWhitespace:!0})}const Ql=i.createContext({ides:[],updateRouteChats:()=>{},initialLoaded:!1,toasts:[],setToasts:()=>{},wsStatus:"connected",isConnected:!0,connectionStates:{},connectionTransports:{},showReconnected:!1,userName:void 0,setUserName:()=>{},isP2PActive:!1,p2pStates:{},userRole:void 0,connectionRetryStatuses:void 0}),Zl=i.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function wi(e){var r,n;let s=0;return e.activeChat!==void 0&&(s+=4),(r=e.childSessions)!=null&&r.length&&(s+=2),e.workspace&&(s+=1),e.machine&&(s+=1),(n=e.agents)!=null&&n.length&&(s+=1),s}function ec(e,s,r){if(r.type!=="adhdev-daemon")return r;const n={...r},a=s.version??r.version??e.version,o=s.serverVersion??e.serverVersion??r.serverVersion,l=s.versionMismatch===!0||e.versionMismatch===!0,c=s.versionUpdateRequired===!0||e.versionUpdateRequired===!0,d=s.versionUpdateReason??e.versionUpdateReason??r.versionUpdateReason;return a&&(n.version=a),o&&(n.serverVersion=o),d&&(n.versionUpdateReason=d),a&&o&&a===o?(delete n.versionMismatch,delete n.serverVersion,delete n.versionUpdateRequired,delete n.versionUpdateReason,n):((s.versionMismatch===!0||l&&a&&o&&a!==o)&&(n.versionMismatch=!0),c&&(n.versionUpdateRequired=!0),n)}function om(e){let s=2166136261;for(let r=0;r<e.length;r+=1)s^=e.charCodeAt(r),s=Math.imul(s,16777619)>>>0;return s.toString(16).padStart(8,"0")}function Xn(e){if(!e||typeof e!="object")return"";const s=e,r=om(Ws(s.content).slice(0,512));return[String(s.id||""),String(s._localId||""),String(s._turnKey||""),String(s.index??""),String(s.role||""),String(s.receivedAt??s.timestamp??""),r].join(":")}function im(e,s){if(!Array.isArray(e))return e;if(s!=null&&s.has(e))return{count:e.length,sharedRef:!0};let r=2166136261;for(const n of e){const a=Xn(n);for(let o=0;o<a.length;o+=1)r^=a.charCodeAt(o),r=Math.imul(r,16777619)>>>0}return{count:e.length,hash:r.toString(16).padStart(8,"0"),first:Xn(e[0]),last:Xn(e[e.length-1])}}function Xa(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function Ja(e,s,r){if(!e||!s||typeof e!="object"||typeof s!="object")return;if(Xa(e)&&Xa(s)){const l=e.messages;Array.isArray(l)&&l===s.messages&&r.add(l)}if(Array.isArray(e)&&Array.isArray(s)){const l=Math.min(e.length,s.length);for(let c=0;c<l;c+=1)Ja(e[c],s[c],r);return}const n=e,a=s,o=new Set([...Object.keys(n),...Object.keys(a)]);for(const l of o)l!=="messages"&&Ja(n[l],a[l],r)}function hr(e,s){return Array.isArray(e)?e.map(r=>hr(r,s)):!e||typeof e!="object"?e:Xa(e)?Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[a])=>n.localeCompare(a)).map(([n,a])=>[n,n==="messages"?im(a,s):hr(a,s)])):Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>[r,hr(n,s)]))}function lm(e,s){try{const r=new WeakSet;return Ja(e,s,r),JSON.stringify(hr(e,r))===JSON.stringify(hr(s,r))}catch{return!1}}function Qa(e,s,r){return lm(e,s)?(e._lastUpdate=r,typeof s.timestamp=="number"&&(e.timestamp=s.timestamp),e):s}function tc(e){var s;return e.daemonId||((s=e.id)==null?void 0:s.split(":")[0])||e.id}function cm(e,s,r){s[r]!==void 0&&(e[r]=s[r])}function ji(e,s,r,n){var c;const a=(c=s.chats)!=null&&c.length?s.chats:e.chats,o=Jl(e.childSessions,s.childSessions,{preserveMissing:n}),l=Xl(s.activeChat,e.activeChat);return ec(e,s,{...e,...s,chats:a,childSessions:o,activeChat:l,_lastUpdate:r})}function dm(e,s,r){var a,o;const n={};s.status&&s.status!==e.status&&(n.status=s.status),s.cdpConnected!==void 0&&(n.cdpConnected=s.cdpConnected),s.childSessions!==void 0&&(n.childSessions=Jl(e.childSessions,s.childSessions,{preserveMissing:r})),(a=s.chats)!=null&&a.length&&!((o=e.chats)!=null&&o.length)&&(n.chats=s.chats);for(const l 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"])cm(n,s,l);return s.machineNickname!==void 0&&s.machineNickname!==e.machineNickname&&(n.machineNickname=s.machineNickname),s.versionMismatch===!0&&(n.versionMismatch=!0),n}function um(e,s,r,n){const a=dm(e,s,n),o=Object.keys(a).length>0?ec(e,s,{...e,...a,_lastUpdate:r}):{...e,_lastUpdate:r};return Qa(e,o,r)}function mm(e){const s=new Set(e.map(o=>o.id)),r=new Set,n=new Set,a=new Set;for(const o of e){const l=tc(o);l&&r.add(l),l&&o.type!=="adhdev-daemon"&&n.add(l),l&&o.type==="adhdev-daemon"&&o._sessionListAuthoritative&&a.add(l)}return{incomingIds:s,incomingDaemonIds:r,daemonIdsWithSessionEntries:n,daemonIdsWithAuthoritativeSessionList:a}}function pm(e,s,r,n,a,o){return!a.has(s)||!o.has(s)||n.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?r>1e4:e.transport==="cdp-page"?r>3e4:!1}function fm(e,s,r,n,a){return e.transport?r.has(s)&&!n.has(s)?!0:a.has(s):!1}function hm(e,s,r){var u,h;const n=Date.now(),a=new Set((r==null?void 0:r.authoritativeDaemonIds)||[]);if(s.length===0)return e.map(g=>({...g,_lastUpdate:n}));const o=new Map;for(const g of s)o.set(g.id,g);const{incomingIds:l,incomingDaemonIds:c,daemonIdsWithSessionEntries:d,daemonIdsWithAuthoritativeSessionList:m}=mm(e);for(const g of e){const j=o.get(g.id);if(!j){o.set(g.id,{...g,_lastUpdate:n});continue}const f=wi(g),p=wi(j),b=tc(g),y=!a.has(b);if(f>p){const N=ji(j,g,n,y);o.set(g.id,Qa(j,N,n));continue}if(f<p){o.set(g.id,um(j,g,n,y));continue}const x=g.timestamp||n,A=j._lastUpdate||j.timestamp||0;if(x>=A){const N=ji(j,g,n,y);o.set(g.id,Qa(j,N,n));continue}(u=g.chats)!=null&&u.length&&!((h=j.chats)!=null&&h.length)&&o.set(g.id,{...j,chats:g.chats})}for(const[g,j]of o){const f=j.daemonId||g.split(":")[0];if(!c.has(f))continue;if(a.has(f)&&m.has(f)&&!l.has(g)){o.delete(g);continue}const p=n-(j._lastUpdate||j.timestamp||0);pm(j,f,p,l,a,d)&&o.delete(g)}for(const[g,j]of o){const f=j.daemonId||g.split(":")[0];if(fm(j,f,c,d,o))continue;n-(j._lastUpdate||j.timestamp||0)>3e5&&j.status!=="online"&&o.delete(g)}return Array.from(o.values())}function xm(e,s){if(e.length!==s.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==s[r])return!1;return!0}function bm({children:e,connectionOverrides:s}){const[r,n]=i.useState([]),[a,o]=i.useState(!1),[l,c]=i.useState([]),[d,m]=i.useState(void 0),u=i.useRef(r);i.useEffect(()=>{u.current=r},[r]);const h=i.useCallback((y,x)=>{n(A=>{let N=!1;const v=A.map(C=>C.id!==y||C.chats===x?C:(N=!0,{...C,chats:x}));return N?v:A})},[]),g=i.useCallback((y,x)=>{n(A=>{const N=A.length===0?y:hm(y,A,x),v=!xm(A,N);return v&&Ks.record({kind:"dashboard.entries_applied",payload:{incoming:gi(y),next:gi(N)}}),v?N:A})},[]),j=i.useCallback(()=>o(!0),[]),f=i.useMemo(()=>({injectEntries:g,markLoaded:j,getIdes:()=>u.current}),[g,j]),p=s,b=i.useMemo(()=>({ides:r,updateRouteChats:h,initialLoaded:a,toasts:l,setToasts:c,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,h,a,l,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 t.jsx(Zl.Provider,{value:f,children:t.jsx(Ql.Provider,{value:b,children:e})})}function ls(){return i.useContext(Ql)}function Nr(){return i.useContext(Zl)}function sc(e){const{baseUrl:s,getToken:r,onUnauthorized:n}=e;function a(c){return c.startsWith("http")?c:`${s}${c.startsWith("/")?"":"/"}${c}`}function o(c){const d=r==null?void 0:r(),m=a(c),u=c.startsWith("http")?new URL(m):new URL(m,typeof window<"u"?window.location.origin:"http://localhost");return d&&u.searchParams.set("token",d),!c.startsWith("http")&&!s?`${u.pathname}${u.search}${u.hash}`:u.toString()}async function l(c,d={}){const m={"Content-Type":"application/json",...d.headers||{}},u=r==null?void 0:r();u&&(m.Authorization=`Bearer ${u}`);const h=a(c),g=new AbortController,j=setTimeout(()=>g.abort(),15e3);try{const f=await fetch(h,{...d,headers:m,signal:g.signal});if(f.status===401)throw n==null||n(),new Error("Unauthorized");if(!f.ok){const p=await f.json().catch(()=>({error:f.statusText}));throw new Error(p.error||`API Error: ${f.status}`)}return f.json()}finally{clearTimeout(j)}}return{getDaemons:()=>l("/api/v1/daemons"),getDaemonStatus:c=>l(`/api/v1/daemons/${c}/status`),sendCommand:(c,d,m={})=>l(`/api/v1/daemons/${c}/command`,{method:"POST",body:JSON.stringify({type:d,payload:m})}),execTerminal:(c,d,m)=>l(`/api/v1/daemons/${c}/terminal`,{method:"POST",body:JSON.stringify({command:d,name:m})}),sendAgentMessage:(c,d,m)=>l(`/api/v1/shortcuts/${c}/chat`,{method:"POST",body:JSON.stringify({agentType:d,message:m})}),getAgentStatus:c=>l(`/api/v1/shortcuts/${c}/status`),approveAgent:(c,d,m)=>l(`/api/v1/shortcuts/${c}/approve`,{method:"POST",body:JSON.stringify({agentType:d,action:m?"approve":"reject"})}),getMuxState:c=>l(`/api/v1/mux/${encodeURIComponent(c)}/state`),getMuxSocketInfo:c=>l(`/api/v1/mux/${encodeURIComponent(c)}/socket-info`),controlMux:(c,d,m={})=>l(`/api/v1/mux/${encodeURIComponent(c)}/control`,{method:"POST",body:JSON.stringify({type:d,payload:m})}),getMuxEventsUrl:c=>o(`/api/v1/mux/${encodeURIComponent(c)}/events`),getRuntimeEventsUrl:c=>o(`/api/v1/runtime/${encodeURIComponent(c)}/events`),request:l}}const gm=sc({baseUrl:"http://localhost:3847"}),ym=i.createContext(gm);function vm({client:e,children:s}){return t.jsx(ym.Provider,{value:e,children:s})}const wm={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},rc=i.createContext(wm);function jm({value:e,children:s}){return t.jsx(rc.Provider,{value:e,children:s})}function wt(){return i.useContext(rc)}function km(e){let s=2166136261;for(const r of e){const n=String(r||"");for(let a=0;a<n.length;a+=1)s^=n.charCodeAt(a),s=Math.imul(s,16777619)>>>0;s^=255,s=Math.imul(s,16777619)>>>0}return s.toString(16).padStart(8,"0")}function Nm(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Sm(e){return e?km([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),Nm(e.content)]):""}const Fe={size:18};function nc({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),t.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),t.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),t.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function jo({size:e=Fe.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polyline",{points:"15 18 9 12 15 6"})})}function os({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),t.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),t.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),t.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),t.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),t.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function ac({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),t.jsx("circle",{cx:"9",cy:"7",r:"4"}),t.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),t.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function Cm({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),t.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function Im({size:e=Fe.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.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 oc({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),t.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"}),t.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),t.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function Tm({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.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"}),t.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),t.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),t.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),t.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function Pn({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"3"}),t.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 ic({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),t.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function Am({size:e=Fe.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function Jt({size:e=Fe.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.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 At({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),t.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),t.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function ko({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),t.jsx("polyline",{points:"14 2 14 8 20 8"}),t.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),t.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function Mm({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"11",cy:"11",r:"8"}),t.jsx("line",{x1:"21",y1:"21",x2:"16.65",y2:"16.65"})]})}function Ns({size:e=Fe.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.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 Tr({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"23 4 23 10 17 10"}),t.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function Sr({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.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"}),t.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),t.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function Hs({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M12 22v-5"}),t.jsx("path",{d:"M9 8V2"}),t.jsx("path",{d:"M15 8V2"}),t.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function ns({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"5",r:"2"}),t.jsx("circle",{cx:"5",cy:"19",r:"2"}),t.jsx("circle",{cx:"19",cy:"19",r:"2"}),t.jsx("line",{x1:"12",y1:"7",x2:"5",y2:"17"}),t.jsx("line",{x1:"12",y1:"7",x2:"19",y2:"17"}),t.jsx("line",{x1:"5",y1:"19",x2:"19",y2:"19"})]})}function Lm({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polygon",{points:"12 2 2 7 12 12 22 7 12 2"}),t.jsx("polyline",{points:"2 12 12 17 22 12"}),t.jsx("polyline",{points:"2 17 12 22 22 17"})]})}function lc({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),t.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function No({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.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"}),t.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"}),t.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),t.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function cc({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"10"}),t.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function Rm({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),t.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),t.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function So({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"4 17 10 11 4 5"}),t.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function _m({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function Co({size:e=Fe.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function dc({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function vt({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),t.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function Pm({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.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"}),t.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"}),t.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),t.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function Dm({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),t.jsx("path",{d:"M12 2v6"}),t.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),t.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function Em({size:e=Fe.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.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 $m({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),t.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 Dn({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),t.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function Bm({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"5"}),t.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),t.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),t.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),t.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),t.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),t.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),t.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),t.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function Om({size:e=Fe.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function Fm({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),t.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),t.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Km({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),t.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function Wm({size:e=Fe.size,className:s}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:t.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function Hm({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),t.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 Um({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.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"}),t.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"}),t.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 zm({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),t.jsx("path",{d:"M13 2h9v9"}),t.jsx("path",{d:"M22 2L13 11"})]})}function Vm({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("polyline",{points:"9 14 4 9 9 4"}),t.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function Gm({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),t.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),t.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),t.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),t.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),t.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),t.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),t.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),t.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),t.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function qm({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),t.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 Ym({size:e=Fe.size,className:s}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:s,children:[t.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),t.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),t.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}const Io="adhdev_chat_activity_visible",ki=new Set(["hidden","debug","internal"]),Ni=new Set(["visible","user","chat"]),Xm=new Set(["debug","trace","internal"]),Jm=new Set(["tool_call","terminal_command","runtime_activity"]),Qm=new Set(["runtime_status","provider_chrome","control"]),Zm=new Set(["thought","tool","terminal"]);function uc(e){const s=e.meta;return s&&typeof s=="object"&&!Array.isArray(s)?s:null}function Rs(e){return typeof e=="string"?e.trim().toLowerCase():""}function Jn(e,s,r){return e[r]??(s==null?void 0:s[r])}function Si(e,s,r){const n=e;return r.some(a=>n[a]===!0||(s==null?void 0:s[a])===!0)}function ep(e,s){const r=Rs(e.kind);return r||(s==="tool"?"tool":"standard")}function Qn(e,s,r){const n=uc(e),a=typeof(n==null?void 0:n.label)=="string"?n.label.trim():"";return a||(s==="terminal"||r==="terminal_command"?"Terminal":s==="tool"||r==="tool_call"?"Tool":s==="thought"?"Thought":r==="runtime_activity"?"Runtime":"Activity")}function tp(e){const s=e.content;return Array.isArray(s)&&s.some(r=>!!r&&typeof r=="object"&&r.type!=="text")}function To(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal"};const s=uc(e),r=Rs(e.role),n=ep(e,r),a=Rs(Jn(e,s,"visibility")),o=Rs(e.transcriptVisibility??(s==null?void 0:s.transcriptVisibility)??a),l=Rs(Jn(e,s,"audience")),c=Rs(Jn(e,s,"source")),d=ki.has(a)||ki.has(o)||Xm.has(l)||Si(e,s,["internal","isInternal","debug","statusOnly","controlOnly"]),m=Ni.has(a)||Ni.has(o)||l==="chat"||Si(e,s,["userFacing"]),u=Zm.has(n)||Jm.has(c);if(d)return{surface:u?"activity":"internal",isUserFacing:!1,isActivityFacing:u,isInternal:!u,role:r,kind:n,label:Qn(e,n,c)};if(m)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:Qn(e,n,c)};if((r==="system"||n==="system")&&tp(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:r,kind:n,label:"Chat"};if(Qm.has(c)||r==="system"||n==="system")return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:r,kind:n,label:"Internal"};if(u)return{surface:"activity",isUserFacing:!1,isActivityFacing:!0,isInternal:!1,role:r,kind:n,label:Qn(e,n,c)};const h=(r==="user"||r==="human"||r==="assistant")&&(n==="standard"||n==="");return{surface:h?"chat":"internal",isUserFacing:h,isActivityFacing:!1,isInternal:!h,role:r,kind:n,label:h?"Chat":"Internal"}}function sp(e){return(Array.isArray(e)?e:[]).filter(s=>To(s).isUserFacing)}function mc(e){return(Array.isArray(e)?e:[]).filter(s=>To(s).isActivityFacing)}function rp(e,s,r){return!r||s.length===0?e:[...e,...s].sort((n,a)=>{const o=Number(n.receivedAt??n.timestamp??0)||0,l=Number(a.receivedAt??a.timestamp??0)||0;if(o!==l)return o-l;const c=Number(n.index??0)||0,d=Number(a.index??0)||0;return c-d})}function Ci(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(Io))==="1"}catch{return!1}}function np(e,s=typeof localStorage<"u"?localStorage:void 0){try{s==null||s.setItem(Io,e?"1":"0")}catch{}}const pc=[Ku,{singleTilde:!1}],fc=[pc,Wu,Hu],ap=[pc],Ao=200,op=80,Ii=650,Zs=new Map;function yn(e,s){if(!e)return!1;const r=String(e.messageFingerprint||"");return r?r===String(s||""):!0}function ip(e,s){if(!Array.isArray(e)||e.length===0)return"0:empty";const r=String(s||"").trim();if(r)return`${e.length}:${r}`;const n=e[e.length-1];return`${e.length}:${Sm(n)}`}function lp(e,s,r,n){return e||!s?!1:yn(r,n)}function cp({scrollTop:e,scrollHeight:s,clientHeight:r,topThresholdPx:n=op,bottomThresholdPx:a=Ao}){const o=Math.max(0,Number(e)||0),l=Math.max(0,Number(s)||0),c=Math.max(0,Number(r)||0);return Math.max(0,l-c)<=0?{showTop:!1,showBottom:!1}:{showTop:o>n,showBottom:Math.max(0,l-o-c)>a}}function dp(e){return cp({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function pr(e,s=Ao){return!!e&&e.fromBottom>=s}function up(e,s){return yn(e,s)?!pr(e):!0}function mp({hasSelection:e,userScrolledUp:s,hasChatContentChanged:r=!0}){return!(e||s||!r)}function pp({hasSelection:e,userScrolledUp:s,contextAutoScrollActive:r}){return e?!1:r||!s}function Zn(e,s){const r=Math.max(0,e.scrollHeight-e.clientHeight-s.fromBottom);e.scrollTop=Number.isFinite(r)?r:s.top}function hc(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function fp(e,s,r){return Number(e.receivedAt||r[vn(e,s)]||0)||0}function xc(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function hp(e){return Array.isArray(e)&&e.some(s=>!!s&&typeof s=="object"&&"type"in s)}function er(e,s){if(!e)return s;try{return(e.startsWith("file://")?new URL(e).pathname:e).split(/[\\/]/).filter(Boolean).pop()||s}catch{return e.split(/[\\/]/).filter(Boolean).pop()||s}}function ea(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 Wr(e,s,r){return t.jsxs("div",{className:"rounded-md border border-border-subtle p-2 text-sm",role:"note",children:[t.jsx("span",{className:"font-medium",children:e}),s?t.jsx("span",{className:"ml-1 break-all",children:s}):null,r?t.jsx("div",{className:"mt-1 opacity-80",style:{whiteSpace:"pre-wrap"},children:r}):null]})}function Ti(e,s){return e?s?t.jsx("pre",{className:"chat-preformatted",children:e}):xc(e)?t.jsx(yo,{remarkPlugins:fc,children:e}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}function tr({parts:e,renderAsPreformatted:s}){return t.jsx("div",{className:"flex flex-col gap-2",children:e.map((r,n)=>{if(r.type==="text")return t.jsx("div",{children:Ti(String(r.text||""),s)},`text-${n}`);if(r.type==="image"){const a=ea(r),o=r.alt||r.description||er(r.uri,"image");return a?t.jsx("img",{src:a,alt:o,className:"max-w-full rounded-md border border-border-subtle"},`image-${n}`):t.jsx("div",{children:Wr("Image",o,r.mimeType)},`image-fallback-${n}`)}if(r.type==="audio"){const a=ea(r);return a?t.jsxs("div",{className:"flex flex-col gap-1",children:[t.jsx("audio",{controls:!0,src:a,className:"max-w-full"}),r.transcript?t.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:r.transcript}):null]},`audio-${n}`):t.jsx("div",{children:Wr("Audio",er(r.uri,"audio"),r.transcript||r.mimeType)},`audio-fallback-${n}`)}if(r.type==="video"){const a=ea(r),o=r.title||r.name||r.alt||er(r.uri,"video"),l=[r.transcript,r.description,r.mimeType].filter(Boolean).join(`
|
|
3
|
-
`);return t.jsxs("div",{className:"flex flex-col gap-1",children:[a?t.jsx("video",{controls:!0,src:a,poster:r.posterUri,className:"max-w-full rounded-md border border-border-subtle"}):Wr("Video",o,l),a&&l?t.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:l}):null]},`video-${n}`)}if(r.type==="resource_link"){const a=r.title||r.name||er(r.uri,"resource"),o=[r.description,r.mimeType].filter(Boolean).join(`
|
|
4
|
-
`);return t.jsxs("div",{className:"flex flex-col gap-1",children:[r.uri?t.jsx("a",{href:r.uri,target:"_blank",rel:"noreferrer",download:!0,className:"underline break-all",children:a}):Wr("Resource",a,o),r.uri&&o?t.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:o}):null]},`resource-link-${n}`)}if(r.type==="resource"&&r.resource){const a=er(r.resource.uri,"resource");if(r.resource.text)return t.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[t.jsx("div",{className:"text-[11px] opacity-70 mb-1",children:a}),Ti(r.resource.text,!0)]},`resource-${n}`);if(r.resource.uri)return t.jsx("a",{href:r.resource.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:a},`resource-uri-${n}`)}return null})})}function vn(e,s){const r=e,n=wo(e.content,{joiner:`
|
|
5
|
-
`});return[e.id?`id:${e.id}`:"",r._localId?`local:${r._localId}`:"",r._turnKey?`turn:${r._turnKey}`:"",typeof e.index=="number"?`msgIndex:${e.index}`:"",e.role?`role:${e.role}`:"",n?`content:${n.slice(0,80)}`:"",`fallback:${s}`].filter(Boolean).join("|")}const xp=i.memo(function({log:s}){return t.jsxs("div",{className:"self-center chat-msg-action",children:[t.jsx(yo,{remarkPlugins:ap,children:s.text}),t.jsx("span",{className:"action-time",children:hc(s.timestamp)})]})},(e,s)=>e.log===s.log),bp=i.memo(function({message:s,receivedAt:r,agentName:n,userName:a,isCliMode:o,isTextExpanded:l,onToggleTextExpanded:c}){var w,k,F;const d=(s.role||"").toLowerCase(),m=d==="user"||d==="human",u=s.kind||(d==="tool"?"tool":"standard"),h=To(s),g=hp(s.content)?s.content:null,j=!!(g!=null&&g.some(_=>_.type!=="text")),f=wo(s.content,{joiner:`
|
|
6
|
-
`});if(h.isActivityFacing&&u!=="thought"&&u!=="tool"&&u!=="terminal"){const _=h.label||"Activity";return t.jsxs("div",{className:"self-start chat-msg-activity","data-chat-activity-row":"true",children:[t.jsxs("div",{className:"chat-msg-activity-meta","aria-label":"Activity message",children:[t.jsx("span",{className:"activity-dot"}),t.jsx("span",{children:_})]}),j&&g?t.jsx("div",{className:"chat-msg-activity-body",children:t.jsx(tr,{parts:g,renderAsPreformatted:!1})}):t.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:f})]})}if(u==="thought"){const _=typeof((w=s.meta)==null?void 0:w.label)=="string"?s.meta.label:"Thought";return t.jsxs("div",{className:"self-start chat-msg-thought","data-chat-activity-row":h.isActivityFacing?"true":void 0,children:[t.jsxs("div",{className:"chat-msg-header",children:[t.jsx(Em,{size:13}),t.jsx("span",{children:_})]}),t.jsx("div",{className:"chat-msg-body",children:f})]})}if(u==="tool")return t.jsxs("div",{className:"self-start chat-msg-tool","data-chat-activity-row":h.isActivityFacing?"true":void 0,children:[t.jsxs("div",{className:"chat-msg-tool-meta","aria-label":"Tool message",children:[t.jsx("span",{className:"tool-icon",children:"⏺"}),t.jsx("span",{className:"tool-label",children:"Tool"})]}),j&&g?t.jsx("div",{className:"tool-text w-full",children:t.jsx(tr,{parts:g,renderAsPreformatted:!1})}):t.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:f})]});if(u==="terminal"){const _=(k=s.meta)!=null&&k.isRunning?"⏳":"✅",S=typeof((F=s.meta)==null?void 0:F.label)=="string"?s.meta.label:"Ran command";return t.jsxs("div",{className:"self-start chat-msg-terminal","data-chat-activity-row":h.isActivityFacing?"true":void 0,children:[t.jsxs("div",{className:"chat-msg-header",children:[t.jsx("span",{children:_}),t.jsx("span",{children:S})]}),j&&g?t.jsx("div",{className:"chat-msg-body",children:t.jsx(tr,{parts:g,renderAsPreformatted:!0})}):t.jsx("pre",{className:"chat-msg-body",children:f})]})}if(u==="system")return t.jsx("div",{className:"self-center chat-msg-system",children:j&&g?t.jsx(tr,{parts:g,renderAsPreformatted:!1}):f.slice(0,100)});const p=s.meta,y=(typeof(p==null?void 0:p.renderMode)=="string"?p.renderMode.trim():"")==="preformatted",x=f,A=!1,N=x,v=y,C=!v&&xc(N),M=["chat-message-row",m?"chat-message-row-user self-end":"chat-message-row-assistant self-start"].join(" ");return t.jsx("div",{className:M,children:(x||j||m)&&t.jsxs("div",{className:`chat-bubble ${m?"chat-bubble-user":"chat-bubble-assistant"}`,children:[t.jsxs("div",{className:`chat-bubble-header ${x||j?"mb-1.5":"mb-0"}`,children:[t.jsx("span",{className:"chat-sender",children:m?a||"You":s.senderName||n}),r!=null&&t.jsx("span",{className:"chat-time",children:hc(r)})]}),(x||j)&&t.jsx("div",{className:"chat-markdown",children:j&&g?t.jsx(tr,{parts:g,renderAsPreformatted:v}):v?t.jsx("pre",{className:"chat-preformatted",children:N}):C?t.jsx(yo,{remarkPlugins:fc,children:N}):t.jsx("div",{style:{whiteSpace:"pre-wrap"},children:N})}),A]})})},(e,s)=>e.message===s.message&&e.receivedAt===s.receivedAt&&e.agentName===s.agentName&&e.userName===s.userName&&e.isCliMode===s.isCliMode&&e.isTextExpanded===s.isTextExpanded),gp=i.forwardRef(function({messages:s,actionLogs:r,agentName:n="Agent",userName:a,isCliMode:o=!1,isWorking:l=!1,contextKey:c="",receivedAtMap:d={},lastMessageHash:m,showActivityMessages:u=!1,emptyState:h,onLoadMore:g,isLoadingMore:j,hasMoreHistory:f,hiddenLiveCount:p=0,loadError:b,scrollToBottomRequestNonce:y,isVisible:x=!0},A){const N=i.useRef(null),v=i.useRef(null),C=i.useRef(null),M=i.useRef(0),w=i.useRef(""),k=i.useRef(""),F=i.useRef(!1),_=i.useRef(null),S=i.useRef(!1),H=i.useRef(null),W=i.useRef(!1),[D,I]=i.useState(new Set),[T,K]=i.useState({showTop:!1,showBottom:!1}),P=i.useRef(!1),$=i.useRef(!1),V=i.useRef(x),Y=i.useRef(x),ge=i.useRef(null);Y.current=x;const fe=()=>{const X=N.current;return X?X.scrollHeight-X.scrollTop-X.clientHeight<Ao:!0},ae=i.useCallback(()=>{const X=N.current,oe=X?dp(X):{showTop:!1,showBottom:!1};K(ee=>ee.showTop===oe.showTop&&ee.showBottom===oe.showBottom?ee:oe)},[]),me=i.useCallback((X="auto")=>{var ee;const oe=N.current;oe&&(oe.scrollTo({top:oe.scrollHeight,behavior:X}),(ee=oe.ownerDocument.defaultView)==null||ee.requestAnimationFrame(()=>ae()))},[ae]),je=i.useCallback((X="auto")=>{var ee;const oe=N.current;oe&&(oe.scrollTo({top:0,behavior:X}),(ee=oe.ownerDocument.defaultView)==null||ee.requestAnimationFrame(()=>ae()))},[ae]),Ne=i.useCallback(()=>{var Ce;const X=N.current,oe=(Ce=window.getSelection)==null?void 0:Ce.call(window);if(!X||!oe||oe.rangeCount===0||oe.isCollapsed){W.current=!1;return}const ee=oe.anchorNode,ke=oe.focusNode;W.current=!!(ee&&ke&&X.contains(ee)&&X.contains(ke))},[]),G=i.useMemo(()=>{const X=sp(s),oe=mc(s);return rp(X,oe,u)},[s,u]),he=G.length===s.length?m:void 0,pe=ip(G,he),ye=i.useCallback(()=>{const X=N.current;if(!X||!c||!Y.current)return;const oe={top:X.scrollTop,fromBottom:Math.max(0,X.scrollHeight-X.scrollTop-X.clientHeight),messageFingerprint:pe};ge.current={contextKey:c,snapshot:oe},Zs.set(c,oe)},[c,pe]),xe=i.useCallback((X="auto")=>{_.current!=null&&cancelAnimationFrame(_.current),_.current=requestAnimationFrame(()=>{_.current=null,me(X)})},[me]),Se=i.useCallback(()=>{P.current=!1,S.current=!0,$.current=!0,H.current!=null&&window.clearTimeout(H.current),H.current=window.setTimeout(()=>{S.current=!1,H.current=null},Ii)},[]);i.useEffect(()=>{const X=!F.current,oe=k.current!==c;if(k.current=c,X||oe){F.current=!0;const ke=c?Zs.get(c):null,Ce=!!ke&&yn(ke,pe);P.current=Ce?pr(ke):!1,S.current=up(ke,pe),W.current||(Ce?requestAnimationFrame(()=>{const ve=N.current;ve&&(Zn(ve,ke),P.current=pr(ke),ae(),$.current=!0)}):xe("auto")),M.current=G.length,w.current=pe;return}G.length>M.current;const ee=pe!==w.current;mp({hasSelection:W.current,userScrolledUp:P.current,hasChatContentChanged:ee})&&xe("auto"),M.current=G.length,w.current=pe},[pe,c,G.length,xe,ae]),i.useEffect(()=>{y&&(Se(),W.current||xe("auto"))},[Se,xe,y]),i.useEffect(()=>{const X=V.current;X&&!x&&ye(),Y.current=x,V.current=x;const oe=c?Zs.get(c):null;if(lp(X,x,oe,pe)){if(!oe)return;P.current=pr(oe),S.current=!1,W.current||requestAnimationFrame(()=>{const ee=N.current;ee&&(Zn(ee,oe),ae())});return}},[x,c,pe,Se,ye,xe,ae]),i.useEffect(()=>()=>{const X=ge.current;X&&Zs.set(X.contextKey,X.snapshot),_.current!=null&&cancelAnimationFrame(_.current),H.current!=null&&window.clearTimeout(H.current)},[]),i.useEffect(()=>{const X=v.current,oe=N.current;if(!X||!oe)return;const ee=()=>{H.current!=null&&window.clearTimeout(H.current),H.current=window.setTimeout(()=>{S.current=!1,H.current=null},Ii)},ke=new ResizeObserver(()=>{ae();const Ce=S.current;pp({hasSelection:W.current,userScrolledUp:P.current,contextAutoScrollActive:Ce})&&(xe("auto"),Ce&&ee())});return ke.observe(X),oe!==X&&ke.observe(oe),()=>{ke.disconnect(),H.current!=null&&(window.clearTimeout(H.current),H.current=null)}},[xe,c,ae]),i.useImperativeHandle(A,()=>({scrollToBottom:(X="smooth")=>{me(X)}}),[me]),i.useEffect(()=>{const X=N.current;if(!X)return;let oe;const ee=()=>{ye(),clearTimeout(oe),oe=setTimeout(()=>{P.current=!fe(),ae()},50)};return X.addEventListener("scroll",ee,{passive:!0}),()=>{X.removeEventListener("scroll",ee),clearTimeout(oe)}},[ye,ae]),i.useEffect(()=>(document.addEventListener("selectionchange",Ne),()=>document.removeEventListener("selectionchange",Ne)),[Ne]);const R=i.useRef(0),re=i.useRef(!1);i.useEffect(()=>{const X=N.current;if(!X||!re.current||R.current===0)return;const oe=X.scrollHeight-R.current;oe>0&&(X.scrollTop=oe),ae(),ye(),R.current=0,re.current=!1},[G.length,ye,ae]),i.useEffect(()=>{if($.current||!c)return;const X=Zs.get(c),oe=N.current;if(!(!X||!oe)){if(!yn(X,pe)){me("auto"),$.current=!0;return}Zn(oe,X),P.current=pr(X),ae(),$.current=!0}},[c,pe,G.length,me,ae]);const Q=()=>{const X=N.current;X&&(R.current=X.scrollHeight),re.current=!0,g==null||g()},ue=()=>{P.current=!0,je("smooth"),ye()},ce=()=>{Se(),me("smooth"),ye()},de=i.useMemo(()=>{const X=G.map((Ce,ve)=>({type:"message",data:Ce,index:ve,ts:fp(Ce,ve,d)}));if(!r||r.length===0)return X;const oe=[...r].sort((Ce,ve)=>Ce.timestamp-ve.timestamp).map((Ce,ve)=>({type:"action",data:Ce,index:ve,ts:Ce.timestamp})),ee=[];let ke=0;for(const Ce of X){for(;ke<oe.length&&Ce.ts>0&&oe[ke].ts<Ce.ts;)ee.push(oe[ke++]);ee.push(Ce)}for(;ke<oe.length;)ee.push(oe[ke++]);return ee},[G,r,d]),te=p>0||!!f,E=p>0?`↑ Show ${Math.min(p,80)} earlier messages${p>80?` (${p} hidden)`:""}`:b?`↻ ${b}`:"↑ Load older messages";return t.jsxs("div",{className:"chat-scroll-frame",children:[t.jsx("div",{ref:N,"data-chat-scroll":!0,className:"chat-container",children:t.jsxs("div",{ref:v,className:"chat-container-content",children:[j&&t.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:"Loading older messages..."}),te&&!j&&t.jsx("div",{className:"text-center py-2",children:t.jsx("button",{type:"button",onClick:Q,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${b&&p===0?"bg-transparent border-yellow-500/30 text-yellow-400 opacity-80 hover:opacity-100":"bg-transparent border-border-subtle text-text-muted opacity-70 hover:opacity-100 hover:border-accent/40"}`,children:E})}),de.length===0&&!te&&(h||t.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:"Waiting for messages..."})),de.map(X=>{if(X.type==="action"){const Ie=X.data;return t.jsx(xp,{log:Ie},`action-${X.index}`)}const oe=X.data,ee=X.index,ke=vn(oe,ee),Ce=oe.receivedAt||d[ke],ve=`${c}-${ke}`,O=D.has(ve);return t.jsx(bp,{message:oe,receivedAt:Ce,agentName:n,userName:a,isCliMode:o,isTextExpanded:O,onToggleTextExpanded:()=>I(Ie=>{const Re=new Set(Ie);return O?Re.delete(ve):Re.add(ve),Re})},`msg-${ke}`)}),l&&t.jsx("div",{className:"self-start chat-typing-wrapper",children:t.jsxs("div",{className:"typing-indicator",children:[t.jsx("div",{className:"dot"}),t.jsx("div",{className:"dot"}),t.jsx("div",{className:"dot"}),t.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:"Agent generating..."})]})}),t.jsx("div",{className:"min-h-10",ref:C})]})}),(T.showTop||T.showBottom)&&t.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":"Chat scroll shortcuts",children:[T.showTop&&t.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:ue,"aria-label":"Jump to oldest messages",title:"Jump to top",children:"↑ Top"}),T.showBottom&&t.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:ce,"aria-label":"Jump to latest messages",title:"Jump to bottom",children:"↓ Latest"})]})]})}),yp=i.memo(gp,(e,s)=>e.messages===s.messages&&e.actionLogs===s.actionLogs&&e.agentName===s.agentName&&e.userName===s.userName&&e.isCliMode===s.isCliMode&&e.isWorking===s.isWorking&&e.contextKey===s.contextKey&&e.receivedAtMap===s.receivedAtMap&&e.lastMessageHash===s.lastMessageHash&&e.showActivityMessages===s.showActivityMessages&&e.emptyState===s.emptyState&&e.onLoadMore===s.onLoadMore&&e.isLoadingMore===s.isLoadingMore&&e.hasMoreHistory===s.hasMoreHistory&&e.hiddenLiveCount===s.hiddenLiveCount&&e.loadError===s.loadError&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&e.isVisible===s.isVisible),vp="modulepreload",wp=function(e){return"/"+e},Ai={},jp=function(s,r,n){let a=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),c=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));a=Promise.allSettled(r.map(d=>{if(d=wp(d),d in Ai)return;Ai[d]=!0;const m=d.endsWith(".css"),u=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const h=document.createElement("link");if(h.rel=m?"stylesheet":vp,m||(h.as="script"),h.crossOrigin="",h.href=d,c&&h.setAttribute("nonce",c),document.head.appendChild(h),m)return new Promise((g,j)=>{h.addEventListener("load",g),h.addEventListener("error",()=>j(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return a.then(l=>{for(const c of l||[])c.status==="rejected"&&o(c.reason);return s().catch(o)})};let Mi=!1;const bc=i.forwardRef(({onInput:e,onViewportMetrics:s,onScrollMetrics:r,fontSize:n=13,readOnly:a=!1,sizingMode:o="measured"},l)=>{const c=i.useRef(null),[d,m]=i.useState(null),u=i.useRef([]),h=i.useRef(!1),g=i.useRef(!1),j=i.useRef(!1),f=i.useRef(!1),p=()=>{const b=c.current;if(b){h.current&&(b.clear(),h.current=!1);for(const y of u.current)b.write(y.data,y.onProcessed);u.current=[],g.current&&(b.fit(),g.current=!1),j.current&&(b.bumpResize(),j.current=!1),f.current&&(b.scrollToTop(),f.current=!1)}};return i.useImperativeHandle(l,()=>({write:(b,y)=>{c.current?c.current.write(b,y):u.current.push({data:b,onProcessed:y})},clear:()=>{c.current?c.current.clear():(u.current=[],h.current=!0)},reset:()=>{c.current&&typeof c.current.reset=="function"?c.current.reset():(u.current=[],h.current=!0)},resize:(b,y)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(b,y)},fit:()=>{c.current?c.current.fit():g.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():j.current=!0},scrollToTop:()=>{c.current?c.current.scrollToTop():f.current=!0},getSelection:()=>{var b,y;return((y=(b=c.current)==null?void 0:b.getSelection)==null?void 0:y.call(b))||""},getVisibleText:()=>{var b,y;return((y=(b=c.current)==null?void 0:b.getVisibleText)==null?void 0:y.call(b))||""}}),[]),i.useEffect(()=>{d&&p()},[d]),i.useEffect(()=>{let b=!1;return jp(()=>import("./terminal-DCVDkSIp.js"),__vite__mapDeps([0,1,2])).then(y=>{Mi||(Mi=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),b||m(()=>y.GhosttyTerminalView)}).catch(y=>{console.error("[CliTerminal] failed to load terminal renderer",y)}),()=>{b=!0}},[]),d?t.jsx(d,{ref:c,onInput:e,onViewportMetrics:s,onScrollMetrics:r,fontSize:n,readOnly:a,sizingMode:o,className:"w-full h-full rounded-lg overflow-hidden"}):t.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});bc.displayName="CliTerminal";function Hr({label:e,value:s,sub:r,icon:n}){return t.jsxs("div",{className:"px-4 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[t.jsx("span",{className:"text-base flex items-center",children:n}),t.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:e})]}),t.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:s}),r&&t.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:r})]})}function Li({value:e,max:s,label:r,color:n="#8b5cf6",detail:a,compact:o=!1}){const l=s>0?Math.min(Math.round(e/s*100),100):0,c=l>85?"#ef4444":l>60?"var(--status-warning)":n;return o?t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex justify-between mb-0.5",children:[t.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide font-semibold",children:r}),t.jsxs("span",{className:"text-[10px] text-text-secondary font-semibold",children:[l,"%"]})]}),t.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:t.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${l}%`,background:c}})})]}):t.jsxs("div",{className:"flex-1",children:[t.jsxs("div",{className:"flex justify-between mb-1.5",children:[t.jsx("span",{className:"text-[11px] text-text-secondary font-medium",children:r}),t.jsxs("span",{className:"text-[13px] text-text-primary font-bold",children:[l,"%"]})]}),t.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:t.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${l}%`,background:`linear-gradient(90deg, ${c}, ${c}cc)`}})}),a&&t.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:a})]})}function kp({cursorPos:e,viewportRef:s,imgRef:r}){var x;if(!e||!r.current)return null;const n=r.current,a=n.getBoundingClientRect(),o=(x=s.current)==null?void 0:x.getBoundingClientRect();if(!o)return null;const l=n.naturalWidth||a.width,c=n.naturalHeight||a.height,d=l/c,m=a.width/a.height;let u,h,g,j;d>m?(u=a.width,h=a.width/d,g=0,j=(a.height-h)/2):(h=a.height,u=a.height*d,g=(a.width-u)/2,j=0);const f=a.left-o.left+g+u*e.nx,p=a.top-o.top+j+h*e.ny,b=Math.max(8,Math.min(o.width-8,f)),y=Math.max(8,Math.min(o.height-8,p));return t.jsxs("div",{style:{position:"absolute",left:b-8,top:y-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[t.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),t.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),t.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 Np({inputMode:e,onToggleInputMode:s,isImeOpen:r,setIsImeOpen:n,isMenuOpen:a,setIsMenuOpen:o,imeText:l,setImeText:c,handleImeSubmit:d,isConnActive:m,zoom:u,isMobile:h,mobileFillZoom:g,onZoomOut:j,onZoomReset:f,onZoomIn:p,transportType:b,screenshotUsage:y,lastActionStatus:x}){return t.jsxs(t.Fragment,{children:[t.jsxs("div",{onTouchStart:A=>A.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:[t.jsxs("div",{onClick:s,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:[t.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),t.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:e==="mouse"?"Mouse":"Touch"})]}),t.jsxs("div",{className:"relative",children:[t.jsx("div",{onClick:()=>{n(A=>!A),o(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${r?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:t.jsx("span",{className:"text-sm",children:"⌨️"})}),r&&t.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:t.jsx("input",{type:"text",placeholder:"Type & Enter...",value:l,autoFocus:!0,onTouchStart:A=>A.stopPropagation(),onChange:A=>c(A.target.value),onKeyDown:A=>{d(A)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),t.jsx("div",{className:"relative",children:t.jsx("div",{onClick:()=>{o(A=>!A),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:t.jsx("span",{className:"text-sm",children:"⚙️"})})}),t.jsx("div",{className:"w-px h-[18px] bg-white/10"}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.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:[t.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:m?"#22c55e":"#eab308",boxShadow:m?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),t.jsx("span",{className:"text-[8px] font-extrabold",style:{color:m?"#22c55e":"#eab308"},children:m?"Connected":"WS"})]}),u>1&&t.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(u*100),"%"]}),b==="direct"&&t.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"}),b==="relay"&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:"TURN relay in use",children:"Relay"}),y&&y.dailyBudgetMinutes>0&&t.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:y.budgetExhausted?"#ef4444":"#c4b5fd",background:y.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:"Daily TURN relay usage",children:y.budgetExhausted?"TURN blocked":`TURN ${y.dailyUsedMinutes}/${y.dailyBudgetMinutes}m`}),x&&t.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:x})]})]}),a&&t.jsxs("div",{onTouchStart:A=>A.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:[t.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:"SETTINGS"}),t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:["ZOOM: ",u<=(h?g:1)+.01?h?"FILL":"FIT":`${Math.round(u*100)}%`]}),t.jsxs("div",{style:{display:"flex",gap:4},children:[t.jsx("button",{onClick:A=>{A.stopPropagation(),j()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),t.jsx("button",{onClick:A=>{A.stopPropagation(),f()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:h?"FILL":"FIT"}),t.jsx("button",{onClick:A=>{A.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 Sp({waitingLabel:e,waitingHint:s,transportType:r}){return t.jsxs("div",{className:"text-center flex flex-col items-center gap-3 px-6",children:[t.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:t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-8 h-8 opacity-90"})}),t.jsx("div",{className:"text-white/85 text-[13px] font-semibold tracking-wide",children:e}),t.jsx("div",{className:"text-[11px] text-white/40",children:s}),r==="relay"&&t.jsx("div",{className:"text-[10px] font-medium",style:{color:"var(--status-warning)",opacity:.8},children:"TURN relay active"})]})}function Cp(){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 Ri(e){return e==null||typeof e=="number"||typeof e=="boolean"?e:typeof e=="string"?e.length>64?`${e.slice(0,61)}...`:e:Array.isArray(e)?`Array(${e.length})`:typeof e=="object"?"Object":typeof e}function Ar(e,s){const r=i.useRef(null),n=i.useRef(0);i.useEffect(()=>{if(!Cp())return;n.current+=1;const a=r.current;if(!a){console.debug(`[render-trace] ${e}#${n.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(s).map(([l,c])=>[l,Ri(c)]))}),r.current=s;return}const o=Object.keys({...a,...s}).filter(l=>!Object.is(a[l],s[l]));o.length>0&&console.debug(`[render-trace] ${e}#${n.current}`,{changed:o,snapshot:Object.fromEntries(o.map(l=>[l,Ri(s[l])]))}),r.current=s})}function Ip({containerRef:e,viewportRef:s,imgRef:r,inputMode:n,setInputMode:a,minZoom:o,zoomRef:l,panXRef:c,panYRef:d,setPanX:m,setPanY:u,setZoom:h,lastWheelTimeRef:g,onAction:j,setLastActionStatus:f,spawnRippleFromNormalized:p,clampPan:b,isMobile:y,mobileFillZoom:x}){const[A,N]=i.useState(null),v=i.useRef(null),C=i.useRef(null),M=i.useRef(null),w=i.useRef(!1),k=i.useRef(null),F=i.useRef(0),_=i.useRef(null),S=i.useRef(1),H=i.useRef({x:0,y:0}),W=i.useRef(!1),D=i.useRef(n),I=i.useRef(j),T=30,K=550,P=18,$=60,V=400,Y=12,ge=()=>{if(v.current)return;const me={nx:.5,ny:.5};v.current=me,N(me)};return i.useEffect(()=>{D.current=n,n==="mouse"&&ge()},[n]),i.useEffect(()=>{I.current=j},[j]),i.useEffect(()=>{const me=e.current;if(!me)return;const je=xe=>{if(!r.current)return null;const Se=r.current.getBoundingClientRect();return!Se.width||!Se.height?null:{nx:Math.max(0,Math.min(1,(xe.clientX-Se.left)/Se.width)),ny:Math.max(0,Math.min(1,(xe.clientY-Se.top)/Se.height))}},Ne=(xe,Se)=>{if(!r.current)return{dnx:0,dny:0};const R=r.current,re=R.getBoundingClientRect(),Q=R.naturalWidth||re.width,ue=R.naturalHeight||re.height,ce=Q/ue,de=re.width/re.height;let te,E;return ce>de?(te=re.width,E=re.width/ce):(E=re.height,te=re.height*ce),{dnx:xe/te,dny:Se/E}},G=(xe,Se,R)=>{if(R<=1.05)return;const re=-(xe-.5)*100,Q=-(Se-.5)*100,ue=b(re,Q,R);(Math.abs(ue.x-c.current)>.1||Math.abs(ue.y-d.current)>.1)&&(m(ue.x),u(ue.y),c.current=ue.x,d.current=ue.y)},he=xe=>{const Se=s.current;if(Se&&xe.target instanceof Node&&Se.contains(xe.target))xe.preventDefault();else return;if(xe.touches.length===1){const R=xe.touches[0];C.current={x:R.clientX,y:R.clientY,time:Date.now()},M.current={x:R.clientX,y:R.clientY},W.current||(w.current=!1),k.current=setTimeout(()=>{if(!w.current&&!W.current)if(w.current=!0,D.current==="mouse"){const re=v.current||{nx:.5,ny:.5};f("Right Click"),p(re.nx,re.ny,"right"),I.current("input_click",{...re,button:"right"}).catch(()=>{})}else{const re=je(R);re&&(f("Right Click"),p(re.nx,re.ny,"right"),I.current("input_click",{...re,button:"right"}).catch(()=>{}))}},500);return}if(xe.touches.length===2){k.current&&clearTimeout(k.current),w.current=!0,W.current=!0;const R=xe.touches[1].clientX-xe.touches[0].clientX,re=xe.touches[1].clientY-xe.touches[0].clientY;_.current=Math.sqrt(R*R+re*re),S.current=l.current,H.current={x:(xe.touches[0].clientX+xe.touches[1].clientX)/2,y:(xe.touches[0].clientY+xe.touches[1].clientY)/2}}},pe=xe=>{const Se=s.current;if(Se&&xe.target instanceof Node&&Se.contains(xe.target)&&xe.preventDefault(),xe.touches.length===1&&M.current){const R=xe.touches[0],re=R.clientX-M.current.x,Q=R.clientY-M.current.y;if(!w.current&&C.current){const ue=R.clientX-C.current.x,ce=R.clientY-C.current.y;Math.sqrt(ue*ue+ce*ce)>8&&(w.current=!0,k.current&&clearTimeout(k.current))}if(w.current)if(D.current==="mouse"){const ue=Ne(re,Q),ce=v.current||{nx:.5,ny:.5},de=Math.max(0,Math.min(1,ce.nx+ue.dnx)),te=Math.max(0,Math.min(1,ce.ny+ue.dny));v.current={nx:de,ny:te},N({nx:de,ny:te}),f(`Cursor: ${Math.round(de*100)}%, ${Math.round(te*100)}%`),G(de,te,l.current);const E=Date.now();E-g.current>=30&&(g.current=E,I.current("input_mouseMoved",{nx:de,ny:te}).catch(()=>{}))}else if(l.current>1){const ue=s.current;if(ue){const ce=ue.clientWidth,de=ue.clientHeight,te=c.current+re/ce*100,E=d.current+Q/de*100,X=b(te,E,l.current);m(X.x),u(X.y),c.current=X.x,d.current=X.y}}else{const ue=je(R);if(ue){const ce=Date.now();ce-g.current>=40&&(g.current=ce,f("Scroll"),I.current("input_wheel",{nx:ue.nx,ny:ue.ny,deltaX:Math.round(-re*2.5),deltaY:Math.round(-Q*2.5)}).catch(()=>{}))}}M.current={x:R.clientX,y:R.clientY};return}if(xe.touches.length===2&&_.current!==null){const R=xe.touches[1].clientX-xe.touches[0].clientX,re=xe.touches[1].clientY-xe.touches[0].clientY,ue=Math.sqrt(R*R+re*re)/_.current,ce=(xe.touches[0].clientX+xe.touches[1].clientX)/2,de=(xe.touches[0].clientY+xe.touches[1].clientY)/2,te=ce-H.current.x,E=de-H.current.y,X=Math.abs(ue-1)>.03;if(D.current==="mouse"){if(X){const oe=Math.max(o,Math.min(5,S.current*ue));h(oe),l.current=oe}else if(Math.abs(te)>2||Math.abs(E)>2){const oe=v.current||{nx:.5,ny:.5},ee=Date.now();ee-g.current>=30&&(g.current=ee,f("Scroll"),I.current("input_wheel",{nx:oe.nx,ny:oe.ny,deltaX:Math.round(-te*3),deltaY:Math.round(-E*3)}).catch(()=>{}))}}else{const oe=Math.max(o,Math.min(5,S.current*ue));h(oe),l.current=oe;const ee=s.current;if(ee&&oe>1){const ke=ee.clientWidth,Ce=ee.clientHeight,ve=c.current+te/ke*100,O=d.current+E/Ce*100,Ie=b(ve,O,oe);m(Ie.x),u(Ie.y),c.current=Ie.x,d.current=Ie.y}}H.current={x:ce,y:de}}},ye=xe=>{var Se;if(k.current&&clearTimeout(k.current),_.current=null,xe.touches.length===1&&W.current){const R=xe.touches[0];C.current={x:R.clientX,y:R.clientY,time:Date.now()},M.current={x:R.clientX,y:R.clientY},w.current=!0;return}if(xe.touches.length===0){if(W.current){W.current=!1,w.current=!1;return}if(xe.changedTouches.length===1){const R=xe.changedTouches[0],re=Date.now(),Q=re-(((Se=C.current)==null?void 0:Se.time)||0),ue=C.current?R.clientX-C.current.x:0,ce=C.current?R.clientY-C.current.y:0,de=Math.sqrt(ue*ue+ce*ce);if(D.current==="mouse"){if(Q<T||Q>K||de>P){w.current=!1;return}const te=v.current||je(R);te&&(f(`Click: ${Math.round(te.nx*100)}%, ${Math.round(te.ny*100)}%`),p(te.nx,te.ny,"left"),I.current("input_click",{...te}).catch(()=>{}))}else{if(w.current){w.current=!1;return}if(Q<$||Q>V||de>Y){w.current=!1;return}const te=je(R);if(!te)return;re-F.current<300?(f("Double tap"),p(te.nx,te.ny,"double"),I.current("input_click",{...te,clickCount:2}).catch(()=>{}),F.current=0):(f(`Tap: ${Math.round(te.nx*100)}%, ${Math.round(te.ny*100)}%`),p(te.nx,te.ny,"left"),I.current("input_click",{...te}).catch(()=>{}),F.current=re)}}w.current=!1}};return me.addEventListener("touchstart",he,{passive:!1}),me.addEventListener("touchmove",pe,{passive:!1}),me.addEventListener("touchend",ye,{passive:!1}),()=>{me.removeEventListener("touchstart",he),me.removeEventListener("touchmove",pe),me.removeEventListener("touchend",ye),k.current&&clearTimeout(k.current)}},[e,s,r,o,l,c,d,m,u,h,g,f,p,b]),{cursorPos:A,cursorPosRef:v,handleToggleInputMode:()=>{a(me=>{const je=me==="touch"?"mouse":"touch";return je==="mouse"&&ge(),je})},handleZoomReset:()=>{const me=y?x:1;h(me),l.current=me,m(0),u(0),c.current=0,d.current=0}}}function gc({onAction:e,addLog:s,connState:r,connScreenshot:n,screenshotUsage:a,transportType:o}){const l=i.useRef(null),c=i.useRef(null),d=i.useRef(null),[m,u]=i.useState(null),[h,g]=i.useState(""),[,j]=i.useState(!1),[f,p]=i.useState([]),b=i.useRef(0),[y,x]=i.useState(!1),[A,N]=i.useState(!1),v=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[C,M]=i.useState(v?"mouse":"touch"),[w,k]=i.useState(1),F=i.useRef(!1),[_,S]=i.useState(1),[H,W]=i.useState(0),[D,I]=i.useState(0);Ar("RemoteView",{connState:r,hasScreenshot:!!n,inputMode:C,zoom:_,panX:H,panY:D,isMenuOpen:y,isImeOpen:A});const T=i.useRef(0),K=i.useRef(_),P=i.useRef(H),$=i.useRef(D);i.useEffect(()=>{K.current=_},[_]),i.useEffect(()=>{P.current=H},[H]),i.useEffect(()=>{$.current=D},[D]),i.useEffect(()=>{var Q;(Q=l.current)==null||Q.focus()},[]);const V=r==="connected",Y=n,ge=V?"Connected. Waiting for first frame...":r==="connecting"?"Connecting to Host...":"Reconnecting to Host...",fe=V?"The remote stream is warming up":"Waiting for the remote stream to catch up";i.useEffect(()=>{if(!v||F.current||!Y)return;const Q=d.current,ue=c.current;if(!Q||!ue)return;const ce=()=>{const de=ue.clientWidth,te=ue.clientHeight,E=Q.naturalWidth,X=Q.naturalHeight;if(!E||!X||!de||!te)return;const oe=Math.min(de/E,te/X),ke=Math.max(de/E,te/X)/oe;ke>1.01&&(k(ke),S(ke),K.current=ke),F.current=!0};Q.complete&&Q.naturalWidth?ce():Q.addEventListener("load",ce,{once:!0})},[Y,v]);const ae=.5;i.useEffect(()=>{_<=ae&&(W(0),I(0))},[_,ae]);const me=(Q,ue,ce)=>{if(ce<=ae)return{x:0,y:0};const de=(ce-1)/(2*ce)*100,te=(ce-1)/(2*ce)*100;return{x:Math.max(-de,Math.min(de,Q)),y:Math.max(-te,Math.min(te,ue))}},je=(Q,ue)=>{if(!d.current)return null;const ce=d.current.getBoundingClientRect();return!ce.width||!ce.height?null:{nx:Math.max(0,Math.min(1,(Q-ce.left)/ce.width)),ny:Math.max(0,Math.min(1,(ue-ce.top)/ce.height))}},Ne=(Q,ue,ce)=>{const de=c.current;if(!de)return;const te=de.getBoundingClientRect(),E=++b.current;p(X=>[...X,{id:E,x:Q-te.left,y:ue-te.top,type:ce}]),setTimeout(()=>p(X=>X.filter(oe=>oe.id!==E)),600)},G=(Q,ue,ce)=>{const de=d.current,te=c.current;if(!de||!te)return;const E=de.getBoundingClientRect(),X=te.getBoundingClientRect(),oe=de.naturalWidth||E.width,ee=de.naturalHeight||E.height,ke=oe/ee,Ce=E.width/E.height;let ve,O,Ie,Re;ke>Ce?(ve=E.width,O=E.width/ke,Ie=0,Re=(E.height-O)/2):(O=E.height,ve=E.height*ke,Ie=(E.width-ve)/2,Re=0);const Ke=E.left-X.left+Ie+ve*Q,He=E.top-X.top+Re+O*ue,Ye=++b.current;p(Xe=>[...Xe,{id:Ye,x:Ke,y:He,type:ce}]),setTimeout(()=>p(Xe=>Xe.filter(st=>st.id!==Ye)),600)},he=async Q=>{var ce;const ue=je(Q.clientX,Q.clientY);if(ue){u(`Click: ${Math.round(ue.nx*100)}%, ${Math.round(ue.ny*100)}%`),Ne(Q.clientX,Q.clientY,"left"),(ce=l.current)==null||ce.focus();try{const de=await e("input_click",{nx:ue.nx,ny:ue.ny});de!=null&&de.success||s(`❌ Click failed: ${de==null?void 0:de.error}`)}catch(de){s(`❌ Click error: ${de.message||de}`)}}},pe=async(Q,ue,ce,de=0)=>{try{await e("input_key",{type:ce?"char":"keyDown",key:Q,code:ue,text:ce?Q:void 0,unmodifiedText:ce?Q:void 0,modifiers:de})}catch(te){s(`❌ Key error: ${te.message||te}`)}},ye=async Q=>{if(Q.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(Q.key)&&Q.preventDefault();let ce=0;Q.altKey&&(ce|=1),Q.ctrlKey&&(ce|=2),Q.metaKey&&(ce|=4),Q.shiftKey&&(ce|=8),u(`Key: ${Q.key}`),await pe(Q.key,Q.code,Q.key.length===1,ce)},xe=async Q=>{if(Q.key==="Enter"){if(Q.nativeEvent.isComposing)return;if(h){const ue=h;g(""),u(`IME Sent: ${ue}`);try{const ce=await e("input_type",{text:ue});ce!=null&&ce.success||s(`❌ IME error: ${ce==null?void 0:ce.error}`)}catch(ce){s(`❌ IME error: ${ce.message}`)}}else u("Key: Enter"),await pe("Enter","Enter",!1)}};i.useEffect(()=>{const Q=l.current;if(!Q)return;const ue=ce=>{var de;if((de=d.current)!=null&&de.contains(ce.target)){ce.preventDefault();const te=Date.now();if(te-T.current<40)return;T.current=te;const E=je(ce.clientX,ce.clientY);if(!E)return;u(`Scroll: ${Math.round(ce.deltaY)}`),e("input_wheel",{nx:E.nx,ny:E.ny,deltaX:Math.round(ce.deltaX),deltaY:Math.round(ce.deltaY)}).catch(()=>{})}};return Q.addEventListener("wheel",ue,{passive:!1}),()=>Q.removeEventListener("wheel",ue)},[e]);const{cursorPos:Se,handleToggleInputMode:R,handleZoomReset:re}=Ip({containerRef:l,viewportRef:c,imgRef:d,inputMode:C,setInputMode:M,minZoom:ae,zoomRef:K,panXRef:P,panYRef:$,setPanX:W,setPanY:I,setZoom:S,lastWheelTimeRef:T,onAction:e,setLastActionStatus:u,spawnRippleFromNormalized:G,clampPan:me,isMobile:v,mobileFillZoom:w});return t.jsxs("div",{ref:l,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:ye,onContextMenu:Q=>Q.preventDefault(),onFocus:()=>j(!0),onBlur:()=>j(!1),tabIndex:0,children:[t.jsxs("div",{ref:c,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[Y?t.jsx("img",{ref:d,src:Y,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${_}) translate(${H}%, ${D}%)`,transformOrigin:"center center",cursor:C==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:he,onContextMenu:Q=>Q.preventDefault(),onDragStart:Q=>Q.preventDefault()}):t.jsx(Sp,{waitingLabel:ge,waitingHint:fe,transportType:o}),C==="mouse"&&Y&&t.jsx(kp,{cursorPos:Se,viewportRef:c,imgRef:d}),f.map(Q=>{const ce={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[Q.type];return t.jsxs("div",{style:{position:"absolute",left:Q.x,top:Q.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[t.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${ce}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),t.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${ce}, 0.9)`,boxShadow:`0 0 12px rgba(${ce}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},Q.id)})]}),t.jsx(Np,{inputMode:C,onToggleInputMode:R,isImeOpen:A,setIsImeOpen:N,isMenuOpen:y,setIsMenuOpen:x,imeText:h,setImeText:g,handleImeSubmit:xe,isConnActive:V,zoom:_,isMobile:v,mobileFillZoom:w,onZoomOut:()=>S(Q=>Math.max(.5,Q-.25)),onZoomReset:re,onZoomIn:()=>S(Q=>Math.min(5,Q+.25)),transportType:o,screenshotUsage:a,lastActionStatus:m}),t.jsx("style",{children:`
|
|
7
|
-
@keyframes slideUp {
|
|
8
|
-
from { opacity: 0; transform: translateY(6px); }
|
|
9
|
-
to { opacity: 1; transform: translateY(0); }
|
|
10
|
-
}
|
|
11
|
-
@keyframes slideUpSidebar {
|
|
12
|
-
from { opacity: 0; transform: translateY(6px); }
|
|
13
|
-
to { opacity: 1; transform: translateY(0); }
|
|
14
|
-
}
|
|
15
|
-
@keyframes click-ripple-ring {
|
|
16
|
-
0% { transform: scale(0.3); opacity: 1; }
|
|
17
|
-
100% { transform: scale(2.2); opacity: 0; }
|
|
18
|
-
}
|
|
19
|
-
@keyframes click-ripple-dot {
|
|
20
|
-
0% { transform: scale(1); opacity: 0.9; }
|
|
21
|
-
50% { transform: scale(1.8); opacity: 0.6; }
|
|
22
|
-
100% { transform: scale(0.5); opacity: 0; }
|
|
23
|
-
}
|
|
24
|
-
@keyframes remote-float {
|
|
25
|
-
0% { transform: translateY(0px); }
|
|
26
|
-
50% { transform: translateY(-7px); }
|
|
27
|
-
100% { transform: translateY(0px); }
|
|
28
|
-
}
|
|
29
|
-
`})]})}function En(e,s={}){if(!e)return"";const{suffix:r="",nowLabel:n="now",nowThreshold:a=60}=s,o=Date.now()-e,l=Math.floor(o/1e3);if(l<a)return n;const c=Math.floor(l/60);if(c<60)return`${c}m${r}`;const d=Math.floor(c/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 yc=e=>En(e);function Tp(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 Xs(e){const s=e.connectionState==="failed"||e.connectionState==="closed",r=e.connectionState==="connecting"||e.connectionState==="new",n=e.status==="generating",a=e.status==="waiting_approval";return{isReconnecting:s,isConnecting:r,isGenerating:n,isWaiting:a}}function Ap(e){const s=new Map,r=(n,a)=>{n&&s.set(n,{sessionId:n,...Tp(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 s}function wn(e,s){if(e.sessionId){const r=s.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 $n(e,s,r){const n=wn(e,s),a=Xs(e),o=a.isReconnecting,l=a.isConnecting,c=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"||c,g=!!(n.inboxBucket==="task_complete"&&n.unread&&!(r!=null&&r.hideOpenTaskCompleteUnread&&(r!=null&&r.isOpenConversation)));return{unread:g,requiresAction:m,isWorking:u,isReconnecting:o,isConnecting:l,isGenerating:c,isWaiting:d,inboxBucket:m?"needs_attention":u?"working":g?"task_complete":"idle"}}function Mp(e,s,r){return $n(e,s,{hideOpenTaskCompleteUnread:!0,isOpenConversation:r==null?void 0:r.isOpenConversation}).unread}function vc({activeConv:e,onModalButton:s}){const[r,n]=i.useState(null);if(i.useEffect(()=>{n(null)},[e.modalMessage,e.status,e.connectionState]),!Xs(e).isWaiting||!e.modalButtons)return null;const o=c=>{r||(n(c),s(c))},l=c=>c.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return t.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&&t.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)}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[t.jsx(Sr,{size:14})," ",r?"PROCESSING...":"ACTION REQUIRED"]}),t.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((c,d)=>{const m=l(c).toLowerCase(),u=/^(run|approve|accept|yes|allow|always)/.test(m),h=/^(reject|deny|delete|remove|abort)/.test(m),g=r===c,j=r!==null;return t.jsx("button",{onClick:()=>o(c),disabled:j,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${u?"font-extrabold":h?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${j&&!g?"opacity-40":"opacity-100"} ${j?"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)"}:h?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:g?"⏳ ...":l(c)},d)})})]})]})}const Mo="adhdev_controls_bar_visible",Za="adhdev:controlsbarvisibilitychange";function ta(e){if(!e)return!1;try{return e.getItem(Mo)==="1"}catch{return!1}}function Lp(e,s){if(s)try{s.setItem(Mo,e?"1":"0")}catch{}}function Rp(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(Za,{detail:{visible:e}}))}function Lo(){const[e,s]=i.useState(()=>typeof window>"u"?!1:ta(window.localStorage)),r=i.useRef(e),n=i.useCallback((l,c=!0)=>{r.current=l,s(l),typeof window<"u"&&Lp(l,window.localStorage),c&&Rp(l)},[]);i.useEffect(()=>{const l=d=>{const m=d.detail,u=typeof(m==null?void 0:m.visible)=="boolean"?m.visible:ta(window.localStorage);r.current=u,s(u)},c=d=>{if(d.key!==Mo)return;const m=ta(window.localStorage);r.current=m,s(m)};return window.addEventListener(Za,l),window.addEventListener("storage",c),()=>{window.removeEventListener(Za,l),window.removeEventListener("storage",c)}},[]);const a=i.useCallback(l=>{n(l)},[n]),o=i.useCallback(()=>{n(!r.current)},[n]);return{isVisible:e,setVisibility:a,toggleVisibility:o}}var _p=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function Pp(e){var s;return(((s=e==null?void 0:e.buttons)==null?void 0:s.length)??0)>0}function gt(e,s){if(Pp(s==null?void 0:s.activeModal))return"waiting_approval";const r=String(e||"idle").trim().toLowerCase();return r==="waiting_approval"?"waiting_approval":_p.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 jn(e){return gt(e)==="generating"}function _i(e,s){return gt(e,s)==="waiting_approval"}function lt(e){return e?e.split("-").map(s=>s.charAt(0).toUpperCase()+s.slice(1).toLowerCase()).join(" "):"IDE"}function Dp(e){if(e<60)return`${Math.round(e)}s`;const s=Math.floor(e/60);if(s<60)return`${s}m`;const r=Math.floor(s/60),n=s%60;if(r<24)return n>0?`${r}h ${n}m`:`${r}h`;const a=Math.floor(r/24),o=r%24;return`${a}d ${o}h`}function sa(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function Bn(e,s){const r=typeof s=="string"?s.trim():"";if(r)return r;const n=typeof e=="string"?e.trim():"";if(!n)return"";const a=n.replace(/[\\/]+$/,""),o=a.split(/[\\/]/).filter(Boolean);return o[o.length-1]||a}function Ep(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const s=e.split("_"),r=s[s.length-1];return r.length>12?`Machine-${r.substring(0,8)}`:r}return e}function $p(e){const s=e.trim().toLowerCase();return s.startsWith("mach_")||s.startsWith("standalone_mach_")||s.startsWith("daemon_mach_")}function Bp(e){return Ep(e.trim().replace(/\.local$/i,""))}function Op(e){const s=e.machineNickname??e.nickname;return typeof s!="string"?null:s.trim()||null}function wc(e,s={}){var a,o;const r=[e.hostname,(a=e.machine)==null?void 0:a.hostname,(o=e.system)==null?void 0:o.hostname].find(l=>typeof l=="string"&&l.trim().length>0&&!$p(l));if(r&&r!=="Unknown")return Bp(r);const n=s.fallbackId||e.id;return n?`Machine-${n.substring(0,8)}`:s.fallbackLabel||"Machine"}function Tt(e,s={}){return Op(e)||wc(e,s)}function jc(e){return!e||!Array.isArray(e.items)?[]:e.items.map(s=>String((s==null?void 0:s.value)||(s==null?void 0:s.shortValue)||"").trim()).filter(Boolean)}function kc(e,s,r={}){const n=String(s).trim();if(!e||!Array.isArray(e.items)||!n)return"";const a=e.items.find(o=>String((o==null?void 0:o.id)||"").trim()===n);return a?String(r.preferShortValue?a.shortValue||a.value||"":a.value||a.shortValue||"").trim():""}function Ss(e,s){return jc(e).join(" · ")}function Cr(e){return e.transport==="pty"}function Bs(e){return e.transport==="acp"}function Fp(e,s){var r,n;return(r=s==null?void 0:s.providerLabels)!=null&&r[e]?s.providerLabels[e]:(n=s==null?void 0:s.providerLabels)!=null&&n[e==null?void 0:e.toLowerCase()]?s.providerLabels[e.toLowerCase()]:s!=null&&s.agentName&&s.agentName!==e?s.agentName:lt(e)}function Pi(e,s,r){const n=(e||"").trim().toLowerCase();if(!n)return!0;const a=(s||"").trim().toLowerCase(),o=(r||"").trim().toLowerCase(),l=lt(r||"").trim().toLowerCase();return n===a||n===o||n===l}function Kp(e,s=[],r=[]){var d,m,u,h;const n=gt(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=s.find(g=>_i(g.status,{activeModal:g.activeModal})||jn(g.status));if(a)return gt(a.status,{activeModal:a.activeModal});const o=r.find(g=>_i(g.status,{activeModal:g.activeModal})||jn(g.status));if(o)return gt(o.status,{activeModal:o.activeModal});if(n&&n!=="idle")return n;const l=gt((d=s[0])==null?void 0:d.status,{activeModal:(m=s[0])==null?void 0:m.activeModal});if(l!=="idle")return l;const c=gt((u=r[0])==null?void 0:u.status,{activeModal:(h=r[0])==null?void 0:h.activeModal});return c!=="idle"?c:"idle"}function Wp(e){return gt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Hp(e){if(!Array.isArray(e)||e.length<=1)return e;const s=new Map,r=["generating","waiting_approval","connected","idle","panel_hidden"];for(const n of e){const a=(n.name||n.id||"").toLowerCase().replace(/\s+/g,"-"),o=s.get(a),l=gt(n.status);if(!o){s.set(a,{...n,status:l});continue}const c=r.indexOf(o.status||"idle"),d=r.indexOf(l||"idle");d>=0&&(c<0||d<c)&&s.set(a,{...n,status:l})}return Array.from(s.values())}function Up(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Date.parse(e);if(Number.isFinite(s))return s}return 0}function zp(e){var r,n;const s=(n=(r=e==null?void 0:e.messages)==null?void 0:r.at)==null?void 0:n.call(r,-1);return s&&Up(s.receivedAt)||0}function Vp(e){return(e.recentLaunches||[]).reduce((r,n)=>Math.max(r,n.lastLaunchedAt||0),0)}function eo(e){return Math.max(Vp(e),zp(e.activeChat))}function Gp(e,s,r,n,a,o){const l=s-e;if(l!==0)return l;const c=r.localeCompare(n);return c!==0?c:a.localeCompare(o)}function Ro(e,s){return Gp(eo(e),eo(s),Tt(e,{fallbackId:e.id}),Tt(s,{fallbackId:s.id}),e.id,s.id)}const Nc="adhdev_notification_prefs",Di={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function qp(){try{const e=localStorage.getItem(Nc);if(e){const s=JSON.parse(e);return{...Di,...s}}}catch{}return{...Di}}function Yp(e){try{localStorage.setItem(Nc,JSON.stringify(e))}catch{}}let qt=qp(),on=[];function Xp(){on.forEach(e=>e())}function Jp(e){qt={...qt,...e},Yp(qt),Xp()}function Qp(){const[,e]=i.useState(0);i.useEffect(()=>{const r=()=>e(n=>n+1);return on.push(r),()=>{on=on.filter(n=>n!==r)}},[]);const s=i.useCallback(r=>{Jp(r)},[]);return[{...qt},s]}function xr(e){if(!qt.globalEnabled)return!1;switch(e){case"disconnect":return qt.disconnectAlert;case"completion":return qt.completionAlert;case"approval":return qt.approvalAlert;case"browser":return qt.browserNotifications;default:return!0}}const Zp={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Sc(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Cc(){return"Notification"in window&&Notification.permission==="granted"}let ds=null;function ef(e){return e!==!1}async function tf(){if(ds!==null)return ds;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return ds=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(ds=!!await e.pushManager.getSubscription(),ds):(ds=!1,!1)}catch{return ds=!1,!1}}function to(e,s,r){if(Cc())try{const n=new Notification(e,{body:s,icon:"/otter-logo.png",tag:r||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>n.close(),8e3),n.onclick=()=>{window.focus(),n.close()}}catch{}}function sf(e,s={}){const r={...Zp,...s},n=i.useRef(new Map),a=i.useRef(0),[o,l]=i.useState(null);i.useEffect(()=>{let d=!1;return tf().then(m=>{d||l(m)}),()=>{d=!0}},[]);const c=i.useCallback((d,m,u)=>{const h=Date.now();h-a.current<r.throttleMs||(a.current=h,to(d,m,u))},[r.throttleMs]);i.useEffect(()=>{var d;if(!(!r.enabled||!Cc())&&xr("browser")&&!ef(o)){if(document.hasFocus()){for(const m of e)n.current.set(m.id,gt(m.status,{activeModal:m.activeModal}));return}for(const m of e){const u=n.current.get(m.id),h=gt(m.status,{activeModal:m.activeModal}),g=m.name||m.id;if(r.onApproval&&xr("approval")&&h==="waiting_approval"&&u!=="waiting_approval"){const j=((d=m.activeModal)==null?void 0:d.message)||"Action requires your approval";c(`🔔 ${g} — Approval needed`,j.slice(0,120),`approval-${m.id}`)}r.onComplete&&xr("completion")&&jn(u)&&h==="idle"&&c(`✅ ${g} — Task complete`,"Agent has finished generating",`complete-${m.id}`),r.onError&&h==="error"&&u!=="error"&&c(`⚠️ ${g} — Error`,"Agent encountered an error",`error-${m.id}`),n.current.set(m.id,h)}}},[e,r.enabled,r.onApproval,r.onComplete,r.onError,o,c])}const rf=/^(run|approve|accept|yes|allow|always)/,nf=/^(run|approve|accept|yes|allow|always|proceed|save)/,af=/^(reject|deny|delete|remove|abort|cancel|no)/;function _o(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function of(e){const s=_o(e).toLowerCase();return rf.test(s)?"primary":af.test(s)?"danger":"default"}function lf(e){return nf.test(_o(e).toLowerCase())?"approve":"reject"}function cf(e){return e.map((s,r)=>({label:_o(s),variant:of(s),action:lf(s),button:s,buttonIndex:r}))}function df(e,s,r){return s?`⚡ ${e}: ${s.replace(/[\n\r]+/g," ").slice(0,80)}`:r}function uf(e,s,r,n){return[{label:"Approve",variant:"primary",onClick:()=>{r(e,s,"approve").catch(a=>n==null?void 0:n("approve",a))}},{label:"Decline",variant:"danger",onClick:()=>{r(e,s,"reject").catch(a=>n==null?void 0:n("reject",a))}}]}class mf{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,"statusEventCallbacks",[]);Qe(this,"resolveActionFn",null);Qe(this,"viewRequestRespondFn",null);Qe(this,"ides",[])}onToast(s){return this.toastCallbacks.push(s),()=>{this.toastCallbacks=this.toastCallbacks.filter(r=>r!==s)}}onStatusEvent(s){return this.statusEventCallbacks.push(s),()=>{this.statusEventCallbacks=this.statusEventCallbacks.filter(r=>r!==s)}}setResolveAction(s){this.resolveActionFn=s}setIdes(s){this.ides=s}setViewRequestRespond(s){this.viewRequestRespondFn=s}emitToast(s){for(const r of this.toastCallbacks)r(s)}showToast(s,r="info",n){const a=(n==null?void 0:n.id)||Date.now();this.emitToast({id:a,message:s,type:r,timestamp:a,duration:5e3,...n})}isDuplicate(s){const r=Date.now(),n=this.dedupMap.get(s)||0;if(r-n<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(s,r),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[a,o]of this.dedupMap)r-o>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(s){if(s.daemonId){const a=this.ides.find(o=>o.id===s.daemonId&&o.type==="adhdev-daemon");if(a)return a}const r=s.targetSessionId&&this.findOwningSession(s.targetSessionId)||void 0;if(r){const a=r.daemonId;if(a){const o=this.ides.find(l=>l.id===a&&l.type==="adhdev-daemon");if(o)return o}}const n=this.ides.filter(a=>a.type==="adhdev-daemon");return n.length===1?n[0]:null}findOwningSession(s){for(const r of this.ides)if(r.id===s||r.sessionId===s||(Array.isArray(r.childSessions)?r.childSessions:[]).some(a=>(a==null?void 0:a.id)===s))return r;return null}resolveActionRouteTarget(s){if(s.targetSessionId){const r=this.findOwningSession(s.targetSessionId);return(r==null?void 0:r.id)||(r==null?void 0:r.daemonId)||null}return s.daemonId||null}resolveConversationKey(s){return s.targetSessionId?s.targetSessionId:s.daemonId?s.daemonId:null}handleRawEvent(s,r){var f;const n=this.resolveConversationKey(s),a=Number.isFinite(s.timestamp)?Number(s.timestamp):Date.now(),o=n||s.daemonId||"",l=s.requestId||s.targetName||s.requesterName||s.modalMessage||String(a),c=`${o}:${s.event}:${l}`;if(this.isDuplicate(c))return;for(const p of this.statusEventCallbacks)p(s);const d=s.targetSessionId?this.findOwningSession(s.targetSessionId):null,m=(d==null?void 0:d.type)||"";let u=lt(m);const h=this.resolveOwningDaemon(s);if(h){const p=Tt(h,{fallbackId:h.id});p&&(u=!m||m==="adhdev-daemon"?p:`${p}/${u}`)}let g="",j="info";if(s.event==="agent:generating_completed"){const p=s.duration?` (${s.duration}s)`:"";g=`✅ ${u} agent task completed${p}`,j="success";try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(s.event!=="agent:generating_started")if(s.event==="agent:waiting_approval"){if(g=`⚡ ${u} approval needed`,j="warning",(f=s.modalButtons)!=null&&f.length&&this.resolveActionFn){const p=this.resolveActionRouteTarget(s);if(!p)return;const b=this.resolveActionFn,y=cf(s.modalButtons).map(N=>({label:N.label,variant:N.variant,onClick:()=>{b(p,"resolve_action",{action:N.action,button:N.button,buttonIndex:N.buttonIndex,...s.targetSessionId&&{targetSessionId:s.targetSessionId}})}})),x=df(u,s.modalMessage,g),A=Date.now();this.emitToast({id:A,message:x,type:j,timestamp:A,targetKey:n||p,actions:y,duration:15e3}),g=""}}else if(s.event==="monitor:long_generating"){const p=s.elapsedSec?` (${Math.round(s.elapsedSec/60)}m)`:"";g=`⚠️ ${u} agent is taking a long time${p}`,j="warning",xr("browser")&&!document.hasFocus()&&to(`⚠️ ${u} — Long Running`,`Agent has been generating for over ${p.replace(/[()]/g,"")}`,`long-${s.targetSessionId||s.daemonId||"daemon"}`)}else if(s.event==="team:view_request"){const p=s.requesterName||"A team member",b=s.requestId,y=s.orgId;if(g=`👁️ ${p} wants to view your session`,j="warning",b&&y&&this.viewRequestRespondFn){const x=Date.now(),A=uf(y,b,this.viewRequestRespondFn,(N,v)=>console.error(`[EventManager] ${N} view request failed:`,v));this.emitToast({id:x,message:g,type:j,timestamp:x,actions:A,duration:3e4}),g=""}xr("browser")&&!document.hasFocus()&&to("👁️ View Request",`${p} wants to view your session`,`view-request-${b}`)}else s.event==="team:view_request_approved"?(g="✅ View request approved",j="success"):s.event==="team:view_request_rejected"&&(g=`❌ ${s.targetName||"Team member"} declined your view request`,j="warning");if(g){const p=Date.now();this.emitToast({id:p,message:g,type:j,timestamp:p,targetKey:n||s.daemonId,duration:5e3})}}}const ot=new mf,Ei=new Map;function kn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Os(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function On(e){return kn(e)?kn(e.result)?e.result:e:null}function pf(e){const s=On(e);return!s||!kn(s.controlResult)||!Array.isArray(s.controlResult.options)?null:s.controlResult}function Ur(e){const s=On(e);return!s||!kn(s.controlResult)||typeof s.controlResult.ok!="boolean"?null:s.controlResult}function sr(e){const s=On(e);if(!(!s||typeof s.error!="string"||!s.error.trim()))return s.error}function zr(e){const s=On(e);return!!s&&s.success===!1}function ff(e){var s,r;for(const n of e||[]){if(n.type==="toast"&&((s=n.toast)!=null&&s.message)){const a=n.toast.level==="warning"?"warning":n.toast.level==="success"?"success":"info";ot.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";ot.showToast(n.notification.body,a)}}}function hf(e,s){return e&&Os(e.currentValue)?e.currentValue:s}function xf(e,s){return Os(s)?Os(e)?typeof e=="string"&&e.trim()==="":!0:!1}function bf(e,s){var o,l;if((s.now??Date.now())<s.localOverrideUntil){const c=s.localValues[e];if(Os(c))return c}const n=(o=s.controlValues)==null?void 0:o[e];if(Os(n))return n;const a=(l=s.defaultValues)==null?void 0:l[e];return Os(a)?a:void 0}function ln(e,s){return e.options||s[e.id]||[]}const gf={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 yf(e,s,r){var n;return((n=gf[s])==null?void 0:n.has(r.id))===!0}function Po(e,s){return(e||[]).filter(r=>r.placement==="bar"&&r.hidden!==!0&&!yf(s.hostIdeType,s.providerType,r)).sort((r,n)=>(r.order??50)-(n.order??50))}function ra(e,s){return{value:s}}function vf(e,s,r){var a;return r?((a=ln(e,s).find(o=>o.value===r))==null?void 0:a.label)||r:""}const wf={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function jf({routeId:e,sessionId:s,hostIdeType:r,providerType:n,displayLabel:a,controls:o,controlValues:l}){const{sendCommand:c}=wt(),d=`${e}:${s||n}`,m=wf[n]||"#94a3b8",[u,h]=i.useState({}),g=i.useRef({}),j=i.useRef(l);g.current=u,j.current=l;const f=i.useRef(0),p={};for(const T of o||[])T.defaultValue!==void 0&&(p[T.id]=T.defaultValue);const b={...p,...l||{},...Date.now()<f.current?u:{}};i.useEffect(()=>{l&&Date.now()>f.current&&h({})},[l]);const[y,x]=i.useState(Ei.get(d)||{}),[A,N]=i.useState(null),[v,C]=i.useState(null),M=i.useCallback(async(T,K={})=>{const P={...K,...s&&{targetSessionId:s}};return await c(e,T,P)},[e,s,c]),w=i.useCallback(async(T,K={})=>{const P=s?{targetSessionId:s}:{agentType:n,...r?{ideType:r}:{}};return await M("invoke_provider_script",{...P,scriptName:T,...K})},[M,n,r,s]),k=i.useCallback((T,K,P)=>{const $=hf(P,K);h(V=>({...V,[T.id]:$})),ff(P==null?void 0:P.effects)},[]),F=i.useCallback((T,K)=>{h(P=>{const $={...P};return K===void 0?delete $[T.id]:$[T.id]=K,$}),f.current=0},[]);if(!o||o.length===0)return null;const _=Po(o,{hostIdeType:r,providerType:n});if(_.length===0)return null;const S=async T=>{if(A===T.id){N(null);return}if(ln(T,y).length>0){N(T.id);return}if(T.dynamic&&T.listScript){C(T.id);try{const P=await w(T.listScript,{}),$=pf(P);if(!$){const ge=sr(P);ge&&ot.showToast(ge,"warning");return}const V=$.options;x(ge=>{const fe={...ge,[T.id]:V};return Ei.set(d,fe),fe});const Y=bf(T.id,{localOverrideUntil:f.current,localValues:g.current,controlValues:j.current,defaultValues:p});if(xf(Y,$.currentValue)){const ge=$.currentValue;h(fe=>({...fe,[T.id]:ge}))}N(T.id)}catch(P){const $=P instanceof Error?P.message:`Could not load ${T.label}`;ot.showToast($,"warning")}finally{C(null)}}},H=async(T,K)=>{N(null);const P=(l==null?void 0:l[T.id])??p[T.id];h($=>({...$,[T.id]:K})),f.current=Date.now()+5e3;try{if(!T.setScript)return;const $=await w(T.setScript,ra(T,K)),V=Ur($);if(V&&!V.ok||zr($))throw new Error((V==null?void 0:V.error)||sr($)||`Could not update ${T.label}`);k(T,K,V)}catch($){F(T,P);const V=$ instanceof Error?$.message:`Could not update ${T.label}`;ot.showToast(V,"warning")}},W=async T=>{const K=ln(T,y).map(fe=>fe.value);if(K.length===0)return;const P=String(b[T.id]||""),V=(K.indexOf(P)+1)%K.length,Y=K[V];if(typeof Y!="string")return;const ge=(l==null?void 0:l[T.id])??p[T.id];h(fe=>({...fe,[T.id]:Y})),f.current=Date.now()+5e3;try{if(!T.setScript)return;const fe=await w(T.setScript,ra(T,Y)),ae=Ur(fe);if(ae&&!ae.ok||zr(fe))throw new Error((ae==null?void 0:ae.error)||sr(fe)||`Could not update ${T.label}`);k(T,Y,ae)}catch(fe){F(T,ge);const ae=fe instanceof Error?fe.message:`Could not update ${T.label}`;ot.showToast(ae,"warning")}},D=async T=>{const P=!b[T.id],$=(l==null?void 0:l[T.id])??p[T.id];h(V=>({...V,[T.id]:P})),f.current=Date.now()+5e3;try{if(!T.setScript)return;const V=await w(T.setScript,ra(T,P)),Y=Ur(V);if(Y&&!Y.ok||zr(V))throw new Error((Y==null?void 0:Y.error)||sr(V)||`Could not update ${T.label}`);k(T,P,Y)}catch(V){F(T,$);const Y=V instanceof Error?V.message:`Could not update ${T.label}`;ot.showToast(Y,"warning")}},I=async T=>{if(!T.invokeScript)return;if(T.confirmMessage){const P=[T.confirmTitle,T.confirmMessage,T.confirmLabel].filter(V=>typeof V=="string"&&V.trim().length>0);if(!window.confirm(P.join(`
|
|
30
|
-
|
|
31
|
-
`)))return}const K=(l==null?void 0:l[T.id])??p[T.id];try{const P=await w(T.invokeScript),$=Ur(P);if($&&!$.ok||zr(P))throw new Error(($==null?void 0:$.error)||sr(P)||`Could not run ${T.label}`);$&&k(T,K??!0,$)}catch(P){F(T,K);const $=P instanceof Error?P.message:`Could not run ${T.label}`;ot.showToast($,"warning")}};return t.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.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(T=>{const K=String(b[T.id]||""),P=vf(T,y,K),$=A===T.id,V=v===T.id,Y=ln(T,y),ge="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(T.type){case"select":return t.jsxs("div",{className:"relative max-w-full",children:[t.jsxs("button",{type:"button",className:`${ge} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:$?`${m}55`:"var(--border-default)",background:$?`${m}10`:"var(--surface-tertiary)",color:K?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void S(T),title:T.label,children:[T.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:T.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:V?"Loading…":P||T.label}),t.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),$&&Y.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"fixed inset-0 z-[59]",onClick:()=>N(null)}),t.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:[t.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.08em] text-text-muted",children:T.label}),Y.map(fe=>t.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:fe.value===K?`${m}14`:"transparent",color:fe.value===K?"var(--text-primary)":"var(--text-secondary)",borderLeft:fe.value===K?`2px solid ${m}`:"2px solid transparent"},title:fe.description||fe.label,onMouseEnter:ae=>{ae.currentTarget.style.background=`${m}10`},onMouseLeave:ae=>{ae.currentTarget.style.background=fe.value===K?`${m}14`:"transparent"},onClick:()=>void H(T,fe.value),children:[t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:fe.label}),fe.value===K&&t.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},fe.value))]})]})]},T.id);case"cycle":return t.jsxs("button",{type:"button",className:`${ge} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:K?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void W(T),title:`Click to cycle: ${Y.map(fe=>fe.label).join(" → ")}`,children:[T.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:T.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:P||T.label}),t.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},T.id);case"toggle":return t.jsxs("button",{type:"button",className:`${ge} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:K?`${m}44`:"var(--border-default)",background:K?`${m}14`:"var(--surface-tertiary)",color:K?m:"var(--text-muted)"},onClick:()=>void D(T),"aria-pressed":!!K,children:[T.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:T.icon}),T.label]},T.id);case"action":return t.jsxs("button",{type:"button",className:`${ge} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void I(T),children:[T.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:T.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:T.resultDisplay==="inline"&&K?`${T.label}: ${K}`:T.label})]},T.id);case"display":return t.jsxs("span",{className:"inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium whitespace-nowrap",style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:K?"var(--text-primary)":"var(--text-muted)"},children:[T.icon&&t.jsx("span",{className:"text-[11px] opacity-70",children:T.icon}),t.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:K?`${T.label}: ${K}`:T.label})]},T.id);default:return null}})]})})}function kf({isActive:e=!0,isCliTerminal:s=!1,routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:l,controls:c,controlValues:d}){const{isVisible:m}=Lo(),u=Po(c,{hostIdeType:a,providerType:o});return!e||s||u.length===0||!m?null:t.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:t.jsx(jf,{routeId:r,sessionId:n,hostIdeType:a,providerType:o,displayLabel:l,controls:u,controlValues:d})})}const rr=5,Ic=10*1024*1024;function Nf({hasDraft:e,isBusy:s=!1}){return!e||s}function Sf(e){return new Promise((s,r)=>{const n=new FileReader;n.onload=()=>s(n.result),n.onerror=()=>r(new Error("Failed to read file")),n.readAsDataURL(e)})}async function Cf(e){if(e.size>Ic)return null;const s=await Sf(e),r=s.indexOf(",");if(r<0)return null;const n=s.slice(r+1);return{mimeType:e.type||"image/png",data:n,name:e.name,previewUrl:s}}function If(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}const Tc=i.memo(function({contextKey:s,panelLabel:r,isSending:n,isBusy:a=!1,statusMessage:o=null,onSend:l,isActive:c=!0,showControlsToggle:d=!1,animateVisibility:m=!0,onControlsToggle:u,messageInput:h}){const g=i.useRef(null),j=i.useRef(null),[f,p]=i.useState(""),[b,y]=i.useState([]),[x,A]=i.useState(null),[N,v]=i.useState(!1),C=i.useRef(!1),{isVisible:M,toggleVisibility:w}=Lo(),k=If(h),F=!!f.trim()||b.length>0;i.useEffect(()=>{p(""),y([]),A(null)},[s]),i.useEffect(()=>{var T;c&&((T=g.current)==null||T.focus({preventScroll:!0}))},[s,c]);const _=i.useCallback(async T=>{A(null);const K=Array.from(T).filter(fe=>fe.type.startsWith("image/"));if(K.length===0)return;const P=rr-b.length;if(P<=0){A(`Max ${rr} images`);return}const $=K.slice(0,P);if($.filter(fe=>fe.size>Ic).length>0){A("Image too large (max 10 MB)");return}const ge=(await Promise.all($.map(Cf))).filter(fe=>fe!==null);y(fe=>[...fe,...ge])},[b.length]),S=i.useCallback(T=>{y(K=>K.filter((P,$)=>$!==T))},[]),H=i.useCallback(async()=>{const T=f.trim();if(!T&&b.length===0||a||C.current)return;C.current=!0;const K=b.length>0?[...b]:void 0;try{await l(T,K)!==!1&&(p(""),y([]),A(null))}finally{C.current=!1}},[f,b,a,l]),W=i.useCallback(T=>{k&&(T.preventDefault(),v(!0))},[k]),D=i.useCallback(()=>v(!1),[]),I=i.useCallback(T=>{k&&(T.preventDefault(),v(!1),T.dataTransfer.files.length>0&&_(T.dataTransfer.files))},[k,_]);return t.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",m?"transition-all duration-200 ease-out":"",N?"ring-1 ring-inset ring-[var(--accent-primary)]":""].filter(Boolean).join(" "),style:{borderTop:c?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:c?200:0,opacity:c?1:0,transform:c?"translateY(0)":"translateY(10px)",padding:c?"10px 12px":"0 12px",pointerEvents:c?"auto":"none"},"aria-hidden":!c,onDragOver:W,onDragLeave:D,onDrop:I,children:[b.length>0&&t.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:b.map((T,K)=>t.jsxs("div",{className:"relative group w-14 h-14 rounded-lg overflow-hidden border border-border-subtle shrink-0",style:{background:"var(--surface-secondary)"},children:[t.jsx("img",{src:T.previewUrl,alt:T.name,className:"w-full h-full object-cover"}),t.jsx("button",{type:"button",onClick:()=>S(K),className:"absolute top-0.5 right-0.5 w-4 h-4 rounded-full bg-black/60 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity text-[10px] leading-none","aria-label":`Remove ${T.name}`,children:"✕"})]},K))}),t.jsxs("div",{className:"flex gap-2 items-center",title:c?`Send message to ${r}`:void 0,children:[d&&t.jsx("button",{type:"button",onClick:()=>{w(),u==null||u()},"aria-label":M?"Hide controls":"Show controls","aria-pressed":M,title:M?"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:t.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[t.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),t.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),t.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),k&&t.jsxs(t.Fragment,{children:[t.jsx("input",{ref:j,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:T=>{T.target.files&&_(T.target.files),T.target.value=""}}),t.jsx("button",{type:"button",onClick:()=>{var T;return(T=j.current)==null?void 0:T.click()},disabled:b.length>=rr,title:b.length>=rr?`Max ${rr} images`:"Attach image",className:"h-10 w-8 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center disabled:opacity-40","aria-label":"Attach image",children:t.jsx("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:t.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"})})})]}),t.jsx("div",{className:"flex-1 relative",children:t.jsx("input",{ref:g,type:"text",placeholder:o||(k&&b.length>0?"Add a message (optional)...":`Send message to ${r}...`),value:f,onChange:T=>p(T.target.value),onPaste:T=>{if(k&&T.clipboardData.files.length>0&&Array.from(T.clipboardData.files).some($=>$.type.startsWith("image/"))){T.preventDefault(),_(T.clipboardData.files);return}const K=T.clipboardData.getData("text");K&&p(P=>P+K),T.preventDefault()},onKeyDown:T=>{if(T.key==="Enter"){if(T.nativeEvent.isComposing){T.preventDefault();return}T.preventDefault(),H()}},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))"}})}),t.jsx("button",{onClick:()=>{H()},disabled:Nf({hasDraft:F,isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${F&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:F&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,"aria-label":"Send message",children:t.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:F?"text-white":"text-text-muted",children:t.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})})]}),(x||k&&N)&&t.jsx("div",{className:`pt-1.5 px-1 text-[11px] ${x?"text-red-400":"text-[var(--accent-primary)]"}`,children:x||"Drop image here"}),o&&!x&&t.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:o})]})}),nt=e=>e.transport==="pty",Js=(e,s)=>nt(e)?e.mode||"terminal":"chat",Ac=(e,s)=>nt(e)&&Js(e)==="terminal",tt=e=>e.transport==="acp",Tf=180;function is(e){return e.streamSource!=="agent-stream"}function As(e){var s;return e.daemonId||((s=e.routeId)==null?void 0:s.split(":")[0])||e.routeId||""}function Mc(e){return e.machineName||""}function Mr(e){return As(e)}function zt(e){return e.agentType||""}function Nn(e){return e.hostIdeType||""}function Do(e){return e.displayPrimary||e.agentName||"Agent"}function Lc(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function Af(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function Rc(e){const s=Af(e),r=Ws(s==null?void 0:s.content),n=Ws(e.lastMessagePreview);return r||n||""}function Mf(e,s=Tf){const r=Ws(e);if(!r||s<=0)return"";const n=Array.from(r);return n.length<=s?r:`${n.slice(0,Math.max(0,s-1)).join("").trimEnd()}…`}function Lf(e){return Mf(Rc(e)||e.displaySecondary||"")}function _c(e){return[e.displaySecondary,Mc(e)].filter(Boolean)}function Us(e){return e.agentName||lt(zt(e))}function Rf(e){var s,r;if(!is(e)){const n=(r=(s=e.displaySecondary)==null?void 0:s.split("·")[0])==null?void 0:r.trim();if(n)return n}return lt(Nn(e)||zt(e))}function Pc(e){return is(e)?e.sessionId:e.nativeSessionId}function $i(e){return is(e)?"native":e.tabKey}function _f(e){return e.sessionId}function Pf(e,s){if(s)return is(e)||!s.childSessions?s:s.childSessions.find(r=>r.id===e.sessionId||r.providerType===e.agentType)||s}function Df(e,s){const r=zt(e),n=is(e),a=nt(e)||tt(e),o=n?a?Us(e)||(s==null?void 0:s.cliName)||lt(Nn(e)||r):s!=null&&s.type?lt(s.type):lt(Nn(e)||r):Us(e);return{isNativeConversation:n,isCli:nt(e),isAcp:tt(e),isCliTerminal:Ac(e),providerType:r,displayLabel:o,targetEntry:Pf(e,s)}}function hs(e){if(!e)return{};const s=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?s:nt(e)||tt(e)?{agentType:zt(e)}:e.streamSource==="agent-stream"?{agentType:zt(e)}:s}function zs(e){return e?Mr(e):""}function nr(e,s){e(r=>[...r,{id:Date.now(),message:s,type:"warning",timestamp:Date.now()}])}function Eo(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function Ef(e){const s=e instanceof Error?e.message:String(e||""),r=s.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.":s||"Unable to send message right now."}function Dc(){return"select_session"}function $f(){return"open_panel"}function Bf({hasMessage:e,blockedMessage:s}){return e?!!s:!0}function Of(e,s,r=2e3){return e?e.tabKey===s.tabKey&&e.message===s.message&&s.timestamp-e.timestamp<r:!1}function Bi(e,s){return e?e.tabKey===s.tabKey&&e.message===s.message&&e.timestamp===s.timestamp?null:e:null}function Sn(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function $o(e){return e instanceof Error?e.message:String(e||"")}function Oi(e){const s=$o(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function Fi(e,s){const r=$o(s);return r?r.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${r}`:`⚠️ **${e}** unavailable`}function Ff(e,s,r){const n=hs(r);if(!s||s.length===0)return{message:e,...n};const a=s.map(o=>({type:"image",mimeType:o.mimeType,data:o.data,alt:o.name}));return e&&a.push({type:"text",text:e}),{message:e,input:{parts:a,textFallback:e},...n}}function Fn({sendDaemonCommand:e,activeConv:s,setActionLogs:r,isStandalone:n}){const[a,o]=i.useState(!1),[l,c]=i.useState(!1),[d,m]=i.useState(null),u=i.useRef(!1),h=i.useRef(null);i.useEffect(()=>{m(null)},[s==null?void 0:s.tabKey]);const g=i.useCallback(async(b,y)=>{if(!s||u.current)return!1;const x=b.trim(),A=Eo(s);if(Bf({hasMessage:!!x,blockedMessage:A,sendInFlight:u.current}))return A&&m(A),!1;const N=Date.now(),v={tabKey:s.tabKey,message:x,timestamp:N};if(Of(h.current,v))return m(null),!0;u.current=!0,c(!0),m(null),h.current=v;try{const C=zs(s);if(!C)return h.current=Bi(h.current,v),m("Unable to send message right now."),!1;const M=await e(C,"send_chat",Ff(x,y,s)),w=Sn(M);if(w!=null&&w.deduplicated)return m(null),!0;if((w==null?void 0:w.sent)===!1)throw new Error((w==null?void 0:w.error)||"Send failed");if((w==null?void 0:w.success)===!1)throw new Error((w==null?void 0:w.error)||"Send failed");return m(null),!0}catch(C){const M=$o(C);return M.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",M):console.warn("Send blocked/failed",C),h.current=Bi(h.current,v),m(Ef(C)),!1}finally{u.current=!1,c(!1)}},[s,e]),j=i.useCallback(async()=>{if(s)try{if(!s.hostIdeType)return;await e(s.routeId,"launch_ide",{ideType:s.hostIdeType,enableCdp:!0})}catch(b){console.error("Relaunch failed",b)}},[s,e]),f=i.useCallback(async b=>{if(s)try{const x=(s.modalButtons||[]).indexOf(b),A=b.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),N=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(A),v=zs(s);if(!v)return;const C=await e(v,"resolve_action",{button:b,action:N?"approve":"reject",...x>=0&&{buttonIndex:x},...hs(s)}),M=Sn(C);M.success||r(w=>[...w,{routeId:s.tabKey,text:Fi(b,M==null?void 0:M.error),timestamp:Date.now()}])}catch(y){Oi(y)||console.error("[ModalButton] Error:",y),r(x=>[...x,{routeId:s.tabKey,text:Oi(y)?Fi(b,y):`❌ **${b}** error`,timestamp:Date.now()}])}},[s,e,r]),p=i.useCallback(async()=>{if(!(!s||a)){o(!0);try{await e(s.routeId,$f(),{...s.sessionId&&{targetSessionId:s.sessionId}})}catch(b){console.error("Focus agent failed",b)}finally{o(!1)}}},[s,a,e]);return{isSendingChat:l,sendFeedbackMessage:d,isFocusingAgent:a,handleSendChat:g,handleRelaunch:j,handleModalButton:f,handleFocusAgent:p}}const Kf=10,Wf=8e3,Hf=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function Uf(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 so(e,s="",r=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(Hf.test(s)&&e.trim())return"[REDACTED:secret-field]";const n=Uf(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=>so(a,s,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,so(a,n,r+1)]))}function ar(e,s){return Array.isArray(e)?e.slice(-s):[]}function zf(e,s=Date.now()){const r=e&&s-e.firstAt<=Wf,n=r?e.count+1:1;return n>=Kf?{state:{count:0,firstAt:s},shouldCollect:!0}:{state:{count:n,firstAt:r?e.firstAt:s},shouldCollect:!1}}function Ec(e){var n,a;const{activeConv:s}=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:s.routeId,tabKey:s.tabKey,sessionId:s.sessionId,providerSessionId:s.providerSessionId,transport:s.transport,agentName:s.agentName,agentType:s.agentType,hostIdeType:s.hostIdeType,status:s.status,connectionState:s.connectionState,title:s.title,workspaceName:s.workspaceName,displayPrimary:s.displayPrimary,displaySecondary:s.displaySecondary,streamSource:s.streamSource,lastMessageHash:s.lastMessageHash},messageCounts:{live:((n=e.chatTailState.liveMessages)==null?void 0:n.length)??s.messages.length,activeConversation:s.messages.length,visible:e.visibleMessages.length,history:((a=e.chatTailState.historyMessages)==null?void 0:a.length)||0,hiddenLive:e.ui.hiddenLiveCount},liveMessagesTail:ar(e.chatTailState.liveMessages??s.messages,10),activeConversationMessagesTail:ar(s.messages,10),visibleMessagesTail:ar(e.visibleMessages,5),historyMessagesTail:ar(e.chatTailState.historyMessages,5),actionLogsTail:ar(e.actionLogs.filter(o=>o.routeId===s.tabKey),20),controls:{visibleBarControlCount:e.visibleBarControlCount,definitions:e.controls||[],values:e.controlValues||{},visible:e.ui.controlsVisible},chatTail:{hasLiveSnapshot:!!e.chatTailState.hasLiveSnapshot,hasMoreHistory:!!e.chatTailState.hasMoreHistory,historyError:e.chatTailState.historyError||null},ui:e.ui,browser:typeof navigator<"u"?{userAgent:navigator.userAgent,language:navigator.language,online:navigator.onLine}:null};return so(r)}function $c(e,s={}){const r=e&&typeof e=="object"?e:{},n=s.locatorCopyStatus??(s.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 Bc(e){var s;if(typeof navigator<"u"&&((s=navigator.clipboard)!=null&&s.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 Oc(e){const s=e&&typeof e=="object"?e:{};if(s.delivery==="daemon_file"){const r=["# ADHDev Chat Debug Bundle saved on daemon","",`bundleId: ${String(s.bundleId||"")}`,`savedPath: ${String(s.savedPath||"")}`,`sizeBytes: ${String(s.sizeBytes||"")}`,`createdAt: ${String(s.createdAt||"")}`];return s.summary&&typeof s.summary=="object"&&r.push("","summary:",JSON.stringify(s.summary,null,2)),Array.isArray(s.warnings)&&s.warnings.length>0&&r.push("","warnings:",...s.warnings.map(n=>`- ${String(n)}`)),r.join(`
|
|
32
|
-
`)}return typeof s.text=="string"?s.text:s.bundle&&typeof s.bundle=="object"?`# ADHDev Chat Debug Bundle
|
|
33
|
-
|
|
34
|
-
\`\`\`json
|
|
35
|
-
${JSON.stringify(s.bundle,null,2)}
|
|
36
|
-
\`\`\``:`# ADHDev Chat Debug Bundle
|
|
37
|
-
|
|
38
|
-
\`\`\`json
|
|
39
|
-
${JSON.stringify(s,null,2)}
|
|
40
|
-
\`\`\``}function na(e,s){return`${e}:${s}`}function Vf(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function or(e,s){Vf()&&console.debug(`[subscription-manager] ${e}`,s)}class Gf{constructor(){Qe(this,"active",new Map);Qe(this,"retryTimers",new Map)}subscribe(s,r,n,a,o){var u;const l=na(n.topic,n.key),c=this.active.get(l);let d=!0;if(c)c.handlers.add(a),c.lastUpdate&&a(c.lastUpdate);else{const h={daemonId:r,request:n,handlers:new Set([a])};this.active.set(l,h),or("subscribe",{daemonId:r,topic:n.topic,key:n.key}),d=((u=s.sendData)==null?void 0:u.call(s,r,n))??!1,!d&&(o!=null&&o.retryIntervalMs)&&this.scheduleRetry(l,s,o.retryIntervalMs)}const m=()=>{var j;this.clearRetry(l);const h=this.active.get(l);if(!h||(h.handlers.delete(a),h.handlers.size>0))return;this.active.delete(l);const g={type:"unsubscribe",topic:n.topic,key:n.key};or("unsubscribe",{daemonId:r,topic:n.topic,key:n.key}),(j=s.sendData)==null||j.call(s,r,g)};return m.initialSendAccepted=d,m}publish(s){const r=na(s.topic,s.key),n=this.active.get(r);n&&(this.clearRetry(r),n.lastUpdate=s,Ks.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.publish",topic:s.topic,payload:{key:s.key}}),n.handlers.forEach(a=>{a(s),Ks.record({interactionId:typeof s.interactionId=="string"?s.interactionId:void 0,kind:"subscription.handler_invoked",topic:s.topic,payload:{key:s.key}})}))}updateParams(s,r,n){const a=na(s,r),o=this.active.get(a);o&&(o.request={...o.request,params:{...o.request.params,...n}})}resubscribeAll(s){var r;or("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=s.sendData)==null||r.call(s,n.daemonId,n.request)}resubscribeForDaemon(s,r){var a;const n=Array.from(this.active.values()).filter(o=>o.daemonId===s);or("resubscribe_daemon",{daemonId:s,count:n.length,subscriptions:n.map(o=>({topic:o.request.topic,key:o.request.key}))});for(const o of n)(a=r.sendData)==null||a.call(r,o.daemonId,o.request)}scheduleRetry(s,r,n){if(this.retryTimers.has(s))return;const a=setTimeout(()=>{var c;this.retryTimers.delete(s);const o=this.active.get(s);if(!o)return;const l=((c=r.sendData)==null?void 0:c.call(r,o.daemonId,o.request))??!1;or("subscribe_retry",{id:s,accepted:l,topic:o.request.topic,key:o.request.key}),l||this.scheduleRetry(s,r,n)},n);this.retryTimers.set(s,a)}clearRetry(s){const r=this.retryTimers.get(s);r!==void 0&&(clearTimeout(r),this.retryTimers.delete(s))}}const Xt=new Gf;function qf(e,s){const r=new Map;for(const n of e||[])if((n.daemonId||n.id.includes(":")&&n.id.split(":")[0]||"")===s&&n.sessionId){r.set(n.sessionId,{parentSessionId:n.parentSessionId,providerSessionId:n.providerSessionId,workspace:n.workspace??null,sessionCapabilities:n.sessionCapabilities,cdpConnected:n.cdpConnected,activeChat:n.activeChat,controlValues:n.controlValues,providerControls:n.providerControls,summaryMetadata:n.summaryMetadata,runtimeWriteOwner:n.runtimeWriteOwner,runtimeAttachedClients:n.runtimeAttachedClients,cliName:n.cliName,type:n.type,mode:n.mode,status:n.status,lastMessagePreview:n.lastMessagePreview,lastMessageRole:n.lastMessageRole,lastMessageAt:n.lastMessageAt,lastMessageHash:n.lastMessageHash,completionMarker:n.completionMarker,seenCompletionMarker:n.seenCompletionMarker,settings:n.settings});for(const o of n.childSessions||[]){if(!(o!=null&&o.id))continue;const l=r.get(o.id)||{};r.set(o.id,{...l,...o})}}return r}function Yf(e){const s=[],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 s.push(n);return{topLevel:s,childrenByParent:r}}function aa(e,s){return s&&(s.startsWith(`${e}:`)?s:`${e}:${s}`)}function Xf(){if(typeof window>"u")return!1;try{return!!(window.__ADHDEV_CONVERSATION_DEBUG__||window.localStorage.getItem("adhdev_conversation_debug")==="1")}catch{return!1}}function Jf(e){Xf()&&console.debug("[dashboard-conversations] statusPayloadToEntries",e.map(s=>({id:s.id,daemonId:s.daemonId,sessionId:s.sessionId,instanceId:s.instanceId,providerSessionId:s.providerSessionId,transport:s.transport,type:s.type})))}function Cn(e,s){const r=[],{daemonId:n,existingDaemon:a,existingEntries:o,timestamp:l}=s,c=l||e.timestamp||Date.now(),d=e.sessions||[],{topLevel:m,childrenByParent:u}=Yf(d),h=qf(o,n),g=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,j=m.filter(b=>b.kind==="workspace"&&b.transport==="cdp-page"),f=m.filter(b=>b.kind==="agent"&&b.transport==="pty"),p=m.filter(b=>b.kind==="agent"&&b.transport==="acp");r.push({...a||{},id:n,type:"adhdev-daemon",status:"online",timestamp:c,...e.version&&{version:e.version},...g&&{machine:g,platform:g.platform},...e.instanceId&&{instanceId:e.instanceId},...e.machineNickname!==void 0&&{machineNickname:e.machineNickname},...e.p2p&&{p2p:e.p2p},...e.workspaces&&{workspaces:e.workspaces},...e.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:e.defaultWorkspaceId},...e.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:e.defaultWorkspacePath},...e.terminalSizingMode!==void 0&&{terminalSizingMode:e.terminalSizingMode},...e.recentLaunches&&{recentLaunches:e.recentLaunches},...e.terminalBackend&&{terminalBackend:e.terminalBackend},...e.detectedIdes&&{detectedIdes:e.detectedIdes},...e.availableProviders&&{availableProviders:e.availableProviders},_sessionListAuthoritative:Array.isArray(e.sessions),cdpConnected:j.some(b=>!!b.cdpConnected)});for(const b of j){const y=h.get(b.id),x=mr(b,y),A=(u.get(b.id)||[]).map(N=>mr(N,h.get(N.id)));r.push({id:`${n}:ide:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:x.parentId,sessionKind:x.kind,transport:x.transport,sessionCapabilities:x.capabilities,type:x.providerType,status:x.cdpConnected?"online":"detected",daemonId:n,instanceId:aa(n,b.id),workspace:x.workspace,terminals:0,childSessions:A,agents:A.map(N=>({id:N.id,name:N.providerName||N.providerType,type:N.providerType,status:N.status})),activeChat:x.activeChat,chats:[],cdpConnected:x.cdpConnected,...x.lastMessagePreview!==void 0&&{lastMessagePreview:x.lastMessagePreview},...x.lastMessageRole!==void 0&&{lastMessageRole:x.lastMessageRole},...x.lastMessageAt!==void 0&&{lastMessageAt:x.lastMessageAt},...x.lastMessageHash!==void 0&&{lastMessageHash:x.lastMessageHash},lastUpdated:x.lastUpdated,unread:x.unread,lastSeenAt:x.lastSeenAt,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,seenCompletionMarker:x.seenCompletionMarker,surfaceHidden:x.surfaceHidden,...x.controlValues!==void 0&&{controlValues:x.controlValues},...x.providerControls!==void 0&&{providerControls:x.providerControls},...x.summaryMetadata!==void 0&&{summaryMetadata:x.summaryMetadata},...x.settings!==void 0&&{settings:x.settings},...x.messageInput!==void 0&&{messageInput:x.messageInput},timestamp:c})}for(const b of f){const y=h.get(b.id),x=mr(b,y);r.push({id:`${n}:cli:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:x.parentId,sessionKind:x.kind,transport:x.transport,sessionCapabilities:x.capabilities,type:x.providerType,agentType:x.providerType,status:x.status||"running",daemonId:n,instanceId:aa(n,b.id),cliName:x.providerName||x.providerType,mode:x.mode||(y==null?void 0:y.mode)||"terminal",workspace:x.workspace||"",activeChat:x.activeChat,...x.resume!==void 0&&{resume:x.resume},...x.runtimeKey!==void 0&&{runtimeKey:x.runtimeKey},...x.runtimeDisplayName!==void 0&&{runtimeDisplayName:x.runtimeDisplayName},...x.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:x.runtimeWorkspaceLabel},...x.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:x.runtimeWriteOwner},...x.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:x.runtimeAttachedClients},...x.lastMessagePreview!==void 0&&{lastMessagePreview:x.lastMessagePreview},...x.lastMessageRole!==void 0&&{lastMessageRole:x.lastMessageRole},...x.lastMessageAt!==void 0&&{lastMessageAt:x.lastMessageAt},...x.lastMessageHash!==void 0&&{lastMessageHash:x.lastMessageHash},lastUpdated:x.lastUpdated,unread:x.unread,lastSeenAt:x.lastSeenAt,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,seenCompletionMarker:x.seenCompletionMarker,surfaceHidden:x.surfaceHidden,...x.controlValues!==void 0&&{controlValues:x.controlValues},...x.providerControls!==void 0&&{providerControls:x.providerControls},...x.summaryMetadata!==void 0&&{summaryMetadata:x.summaryMetadata},...x.settings!==void 0&&{settings:x.settings},...x.messageInput!==void 0&&{messageInput:x.messageInput},timestamp:c,_isCli:!0})}for(const b of p){const y=h.get(b.id),x=mr(b,y);r.push({id:`${n}:acp:${b.id}`,sessionId:b.id,providerSessionId:b.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:x.parentId,sessionKind:x.kind,transport:x.transport,sessionCapabilities:x.capabilities,type:x.providerType,agentType:x.providerType,status:x.status||"running",daemonId:n,instanceId:aa(n,b.id),cliName:x.providerName||x.providerType,mode:"chat",workspace:x.workspace||"",activeChat:x.activeChat,...x.runtimeKey!==void 0&&{runtimeKey:x.runtimeKey},...x.runtimeDisplayName!==void 0&&{runtimeDisplayName:x.runtimeDisplayName},...x.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:x.runtimeWorkspaceLabel},...x.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:x.runtimeWriteOwner},...x.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:x.runtimeAttachedClients},...x.lastMessagePreview!==void 0&&{lastMessagePreview:x.lastMessagePreview},...x.lastMessageRole!==void 0&&{lastMessageRole:x.lastMessageRole},...x.lastMessageAt!==void 0&&{lastMessageAt:x.lastMessageAt},...x.lastMessageHash!==void 0&&{lastMessageHash:x.lastMessageHash},lastUpdated:x.lastUpdated,unread:x.unread,lastSeenAt:x.lastSeenAt,inboxBucket:x.inboxBucket,completionMarker:x.completionMarker,seenCompletionMarker:x.seenCompletionMarker,surfaceHidden:x.surfaceHidden,...x.controlValues!==void 0&&{controlValues:x.controlValues},...x.providerControls!==void 0&&{providerControls:x.providerControls},...x.summaryMetadata!==void 0&&{summaryMetadata:x.summaryMetadata},...x.settings!==void 0&&{settings:x.settings},...x.messageInput!==void 0&&{messageInput:x.messageInput},timestamp:c,_isAcp:!0})}return Jf(r),r}const Qf=15e3,Zf=15e3,eh=6e4,th=1200,Ki=12,sh=8e3,rh=4e3,oa=new Map,ia=new Map,Vr=new Set,br=new Map;function nh(e){if(!e||typeof e!="object")return null;const s=e,r=s.status;if(r&&typeof r=="object")return r;const n=s.result;if(n&&typeof n=="object"&&"status"in n){const a=n.status;if(a&&typeof a=="object")return a}return s}function Wi(e,s){const r=br.get(e);!r||r.size===0||(br.delete(e),r.forEach(n=>n(s)))}function ah(e,s){return new Promise(r=>{const n=br.get(e)||new Set;br.set(e,n);const a=l=>{clearTimeout(o),n.delete(a),n.size===0&&br.delete(e),r(l)},o=setTimeout(()=>a(!1),s);n.add(a)})}function Lr(){const{sendCommand:e,sendData:s}=wt(),{injectEntries:r,getIdes:n}=Nr();return i.useCallback(async(a,o)=>{if(!a)return;const l=(o==null?void 0:o.minFreshMs)??eh,c=ia.get(a)||0;if(!(o!=null&&o.force)&&Vr.has(a)&&c>0||!(o!=null&&o.force)&&c>0&&Date.now()-c<l)return;const d=oa.get(a);if(d)return d;const m=(async()=>{if(s&&!Vr.has(a)){const p=Xt.subscribe({sendData:s},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},b=>{const y=n(),x=y.find(N=>N.id===a),A=Cn(b.status,{daemonId:a,existingDaemon:x,existingEntries:y,timestamp:b.timestamp});A.length>0&&r(A),ia.set(a,Date.now()),Wi(a,!0)});if(p.initialSendAccepted?Vr.add(a):Vr.delete(a),!(o!=null&&o.force)&&p.initialSendAccepted&&await ah(a,th))return}const u=await e(a,"get_status_metadata"),h=nh(u);if(!h)return;const g=n(),j=g.find(p=>p.id===a),f=Cn(h,{daemonId:a,existingDaemon:j,existingEntries:g,timestamp:h.timestamp||Date.now()});f.length>0&&r(f,{authoritativeDaemonIds:[a]}),ia.set(a,Date.now()),Wi(a,!0)})().finally(()=>{oa.delete(a)});return oa.set(a,m),m},[n,r,e,s])}function oh(e){const s=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(s)?s:0}const ih=60,lh=50;function Fc(e={}){return e.isCliLike?lh:ih}function ch(e={}){return Fc(e)}function Ct(e){return(typeof e=="string"?e.trim():"")||void 0}function Yt(e,s){const r=Ct(s);return r?`${e}:${r}`:void 0}function as(e,s,r){const n=Yt(s,r),a=Ct(r);n&&e.push(n),a&&e.push(a)}function Es(e){const s=[],r=new Set;for(const n of e)!n||r.has(n)||(r.add(n),s.push(n));return s}function Kc(e){return Ct(e.providerSessionId)||Ct(e.sessionId)||Ct(e.tabKey)||Ct(e.routeId)}function Bo(e){return Es([Ct(e.providerSessionId),Ct(e.sessionId)])}function Fs(e){const s=[];return as(s,"provider",e.providerSessionId),as(s,"session",e.sessionId),as(s,"tab",e.tabKey),as(s,"route",e.routeId),Es(s)}function dh(e){const s=[];return Ct(e.providerSessionId)?(as(s,"provider",e.providerSessionId),Es(s)):Ct(e.sessionId)?(as(s,"session",e.sessionId),Es(s)):Ct(e.tabKey)?(as(s,"tab",e.tabKey),Es(s)):Ct(e.routeId)?(as(s,"route",e.routeId),Es(s)):[]}function Oo(e){return Yt("provider",e.providerSessionId)||Yt("session",e.sessionId)||Yt("tab",e.tabKey)||Yt("route",e.routeId)||"unknown:"}function Rr(e){return Bo(e)[0]}function uh(e){const s=Ct(e.providerSessionId),r=Ct(e.sessionId),n=Ct(e.tabKey),a=Ct(e.routeId),o=[Yt("provider",s),Yt("session",r),Yt("tab",n),Yt("route",a)].filter(d=>typeof d=="string"),l=Fs({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),c=Oo({providerSessionId:s,sessionId:r,tabKey:n,routeId:a});return{providerSessionId:s,sessionId:r,tabKey:n,routeId:a,canonicalKey:c,targetKey:c,targetValue:Kc({providerSessionId:s,sessionId:r,tabKey:n,routeId:a}),historySessionId:Rr({providerSessionId:s,sessionId:r}),runtimeSessionId:r,allKeys:o,lookupKeys:l}}function ro(e,s){const r=uh(e);return dh(s).some(n=>r.lookupKeys.includes(n))}const _r=60,mh=1e3,Fo=12e4,ph=new Set(["generating","waiting_approval","starting","streaming","working"]),Hi=new Map;function Wc(e,s){return`${e}::${s}`}function no(e=_r){return{liveMessages:[],hasLiveSnapshot:!1,cursor:fh([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function fh(e,s=_r){return{tailLimit:s}}function Ui(e,s){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 hh{constructor(s){Qe(this,"manager");Qe(this,"sendData");Qe(this,"daemonId");Qe(this,"sessionId");Qe(this,"historySessionId");Qe(this,"subscriptionKey");Qe(this,"fallbackRecentCount");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=s.manager||Xt,this.sendData=s.sendData,this.daemonId=s.daemonId,this.sessionId=s.sessionId,this.historySessionId=s.historySessionId,this.subscriptionKey=s.subscriptionKey,this.fallbackRecentCount=Math.max(0,s.fallbackRecentCount??0),this.snapshot=no(Math.max(0,s.tailLimit??_r))}updateOptions(s){if(s.manager&&(this.manager=s.manager),s.sendData&&(this.sendData=s.sendData),s.historySessionId&&(this.historySessionId=s.historySessionId),s.fallbackRecentCount!==void 0&&(this.fallbackRecentCount=Math.max(0,s.fallbackRecentCount)),s.tailLimit!==void 0){const r=Math.max(0,s.tailLimit);r!==this.snapshot.cursor.tailLimit&&(this.snapshot={...this.snapshot,cursor:{tailLimit:r}},this.transportSubscription&&(this.disconnect(),this.connect()))}}getSnapshot(){return this.snapshot}subscribe(s){return this.listeners.add(s),s(this.snapshot),()=>{this.listeners.delete(s)}}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(s){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const r=(async()=>{try{const n=this.snapshot.hasLiveSnapshot,a=n?this.snapshot.liveMessages.length:Math.max(this.snapshot.liveMessages.length,this.fallbackRecentCount),o=await s({offset:this.snapshot.historyOffset,excludeRecentCount:a}),l=Array.isArray(o.messages)?o.messages:[],c=!n&&l.length===0&&o.hasMore!==!0&&this.fallbackRecentCount>0;this.snapshot={...this.snapshot,historyMessages:[...l,...this.snapshot.historyMessages],historyOffset:this.snapshot.historyOffset+l.length,hasMoreHistory:c?!0:o.hasMore===!0,historyError:null}}catch(n){this.snapshot={...this.snapshot,historyError:n instanceof Error?n.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=r,r}buildSubscribeRequest(){return{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{}}}}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,this.buildSubscribeRequest(),s=>{this.handleUpdate(s)},{retryIntervalMs:mh}))}disconnect(){var s;(s=this.transportSubscription)==null||s.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(s=>s(this.snapshot))}handleUpdate(s){if(s.error)return;const r=Array.isArray(s.messages)?s.messages:[],n={tailLimit:this.snapshot.cursor.tailLimit};Ui(this.snapshot.liveMessages)===Ui(r)&&this.snapshot.cursor.tailLimit===n.tailLimit||(this.snapshot={...this.snapshot,liveMessages:r,hasLiveSnapshot:!0,cursor:n},this.emit())}}function Hc(e){const s=Wc(e.daemonId,e.sessionId),r=Hi.get(s);if(r)return r.updateOptions(e),r;const n=new hh(e);return Hi.set(s,n),n}function xh(e,s){return{...e,loadHistoryPage:s}}function bh(e,s){return e.subscriptionKey.localeCompare(s.subscriptionKey)||e.daemonId.localeCompare(s.daemonId)||e.sessionId.localeCompare(s.sessionId)||e.historySessionId.localeCompare(s.historySessionId)}function gh(e,s={}){const r=String(e.status||"").trim().toLowerCase();if(ph.has(r)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const n=s.now??Date.now(),a=Math.max(0,Number(s.recentActivityMs??Fo)),o=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return o>0?n-o<=a:Array.isArray(e.messages)&&e.messages.length>0}function yh(e=Fo){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function vh(e,s={}){const r=new Set,n=[];for(const a of e){if(!gh(a,s))continue;const o=Mr(a),l=a.sessionId||"";if(!o||!l)continue;const c=Wc(o,l);if(r.has(c))continue;r.add(c);const d=Rr(a);n.push({daemonId:o,sessionId:l,historySessionId:d||l,subscriptionKey:`daemon:${o}:session:${l}`})}return n.sort(bh),{descriptors:n,signature:n.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function wh(e,s){const{sendData:r,sendCommand:n}=wt(),a=(s==null?void 0:s.enabled)!==!1,o=Mr(e),l=e.sessionId||"",c=Rr(e)||l,d=`daemon:${o}:session:${l}`,m=Math.max(0,(s==null?void 0:s.tailLimit)??_r),u=i.useMemo(()=>!a||!o||!l?null:Hc({daemonId:o,sessionId:l,historySessionId:c,subscriptionKey:d,sendData:r,tailLimit:m,fallbackRecentCount:e.messages.length}),[e.messages.length,o,a,c,r,l,d,m]),[h,g]=i.useState(()=>(u==null?void 0:u.getSnapshot())||no(m));i.useEffect(()=>{if(!u){g(no(m));return}u.retain(),g(u.getSnapshot());const f=u.subscribe(p=>{g(p)});return()=>{f(),u.release()}},[u,m]);const j=i.useCallback(async()=>{!u||!o||!l||await u.loadHistoryPage(async({offset:f,excludeRecentCount:p})=>{const b=e.agentType,y=await n(o,"chat_history",{agentType:b,offset:f,limit:30,targetSessionId:l,historySessionId:c,excludeRecentCount:p}),x=y&&typeof y=="object"&&"result"in y?y.result||{}:y||{};return{messages:Array.isArray(x.messages)?x.messages:[],hasMore:x.hasMore===!0}})},[e.agentType,u,o,c,n,l]);return i.useMemo(()=>xh(h,j),[j,h])}function jh(e,s){const{sendData:r}=wt(),n=(s==null?void 0:s.enabled)!==!1,a=Math.max(0,(s==null?void 0:s.tailLimit)??_r),o=Math.max(0,Number((s==null?void 0:s.recentActivityMs)??Fo)),l=yh(o),[c,d]=i.useState(0);i.useEffect(()=>{if(!n||e.length===0)return;const u=setInterval(()=>{d(h=>h+1)},l);return()=>{clearInterval(u)}},[e.length,n,l]);const m=i.useMemo(()=>vh(e,{recentActivityMs:o}),[e,o,c]);i.useEffect(()=>{if(!n||!r||m.descriptors.length===0)return;const u=m.descriptors.map(h=>Hc({...h,sendData:r,tailLimit:a}));return u.forEach(h=>{h.retain()}),()=>{u.forEach(h=>h.release())}},[m.signature,n,r,a])}function kh(e,s){return s!=null&&s.hasLiveSnapshot?s.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function zi(e){const s=String(e.role||"").toLowerCase();if(s!=="user"&&s!=="assistant")return!1;const r=String(e.kind||"standard").toLowerCase();return r===""||r==="standard"}function Nh(e,s){if(e.length===0)return[];if(s.some(zi))return[];const r=[],n=new Set;for(let a=e.length-1;a>=0&&r.length<2;a-=1){const o=e[a];if(!o||!zi(o))continue;const l=String(o.role||"").toLowerCase();n.has(l)||(n.add(l),r.unshift(o))}return r}function Sh(e){const{historyMessages:s,liveMessages:r,visibleLiveCount:n}=e,a=Math.max(0,r.length-n),o=a>0?r.slice(0,a):[],l=a>0?r.slice(-n):r,c=Nh(o,l),d=c.length>0?[...c,...l]:l;return s.length===0?d:[...s,...d]}function Ch(e,s){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(s)}function Ih(e){return Ch(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}function Th(e,s,r=`${s}s`){return`${e} ${e===1?s:r}`}function Ah(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function Mh(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function Uc(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function zc(e){const s=typeof e.completionMarker=="string"?e.completionMarker.trim():"";return s||(e.lastMessageHash?e.lastMessageHash:e.lastMessageAt?String(e.lastMessageAt):e.lastUpdated?String(e.lastUpdated):"")}function Lh(e){return Uc(e)?!1:e.inboxBucket==="task_complete"&&zc(e).length>0}function Vi(e){return e.branch||"detached HEAD"}function Rh(e){if(e.error)return`${Vi(e)} · Git error: ${e.error}`;const s=[Vi(e)];return e.changedFiles>0?s.push(Th(e.changedFiles,"file")+" changed"):e.dirty||s.push("clean"),e.ahead>0&&s.push(`ahead ${e.ahead}`),e.behind>0&&s.push(`behind ${e.behind}`),e.hasConflicts&&s.push("conflicts"),s.join(" · ")}function _h(e,s){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${Rh(s)}`}function Ph(e,s){return e.lastUpdated||e.lastMessageAt||s.lastCheckedAt||0}function Dh(e,s={}){if(s.enabled===!1)return[];if(!Mh(e))return[];const r=Uc(e)?"working":Lh(e)?"complete":null;if(!r)return[];const n=r==="complete"?zc(e):"";return[{id:r==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${Ah(n)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:_h(r,e.git),timestamp:Ph(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 Eh=60;function ao({activeConv:e,ideEntry:s,handleSendChat:r,isSendingChat:n=!1,sendFeedbackMessage:a=null,handleFocusAgent:o,isFocusingAgent:l,actionLogs:c,userName:d,scrollToBottomRequestNonce:m,isInputActive:u=!0,isVisible:h=!0}){var Se,R,re,Q,ue,ce,de;const g=i.useRef(new Map),j=i.useRef(void 0),f=Lr(),{sendCommand:p}=wt(),{isVisible:b}=Lo();Ar("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:c.length,isSendingChat:n});const y=kt.useMemo(()=>Xs(e),[e.status,e.connectionState]),x=i.useMemo(()=>Df(e,s),[e,s]),A=i.useMemo(()=>{var te;return Po((te=x.targetEntry)==null?void 0:te.providerControls,{hostIdeType:e.hostIdeType,providerType:x.providerType})},[e.hostIdeType,x.providerType,(Se=x.targetEntry)==null?void 0:Se.providerControls]),N=Fc({isCliLike:x.isCli||x.isAcp}),v=ch({isCliLike:x.isCli||x.isAcp}),C=wh(e,{enabled:h&&!!e.sessionId,tailLimit:v}),[M,w]=i.useState(N),[k,F]=i.useState(()=>Ci()),_=e.tabKey,S=C.historyMessages,H=C.hasMoreHistory,W=C.historyError,D=kh(e,C),I=mc(D).length;i.useEffect(()=>{w(N)},[N,_]);const T=Math.max(0,D.length-M),K=Do(e),P=Mr(e),$=Ih(e),V=Eo(e),Y=a||V,ge=!!V,[fe,ae]=i.useState(!1);i.useEffect(()=>{const te=x.targetEntry;P&&(!te||te.providerControls===void 0||te.controlValues===void 0)&&f(P,{minFreshMs:3e4}).catch(()=>{})},[P,x.isAcp,(R=x.targetEntry)==null?void 0:R.providerControls,(re=x.targetEntry)==null?void 0:re.controlValues,f]);const me=i.useCallback(async()=>{if(!fe){if(D.length>M){w(te=>Math.min(D.length,te+Eh));return}ae(!0);try{await C.loadHistoryPage()}finally{ae(!1)}}},[C,fe,D.length,M]),{allMessages:je,receivedAtMap:Ne}=i.useMemo(()=>{const te=Sh({historyMessages:S,liveMessages:D,visibleLiveCount:M}),E=Dh(e),X=E.length>0?[...te,...E]:te,oe={};return X.forEach((ee,ke)=>{const Ce=`${e.tabKey}:${vn(ee,ke)}`;let ve=oh(ee)||g.current.get(Ce)||0;ve||(ve=Date.now(),g.current.set(Ce,ve)),oe[vn(ee,ke)]=ve}),{allMessages:X,receivedAtMap:oe}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,T,S,D,M]),G=i.useMemo(()=>c.filter(te=>te.routeId===e.tabKey).sort((te,E)=>te.timestamp-E.timestamp),[c,e.tabKey]),he=i.useCallback(async()=>{var ke,Ce;if(!P)return;const te=Ec({activeConv:e,visibleMessages:je,actionLogs:c,controls:(ke=x.targetEntry)==null?void 0:ke.providerControls,controlValues:(Ce=x.targetEntry)==null?void 0:Ce.controlValues,visibleBarControlCount:A.length,chatTailState:{liveMessages:C.liveMessages,hasLiveSnapshot:C.hasLiveSnapshot,hasMoreHistory:H,historyError:W,historyMessages:S},ui:{controlsVisible:b,visibleLiveCount:M,activityVisible:k,activityCount:I,hiddenLiveCount:T,isInputActive:u,isVisible:h}}),E=await p(P,"get_chat_debug_bundle",{agentType:x.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:te}),X=Sn(E),oe=Oc(X),ee=await Bc(oe);ee==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),ot.showToast($c(X,{locatorCopyStatus:ee}),ee==="failed"?"warning":"success")},[e,c,I,je,b,C.hasLiveSnapshot,C.liveMessages,x.providerType,(Q=x.targetEntry)==null?void 0:Q.controlValues,(ue=x.targetEntry)==null?void 0:ue.providerControls,P,H,T,S,u,h,W,p,k,A.length,M]),pe=i.useCallback(()=>{F(te=>{const E=!te;return np(E),E})},[]);i.useEffect(()=>{const te=E=>{E.key===Io&&F(Ci())};return window.addEventListener("storage",te),()=>window.removeEventListener("storage",te)},[]);const ye=i.useCallback(()=>{const te=zf(j.current);j.current=te.state,te.shouldCollect&&he().catch(E=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",E),ot.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[he]),xe=i.useMemo(()=>{if(D.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[t.jsx("div",{className:"connecting-logo-float",children:t.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:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),t.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[t.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:["Connecting to your machine",t.jsx("span",{className:"connecting-dots"})]}),t.jsx("div",{className:"text-[11px] opacity-35",children:"Establishing P2P connection"})]})]});if((y.isGenerating||e.status==="streaming")&&ae(!1),e.status==="not_monitored"&&$)return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-3xl opacity-60",children:t.jsx(Hs,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent not monitored"}),t.jsx("button",{onClick:o,disabled:l,className:"btn btn-primary",children:l?"⌛ Switching...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ns,{size:14})," Open ",K," Panel"]})}),t.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:"Click to switch monitoring to this agent"})]});if(e.status==="panel_hidden"&&$)return t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-3xl opacity-60",children:t.jsx(lc,{size:28})}),t.jsx("div",{className:"text-[13px] opacity-50",children:"Agent panel is not visible yet"}),t.jsx("button",{onClick:o,disabled:l,className:"btn btn-primary",children:l?"⌛ Opening...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Ns,{size:14})," Open ",K," Panel"]})}),t.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"&&!fe)return!H&&S.length===0?t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-2xl opacity-40",children:"💬"}),t.jsx("div",{className:"text-[13px] opacity-40",children:"No messages yet"})]}):t.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[t.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),t.jsx("div",{className:"text-[13px] opacity-40",children:"Loading chat..."})]})}},[e.connectionState,e.status,$,o,H,S.length,l,fe,D.length,K,y.isGenerating]);return t.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col",children:[t.jsx("div",{className:"chat-activity-toggle-bar",children:t.jsxs("button",{type:"button",className:`chat-activity-toggle ${k?"chat-activity-toggle-active":""}`,onClick:pe,"aria-pressed":k,title:"Show tool, terminal, and runtime activity rows",children:[t.jsx("span",{className:"chat-activity-toggle-dot"}),"Activity",I>0&&t.jsx("span",{className:"chat-activity-toggle-count",children:I})]})}),t.jsx(yp,{messages:je,actionLogs:G,agentName:Us(e)||K||"Agent",userName:d,isCliMode:x.isCli||x.isAcp,isWorking:y.isGenerating,contextKey:e.tabKey,receivedAtMap:Ne,lastMessageHash:e.lastMessageHash,showActivityMessages:k,onLoadMore:me,isLoadingMore:fe,hasMoreHistory:H,hiddenLiveCount:T,loadError:W??void 0,emptyState:xe,scrollToBottomRequestNonce:m,isVisible:h}),t.jsx(kf,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:x.providerType,displayLabel:x.displayLabel,controls:(ce=x.targetEntry)==null?void 0:ce.providerControls,controlValues:(de=x.targetEntry)==null?void 0:de.controlValues,isActive:u,isCliTerminal:x.isCliTerminal}),!x.isCliTerminal&&t.jsx(Tc,{contextKey:e.tabKey,panelLabel:K,isSending:n,isBusy:ge,statusMessage:Y,onSend:r,isActive:u,showControlsToggle:A.length>0,onControlsToggle:ye,messageInput:e.messageInput})]})}let Vc=ls;function Gc(){return Vc()}class $h{constructor(){Qe(this,"listeners",new Map)}send(s){}isConnected(){return!1}on(s,r){return this.listeners.has(s)||this.listeners.set(s,new Set),this.listeners.get(s).add(r),()=>{var n;(n=this.listeners.get(s))==null||n.delete(r)}}emit(s,...r){var n;(n=this.listeners.get(s))==null||n.forEach(a=>a(...r))}}let qc=new $h;class Bh{sendPtyInput(s,r,n){return!1}retryConnection(s){}getState(s){return"disconnected"}sendData(s,r){return!1}get(s){}onScreenshot(s,r){return()=>{}}onRuntimeEvent(s,r,n){return()=>{}}requestRuntimeSnapshot(s,r,n){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let ut=new Bh;function Oh(e){e.dashboardWS&&(qc=e.dashboardWS),e.connectionManager&&(ut=e.connectionManager),e.useDaemonsHook&&(Vc=e.useDaemonsHook)}const Fh=.5,Kh=1.25;function dt(e){return Do(e)}function Cs(e){return _c(e).join(" · ")}function Yc(e){const s=Rc(e);return s||(e.title?e.title:Cs(e)||"No messages yet")}function Xc(e,s){const{isReconnecting:r,isConnecting:n}=Xs(e);return r?"Reconnecting…":n?"Connecting…":s!=null&&s.requiresAction?"Action needed":null}function Wh(e,s){const r=["Chat",..._c(e)];return s!=null&&s.timestampLabel&&r.push(s.timestampLabel),r.filter(Boolean).join(" · ")}function xs(e){return Xc(e)||Cs(e)}function Hh(e){return`${dt(e)} · ${Yc(e)}`}function Uh(e){const s=Nn(e),r=s?lt(s):Us(e);return`${dt(e)} — ${r||"Agent"}`}function zh(e){return Us(e)||"CLI"}function Jc(e){return Lc(e)}function Qc(e){return e?`Remote · ${dt(e)||e.workspaceName||"Session"}`:"Remote"}function Vh({activeConv:e,clearToken:s=0,terminalRef:r,handleSendChat:n,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:l=!0,isInputActive:c=!0}){var ie;ls();const{sendPtyInput:d}=wt(),[m,u]=i.useState(!1),h=i.useRef(!1);h.current=m;const[g,j]=i.useState("Runtime terminal unavailable"),[f,p]=i.useState(!1),[b,y]=i.useState(null),[x,A]=i.useState(!1),[N,v]=i.useState(!1),[C,M]=i.useState(1),[w,k]=i.useState(!1),[F,_]=i.useState({width:0,height:0}),[S,H]=i.useState({width:0,height:0}),[W,D]=i.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[I,T]=i.useState(null),K=i.useRef(null),P=i.useRef(null),$=i.useRef(!1),V=i.useRef(!1),Y=i.useRef(l),ge=i.useRef(0),fe=i.useRef(!1),ae=i.useRef(""),me=i.useRef(null),je=i.useRef(!1),Ne=i.useRef(!1),G=i.useRef(null),he=i.useRef(null),pe=i.useRef(null),ye=32*1024,xe=()=>{var B,q,ne,le;return((q=(B=K.current)==null?void 0:B.ownerDocument)==null?void 0:q.defaultView)||((le=(ne=P.current)==null?void 0:ne.ownerDocument)==null?void 0:le.defaultView)||window},Se=B=>{const q=xe();return{ownerWindow:q,frameId:q.requestAnimationFrame(B)}},R=()=>{const B=G.current;if(B){try{B.ownerWindow.cancelAnimationFrame(B.frameId)}catch{}G.current=null}},re=()=>{const B=he.current;if(B){try{B.ownerWindow.clearTimeout(B.timeoutId)}catch{}he.current=null}},Q=()=>{const B=pe.current;if(B){try{B.ownerWindow.clearTimeout(B.timeoutId)}catch{}pe.current=null}},ue=()=>{l&&G.current===null&&(G.current=Se(()=>{st()}))},ce=e.tabKey,de=e.sessionId||"",te=e.daemonId||((ie=e.routeId)==null?void 0:ie.split(":")[0])||e.routeId||"",E=Eo(e),X=m?o||E:g,oe=Fh,ee=Kh,ke=.05,Ce=()=>{const B=S.width,q=S.height;if(!Number.isFinite(F.width)||F.width<=0||!Number.isFinite(F.height)||F.height<=0||!Number.isFinite(B)||B<=0||!Number.isFinite(q)||q<=0)return 1;const ne=F.width/B,le=F.height/q;return Number(Math.min(ee,Math.max(oe,Math.min(ne,le))).toFixed(2))},ve=Ce(),O=$.current&&C>ve,Ie=Number.isFinite(S.width)&&S.width>0?Math.max(F.width,Math.round(S.width*C)):F.width,Re=Number.isFinite(S.height)&&S.height>0?Math.max(F.height,Math.round(S.height*C)):F.height,Ke=()=>{Se(()=>{const B=P.current;B&&(B.scrollLeft=0,B.scrollTop=B.scrollHeight-B.clientHeight)})},He=()=>{var B,q;ge.current=0,fe.current=!1,ae.current="",me.current=null,je.current=!1,Ne.current=!1,$.current||(V.current=!1,M(1)),G.current!==null&&R(),u(!1),j("Runtime terminal unavailable"),Q(),re(),y(null),T(null),k(!1),p(!1),A(!1),v(!1),(q=(B=r.current)==null?void 0:B.reset)==null||q.call(B)},Ye=()=>{var B,q;ge.current=0,fe.current=!1,ae.current="",me.current=null,je.current=!1,Ne.current=!1,G.current!==null&&R(),u(!0),j(""),Q(),re(),y(null),T(null),k(!1),p(!1),A(!1),v(!1),(q=(B=r.current)==null?void 0:B.reset)==null||q.call(B)},Xe=()=>{Ne.current&&(Ne.current=!1,Se(()=>{var B,q;(q=(B=r.current)==null?void 0:B.scrollToTop)==null||q.call(B)}))},st=()=>{if(G.current=null,!l)return;const B=ae.current;if(!B)return;const q=B.slice(0,ye);ae.current=B.slice(q.length);const ne=r.current;if(!ne){ae.current=q+ae.current,ue();return}ne.write(q,()=>{if(ae.current.length>0){ue();return}Xe()})},mt=B=>{B&&(ae.current+=B,ue())},ht=(B,q=0,ne,le,we={})=>{var De,Me,Ee,Oe;const _e=!!we.force;!_e&&q>0&&ge.current>=q||!_e&&q===0&&fe.current||(ge.current=q,q>0&&A(!0),u(!0),j(""),typeof ne=="number"&&typeof le=="number"&&ne>0&&le>0&&((Me=(De=r.current)==null?void 0:De.resize)==null||Me.call(De,ne,le)),ae.current="",(Oe=(Ee=r.current)==null?void 0:Ee.reset)==null||Oe.call(Ee),B?mt(B):Xe())};i.useEffect(()=>{He()},[de]),i.useEffect(()=>{var q;if(!de)return;const B=((q=ut.onRuntimeEvent)==null?void 0:q.call(ut,de,ne=>{if(!(!ne||ne.sessionId!==de)){if(ne.type==="runtime_snapshot"){if(!l){me.current={text:ne.text||"",seq:ne.seq||0,cols:ne.cols,rows:ne.rows,force:!!ne.force};return}ht(ne.text||"",ne.seq||0,ne.cols,ne.rows,{force:!!ne.force});return}if(ne.type==="session_output"){fe.current=!0,typeof ne.seq=="number"&&(ge.current=Math.max(ge.current,ne.seq),ne.seq>0&&A(!0)),h.current||u(!0),h.current||j(""),typeof ne.data=="string"&&mt(ne.data);return}if(ne.type==="session_cleared"){if(!l){je.current=!0,ae.current="",me.current=null;return}Ye();return}if(ne.type==="session_io_error"){const le=typeof ne.error=="string"&&ne.error?ne.error:typeof ne.reason=="string"&&ne.reason?ne.reason:"unknown error";u(!1),j(`Runtime input failed: ${le}`);return}}},te))||(()=>{});return()=>{B()}},[te,de,r,l]);const yt=async(B={})=>{var q;if(!te||!de)return{success:!1,error:"daemonId and sessionId are required"};B.preserveStatus||j(B.loadingMessage||"Loading runtime terminal...");try{const ne=await((q=ut.requestRuntimeSnapshot)==null?void 0:q.call(ut,te,de,{sinceSeq:B.sinceSeq,force:B.force}));return ne&&ne.success===!1?(B.preserveStatus||(u(!1),j(`Runtime terminal unavailable: ${ne.error}`)),ne):ne||{success:!0}}catch(ne){const le=(ne==null?void 0:ne.message)||String(ne);return B.preserveStatus||(u(!1),j(`Runtime terminal unavailable: ${le}`)),{success:!1,error:le}}},Te=async B=>{var _e,De;const q=((_e=K.current)==null?void 0:_e.ownerDocument)||document,ne=q.defaultView||window,le=(De=ne.navigator)==null?void 0:De.clipboard;if(le!=null&&le.writeText&&ne.isSecureContext)try{return await le.writeText(B),!0}catch{}let we=null;try{return we=q.createElement("textarea"),we.value=B,we.setAttribute("readonly","true"),we.style.position="fixed",we.style.left="-9999px",we.style.top="0",q.body.appendChild(we),we.focus(),we.select(),q.execCommand("copy")}catch{return!1}finally{we==null||we.remove()}},Ue=B=>{re(),T(B);const q=xe();he.current={ownerWindow:q,timeoutId:q.setTimeout(()=>{he.current=null,T(ne=>ne===B?null:ne)},2200)}},et=B=>{Q(),y(B);const q=xe();pe.current={ownerWindow:q,timeoutId:q.setTimeout(()=>{pe.current=null,y(ne=>ne===B?null:ne)},2200)}},ze=async()=>{var we,_e,De,Me;const B=((_e=(we=r.current)==null?void 0:we.getSelection)==null?void 0:_e.call(we))||"",q=((Me=(De=r.current)==null?void 0:De.getVisibleText)==null?void 0:Me.call(De))||"",ne=B.trimEnd()||q.trimEnd();if(!ne){Ue("Nothing to copy");return}if(!await Te(ne)){Ue("Copy failed");return}Ue(B.trimEnd()?"Copied selection":"Copied visible terminal")},at=B=>{if(!m||!l)return;((d==null?void 0:d(te,de,B))??!1)||Ue("Terminal input failed")},U=async()=>{if(f)return;p(!0),y("Loading older terminal output..."),Ne.current=!0;const B=await yt({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:m});if(p(!1),(B==null?void 0:B.success)===!1){Ne.current=!1,y(`Older terminal output unavailable: ${B.error}`);return}v(!0),et("Older terminal output loaded"),Se(()=>{var q;(q=r.current)==null||q.bumpResize()})};i.useEffect(()=>{var q,ne;if(!de)return;te&&((q=ut.getState)==null?void 0:q.call(ut,te))==="connected"&&yt();const B=(ne=ut.onStateChange)==null?void 0:ne.call(ut,(le,we)=>{le!==te||we!=="connected"||yt()});return()=>{B==null||B()}},[te,de,r]),i.useEffect(()=>{s&&He()},[s,ce,r]),i.useEffect(()=>{var le,we;const B=K.current,q=(we=(le=B==null?void 0:B.ownerDocument)==null?void 0:le.defaultView)==null?void 0:we.ResizeObserver;if(!B||!q)return;const ne=new q(_e=>{const De=_e[0];if(!De)return;const{width:Me,height:Ee}=De.contentRect;_(Oe=>{const Ae=Math.round(Me),Je=Math.round(Ee);return Oe.width===Ae&&Oe.height===Je?Oe:{width:Ae,height:Je}})});return ne.observe(B),()=>ne.disconnect()},[]),i.useEffect(()=>{if($.current)return;const B=Ce();!Number.isFinite(B)||B<=0||M(q=>V.current?B<q-ke?B:q:(V.current=!0,B))},[S.height,S.width,F.height,F.width]),i.useEffect(()=>{O&&Ke()},[O,Re,Ie]),i.useEffect(()=>{var ne;const B=Y.current;if(Y.current=l,!l)return;B||v(!1),je.current&&(je.current=!1,Ye());const q=me.current;q&&(me.current=null,ht(q.text,q.seq,q.cols,q.rows,{force:!!q.force})),te&&de&&((ne=ut.getState)==null?void 0:ne.call(ut,te))==="connected"&&yt(),ae.current&&G.current===null&&ue(),Se(()=>{var le;(le=r.current)==null||le.bumpResize()})},[te,l,de]),i.useEffect(()=>()=>{G.current!==null&&R(),re(),Q()},[]),i.useEffect(()=>{const B=le=>{var _e;const we=le.detail;we!=null&&we.sessionId&&we.sessionId!==de||m&&((_e=r.current)==null||_e.bumpResize())},q=xe(),ne=q===window?[window]:[window,q];for(const le of ne)le.addEventListener("adhdev:fit-cli-terminal",B);return()=>{for(const le of ne)le.removeEventListener("adhdev:fit-cli-terminal",B)}},[m,de,r]);const Z=m&&x&&!N&&(W.atTop||!W.canScroll)||f||!!b;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{ref:K,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[Z&&t.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[t.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:()=>{U()},disabled:!de||f,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:f?"Loading older...":"Load older terminal output"}),b&&t.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:b})]}),t.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[I&&t.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:I}),t.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{ze()},disabled:!m,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:"Copy"}),t.jsxs("div",{className:"relative",children:[t.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>k(B=>!B),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&&t.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:[t.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Terminal keys"}),t.jsx("button",{type:"button",className:"rounded-full px-2 py-0.5 text-[11px] text-white/55 transition-colors hover:bg-white/10 hover:text-white/85",onClick:()=>k(!1),"aria-label":"Close terminal control keys",children:"×"})]}),t.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[t.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:()=>at("\x1B"),children:"Esc"}),t.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:()=>at(" "),children:"Tab"}),t.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:()=>at("\r"),children:"Enter"}),t.jsx("span",{"aria-hidden":"true"}),t.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:()=>at("\x1B[A"),"aria-label":"Arrow up",children:"↑"}),t.jsx("span",{"aria-hidden":"true"}),t.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:()=>at("\x1B[D"),"aria-label":"Arrow left",children:"←"}),t.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:()=>at("\x1B[B"),"aria-label":"Arrow down",children:"↓"}),t.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:()=>at("\x1B[C"),"aria-label":"Arrow right",children:"→"}),t.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:()=>at(""),children:"Ctrl-C"}),t.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:()=>at(""),children:"Ctrl-D"}),t.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:()=>at(""),children:"Bksp"})]})]})]}),t.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(B=>{const q=Math.max(ve,Number((B-.1).toFixed(2)));return q>ve&&Ke(),q})},title:"Shrink terminal viewport",children:"-"}),t.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(B=>{const q=Math.min(ee,Number((B+.1).toFixed(2)));return q>ve&&Ke(),q})},title:"Increase terminal viewport",children:"+"})]}),t.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:t.jsx("div",{style:{width:Ie>0?`${Ie}px`:"100%",height:Re>0?`${Re}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:t.jsx("div",{style:{width:S.width>0?`${S.width}px`:"100%",height:S.height>0?`${S.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:C},children:t.jsx(bc,{ref:r,readOnly:!m||!l,sizingMode:"measured",onViewportMetrics:H,onScrollMetrics:D,onInput:B=>{!m||(d==null||d(te,de,B))}})})})}),!m&&t.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:g})]}),t.jsx(Tc,{contextKey:e.tabKey,panelLabel:dt(e),isSending:a,isBusy:!!E,statusMessage:X,onSend:async B=>E?!1:n(B),isActive:c&&l,showControlsToggle:!1,animateVisibility:!1})]})}const Gh=5e3,qh=12e3;function Yh(e){return e==="disconnected"||e==="reconnecting"}function Xh({wsStatus:e,showReconnected:s,loginUrl:r,onReconnect:n,reconnectDelayMs:a=Gh,reconnectActionDelayMs:o=qh}){const l=Yh(e),[c,d]=i.useState(()=>!l||a<=0),[m,u]=i.useState(()=>!l||o<=0),h=i.useRef(!1);i.useEffect(()=>{if(!l){d(!1);return}if(h.current=!1,a<=0){h.current=!0,d(!0);return}d(!1);const v=setTimeout(()=>{h.current=!0,d(!0)},a);return()=>clearTimeout(v)},[a,l]),i.useEffect(()=>{if(!l){u(!1);return}if(o<=0){u(!0);return}u(!1);const v=setTimeout(()=>{u(!0)},o);return()=>clearTimeout(v)},[o,l]);const g=l?c:e==="offline"||e==="auth_failed",j=!!(n&&e!=="auth_failed"&&(!l||m)),f=i.useMemo(()=>!s||e!=="connected"?!1:a<=0||h.current,[a,s,e]),p=e==="auth_failed"?"red":e==="offline"?"orange":"accent",b={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},y={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},x={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},A="fixed left-1/2 top-4 z-[1400] flex items-center justify-center pointer-events-none",N={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return t.jsxs(t.Fragment,{children:[g&&t.jsx("div",{className:A,style:N,children:t.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:b[p],border:y[p],color:x[p]},children:[t.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}}),t.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?t.jsxs(t.Fragment,{children:["Session expired."," ",t.jsx("a",{href:r,className:"text-inherit underline",children:"Log in again"})]}):"Connection failed — refresh the page or try again shortly.")]}),j&&t.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"})]})}),f&&t.jsx("div",{className:A,style:N,children:t.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:[t.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),"Connected"]})})]})}function Jh({terminalBackend:e,isStandalone:s=!1,machineLabel:r,machineKey:n}){const a=i.useMemo(()=>!n||!e?null:`adhdev:terminal-backend-banner:dismissed:${n}:${e.backend}`,[n,e]),[o,l]=i.useState(!1);if(i.useEffect(()=>{if(!a){l(!1);return}try{l(localStorage.getItem(a)==="1")}catch{l(!1)}},[a]),!s||!e||e.backend!=="xterm"||o)return null;const c=(r==null?void 0:r.trim())||"This machine",d=()=>{if(a)try{localStorage.setItem(a,"1")}catch{}l(!0)};return t.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:[t.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5 justify-center flex-wrap",children:[t.jsxs("span",{children:[c," is using `xterm` fallback."]}),t.jsx("span",{style:{opacity:.8},children:"ghostty-vt is unavailable on this machine, so terminal rendering may be less accurate."})]}),t.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 Ko({mode:e,onChange:s,compact:r=!1}){const n=r?14:15;return t.jsx("button",{type:"button",onClick:()=>s(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:e==="chat"?"Switch to Terminal view":"Switch to Chat view",children:e==="chat"?t.jsx(So,{size:n}):t.jsx(Jt,{size:n})})}const Ht="New session",Zc="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 Qh(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 s=[e.branch||"Git"];return e.changedFiles>0&&s.push(`±${e.changedFiles}`),e.ahead>0&&s.push(`↑${e.ahead}`),e.behind>0&&s.push(`↓${e.behind}`),s.length===1&&e.dirty&&s.push("dirty"),s.join(" ")}function Zh(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 ex(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 Vs({git:e,className:s="",compact:r=!1}){const n=Qh(e),a=Zh(e);if(!n||!a)return null;const o=[e!=null&&e.branch?`Branch: ${e.branch}`:null,e!=null&&e.changedFiles?`Changed files: ${e.changedFiles}`:null,e!=null&&e.ahead?`Ahead: ${e.ahead}`:null,e!=null&&e.behind?`Behind: ${e.behind}`:null,e!=null&&e.hasConflicts?"Conflicts detected":null,e!=null&&e.error?`Git error: ${e.error}`:null].filter(Boolean);return t.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 ${ex(a)} ${s}`.trim(),title:o.join(" · ")||n,"data-git-tone":a,children:[t.jsx("span",{"aria-hidden":"true",children:"⑂"}),t.jsx("span",{className:"truncate",children:n})]})}function tx({wsStatus:e,isConnected:s,daemonCount:r,p2pStates:n={}}){if(e!=="connected")return{tone:"disconnected",title:"Disconnected",subtitle:null};const a=Object.values(n),o=a.filter(c=>c==="connected").length,l=a.filter(c=>c==="connecting"||c==="new"||c==="checking").length;return r>0&&l>0&&o===0?{tone:"limited",title:"Connected to dashboard",subtitle:"Connecting to machine..."}:s?{tone:"connected",title:"Connected",subtitle:null}:{tone:"limited",title:"Connected to dashboard",subtitle:null}}function Gi({value:e}){return e?t.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function qi({notification:e,shortcutIndex:s,onOpen:r,onMarkRead:n,onMarkUnread:a,onDelete:o}){const l=En(e.updatedAt),c=!e.readAt;return t.jsxs("div",{className:`dashboard-header-inbox-item ${c?"is-attention":""}`.trim(),children:[t.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:r,children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[s?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",s]}):null,[e.type==="needs_attention"?"Action needed":"Task complete",l].filter(Boolean).join(" · ")]}),e.preview?t.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),t.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[c?t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),n()},children:"Mark read"}):t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),a()},children:"Mark unread"}),t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:d=>{d.stopPropagation(),o()},children:"Delete"})]})]})}function sx({activeConv:e,wsStatus:s,isConnected:r,conversations:n,onOpenHistory:a,onOpenRemote:o,onStopCli:l,activeCliViewMode:c,onSetCliViewMode:d,onHideConversation:m,hiddenConversations:u=[],onShowConversation:h,onShowAllHidden:g,onResetPanelsToMain:j,inboxOpen:f,onInboxOpenChange:p,hiddenOpen:b,onHiddenOpenChange:y,onOpenNewSession:x,onOpenDashboardGuide:A,guideNudgeVisible:N=!1,actionShortcuts:v,notifications:C,notificationUnreadCount:M,onOpenNotification:w,onMarkNotificationRead:k,onMarkNotificationUnread:F,onDeleteNotification:_,onOpenGitDialog:S,onOpenMeshGraph:H}){var Se;const{ides:W,p2pStates:D={}}=ls(),I=!!e&&nt(e)&&!tt(e),T=!!e&&tt(e),K=!!(e!=null&&e.daemonId)&&typeof((Se=e==null?void 0:e.settings)==null?void 0:Se.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.length>0,P=c||(e?Ac(e)?"terminal":"chat":null),[$,V]=i.useState(!1),Y=i.useRef(null),ge=i.useRef(null),fe=W.filter(R=>R.type==="adhdev-daemon"),ae=tx({wsStatus:s,isConnected:r,daemonCount:fe.length,p2pStates:D}),me=ae.subtitle,je=ae.tone==="connected"?"#22c55e":ae.tone==="limited"?"#eab308":"#ef4444",Ne=ae.tone==="connected"?"0 0 4px #22c55e80":ae.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",G=i.useMemo(()=>C.filter(R=>!R.readAt),[C]),he=i.useMemo(()=>C.filter(R=>!!R.readAt),[C]),pe=i.useMemo(()=>G.slice(0,9),[G]),ye=M;i.useEffect(()=>{if(!f)return;const R=re=>{var Q;(Q=Y.current)!=null&&Q.contains(re.target)||p(!1)};return document.addEventListener("mousedown",R),()=>document.removeEventListener("mousedown",R)},[f,p]),i.useEffect(()=>{if(!b)return;const R=re=>{var Q;(Q=ge.current)!=null&&Q.contains(re.target)||y(!1)};return document.addEventListener("mousedown",R),()=>document.removeEventListener("mousedown",R)},[b,y]),i.useEffect(()=>{if(!b&&!f)return;const R=re=>{if(!re.altKey)return;const Q=re.code.match(/^Digit([1-9])$/);if(!Q)return;const ue=Number(Q[1])-1,ce=b?u[ue]:void 0,de=f?pe[ue]:void 0;if(!(!ce&&!de)){if(re.preventDefault(),re.stopPropagation(),ce){h==null||h(ce),y(!1);return}de&&(w(de),p(!1))}};return window.addEventListener("keydown",R,!0),()=>window.removeEventListener("keydown",R,!0)},[u,b,f,pe,y,p,w,h]);const xe=R=>{if(!R)return;const re=n.find(Q=>Q.tabKey===R);re&&(m==null||m(re))};return t.jsxs("div",{className:"dashboard-header",children:[t.jsx("div",{className:"flex items-center gap-3",children:t.jsx("div",{className:"header-title-block",children:t.jsxs("div",{className:"header-title-row",children:[t.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[t.jsx(Jt,{size:18}),t.jsx("span",{className:"header-title-desktop",children:"Dashboard"}),t.jsx("span",{className:"header-title-mobile",children:e?dt(e):"Dashboard"}),t.jsx("span",{title:ae.title,"aria-label":ae.title,className:"header-title-status-dot",style:{background:je,boxShadow:Ne}}),t.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:t.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:je,boxShadow:Ne}})})]}),t.jsxs("div",{className:"header-subtitle flex items-center",children:[me&&t.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",me]}),x&&t.jsx("button",{type:"button",onClick:x,className:"btn btn-secondary btn-sm ml-2",title:`${Ht}${v!=null&&v.openNewSession?` (${v.openNewSession})`:""}`,"aria-label":Ht,children:t.jsx(dc,{size:14})})]})]})})}),t.jsxs("div",{className:"flex gap-2 items-center",children:[A&&t.jsxs("button",{type:"button",onClick:A,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:[t.jsx("span",{className:"font-semibold leading-none",children:"?"}),N&&t.jsx("span",{children:"Guide"})]}),e&&(I||T||!tt(e))&&t.jsxs("div",{className:"dashboard-header-actions-group",children:[t.jsx("span",{className:"dashboard-header-action-target",title:Cs(e)||dt(e),children:dt(e)}),S&&e.git&&e.daemonId&&e.workspacePath?t.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:()=>S(e.daemonId,e.workspacePath),children:t.jsx(Vs,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):t.jsx(Vs,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),K&&H&&t.jsxs("button",{type:"button",onClick:()=>H(e),className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",title:"Open live repo mesh graph",children:[t.jsx(ns,{size:14}),t.jsx("span",{className:"hidden lg:inline",children:"Mesh graph"})]}),(I||T)&&l&&t.jsxs(t.Fragment,{children:[I&&d&&P&&t.jsx(Ko,{mode:P,onChange:d,compact:!0}),t.jsx("button",{onClick:()=>l(e),className:"btn btn-secondary btn-sm",title:T?"Stop ACP session":"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:t.jsx(vt,{size:14})})]}),!tt(e)&&t.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:"Chat History",children:t.jsx(ko,{size:14})}),!I&&!tt(e)&&t.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:"Remote Control",children:t.jsx(At,{size:14})})]}),t.jsxs("div",{className:"dashboard-header-inbox",ref:Y,children:[t.jsxs("div",{className:`dashboard-header-hidden${$?" is-drop-target":""}`,ref:ge,onDragEnter:R=>{R.dataTransfer.types.includes("text/tab-key")&&(R.preventDefault(),V(!0))},onDragOver:R=>{R.dataTransfer.types.includes("text/tab-key")&&(R.preventDefault(),R.dataTransfer.dropEffect="move",V(!0))},onDragLeave:R=>{R.currentTarget.contains(R.relatedTarget)||V(!1)},onDrop:R=>{const re=R.dataTransfer.getData("text/tab-key");R.preventDefault(),V(!1),xe(re)},children:[t.jsxs("button",{type:"button",onClick:()=>y(!b),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`Hidden tabs${v!=null&&v.toggleHiddenTabs?` (${v.toggleHiddenTabs})`:""}. Drag a tab here to hide it.`,children:[t.jsx(No,{size:16}),u.length>0&&t.jsx("span",{className:"dashboard-header-hidden-badge",children:u.length})]}),b&&t.jsxs("div",{className:"dashboard-header-hidden-popover",children:[t.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[t.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:"Hidden tabs"}),t.jsx(Gi,{value:v==null?void 0:v.toggleHiddenTabs})]}),t.jsxs("div",{className:"dashboard-header-hidden-actions",children:[j&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:j,children:"Reset panels"}),u.length>0&&g&&t.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{g(),y(!1)},children:"Restore all"})]})]}),e&&m&&t.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>m(e),children:[t.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[t.jsx("span",{className:"dashboard-header-hidden-current-label",children:"Hide current tab"}),t.jsx(Gi,{value:v==null?void 0:v.hideCurrentTab})]}),t.jsx("span",{className:"dashboard-header-hidden-current-title",children:dt(e)})]}),u.length>0?t.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(R=>t.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{h==null||h(R),y(!1)},children:[t.jsx("span",{className:"dashboard-header-inbox-item-title",children:dt(R)}),t.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(R)<9?t.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(R)+1]}):null,Cs(R)]})]},R.tabKey))}):t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No hidden tabs."})]})]}),t.jsxs("button",{type:"button",onClick:()=>p(!f),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:"Activity inbox",children:[t.jsx(Dn,{size:16}),ye>0&&t.jsx("span",{className:"dashboard-header-inbox-badge",children:ye})]}),f&&t.jsxs("div",{className:"dashboard-header-inbox-popover",children:[G.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Unread"}),G.map(R=>t.jsx(qi,{notification:R,shortcutIndex:pe.indexOf(R)>=0?pe.indexOf(R)+1:void 0,onOpen:()=>w(R),onMarkRead:()=>k(R.id),onMarkUnread:()=>F(R.id),onDelete:()=>_(R.id)},R.id))]}),he.length>0&&t.jsxs("div",{className:"dashboard-header-inbox-section",children:[t.jsx("div",{className:"dashboard-header-inbox-section-title",children:"Read"}),he.map(R=>t.jsx(qi,{notification:R,onOpen:()=>w(R),onMarkRead:()=>k(R.id),onMarkUnread:()=>F(R.id),onDelete:()=>_(R.id)},R.id))]}),C.length===0&&t.jsx("div",{className:"dashboard-header-inbox-empty",children:"No pending activity."})]})]})]})]})}function Nt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function rx(e,s){return String(e||"")!==String(s||"")}function nx(e,s={}){const r=String(s.textQuery||"").trim().toLowerCase(),n=String(s.workspaceQuery||"").trim().toLowerCase(),a=String(s.modelQuery||"").trim().toLowerCase(),o=!!s.resumableOnly;return!r&&!n&&!a&&!o?e:e.filter(l=>!(o&&!l.canResume||r&&![l.title,l.preview].map(d=>String(d||"").toLowerCase()).join(`
|
|
41
|
-
`).includes(r)||n&&!String(l.workspace||"").toLowerCase().includes(n)||a&&!jc(l.summaryMetadata).map(d=>d.toLowerCase()).join(`
|
|
42
|
-
`).includes(a)))}function ax(e,s="recent"){const r=e.slice();return r.sort((n,a)=>{if(s==="oldest")return(Number(n.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(s==="messages"){const o=(Number(a.messageCount)||0)-(Number(n.messageCount)||0);if(o!==0)return o}return(Number(a.lastMessageAt)||0)-(Number(n.lastMessageAt)||0)}),r}function ed(e,s={}){return ax(nx(e,s),s.sortMode||"recent")}function In(e){return e?"Resume saved history":"Start fresh"}function Wo(e){return e?"Resuming saved history…":"Starting fresh…"}function ox(){return"Start fresh"}function td(e,s=!1){return e==="cli"?In(s):e==="ide"?"Start IDE":"Start ACP session"}function sd(e,s=!1){return e==="cli"?Wo(s):e==="ide"?"Starting IDE…":"Starting ACP session…"}function ix(){return"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function lx(){return"Open saved history"}function cx(){return"Saved History"}function Ho(){return"Use saved history when you want continuity in the same provider conversation."}function dx(){return"No saved history found yet."}function ux(){return"Refresh saved history"}function mx(){return"Refreshing saved history…"}function bs(e,s){return e==="start-fresh"?`Start fresh with ${s}?`:`Restart ${s}?`}function gs(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 Gs(e){return e==="start-fresh"?"Start fresh":"Restart"}function qs(e){return e==="start-fresh"?"Starting fresh…":"Restarting…"}function Uo(e){return`Resume saved history with ${e}?`}function zo(){return"Review or change the target workspace before resuming saved history."}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 Vo({activeConv:e,ides:s,isCreatingChat:r,isRefreshingHistory:n,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:l=null,savedHistoryFilters:c,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:m,onClose:u,onNewChat:h,onSwitchSession:g,onRefreshHistory:j,onResumeSavedSession:f}){var _;const p=s.find(S=>S.id===e.routeId),b=(p==null?void 0:p.chats)||[],y=(_=p==null?void 0:p.activeChat)==null?void 0:_.id,x=nt(e)&&!tt(e),[A,N]=i.useState(()=>Nt()),v=c||A,C=String(d||"").trim(),M=S=>{if(m){m(S);return}N(S)},w=i.useMemo(()=>a.map(S=>{const H=String(S.workspace||"").trim();return S.canResume||H||!C?S:{...S,workspace:C,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[C,a]),k=i.useMemo(()=>ed(w,{textQuery:v.textQuery,workspaceQuery:v.workspaceQuery,modelQuery:v.modelQuery,resumableOnly:v.resumableOnly,sortMode:v.sortMode}),[w,v.modelQuery,v.resumableOnly,v.sortMode,v.textQuery,v.workspaceQuery]),F=t.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:[t.jsx("div",{onClick:u,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),t.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:[t.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:[t.jsxs("div",{children:[t.jsx("h3",{className:"m-0 text-lg font-extrabold",children:x?cx():"Chat History"}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Uh(e)}),x&&t.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Ho()})]}),t.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:t.jsx(vt,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!x&&t.jsx("button",{onClick:h,disabled:r,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:r?"⌛ Creating...":"+ Start New Chat Session"}),x?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[t.jsx("input",{type:"text",value:v.textQuery,onChange:S=>M({...v,textQuery:S.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"}),t.jsx("input",{type:"text",value:v.workspaceQuery,onChange:S=>M({...v,workspaceQuery:S.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"}),t.jsx("input",{type:"text",value:v.modelQuery,onChange:S=>M({...v,modelQuery:S.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"}),t.jsxs("select",{value:v.sortMode,onChange:S=>M({...v,sortMode:S.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[t.jsx("option",{value:"recent",children:"Most recent"}),t.jsx("option",{value:"oldest",children:"Oldest first"}),t.jsx("option",{value:"messages",children:"Most messages"})]})]}),t.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[t.jsx("input",{type:"checkbox",checked:v.resumableOnly,onChange:S=>M({...v,resumableOnly:S.target.checked})}),"Resume-ready only"]})]}),k.map(S=>{const H=e.providerSessionId===S.providerSessionId,W=H||!S.canResume||!!l,D=S.workspaceFallbackSource==="selected-workspace";return t.jsxs("button",{type:"button",onClick:()=>{W||!f||f(S)},disabled:W,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${H?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${W?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:`font-bold text-sm mb-1 truncate ${H?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:S.title||"Untitled Session"}),t.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:S.providerSessionId})]}),t.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:px(S.lastMessageAt)})]}),t.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:S.preview||"No saved preview yet"}),t.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[t.jsxs("div",{className:"truncate",children:[S.workspace||"Workspace unknown",D?" · selected workspace":"",Ss(S.summaryMetadata)?` · ${Ss(S.summaryMetadata)}`:"",S.messageCount>0?` · ${S.messageCount} msgs`:""]}),t.jsx("div",{className:"shrink-0",children:H?"ACTIVE":S.canResume?D?"RESUME IN SELECTED WORKSPACE":l===S.providerSessionId?"RESUMING...":"RESUME":"MISSING WORKSPACE"})]})]},S.id)})]}):b.map(S=>t.jsxs("div",{onClick:()=>{g(e.routeId,S.id),u()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${y===S.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[t.jsx("div",{className:`font-bold text-sm mb-1 ${y===S.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:S.title||"Untitled Session"}),t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[S.id.substring(0,12),"..."]}),y===S.id&&t.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:"ACTIVE"})]})]},S.id)),(x&&!o&&k.length===0||!x&&b.length===0)&&t.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[t.jsx("div",{className:"text-3xl mb-3 opacity-60",children:t.jsx($m,{size:32})}),t.jsx("div",{className:"text-[13px]",children:x?a.length>0?"No saved history matches these filters.":dx():"No recent chat sessions found."})]}),x&&o&&t.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:t.jsx("div",{className:"text-[13px]",children:mx()})})]}),t.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:t.jsx("button",{onClick:j,disabled:n||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:n||o?"⌛ Refreshing...":t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Tr,{size:13})," ",x?ux():"Refresh History"]})})})]})]});return typeof document>"u"?F:kr.createPortal(F,document.body)}const Yi={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 rd({toasts:e,onDismiss:s,onClickToast:r}){return t.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=Yi[n.type]||Yi.info;return t.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var o;(o=n.actions)!=null&&o.length||r&&r(n)},children:[t.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))`}}),t.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:o=>{o.stopPropagation(),s(n.id)},"aria-label":"Dismiss",children:t.jsx(vt,{size:14})}),t.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[t.jsx("div",{className:"flex items-center gap-2 pr-8",children:t.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})}),t.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:n.message}),n.actions&&n.actions.length>0&&t.jsx("div",{className:"flex gap-2 mt-3",children:n.actions.map((o,l)=>t.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${o.variant==="primary"||o.variant==="danger",""}`,style:o.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:o.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:c=>{c.stopPropagation(),o.onClick(),s(n.id)},children:o.label},l))})]})]},n.id)})})}const fx=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function hx(e){const s=e.workspace||"";if(!s)return"";const r=s.split(/[/\\]/).filter(Boolean);return r.length>0?r[r.length-1]:s}function xx(e){return e.sessionId||e.instanceId||e.agentType}function la(e,s){return s||e||"unknown"}function nd(e=[]){const s={};for(const r of e)r.type==="adhdev-daemon"&&(s[r.id]=Tt(r,{fallbackId:r.id}));return s}function ad(e,s={}){var n,a;const r=e.daemonId||((n=e.id)==null?void 0:n.split(":")[0])||e.id;return{machineName:e.daemonId&&((a=s.machineNames)==null?void 0:a[e.daemonId])||void 0,connectionState:s.connectionStates?s.connectionStates[r]||s.defaultConnectionState||"new":s.defaultConnectionState}}function Go(e,s={}){return bx(e,ad(e,s))}function bx(e,s={}){var h,g,j,f,p;const r=[],n=s.machineName,a=s.connectionState,o=hx(e),l=e.workspace||"",c=Fp(e.type,{agentName:e.cliName}),d=nt(e)||tt(e)?c:lt(e.type),m=Array.isArray(e.childSessions)?e.childSessions.map(b=>{var y,x;return{sessionId:b.id,instanceId:b.id,providerSessionId:b.providerSessionId,transport:b.transport,sessionCapabilities:b.capabilities,agentType:b.providerType,agentName:b.providerName||lt(b.providerType),status:b.status,title:b.title,lastMessagePreview:b.lastMessagePreview,lastMessageRole:b.lastMessageRole,lastMessageAt:b.lastMessageAt,lastMessageHash:b.lastMessageHash,messages:((y=b.activeChat)==null?void 0:y.messages)||[],activeModal:((x=b.activeChat)==null?void 0:x.activeModal)||void 0,unread:b.unread,lastSeenAt:b.lastSeenAt,lastUpdated:b.lastUpdated,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,surfaceHidden:b.surfaceHidden,git:b.git,settings:b.settings,messageInput:b.messageInput}}):[],u=fx(e);if(u){const b=e.sessionId||e.instanceId,y=(h=e.settings)==null?void 0:h.meshCoordinatorFor,x=(g=e.settings)==null?void 0:g.meshNodeFor,A=y?" (Coordinator)":x?" (Mesh Node)":"",N=c+A,v=(j=e.activeChat)==null?void 0:j.activeModal,C=v&&Array.isArray(v.buttons)&&v.buttons.length>0,M=Kp(e.activeChat,[{status:e.status,activeModal:(f=e.activeChat)==null?void 0:f.activeModal}],e.agents||[]),w=e.activeChat||{title:"",messages:[]};let k=w.title&&String(w.title).trim()?String(w.title).trim():"";const F=(p=e.activeChat)==null?void 0:p.id,_=e.chats;if(F&&Array.isArray(_)&&_.length>0){const D=_.find(I=>I.id===F||I.id&&String(I.id)===String(F));D!=null&&D.title&&String(D.title).trim()&&(k=String(D.title).trim())}const S=(nt(e)||tt(e),e.type),H=(nt(e)||tt(e))&&Pi(k,N,S)?"":k,W=w.messages||[];r.push({routeId:e.id,sessionId:b,providerSessionId:e.providerSessionId,nativeSessionId:b,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:nt(e)?e.mode||"terminal":"chat",agentName:N,agentType:S,status:M,title:H,messages:W,resume:e.resume,hostIdeType:!nt(e)&&!tt(e)?e.type:void 0,workspaceName:o,workspacePath:l,git:e.git,displayPrimary:H||o||(nt(e)?e.mode==="chat"?N:`Terminal${A}`:N),displaySecondary:nt(e)&&o?N: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:C?v.buttons:void 0,modalMessage:C?v.message:void 0,streamSource:"native",tabKey:la(b,e.id),machineName:n,connectionState:a,settings:e.settings,messageInput:e.messageInput})}if(u&&(nt(e)||tt(e)))return r;for(const b of m){const y=b.activeModal&&Array.isArray(b.activeModal.buttons)&&b.activeModal.buttons.length>0,x=Wp(b),A=xx(b),N=`${e.id}:${A}`,v=b.title&&String(b.title).trim()||"",C=Pi(v,b.agentName,b.agentType)?"":v,M=b.messages||[];(b.transport==="cdp-webview"||b.sessionId||b.providerSessionId||M.length>0||y||C||!["idle","panel_hidden","disconnected","not_monitored"].includes(x))&&r.push({routeId:e.id,sessionId:b.sessionId||b.instanceId,providerSessionId:b.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:b.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:b.sessionCapabilities,mode:"chat",agentName:b.agentName,agentType:b.agentType,status:x,title:C,messages:M,hostIdeType:e.type,workspaceName:o,workspacePath:l,git:b.git||e.git,displayPrimary:C||o||b.agentName||d,displaySecondary:`${d} · ${b.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:b.lastMessagePreview,lastMessageRole:b.lastMessageRole,lastMessageAt:b.lastMessageAt,lastMessageHash:b.lastMessageHash,lastUpdated:b.lastUpdated||e.lastUpdated,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,modalButtons:y?b.activeModal.buttons:void 0,modalMessage:y?b.activeModal.message:void 0,streamSource:"agent-stream",tabKey:la(b.sessionId||b.instanceId,N),machineName:n,connectionState:a,settings:b.settings,messageInput:b.messageInput})}return r.length===0&&r.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:o,workspacePath:l,git:e.git,displayPrimary:o||d,displaySecondary:d,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:la(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),r}function od(e){return String(e.type||e.id||"").trim()}function gx(e){var s;return e.category!=="cli"||!od(e)||e.enabled===!1?!1:e.machineStatus?e.machineStatus==="detected":((s=e.lastDetection)==null?void 0:s.ok)===!0||e.installed===!0||!!e.detectedPath}function yx(e){var n;const s=new Set,r=[];for(const a of e||[]){if(!gx(a))continue;const o=od(a);if(!o||s.has(o))continue;s.add(o);const l=String(a.displayName||a.name||o),c=a.detectedPath||((n=a.lastDetection)==null?void 0:n.path)||null;r.push({type:o,label:l,icon:a.icon,statusLabel:c?`Detected at ${c}`:"Detected on this machine",detectedPath:c})}return r}function Kn(e){const s=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],r=new Set,n=[];for(const a of s){const o=typeof a=="string"?a.trim():"";!o||r.has(o)||(r.add(o),n.push(o))}return n}function oo(e,s){const r=new Set(s.map(n=>n.type));return Kn(e).filter(n=>r.has(n))}function vx(e){return e.map(s=>s.type)}function wx(e,s){const r=Kn(e),n=s.trim();return!n||r.includes(n)?r:[...r,n]}function jx(e,s){return Kn(e).filter(r=>r!==s)}function Xi(e,s,r){const n=Kn(e),a=n.indexOf(s);if(a<0)return n;const o=n.filter(c=>c!==s);if(r==="top")return[s,...o];if(r==="bottom")return[...o,s];const l=r==="up"?Math.max(0,a-1):Math.min(o.length,a+1);return o.splice(l,0,s),o}function Ji({direction:e}){return t.jsx("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e==="up"?t.jsx("polyline",{points:"18 15 12 9 6 15"}):t.jsx("polyline",{points:"6 9 12 15 18 9"})})}function Qi({value:e,availableProviders:s,onChange:r,disabled:n=!1,saveButton:a}){const[o,l]=i.useState(""),c=i.useMemo(()=>new Map(s.map(g=>[g.type,g])),[s]),d=i.useMemo(()=>oo(e,s),[e,s]),m=e.length-d.length,u=s.filter(g=>!d.includes(g.type)),h=()=>{o&&(r(wx(d,o)),l(""))};return t.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[t.jsx("div",{className:"flex flex-col gap-2",children:d.length===0?t.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:"No provider priority configured. Launches without an explicit CLI provider will fail closed."}):d.map((g,j)=>{const f=c.get(g);return t.jsxs("div",{className:"flex flex-col gap-2 rounded-md border border-border-subtle bg-bg-primary px-3 py-2 sm:flex-row sm:items-center sm:justify-between",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",j+1]}),(f==null?void 0:f.icon)&&t.jsx("span",{"aria-hidden":"true",children:f.icon}),t.jsx("span",{className:"font-mono text-[12px] text-text-primary",children:g}),t.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:"available"})]}),t.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:f?`${f.label} · ${f.statusLabel}`:g})]}),t.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move up",disabled:n||j===0,title:"Move up",onClick:()=>r(Xi(d,g,"up")),children:t.jsx(Ji,{direction:"up"})}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move down",disabled:n||j===d.length-1,title:"Move down",onClick:()=>r(Xi(d,g,"down")),children:t.jsx(Ji,{direction:"down"})}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:n,onClick:()=>r(jx(d,g)),children:"Remove"})]})]},g)})}),t.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[t.jsxs("label",{className:"flex-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:"Add available CLI provider"}),t.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:o,onChange:g=>l(g.target.value),disabled:n||u.length===0,children:[t.jsx("option",{value:"",children:u.length?"Select provider…":"No additional detected CLI providers"}),u.map(g=>t.jsxs("option",{value:g.type,children:[g.label," (",g.type,")"]},g.type))]})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:n||!o,onClick:h,children:"Add provider"}),a]}),t.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Inventory is filtered to CLI providers detected on this machine. New launches use this order; existing running sessions may need restart.",m>0?` ${m} provider${m===1?"":"s"} from the saved policy are not detected now and will be omitted when saved.`:""]})]})}function kx(e){const s=e.split(":");return s.length>=3&&(s[1]==="ide"||s[1]==="cli"||s[1]==="acp")?{daemonId:s[0],targetSessionId:s.slice(2).join(":")||void 0}:{daemonId:e}}function id(e,s){const r=kx(e);return{daemonId:r.daemonId,payload:{...s,...r.targetSessionId&&!s.targetSessionId?{targetSessionId:r.targetSessionId}:{}}}}const ld=[{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:"🏄"}],cd=[{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:"🧩"}],dd=[{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:"🟠"}],Nx=ld,Sx=cd,Cx=dd;function Qt(...e){return Uu(zu(e))}function Ix({icon:e,title:s,subtitle:r,badge:n,actions:a,className:o}){return t.jsxs("div",{className:Qt("dashboard-header",o),children:[t.jsxs("div",{children:[t.jsxs("h1",{className:"header-title flex items-center gap-2",children:[t.jsx("span",{className:"flex items-center text-lg",children:e})," ",s,n&&t.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&&t.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:r})]}),a&&t.jsx("div",{className:"flex gap-2",children:a})]})}function gr({icon:e,title:s,subtitle:r,badge:n,actions:a,widthClassName:o="max-w-6xl",contentClassName:l,children:c}){return t.jsxs("div",{className:"flex flex-col h-full",children:[t.jsx(Ix,{icon:e,title:s,subtitle:r,badge:n,actions:a}),t.jsx("div",{className:"page-content",children:t.jsx("div",{className:Qt("mx-auto flex w-full flex-col gap-4",o,l),children:c})})]})}const io="adhdev:themechange";function Tx(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function _s(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Ps(e){return e==="system"?Tx():e}function ud(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function cn(e,s){typeof window>"u"||window.dispatchEvent(new CustomEvent(io,{detail:{preference:e,theme:s}}))}function Ax(){const e=_s(),s=Ps(e);ud(s),cn(e,s)}function qo(){const[e,s]=i.useState(_s),[r,n]=i.useState(()=>Ps(_s()));i.useEffect(()=>{ud(r)},[r]),i.useEffect(()=>{const l=window.matchMedia("(prefers-color-scheme: light)"),c=d=>{if(e==="system"){const m=d.matches?"light":"dark";n(m),cn("system",m)}};return l.addEventListener("change",c),()=>l.removeEventListener("change",c)},[e]),i.useEffect(()=>{const l=d=>{const m=d.detail||{},u=m.preference,h=m.theme;s(u==="dark"||u==="light"||u==="system"?u:_s()),n(h==="dark"||h==="light"?h:Ps(_s()))},c=d=>{if(d.key!=="theme")return;const m=_s(),u=Ps(m);s(m),n(u)};return window.addEventListener(io,l),window.addEventListener("storage",c),()=>{window.removeEventListener(io,l),window.removeEventListener("storage",c)}},[]);const a=i.useCallback(l=>{const c=Ps(l);s(l),n(c);try{localStorage.setItem("theme",l)}catch{}cn(l,c)},[]),o=i.useCallback(()=>{s(l=>{const c=l==="dark"?"light":l==="light"?"system":"dark",d=Ps(c);n(d);try{localStorage.setItem("theme",c)}catch{}return cn(c,d),c})},[]);return{theme:r,preference:e,setPreference:a,cycleTheme:o,isDark:r==="dark"}}const Zi={dark:"Dark",light:"Light",system:"System"};function Mx({collapsed:e}){const{preference:s,cycleTheme:r}=qo(),n=s==="dark"?t.jsx(Om,{size:16}):s==="light"?t.jsx(Bm,{size:16}):t.jsx(Fm,{size:16});return t.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:r,title:`Theme: ${Zi[s]} (click to cycle)`,children:[t.jsx("span",{className:"nav-icon",children:n}),!e&&t.jsx("span",{className:"text-xs",children:Zi[s]})]})}function ca(e,s){return e?typeof e=="function"?e(s):e:null}function Lx({children:e,brand:s,navItems:r,sidebarSections:n=[],footerItems:a=[],footerInfo:o,footerActions:l,preMainContent:c,collapsedStorageKey:d="sidebar-collapsed"}){const[m,u]=i.useState(!1),[h,g]=i.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),j=()=>u(!0),f=()=>u(!1),p=()=>{g(A=>{const N=!A;try{localStorage.setItem(d,N?"1":"0")}catch{}return N})},b=i.useMemo(()=>({collapsed:h,mobileMenuOpen:m,openMobileMenu:j,closeMobileMenu:f,toggleCollapsed:p}),[h,m]),y=A=>`nav-item${A.active?" active":""} cursor-pointer ${h?"justify-center py-2.5 px-0":""}${A.className?` ${A.className}`:""}`,x=A=>t.jsxs("div",{className:y(A),id:`nav-${A.id}`,onClick:()=>{A.onSelect(),f()},title:h?A.title??(typeof A.label=="string"?A.label:void 0):A.title,children:[t.jsx("span",{className:"nav-icon",children:A.icon}),!h&&A.label]},A.id);return t.jsxs("div",{className:`app-layout${m?" mobile-menu-open":""}${h?" sidebar-collapsed":""}`,children:[t.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":"Open menu",onClick:j,children:[t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"}),t.jsx("span",{className:"mobile-menu-icon"})]}),m&&t.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":"Close menu",onClick:f,onKeyDown:A=>A.key==="Escape"&&f()}),t.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[t.jsxs("div",{className:"sidebar-header",children:[t.jsx("div",{className:`sidebar-logo ${h?"justify-center gap-0":""}`,children:ca(s,b)}),t.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":"Close menu",onClick:f,children:t.jsx(vt,{size:16})})]}),t.jsx("nav",{className:"sidebar-nav",children:r.map(x)}),n.map(A=>t.jsxs("div",{className:A.className??"border-t border-border-subtle pt-2 mt-2",children:[!h&&A.title?t.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:A.title}):null,A.items.map(x)]},A.key)),t.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(x),ca(o,b),t.jsx(Mx,{collapsed:h}),ca(l,b)]})]}),t.jsx("main",{className:"main-content relative",children:t.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function jt({title:e,icon:s,description:r,accentColor:n,className:a,children:o}){return t.jsxs("div",{className:Qt("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)&&t.jsxs("div",{className:"mb-4",children:[e&&t.jsxs("h3",{className:"text-base font-semibold text-text-primary",children:[s&&t.jsx("span",{className:"mr-1.5",children:s}),e]}),r&&t.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:r})]}),o]})}function Tn({icon:e,title:s,description:r,action:n,className:a}){return t.jsxs("div",{className:Qt("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[t.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),t.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:s}),t.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:r}),n]})}const Rx={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"},_x={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function $s({variant:e,children:s,onDismiss:r,className:n}){return t.jsxs("div",{className:Qt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Rx[e],n),children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{children:_x[e]}),t.jsx("span",{children:s})]}),r&&t.jsx("button",{onClick:r,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function Mt({label:e,hint:s,children:r,className:n}){return t.jsxs("div",{className:Qt("mb-5",n),children:[t.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),r,s&&t.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:s})]})}function da(e){const{className:s,...r}=e;return t.jsx("input",{...r,className:Qt("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",s)})}const Px={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"},Dx={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Ex({status:e,label:s,className:r}){const n=s||e;return t.jsxs("span",{className:Qt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Px[e],r),children:[t.jsx("span",{className:Qt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Dx[e])}),n]})}function ps({label:e,description:s,checked:r,disabled:n,onChange:a,extra:o}){return t.jsxs("div",{className:`flex justify-between items-center ${n?"opacity-60":""}`,children:[t.jsxs("div",{className:"pr-4",children:[t.jsx("div",{className:"font-medium text-sm",children:e}),t.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:s})]}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[o,t.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:[t.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))"}}),t.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 $x({onPrefChange:e}){const[s,r]=Qp(),[n,a]=i.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);i.useEffect(()=>{const l=()=>{if(typeof window>"u"||!("Notification"in window)){a("unsupported");return}a(Notification.permission)};return l(),window.addEventListener("focus",l),document.addEventListener("visibilitychange",l),()=>{window.removeEventListener("focus",l),document.removeEventListener("visibilitychange",l)}},[]);const o=(l,c)=>{r({[l]:c}),e==null||e(l,c)};return t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(ps,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Dn,{size:15})," Notifications"]}),description:"Master toggle for all alerts",checked:s.globalEnabled,onChange:l=>o("globalEnabled",l)}),s.globalEnabled&&t.jsx("div",{className:"border-t border-border-subtle my-0.5"}),s.globalEnabled&&t.jsx(ps,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(At,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:s.browserNotifications,onChange:l=>o("browserNotifications",l)}),s.globalEnabled&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.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"&&t.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-amber-300",children:[t.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),t.jsx("button",{onClick:()=>{Sc().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"&&t.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"&&t.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."})]}),s.globalEnabled&&s.browserNotifications&&t.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[t.jsx(ps,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Km,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:s.completionAlert,onChange:l=>o("completionAlert",l)}),t.jsx(ps,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Wm,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:s.approvalAlert,onChange:l=>o("approvalAlert",l)}),t.jsx(ps,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Hs,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:s.disconnectAlert,onChange:l=>o("disconnectAlert",l)})]}),!s.globalEnabled&&t.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 s=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/);return s?[Number(s[1]),Number(s[2]),Number(s[3])]:null}function Bx(e,s){const r=An(e),n=An(s);if(!r||!n)return e.localeCompare(s);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 md(e,s){const r=e.version||null;return e.versionMismatch===!0?!0:!r||!s?!1:r!==s}function yr(e,s){if(e.versionUpdateRequired===!0)return!0;const r=e.version||null;if(!r||!s||r===s||Bx(r,s)>=0)return!1;const n=An(r),a=An(s);return!n||!a?!1:n[0]!==a[0]||n[1]!==a[1]}function Ox(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function ua(e,s){return e instanceof Error?e.message:s}function Fx({ides:e,emptyMessage:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){const o=e.filter(l=>l.type==="adhdev-daemon");return o.length===0?t.jsx(Tn,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:"No machines connected",description:s||"Install ADHDev on a machine and sign in to connect it here."}):t.jsx("div",{className:"flex flex-col gap-2",children:o.map(l=>t.jsx(Wx,{ide:l,allIdes:e,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a},l.id))})}function el({title:e,message:s,confirmLabel:r,confirmColor:n,onConfirm:a,onCancel:o}){const l=n==="red"?"bg-red-500/20 text-red-400 border-red-500/30 hover:bg-red-500/30":"";return kr.createPortal(t.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:9999},onClick:o,children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:c=>c.stopPropagation(),children:[t.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),t.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:s}),t.jsxs("div",{className:"flex gap-2 justify-end",children:[t.jsx("button",{onClick:o,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:"Cancel"}),t.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${l}`,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 Kx(e){const s=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),n=[...Nx,...Sx,...Cx].find(a=>a.id===s||s.includes(a.id)||a.id.includes(s));return n?{icon:n.icon,name:n.name}:{icon:"📝",name:e}}function Wx({ide:e,allIdes:s,sendDaemonCommand:r,onDisconnect:n,onRevokeToken:a}){var W,D;const[o,l]=i.useState("idle"),[c,d]=i.useState(""),[m,u]=i.useState(null),[h,g]=i.useState("idle"),[j,f]=i.useState(""),p=e.version||null,b=((W=e.machine)==null?void 0:W.platform)||((D=e.system)==null?void 0:D.platform)||"",y=Tt(e,{fallbackId:e.id}),x=b==="win32"?"🪟":b==="darwin"?"🍎":"🐧",A=s.filter(I=>I.daemonId===e.id&&I.transport==="cdp-page"),N=s.filter(I=>I.daemonId===e.id&&I.transport==="pty"),v=s.filter(I=>I.daemonId===e.id&&I.transport==="acp"),C=e.p2p,M=async()=>{if(r){l("upgrading"),d("Starting upgrade...");try{const I=Ox(await r(e.id,"daemon_upgrade",{}));I.alreadyLatest?(l("done"),d(`Already on v${I.version||"latest"}.`)):I.upgraded||I.success?(l("done"),d(`Upgrade to v${I.version||"latest"} started. Daemon is restarting...`)):(l("error"),d(I.error||"Upgrade failed"))}catch(I){l("error"),d(ua(I,"Connection lost during upgrade"))}}},w=async()=>{if(u(null),!!n){g("loading");try{await n(e.id),g("done"),f("Machine disconnected.")}catch(I){g("error"),f(ua(I,"Failed to disconnect"))}}},k=async()=>{if(u(null),!!a){g("loading");try{await a(e.id),g("done"),f("Token revoked. Restart ADHDev on that machine to reconnect.")}catch(I){g("error"),f(ua(I,"Failed to revoke token"))}}},F="0.9.81",_=md(e,F),S=yr(e,F),H=A.length+N.length+v.length;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("span",{className:"text-xl",children:x}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-sm",children:y}),t.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[t.jsxs("span",{children:[e.id.substring(0,12),"…"]}),p&&t.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,!_&&" ✓"]})]})]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[r&&_&&t.jsx("button",{onClick:M,disabled:o==="upgrading"||o==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${F}`,children:o==="upgrading"?t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx("span",{className:"animate-spin",children:"⟳"})," Upgrading..."]}):o==="done"?"✓ Updated":`${S?"↑ Update now":`↑ Update${` to v${F}`}`}`}),n&&t.jsx("button",{onClick:()=>u("disconnect"),disabled:h==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:"Disconnect"}),a&&t.jsx("button",{onClick:()=>u("revoke"),disabled:h==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:"Remove"}),t.jsx(Ex,{status:e.status==="online"?"online":"error"})]})]}),t.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[C&&t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${C.state==="connected"?"bg-green-400":"bg-text-muted/30"} ${C.state==="connecting"||C.state==="new"?"animate-pulse":""}`,style:C.state==="connecting"||C.state==="new"?{background:"var(--status-warning)"}:void 0}),t.jsxs("span",{className:"text-text-muted",children:["P2P ",C.state==="connected"?"connected":C.state==="connecting"||C.state==="new"?"connecting...":C.state||"off"]}),C.peers!==void 0&&C.peers>0&&t.jsxs("span",{className:"text-text-muted/60",children:["(",C.peers," peer",C.peers!==1?"s":"",")"]})]}),C&&H>0&&t.jsx("span",{className:"text-border-subtle",children:"·"}),H>0?t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[A.map(I=>{const T=Kx(I.type),K=I.cdpConnected;return t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:T.icon}),t.jsx("span",{children:T.name}),K!==void 0&&t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${K?"bg-green-400":"animate-pulse"}`,style:K?void 0:{background:"var(--status-warning)"},title:K?"CDP connected":"CDP connecting..."})]},I.id)}),N.map(I=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"⌨️"}),t.jsx("span",{children:I.cliName||"CLI"})]},I.id)),v.map(I=>t.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[t.jsx("span",{children:"🔗"}),t.jsx("span",{children:I.cliName||"ACP"})]},I.id))]}):t.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:"No IDEs connected"})]}),(c||j)&&t.jsx("div",{className:`text-xs mt-2 px-1 ${o==="error"||h==="error"?"text-red-400":o==="done"||h==="done"?"text-green-400":"text-text-muted"}`,children:j||c})]}),m==="disconnect"&&t.jsx(el,{title:"🔌 Disconnect Machine",message:`Disconnect "${y}" from ADHDev?
|
|
43
|
-
|
|
44
|
-
This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
|
|
45
|
-
|
|
46
|
-
Use this if you want to temporarily stop remote control.`,confirmLabel:"Disconnect",confirmColor:"amber",onConfirm:w,onCancel:()=>u(null)}),m==="revoke"&&t.jsx(el,{title:"⚠️ Remove Machine",message:`Remove "${y}" from your dashboard?
|
|
47
|
-
|
|
48
|
-
This will:
|
|
49
|
-
• Immediately disconnect the machine
|
|
50
|
-
• Delete the machine registration
|
|
51
|
-
• Require restarting ADHDev on that machine
|
|
52
|
-
|
|
53
|
-
Use this if you want to permanently remove a machine.`,confirmLabel:"Remove Machine",confirmColor:"red",onConfirm:k,onCancel:()=>u(null)})]})}const Hx=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Ux(){const{preference:e,setPreference:s}=qo();return t.jsx("div",{className:"flex gap-2",children:Hx.map(r=>t.jsxs("button",{onClick:()=>s(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:[t.jsx("span",{children:r.icon}),r.label]},r.id))})}function zx(e){const s=e.trim();return/^#[0-9a-fA-F]{6}$/.test(s)?s:/^#[0-9a-fA-F]{3}$/.test(s)?`#${s[1]}${s[1]}${s[2]}${s[2]}${s[3]}${s[3]}`:null}function Vx(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function ma(e){const s=e/255;return s<=.04045?s/12.92:((s+.055)/1.055)**2.4}function tl(e){const{r:s,g:r,b:n}=Vx(e);return .2126*ma(s)+.7152*ma(r)+.0722*ma(n)}function sl(e,s){const r=tl(e),n=tl(s),a=Math.max(r,n),o=Math.min(r,n);return(a+.05)/(o+.05)}function pd(e){const s=zx(e);if(!s)return"#111827";const r="#111827",n="#ffffff";return sl(s,r)>=sl(s,n)?r:n}const lo={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},co={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},Gx=[{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"}}}],fd="adhdev-chat-theme",hd="adhdev-chat-theme-custom";function dn(){if(typeof window>"u")return"ember";try{return localStorage.getItem(fd)||"ember"}catch{return"ember"}}function $t(e){try{const s=localStorage.getItem(hd);if(s){const r=JSON.parse(s);return{...e==="dark"?lo:co,...r[e]}}}catch{}return e==="dark"?lo:co}function Gr(e,s){try{localStorage.setItem(hd,JSON.stringify({dark:e,light:s}))}catch{}}function Rt(e,s){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}, ${s})`}function Mn(e,s){const r=Math.min(255,parseInt(e.slice(1,3),16)+s),n=Math.min(255,parseInt(e.slice(3,5),16)+s),a=Math.min(255,parseInt(e.slice(5,7),16)+s);return`#${r.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const qx={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function vr(e,s){var a;const r=(a=qx[e])==null?void 0:a[s];if(!r)return;const n=document.documentElement;n.style.setProperty("--accent-primary",r),n.style.setProperty("--accent-primary-light",Mn(r,24)),n.style.setProperty("--accent-on-primary",pd(r)),n.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${r}, ${Mn(r,18)})`),n.style.setProperty("--border-accent",Rt(r,.35)),n.style.setProperty("--nav-active-bg",Rt(r,.1)),n.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${r}, 0 0 12px ${Rt(r,.06)}`)}function ys(e){const s=document.documentElement;s.style.setProperty("--bg-primary",e.bgPrimary),s.style.setProperty("--bg-secondary",e.bgSecondary),s.style.setProperty("--bg-card",Rt(e.surfacePrimary,.92)),s.style.setProperty("--surface-primary",e.surfacePrimary),s.style.setProperty("--surface-secondary",e.bgSecondary),s.style.setProperty("--bg-glass",Rt(e.borderSubtle,.15)),s.style.setProperty("--bg-glass-hover",Rt(e.borderSubtle,.25)),s.style.setProperty("--text-primary",e.textPrimary),s.style.setProperty("--text-secondary",e.textSecondary),s.style.setProperty("--text-muted",e.textMuted),s.style.setProperty("--border-subtle",Rt(e.borderSubtle,.5)),s.style.setProperty("--border-default",Rt(e.borderDefault,.5)),s.style.setProperty("--accent-primary",e.accentColor),s.style.setProperty("--accent-primary-light",Mn(e.accentColor,30)),s.style.setProperty("--accent-on-primary",pd(e.accentColor)),s.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Mn(e.accentColor,40)})`),s.style.setProperty("--border-accent",Rt(e.accentColor,.35)),s.style.setProperty("--nav-active-bg",Rt(e.accentColor,.1)),s.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Rt(e.accentColor,.06)}`),s.style.setProperty("--chat-user-bg",e.userBubble),s.style.setProperty("--chat-user-color",e.userText),s.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),s.style.setProperty("--chat-assistant-bg",e.assistantBubble),s.style.setProperty("--chat-assistant-color",e.assistantText),s.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),s.style.setProperty("--chat-assistant-border",`1px solid ${Rt(e.accentColor,.12)}`),s.style.setProperty("--chat-container-bg",e.containerBg),s.style.setProperty("--dashboard-pane-bg",e.containerBg),s.style.setProperty("--chat-thought-accent",e.accentColor),s.style.setProperty("--chat-tool-accent",e.accentColor),s.style.setProperty("--chat-action-color",e.accentColor),s.style.setProperty("--chat-send-bg",e.sendButton),s.style.setProperty("--chat-input-border",e.inputBorder)}function Yo(){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 Yx(e){try{localStorage.setItem(fd,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=vs()?"dark":"light";ys($t(s))}else Yo(),vr(e,vs()?"dark":"light")}function Xx(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=dn();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const s=vs()?"dark":"light";ys($t(s))}else Yo(),vr(e,vs()?"dark":"light")}function vs(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function St({label:e,value:s,onChange:r}){return t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[t.jsx("input",{type:"color",value:s,onChange:n=>r(n.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),t.jsx("input",{type:"text",value:s,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 ir({title:e,children:s}){return t.jsxs("div",{style:{marginBottom:14},children:[t.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}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:s})]})}function Jx({dark:e,onColorsChange:s}){const r=e?"dark":"light",[n,a]=i.useState(()=>$t(r));i.useEffect(()=>{a($t(r))},[r]);const o=i.useCallback((l,c)=>{a(d=>{const m={...d,[l]:c},h=$t(r==="dark"?"light":"dark");return r==="dark"?Gr(m,h):Gr(h,m),ys(m),s(m),m})},[r,s]);return t.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[t.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",t.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"]})]}),t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[t.jsxs("div",{children:[t.jsxs(ir,{title:"App Background",children:[t.jsx(St,{label:"Background",value:n.bgPrimary,onChange:l=>o("bgPrimary",l)}),t.jsx(St,{label:"Surface",value:n.bgSecondary,onChange:l=>o("bgSecondary",l)}),t.jsx(St,{label:"Card",value:n.surfacePrimary,onChange:l=>o("surfacePrimary",l)})]}),t.jsxs(ir,{title:"App Text",children:[t.jsx(St,{label:"Primary",value:n.textPrimary,onChange:l=>o("textPrimary",l)}),t.jsx(St,{label:"Secondary",value:n.textSecondary,onChange:l=>o("textSecondary",l)}),t.jsx(St,{label:"Muted",value:n.textMuted,onChange:l=>o("textMuted",l)})]}),t.jsxs(ir,{title:"Borders & Accent",children:[t.jsx(St,{label:"Border subtle",value:n.borderSubtle,onChange:l=>o("borderSubtle",l)}),t.jsx(St,{label:"Border default",value:n.borderDefault,onChange:l=>o("borderDefault",l)}),t.jsx(St,{label:"Accent",value:n.accentColor,onChange:l=>o("accentColor",l)})]})]}),t.jsxs("div",{children:[t.jsxs(ir,{title:"Chat Bubbles",children:[t.jsx(St,{label:"User bubble",value:n.userBubble,onChange:l=>o("userBubble",l)}),t.jsx(St,{label:"User text",value:n.userText,onChange:l=>o("userText",l)}),t.jsx(St,{label:"Agent bubble",value:n.assistantBubble,onChange:l=>o("assistantBubble",l)}),t.jsx(St,{label:"Agent text",value:n.assistantText,onChange:l=>o("assistantText",l)})]}),t.jsxs(ir,{title:"Chat Layout",children:[t.jsx(St,{label:"Chat BG",value:n.containerBg,onChange:l=>o("containerBg",l)}),t.jsx(St,{label:"Send button",value:n.sendButton,onChange:l=>o("sendButton",l)}),t.jsx(St,{label:"Input border",value:n.inputBorder,onChange:l=>o("inputBorder",l)}),t.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[t.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:"Bubble radius"}),t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[t.jsx("input",{type:"range",min:4,max:24,value:n.bubbleRadius,onChange:l=>o("bubbleRadius",Number(l.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),t.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[n.bubbleRadius,"px"]})]})]})]})]})]}),t.jsx("button",{onClick:()=>{const l=e?lo:co,d=$t(e?"light":"dark");e?Gr(l,d):Gr(d,l),a(l),ys(l),s(l)},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 Qx(){const[e,s]=i.useState(dn),[r,n]=i.useState(!0),[a,o]=i.useState(()=>$t("dark"));i.useEffect(()=>{n(vs());const d=new MutationObserver(()=>{const h=vs();n(h);const g=dn();g==="custom"?ys($t(h?"dark":"light")):vr(g,h?"dark":"light")});d.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const m=window.matchMedia("(prefers-color-scheme: dark)"),u=()=>{const h=vs();n(h);const g=dn();g==="custom"?ys($t(h?"dark":"light")):vr(g,h?"dark":"light")};return m.addEventListener("change",u),()=>{d.disconnect(),m.removeEventListener("change",u)}},[]),i.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",e),e==="custom"?ys($t(r?"dark":"light")):(Yo(),vr(e,r?"dark":"light"))},[e,r]),i.useEffect(()=>{o($t(r?"dark":"light"))},[r]);const l=d=>{s(d),Yx(d)},c=[...Gx,{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 t.jsxs("div",{children:[t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:c.map(d=>{const m=e===d.id,u=r?d.preview.dark:d.preview.light,h=d.id==="honey"||d.id==="ember"?"#1a1a1a":d.id==="custom"?a.userText:"#fff";return t.jsxs("button",{onClick:()=>l(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:[t.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:u.containerBg},children:[t.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?"}),t.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:u.userBubble,color:h},children:"Fix the bug please"}),t.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! ✨"})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[m&&t.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:d.id==="custom"?"🎨 Custom":d.name}),t.jsx("div",{className:"text-[10px] text-text-muted",children:d.description})]})]})]},d.id)})}),e==="custom"&&t.jsx(Jx,{dark:r,onColorsChange:d=>o(d)})]})}const Xo="adhdev_mobileDashboardMode_v1",uo="adhdev:mobile-dashboard-mode-change";function Jo(){try{return localStorage.getItem(Xo)==="workspace"?"workspace":"chat"}catch{return"chat"}}function Zx(e){if(typeof window>"u")return()=>{};const s=a=>{e(a??Jo())},r=a=>{const o=a.detail;s(o)},n=a=>{a.key&&a.key!==Xo||s()};return window.addEventListener(uo,r),window.addEventListener("storage",n),()=>{window.removeEventListener(uo,r),window.removeEventListener("storage",n)}}function eb(e){try{localStorage.setItem(Xo,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(uo,{detail:e}))}function tb(){const[e,s]=i.useState(!0);return i.useEffect(()=>{s(Jo()==="chat")},[]),t.jsx(ps,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Jt,{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=>{s(r),eb(r?"chat":"workspace")},extra:t.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const pa=new Map,rl=new Map;function sb(e){if(!e||typeof e!="object")return null;const s=e,r=s.result&&typeof s.result=="object"?s.result:s,n=r.machine;return!n||typeof n!="object"?null:{machine:n,timestamp:typeof r.timestamp=="number"?r.timestamp:void 0}}function rb(e,s,r,n){return{...e||{},id:s,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 xd(){const{sendCommand:e}=wt(),{injectEntries:s,getIdes:r}=Nr();return i.useCallback(async(n,a)=>{if(!n)return;const o=(a==null?void 0:a.minFreshMs)??Zf,l=rl.get(n)||0;if(!(a!=null&&a.force)&&l>0&&Date.now()-l<o)return;const c=pa.get(n);if(c)return c;const d=(async()=>{const m=await e(n,"get_machine_runtime_stats"),u=sb(m);if(!u)return;const h=r().find(j=>j.id===n),g=rb(h,n,u.machine,u.timestamp||Date.now());s([g]),rl.set(n,Date.now())})().finally(()=>{pa.delete(n)});return pa.set(n,d),d},[r,s,e])}function nb(e,s,r){return{...e||{},id:s,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 ab(e,s){const{sendData:r}=wt(),{injectEntries:n,getIdes:a}=Nr(),o=Array.from(new Set(e.filter(Boolean))).join("|");i.useEffect(()=>{if(!(s!=null&&s.enabled)||!r)return;const l=o?o.split("|"):[];if(l.length===0)return;const c=l.map(d=>Xt.subscribe({sendData:r},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:s==null?void 0:s.intervalMs}},u=>{const h=a().find(j=>j.id===d),g=nb(h,d,u);n([g])}));return()=>{c.forEach(d=>d())}},[o,a,n,s==null?void 0:s.enabled,s==null?void 0:s.intervalMs,r])}function ob(e,s){const{sendData:r}=wt(),[n,a]=i.useState(null),[o,l]=i.useState(!1);return i.useEffect(()=>{if(!e){a(null),l(!1);return}if(!(s!=null&&s.enabled)||!r){l(!1);return}a(null),l(!0);let c=null;const d=Xt.subscribe({sendData:r},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(s==null?void 0:s.includeSessions)!==!1,...typeof(s==null?void 0:s.limit)=="number"?{limit:s.limit}:{},...typeof(s==null?void 0:s.intervalMs)=="number"?{intervalMs:s.intervalMs}:{}}},m=>{c&&(clearTimeout(c),c=null),a(m.diagnostics),l(!1)});return d.initialSendAccepted?c=setTimeout(()=>{l(!1)},rh):l(!1),()=>{c&&clearTimeout(c),d()}},[e,s==null?void 0:s.enabled,s==null?void 0:s.includeSessions,s==null?void 0:s.intervalMs,s==null?void 0:s.limit,r]),{diagnostics:n,loading:o,applyDiagnostics:a}}function ib(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function bd(e){const{sendData:s}=wt(),[r,n]=i.useState({});return i.useEffect(()=>{const a=ib(e);if(!a||!e.sessionId||!s){n({});return}const o=Xt.subscribe({sendData:s},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},l=>{n({status:l.status,modalMessage:l.modalMessage,modalButtons:l.modalButtons}),Ks.record({interactionId:l.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:l.status,modalButtonCount:Array.isArray(l.modalButtons)?l.modalButtons.length:0}})});return o.initialSendAccepted||n({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,s]),r}const gd="adhdev_hiddenTabs",yd="adhdev_autoHiddenMeshTabs";function lb(){try{const e=localStorage.getItem(gd);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function us(e){try{localStorage.setItem(gd,JSON.stringify([...e]))}catch{}}function cb(){try{const e=localStorage.getItem(yd);if(e)return new Set(JSON.parse(e))}catch{}return new Set}function nl(e){try{localStorage.setItem(yd,JSON.stringify([...e]))}catch{}}function fr(e){return Oo(e)}function Wn(e,s){return Fs(s).some(r=>e.has(r))}function db(e){var s,r,n;return((s=e.settings)==null?void 0:s.launchedByCoordinator)===!0&&typeof((r=e.settings)==null?void 0:r.meshNodeFor)=="string"&&e.settings.meshNodeFor.trim().length>0&&((n=e.settings)==null?void 0:n.spawnedSessionVisibility)==="hidden"}function ub(e,s,r=new Set){return e.filter(n=>{if(!db(n))return!1;const a=fr(n);return r.has(a)?!1:!Wn(s,n)})}function mb(){const[e,s]=i.useState(lb),[r,n]=i.useState(cb),a=i.useCallback(g=>{const j=fr(g);s(f=>{const p=new Set(f);return p.has(j)?p.delete(j):p.add(j),us(p),p})},[]),o=i.useCallback(g=>{const j=fr(g);s(f=>{if(f.has(j))return f;const p=new Set(f);return p.add(j),us(p),p})},[]),l=i.useCallback(g=>{const j=fr(g);s(f=>{if(f.has(j))return f;const p=new Set(f);return p.add(j),us(p),p}),n(f=>{if(f.has(j))return f;const p=new Set(f);return p.add(j),nl(p),p})},[]),c=i.useCallback(g=>{const j=fr(g);s(f=>{if(!f.has(j))return f;const p=new Set(f);return p.delete(j),us(p),p}),n(f=>{if(f.has(j))return f;const p=new Set(f);return p.add(j),nl(p),p})},[]),d=i.useCallback(()=>{s(g=>{if(g.size===0)return g;const j=new Set;return us(j),j})},[]),m=i.useCallback((g,j)=>{s(f=>{const p=new Set(f);for(const b of j)p.add(b);return us(p),p})},[]),u=i.useCallback((g,j)=>{s(f=>{const p=new Set(f);for(const b of j)p.delete(b);return us(p),p})},[]),h=i.useCallback(g=>Wn(e,g),[e]);return{hiddenTabs:e,autoHiddenTabs:r,toggleTarget:a,hideTarget:o,autoHideTarget:l,showTarget:c,showAllTabs:d,hideAllForDaemon:m,showAllForDaemon:u,isHidden:h}}function vd(e){return e instanceof Error?e.message:String(e||"")}function wd(e){const s=vd(e);return s.includes("P2P command timeout")||s.includes("P2P not connected")||s.includes("P2P channel not open")||s.includes("P2P not available")||s.includes("P2P data channel closed")||s.includes("P2P receiver stopped")}function jd(e){const s=vd(e);return s.includes("P2P command timeout")||s.includes("P2P data channel closed")||s.includes("P2P receiver stopped")}async function kd({conversation:e,mode:s,ides:r,sendDaemonCommand:n,setCliViewModeOverrides:a}){if(!e||!nt(e)||tt(e))return;const o=Js(e);if(o===s)return;const l=e.sessionId;l&&a(c=>({...c,[l]:s}));try{await n(As(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:zt(e),mode:s})}catch(c){const d=jd(c);l&&!d&&a(m=>{const u={...m};return o===Nd(r,l)?delete u[l]:u[l]=o,u}),wd(c)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",c instanceof Error?c.message:String(c)):console.error("Failed to switch CLI view mode:",c)}}function al(e,s){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=s[r];return!n||e.mode===n?e:{...e,mode:n}}function pb(e,s){if(!Array.isArray(e)||e.length===0||!s||Object.keys(s).length===0)return e;let r=!1;const n=e.map(a=>{const o=al(a,s),l=Array.isArray(a.childSessions)?a.childSessions.map(d=>al(d,s)):a.childSessions,c=l!==a.childSessions;return o!==a||c?(r=!0,{...o,...c?{childSessions:l}:{}}):a});return r?n:e}function Nd(e,s){if(!s)return null;for(const r of e){if(r.sessionId===s&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal";for(const n of r.childSessions||[])if(n.id===s&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal"}return null}function fb(e,s){if(!e||Object.keys(e).length===0)return e;let r=!1;const n={...e};for(const[a,o]of Object.entries(e))Nd(s,a)===o&&(delete n[a],r=!0);return r?n:e}function hb({visibleConversations:e,clearedTabs:s,setClearedTabs:r,setActionLogs:n}){i.useEffect(()=>{Sc()},[]);const a=i.useMemo(()=>e.map(o=>({id:o.tabKey,name:Jc(o),status:o.status,activeModal:o.modalMessage?{message:o.modalMessage,buttons:o.modalButtons}:null})),[e]);return sf(a),i.useEffect(()=>{if(Object.keys(s).length===0)return;const l=setTimeout(()=>{r(c=>{const d=Date.now(),m={};for(const[u,h]of Object.entries(c))d-h<5e3&&(m[u]=h);return Object.keys(m).length===Object.keys(c).length?c:m})},5500);return()=>clearTimeout(l)},[s,r]),i.useEffect(()=>{const o=setInterval(()=>{const l=Date.now()-3e5;n(c=>{const d=c.filter(m=>m.timestamp>l).slice(-100);return d.length===c.length?c:d})},6e4);return()=>clearInterval(o)},[n]),null}function ol(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const s=Date.parse(e);if(Number.isFinite(s))return s}return 0}function ws(e){const s=[...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=ol(s==null?void 0:s.receivedAt)||ol(s==null?void 0:s.timestamp)||0;return Math.max(r,n)}function mo(e,s=0){return ws(e)||e.lastUpdated||s||0}function Sd(e){return ws(e)||e.lastUpdated||0}function Cd(e,s,r=Sd){const n=r(s)-r(e);if(n!==0)return n;const a=(e.machineName||"").localeCompare(s.machineName||"");if(a!==0)return a;const o=e.displayPrimary.localeCompare(s.displayPrimary);if(o!==0)return o;const l=e.displaySecondary.localeCompare(s.displaySecondary);return l!==0?l:e.tabKey.localeCompare(s.tabKey)}function po(e){var r;const s=gt(e.status,{activeModal:(r=e.modalButtons)!=null&&r.length?{buttons:e.modalButtons}:null});return s==="generating"||s==="waiting_approval"}function xb(e){var s;return e.messages.length===0&&!((s=e.modalButtons)!=null&&s.length)&&!po(e)&&!e.title.trim()}function bb(e){return e.length===0?null:[...e].sort((s,r)=>{const n=Number(po(r))-Number(po(s));if(n!==0)return n;const a=r.messages.length-s.messages.length;return a!==0?a:Cd(s,r)})[0]||null}function Bt(e,s){const r=e.filter(l=>l.routeId===s);if(r.length===0)return null;const n=r.find(l=>l.streamSource==="native")||null,a=r.filter(l=>l.streamSource==="agent-stream"),o=bb(a);return n?o&&xb(n)?o:n:o||r[0]||null}function gb(e){const s=String(e.daemonId||"").trim(),r=String(e.id||"").trim();return!s||r.startsWith(`${s}:`)?r:`${s}:${r}`}function yb(e){const s=e.filter(n=>n.type!=="adhdev-daemon"),r=new Map;for(const n of s){const a=gb(n),o=r.get(a);if(!o){r.set(a,n);continue}const l=(o.workspace?1:0)+(o.activeChat?1:0);((n.workspace?1:0)+(n.activeChat?1:0)>l||(n.timestamp||0)>(o.timestamp||0))&&r.set(a,n)}return Array.from(r.values())}function fa(e,s){if(e.length!==s.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==s[r])return!1;return!0}function vb(e){let s=2166136261;for(let r=0;r<e.length;r+=1)s^=e.charCodeAt(r),s=Math.imul(s,16777619)>>>0;return s.toString(16).padStart(8,"0")}function il(e){if(!e)return"";const s=Array.isArray(e.messages)?e.messages:[],r=s[s.length-1],n=r?vb(Ws(r.content)):"";return[e.id||"",e.title||"",e.status||"",s.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 wb(e){const s=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||""),il(e.activeChat),...s.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||""),il(r.activeChat)].join(":"))].join("|")}function jb(e,s){const r=Date.now();return e.map(n=>{const a=s[n.tabKey];return a&&r-a<5e3?{...n,messages:[],title:""}:n})}function kb(e,s){const r=new Map;for(const n of e){const a=s.get(n.routeId)||n;for(const o of Fs({routeId:n.routeId}))r.set(o,a);for(const o of Fs({providerSessionId:n.providerSessionId,sessionId:n.sessionId}))r.set(o,n.streamSource==="native"?a:n);for(const o of Fs({tabKey:n.tabKey}))r.set(o,n)}return r}function Nb(e){return[...e.messages].reverse().find(s=>!(s!=null&&s._localId))||e.messages[e.messages.length-1]}function Sb(e){const s=Nb(e);if(!s)return`empty:${e.messages.length}`;if(s.id)return`id:${String(s.id)}`;if(s._localId)return`local:${String(s._localId)}`;const r=String(s.role||""),n=Ws(s.content).slice(0,240);return`${e.messages.length}:${r}:${n}`}function Cb({ides:e,connectionStates:s,clearedTabs:r,hiddenTabs:n}){const a=i.useMemo(()=>yb(e),[e]),o=i.useMemo(()=>nd(e),[e]),l=i.useRef([]),c=i.useRef([]),d=i.useRef([]),m=i.useRef(new Map),u=i.useRef(new Map),h=i.useMemo(()=>{const N=new Map,v=[];for(const k of a){const{connectionState:F="new",machineName:_}=ad(k,{machineNames:o,connectionStates:s,defaultConnectionState:"new"}),S=wb(k),H=m.current.get(k.id);if(H&&H.ide===k&&H.sourceSignature===S&&H.connectionState===F&&H.machineName===_){N.set(k.id,H),v.push(...H.conversations);continue}const W=Go(k,{machineNames:o,connectionStates:s,defaultConnectionState:"new"}),D={ide:k,sourceSignature:S,connectionState:F,machineName:_,conversations:W};N.set(k.id,D),v.push(...W)}m.current=N;const C=new Map,M=k=>{const F=Sb(k),_=u.current.get(k.tabKey);if(_&&_.signature===F)return C.set(k.tabKey,_),_.timestamp;const S={signature:F,timestamp:Sd(k)||(_==null?void 0:_.timestamp)||0};return C.set(k.tabKey,S),S.timestamp},w=[...v].sort((k,F)=>Cd(k,F,M));return u.current=C,w},[a,s,o]),g=i.useMemo(()=>{const N=jb(h,r);return fa(l.current,N)?l.current:(l.current=N,N)},[h,r]),j=i.useMemo(()=>{const N=new Map,v=Array.from(new Set(g.map(C=>C.routeId)));for(const C of v){const M=Bt(g,C);M&&N.set(C,M)}return N},[g]),f=i.useMemo(()=>{const N=new Map;for(const v of g){const C=j.get(v.routeId),M=v.streamSource==="native"&&C?C:v;for(const w of Fs({providerSessionId:v.providerSessionId,sessionId:v.sessionId,tabKey:v.tabKey}))N.set(w,M)}return N},[g,j]),p=i.useMemo(()=>kb(g,j),[g,j]),b=i.useCallback(N=>{if(N)return f.get(N)},[f]),y=i.useCallback(N=>{if(N)return p.get(N)},[p]),x=i.useMemo(()=>{const N=g.filter(v=>!Wn(n,v));return fa(c.current,N)?c.current:(c.current=N,N)},[g,n]),A=i.useMemo(()=>{const N=x.map(v=>v.tabKey);return fa(d.current,N)?d.current:(d.current=N,N)},[x]);return{chatIdes:a,conversations:g,visibleConversations:x,visibleTabKeys:A,resolveConversationBySessionId:b,resolveConversationByTarget:y}}function Ib({isMobile:e,urlActiveTab:s,resolveConversationBySessionId:r,setSearchParams:n}){const a=i.useMemo(()=>{var c;return e||!s?null:((c=r(s))==null?void 0:c.tabKey)??null},[e,r,s]),o=i.useMemo(()=>{var c;return!e||!s?null:((c=r(s))==null?void 0:c.tabKey)??null},[e,r,s]),l=i.useCallback(()=>{s&&n(c=>{const d=new URLSearchParams(c);return d.delete("activeTab"),d},{replace:!0})},[n,s]);return{requestedDesktopTabKey:a,requestedMobileTabKey:o,consumeRequestedActiveTab:l}}function Tb({ides:e,sendDaemonCommand:s,setToasts:r,resolveConversationByTarget:n}){i.useEffect(()=>{ot.setIdes(e)},[e]),i.useEffect(()=>{ot.setResolveAction((a,o,l)=>{s(a,o,l).catch(()=>{})})},[s]),i.useEffect(()=>{const a=ot.onToast(o=>{r(c=>c.some(m=>m.message===o.message&&o.timestamp-m.timestamp<3e3)?c:[...c.slice(-4),{id:o.id,message:o.message,type:o.type,timestamp:o.timestamp,targetKey:o.targetKey,actions:o.actions}]);const l=o.duration||5e3;setTimeout(()=>r(c=>c.filter(d=>d.id!==o.id)),l)});return()=>{a()}},[r]),i.useEffect(()=>{const a=qc.on("status_event",o=>{ot.handleRawEvent(o,"ws")});return()=>{a()}},[]),i.useEffect(()=>{var o;const a=l=>{var p;const c=l.data;if((c==null?void 0:c.type)!=="notification_action"||typeof c.action!="string"||!c.action.startsWith("approval_")||!(c.daemonId||c.targetSessionId||c.targetKey))return;const d=c.targetSessionId||c.targetKey||c.daemonId,m=n(d),u=(m==null?void 0:m.routeId)||c.daemonId;if(!u)return;const h=Number(c.buttonIndex),g=c.button||((p=m==null?void 0:m.modalButtons)==null?void 0:p[h])||"Approve",j=String(g).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),f=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(j);s(u,"resolve_action",{action:f?"approve":"reject",button:g,...Number.isFinite(h)&&{buttonIndex:h},...(m==null?void 0:m.sessionId)&&{targetSessionId:m.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(b=>console.error("[SW Action] approval failed:",b))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",a),()=>{var l;return(l=navigator.serviceWorker)==null?void 0:l.removeEventListener("message",a)}},[n,s])}const Ab="adhdev_dashboardLayout_v1",Mb="adhdev_dashboardDockview_v1",Lb="adhdev_dashboardDockviewHiddenRestore_v1",lr={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Qo(e,s){try{const r=localStorage.getItem(e);return r?JSON.parse(r):s}catch{return s}}function Rb(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Id(e){return`${Ab}:${e}`}function _b(e){const s=Id(e);return Qo(s,null)}function Pb(e,s){try{const r=s.groupAssignments.length===0&&s.focusedGroup===0&&Object.keys(s.groupActiveTabIds).length===0&&Object.keys(s.groupTabOrders).length===0&&s.groupSizes.length===0,n=Id(e);if(r){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(s))}catch{}}function Td(e){return`${Mb}:${e}`}function Db(e){const s=Td(e);return Qo(s,null)}function Eb(e,s){try{const r=Td(e);if(!s){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Ad(e){return`${Lb}:${e}`}function $b(e){const s=Ad(e);return Qo(s,{})}function Bb(e,s){try{const r=Ad(e);if(Object.keys(s).length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(s))}catch{}}function Ob(){return{groupAssignments:[...lr.groupAssignments],focusedGroup:lr.focusedGroup,groupActiveTabIds:{...lr.groupActiveTabIds},groupTabOrders:{...lr.groupTabOrders},groupSizes:[...lr.groupSizes]}}function Fb(e,s){return e?e.length===s.length&&e.every((r,n)=>r===s[n]):s.length===0}function Kb(){const[e]=i.useState(()=>Rb(typeof window<"u"?window.innerWidth:1280)),[s,r]=i.useState(()=>new Map),[n,a]=i.useState(0),[o,l]=i.useState({}),[c,d]=i.useState({}),[m,u]=i.useState([]),[h,g]=i.useState(()=>typeof window<"u"&&window.innerWidth<768),[j,f]=i.useState(!1),p=i.useCallback(()=>{if(j)return;const k=_b(e)??Ob();r(new Map(k.groupAssignments)),a(k.focusedGroup),l(k.groupActiveTabIds),d(k.groupTabOrders),u(k.groupSizes),f(!0)},[j,e]);i.useEffect(()=>{j&&Pb(e,{groupAssignments:[...s.entries()],focusedGroup:n,groupActiveTabIds:o,groupTabOrders:c,groupSizes:m})},[j,e,s,n,o,c,m]),i.useEffect(()=>{const k=window.matchMedia("(max-width: 767px)"),F=_=>g(_.matches);return k.addEventListener("change",F),()=>k.removeEventListener("change",F)},[]);const b=i.useCallback(k=>{r(k)},[]),y=i.useCallback(k=>{a(k)},[]),x=i.useCallback(k=>{l(k)},[]),A=i.useCallback(k=>{d(k)},[]),N=i.useCallback(k=>{u(k)},[]),v=i.useCallback(k=>{y(k)},[y]),C=i.useCallback((k,F)=>{l(_=>(_[k]??null)===(F??null)?_:{..._,[k]:F})},[]),M=i.useCallback((k,F)=>{d(_=>{const S=_[k];return Fb(S,F)?_:{..._,[k]:F}})},[]),w=i.useCallback((k,F)=>{const _=F.get(k)??0;return C(_,k),v(_),_},[v,C]);return{layoutProfile:e,groupAssignments:s,updateGroupAssignments:b,focusedGroup:n,updateFocusedGroup:y,focusGroup:v,groupActiveTabIds:o,updateGroupActiveTabIds:x,setGroupActiveTab:C,groupTabOrders:c,updateGroupTabOrders:A,setGroupTabOrder:M,groupSizes:m,updateGroupSizes:N,isMobile:h,hasHydratedStoredLayout:j,hydrateStoredLayout:p,focusConversationTab:w}}function Wb(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0],n=Bo(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Hb({urlActiveTab:e,conversations:s,resolveConversationBySessionId:r,normalizedGroupAssignments:n,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:l,setSearchParams:c,historyModalOpen:d,activeConv:m,isRefreshingHistory:u,ides:h,handleRefreshHistory:g}){const j=i.useRef(!1),f=i.useRef(!1),p=i.useRef(null),b=i.useRef(!1);i.useEffect(()=>{if(!e||j.current||s.length===0)return;if(!a){o();return}const y=r(e);y&&(l(y.tabKey,n),j.current=!0,f.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),c(x=>{const A=new URLSearchParams(x);return A.delete("activeTab"),A},{replace:!0}))},[e,s,r,n,a,o,l,c]),i.useEffect(()=>{if(!(f.current||a)&&s.length!==0){if(!e){o(),f.current=!0;return}if(j.current){f.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(f.current||a)&&(o(),f.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,s.length,a,o]),i.useEffect(()=>{if(!d){b.current=!1;return}if(!m||b.current||u)return;const y=h.find(x=>x.id===m.routeId);y&&(!y.chats||y.chats.length===0||Wb(y.chats,m))&&(b.current=!0,g())},[d,m,u,h,g])}function ha(e,s){if(!Array.isArray(e)||e.length!==1||!s)return!1;const r=e[0];if((r==null?void 0:r.active)===!0)return!0;const n=Bo(s);return typeof(r==null?void 0:r.id)=="string"&&n.includes(r.id)}function Md({sendDaemonCommand:e,activeConv:s,chats:r,updateRouteChats:n,setToasts:a,setClearedTabs:o}){const[l,c]=i.useState(!1),[d,m]=i.useState(!1),u=i.useCallback(async f=>{try{await e("standalone","launch_ide",{ideType:f,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),h=i.useCallback(async(f,p)=>{try{const b=f||(s==null?void 0:s.daemonId)||"",y=await e(b,"switch_chat",{id:p,sessionId:p,...hs(s)}),x=y==null?void 0:y.result;if((y==null?void 0:y.success)===!0||x==="switched"||x==="switched-by-title")return;x===!1||x==="not_found"?nr(a,"⚠️ Session tab not found — try refreshing history"):typeof x=="string"&&x.startsWith("error:")?nr(a,`⚠️ Switch error: ${x}`):nr(a,"⚠️ Session switch failed")}catch(b){console.error("Switch failed",b),nr(a,`❌ Switch failed: ${b.message||"connection error"}`)}},[s,e,a]),g=i.useCallback(async()=>{if(!(!s||l)){c(!0);try{const f=zs(s);await e(f,"new_chat",{...hs(s)}),o(p=>({...p,[s.tabKey]:Date.now()}))}catch(f){console.error("New chat failed",f)}finally{c(!1)}}},[s,l,e,o]),j=i.useCallback(async()=>{var f,p;if(!(!s||d)){m(!0);try{const b=zs(s),y=async()=>e(b,"list_chats",{forceExpand:!0,...hs(s)});let x=await y(),A=(x==null?void 0:x.chats)||((f=x==null?void 0:x.result)==null?void 0:f.chats);ha(A,s)&&(await new Promise(N=>setTimeout(N,450)),x=await y(),A=(x==null?void 0:x.chats)||((p=x==null?void 0:x.result)==null?void 0:p.chats)),x!=null&&x.success&&Array.isArray(A)&&(n(s.routeId,A),ha(A,s)&&!ha(r,s)&&nr(a,"⚠️ History dialog did not fully open — try once more"))}catch(b){console.error("Refresh history failed",b)}finally{m(!1)}}},[s,r,d,e,n,a]);return{isCreatingChat:l,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:h,handleNewChat:g,handleRefreshHistory:j}}function Ub(e,s){if(e.size!==s.size)return!1;for(const[r,n]of e)if(s.get(r)!==n)return!1;return!0}function zb(e,s){return e.length!==s.length?!1:e.every((r,n)=>r===s[n])}function ll(e,s){const r=Object.keys(e),n=Object.keys(s);return r.length!==n.length?!1:r.every(a=>s[Number(a)]===e[Number(a)])}function qr(e,s){const r=new Set(s),n=s.length>0?[0]:[];for(const[l,c]of e)!r.has(l)||c<=0||n.includes(c)||n.push(c);n.sort((l,c)=>l-c);const a={};n.forEach((l,c)=>{a[l]=c}),n.length===0&&(a[0]=0);const o=new Map;for(const[l,c]of e){if(!r.has(l)||c<=0)continue;const d=a[c];typeof d=="number"&&d>0&&o.set(l,d)}return{assignments:o,groupCount:Math.max(1,n.length),mapping:a,usedGroups:n}}function cl(e,s){const r={};for(const[n,a]of Object.entries(e)){const o=s[Number(n)];typeof o=="number"&&(r[o]=a)}return r}function Vb(e,s,r){if(s.length===0)return 0;if(typeof r[e]=="number")return r[e];const n=[...s].reverse().find(a=>a<e)??s[0];return r[n]??0}function Gb(e,s,r){if(s.length<=1)return[];const n=s.map(l=>e[l]).filter(l=>Number.isFinite(l)),a=n.length===s.length?n:Array(r).fill(100/r),o=a.reduce((l,c)=>l+c,0);return o>0?a.map(l=>l/o*100):Array(r).fill(100/r)}function dl(e,s){const r={};for(const[n,a]of Object.entries(e)){const o=Number(n);r[o>=s?o+1:o]=a}return r}function ul(e){return Array(e).fill(100/e)}function qb({groupAssignments:e,updateGroupAssignments:s,updateFocusedGroup:r,updateGroupActiveTabIds:n,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:l,isMobile:c,visibleConversations:d,visibleTabKeys:m}){const u=i.useRef(null),h=i.useMemo(()=>qr(e,m),[e,m]),g=h.assignments,j=i.useMemo(()=>c?1:h.groupCount,[h.groupCount,c]),f=j>1,p=i.useCallback((v,C)=>{s(M=>{const w=new Map(qr(M,m).assignments);return C===0?w.delete(v):w.set(v,C),w}),n(M=>({...M,[C]:v})),r(C)},[s,m,n,r]),b=i.useCallback(v=>{s(C=>{const M=qr(C,m).assignments,w=new Map;for(const[k,F]of M)F!==v&&(F>v?w.set(k,F-1):w.set(k,F));return w}),l(C=>{if(C.length<=1)return[];const M=[...C];M.splice(v,1);const w=M.reduce((k,F)=>k+F,0);return w>0?M.map(k=>k/w*100):[]}),r(0)},[s,m,l,r]),y=i.useCallback((v,C)=>{C.preventDefault();const M=u.current;if(!M)return;const w=C.clientX,k=M.offsetWidth,F=o.length===j?[...o]:ul(j),_=H=>{const D=(H.clientX-w)/k*100,I=[...F];I[v]=Math.max(15,F[v]+D),I[v+1]=Math.max(15,F[v+1]-D),l(I)},S=()=>{document.removeEventListener("mousemove",_),document.removeEventListener("mouseup",S),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",S)},[o,j,l]),x=i.useCallback((v,C,M)=>{if(j>=4)return;const w=M==="left"?C:C+1;s(k=>{const F=qr(k,m).assignments,_=new Map;for(const S of d){const H=F.get(S.tabKey)??0,W=H>=w?H+1:H;W>0&&_.set(S.tabKey,W)}return w>0&&_.set(v,w),_}),l(k=>{const F=k.length===j?[...k]:ul(j),_=F[C]??100/j,S=Math.max(15,_/2),H=Math.max(15,_/2),W=[...F];W[C]=S,W.splice(w,0,H);const D=W.reduce((I,T)=>I+T,0);return W.map(I=>I/D*100)}),n(k=>{const F=dl(k,w);return F[w]=v,F}),a(k=>{const F=dl(k,w);return F[w]=[v],F}),r(w)},[j,s,m,d,l,n,a,r]);i.useEffect(()=>{Ub(e,g)||s(g)},[e,g,s]),i.useEffect(()=>{const{mapping:v,usedGroups:C}=h;n(M=>{const w=cl(M,v);return ll(M,w)?M:w}),a(M=>{const w=cl(M,v);return ll(M,w)?M:w}),r(M=>{const w=c?0:Vb(M,C,v);return M===w?M:w}),l(M=>{const w=c?[]:Gb(M,C,h.groupCount);return zb(M,w)?M:w})},[h,c,n,a,r,l]);const A=i.useMemo(()=>{const v=Array.from({length:j},()=>[]);for(const C of d){const M=g.get(C.tabKey)??0,w=Math.min(M,j-1);v[w].push(C)}return v},[d,g,j]),N=i.useCallback(()=>{s(new Map),r(0)},[s,r]);return{containerRef:u,normalizedGroupAssignments:g,numGroups:j,isSplitMode:f,groupedConvs:A,moveTabToGroup:p,closeGroup:b,handleResizeStart:y,splitTabRelative:x,clearAllSplits:N}}function xa(e){if(typeof e!="string")return null;const s=e.trim().toLowerCase();return s==="stable"||s==="latest"?"stable":s==="preview"||s==="next"?"preview":null}function Yb(e){if(typeof e!="string")return null;const s=e.trim().toLowerCase();return s==="latest"||s==="stable"?"latest":s==="next"||s==="preview"?"next":null}function Yr(e){if(typeof e!="string")return null;const s=e.trim();return s.length>0?s:null}function Zo(e){const s=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},r=xa(s.channel)||xa(e.updateChannel)||xa(e.releaseChannel)||void 0,n=Yb(s.npmTag)||(r==="preview"?"next":r==="stable"?"latest":void 0),a=Yr(s.targetVersion)||Yr(e.serverVersion)||void 0,o=Yr(s.minVersion)||void 0,l=Yr(s.updateCommand)||(r?`adhdev update --channel ${r}`:void 0);return{...r?{channel:r}:{},...n?{npmTag:n}:{},...a?{targetVersion:a}:{},...o?{minVersion:o}:{},...l?{updateCommand:l}:{}}}function Ds(e,s=null){return Zo(e).targetVersion||s}function Ld(e){return Zo(e).channel||null}function Rd(e){const s=Zo(e);return{...s.channel?{channel:s.channel}:{},...s.npmTag?{npmTag:s.npmTag}:{},...s.targetVersion?{targetVersion:s.targetVersion}:{},...Object.keys(s).length>0?{updatePolicy:s}:{}}}function Xb({ides:e,sendDaemonCommand:s}){const r="0.9.81",n=i.useMemo(()=>e.filter(h=>h.type!=="adhdev-daemon"?!1:md(h,Ds(h,r))).sort((h,g)=>Number(yr(g,Ds(g,r)))-Number(yr(h,Ds(h,r)))),[r,e]),a=i.useMemo(()=>n.some(h=>yr(h,Ds(h,r))),[r,n]),o=i.useMemo(()=>n.map(h=>Ds(h,r)).find(h=>typeof h=="string"&&h.trim().length>0)||r,[r,n]),[l,c]=i.useState(!1),[d,m]=i.useState({}),u=i.useCallback(async h=>{var j,f;const g=e.find(p=>p.id===h);if(g){m(p=>({...p,[h]:"upgrading"}));try{const p=await s(h,"daemon_upgrade",Rd(g));(j=p==null?void 0:p.result)!=null&&j.upgraded||(f=p==null?void 0:p.result)!=null&&f.success?m(b=>({...b,[h]:"done"})):m(b=>({...b,[h]:"error"}))}catch{m(p=>({...p,[h]:"error"}))}}},[e,s]);return{versionMismatchDaemons:n,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:l,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:u}}const _d=80;function un(e,s=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:s}function Jb(e){return{...e,createdAt:un(e.createdAt),updatedAt:un(e.updatedAt,e.createdAt),lastEventAt:un(e.lastEventAt,e.updatedAt||e.createdAt)}}function Qb(e){const s=Oo(e);return s==="unknown:"?e.id:s}function Zb(e){return[e.type,Kc(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function eg(e,s=_d){const r=new Map;for(const n of e){if(n.deletedAt)continue;const a=Qb(n),o=r.get(a);if(!o){r.set(a,n);continue}(n.updatedAt>o.updatedAt||n.updatedAt===o.updatedAt&&n.createdAt>o.createdAt)&&r.set(a,n)}return Array.from(r.values()).sort((n,a)=>{const o=a.updatedAt-n.updatedAt;return o!==0?o:a.createdAt-n.createdAt}).slice(0,Math.max(0,s))}function tg(e,s){const r=Date.now(),n=[];for(const a of e){const o=a.sessionId?s.get(a.sessionId):void 0;if(o!=null&&o.surfaceHidden)continue;const l=$n(a,s),c=l.inboxBucket==="needs_attention"?"needs_attention":l.inboxBucket==="task_complete"&&l.unread?"task_complete":null;if(!c)continue;const d=un(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,r),m=Zb({type:c,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(o==null?void 0:o.lastUpdated)||a.lastUpdated});n.push(Jb({id:m,dedupKey:m,type:c,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Lc(a),preview:Lf(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return eg(n)}function sg(e){return e.filter(s=>!s.readAt&&!s.deletedAt).length}function rg(e){const{conversations:s,liveSessionInboxState:r,maxItems:n=_d}=e,a=i.useMemo(()=>tg(s,r).slice(0,Math.max(0,n)),[s,r,n]),o=i.useMemo(()=>sg(a),[a]);return{notifications:a,unreadCount:o}}function ng({notifications:e,sendDaemonCommand:s}){const r=i.useCallback(o=>{const l=e.find(d=>d.id===o),c=Math.max(Date.now(),(l==null?void 0:l.updatedAt)||0);l!=null&&l.sessionId&&s(l.machineId||l.routeId,"mark_session_seen",{sessionId:l.sessionId,seenAt:c}).catch(()=>{})},[e,s]),n=i.useCallback(o=>{const l=e.find(c=>c.id===o);l!=null&&l.sessionId&&s(l.machineId||l.routeId,"mark_notification_unread",{sessionId:l.sessionId,notificationId:l.id}).catch(()=>{})},[e,s]),a=i.useCallback(o=>{const l=e.find(c=>c.id===o);l!=null&&l.sessionId&&s(l.machineId||l.routeId,"delete_notification",{sessionId:l.sessionId,notificationId:l.id}).catch(()=>{})},[e,s]);return{handleMarkDashboardNotificationRead:r,handleMarkDashboardNotificationUnread:n,handleDeleteDashboardNotification:a}}const ag=i.createContext(null);function Pd(){return i.useContext(ag)}function Hn(...e){const s=new Set,r=[],n=a=>{const o=typeof a=="string"?a.trim():"";if(!o)return;const l=o.toLowerCase();s.has(l)||(s.add(l),r.push(o))};for(const a of e){if(Array.isArray(a)){for(const o of a)n(o);continue}n(a)}return r}function og(e){const s=e.trim();if(!s)return null;if(s.startsWith("~"))return s;if(/^[A-Za-z]:$/.test(s))return`${s[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(s))return`${s[0].toUpperCase()}:${s.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(s))return`${s[0].toUpperCase()}:\\${s.slice(2).replace(/[\\/]+/g,"\\")}`;const r=s.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(r){const n=r[1].toUpperCase(),a=(r[2]||"").replace(/[\\/]+/g,"\\");return a?`${n}:\\${a}`:`${n}:\\`}return null}function Un(e,s=[]){if(e==="win32"){for(const r of s){if(typeof r!="string")continue;const n=og(r);if(n)return n}return"C:\\"}for(const r of s){const n=typeof r=="string"?r.trim():"";if(n)return n}return"~"}function ig(e){const s=e.replace(/[\\/]+$/,"");if(!s||s==="/"||/^[A-Za-z]:$/.test(s))return null;const r=s.includes("\\")?"\\":"/",n=s.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 lg(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function zn(e,s,r){const n=await e(s,"file_list_browse",{path:r}),a=lg(n);if(!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||(n==null?void 0:n.error)||"Could not browse folder");const o=typeof(a==null?void 0:a.path)=="string"?a.path:r,l=o.includes("\\")?"\\":"/",c=(m,u)=>/^[A-Za-z]:\\?$/.test(m)?`${m.replace(/\\?$/,"\\")}${u}`:m==="/"||m==="\\"?`${l}${u}`:`${m.replace(/[\\/]+$/,"")}${l}${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:c(o,m.name)})).sort((m,u)=>m.name.localeCompare(u.name)):[];return{path:o,directories:d}}function cg(e,s){const r={meshId:s.meshId||"",workspace:s.workspace||"",serverName:s.serverName||"adhdev-mesh",adhdevMcpCommand:s.adhdevMcpCommand||"adhdev-mcp"};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand)\s*\}\}/g,(n,a)=>r[a]||"")}function Dd(e,s={}){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:cg(r.template||"",{...s,serverName:r.serverName||"adhdev-mesh"})}}function dg(e){if(!e||typeof e!="object")return null;const s=e,r=typeof s.instructions=="string"?s.instructions:"",n=typeof s.template=="string"?s.template:"";return!r&&!n?null:{serverName:typeof s.serverName=="string"?s.serverName:void 0,configFormat:typeof s.configFormat=="string"?s.configFormat:void 0,configPathCommand:typeof s.configPathCommand=="string"?s.configPathCommand:void 0,requiresRestart:s.requiresRestart===!0,instructions:r||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:n}}function Vt(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Ed(e){return Rr(e)||e.tabKey||e.routeId||null}function $d(e){const s=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",r=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",n=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",a=e.conversations.find(o=>{if(n&&o.routeId!==n)return!1;const l=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey].map(c=>typeof c=="string"?c.trim():"").filter(Boolean);return!!(s&&l.includes(s)||r&&l.includes(r)||n&&o.routeId===n)});if(a!=null&&a.tabKey)return a.tabKey;if(n){const o=Bt(e.conversations,n)||e.conversations.find(l=>l.routeId===n);if(o!=null&&o.tabKey)return o.tabKey}return s||r||n||null}function rs(e){return String(e||"").trim()}function Bd(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function Ln(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ug(e,s){return!e||!s?!1:e===s||e.endsWith(`/${s}`)||s.endsWith(`/${e}`)}function mg(e,s){const r=rs(e.providerSessionId),n=rs(e.targetSessionId),a=s.find(o=>{const l=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(rs).filter(Boolean);return!!(r&&l.includes(r)||n&&l.includes(n))});return a?a.tabKey:n||r||null}function pg(e,s,r){if(s.event!=="agent:generating_completed")return null;const n=Bd(s.daemonId);if(n&&n!==e.machineId)return null;const a=rs(s.providerType);if(e.providerType&&a!==e.providerType)return null;const o=rs(e.resumeSessionId),l=rs(e.launchedSessionId),c=rs(s.providerSessionId),d=rs(s.targetSessionId);if(o&&o!==c&&o!==d||l&&l!==c&&l!==d)return null;const m=Ln(e.workspacePath);if(m){const u=Ln(s.workspaceName);if(u&&!ug(u,m))return null}return mg(s,r)}function ml(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function fg({ides:e,conversations:s,onOpenSession:r}){const[n,a]=i.useState(null),o=i.useRef(null),l=i.useCallback(()=>{o.current=null,a(null)},[]),c=i.useCallback(d=>{o.current=d,a(d)},[]);return i.useEffect(()=>{if(!n)return;const d=Ln(n.workspacePath),m=e.find(h=>{var b,y,x,A;if(!h||h.type==="adhdev-daemon"||Bd(h.daemonId||h.id)!==n.machineId||(Cr(h)?"cli":Bs(h)?"acp":"ide")!==n.kind)return!1;const f=String(h.agentType||h.type||"");if(n.providerType&&f!==n.providerType)return!1;if(n.resumeSessionId)return String(h.providerSessionId||"")===n.resumeSessionId;if(n.launchedSessionId){const N=String(n.launchedSessionId||"");return[h.providerSessionId,h.sessionId,h.instanceId,h.id].map(C=>String(C||"")).filter(Boolean).includes(N)}if(d){const N=Ln(h.workspace||h.runtimeWorkspaceLabel);return N?N===d:!1}return Number(h.lastUpdated||h._lastUpdate||h.timestamp||((A=(x=(y=(b=h.activeChat)==null?void 0:b.messages)==null?void 0:y.at)==null?void 0:x.call(y,-1))==null?void 0:A.timestamp)||0)>=n.startedAt-5e3});if(!m)return;const u=$d({entrySessionId:m.sessionId,entryInstanceId:m.instanceId,entryRouteId:m.id,conversations:s});u&&(l(),r(u))},[l,s,e,r,n]),i.useEffect(()=>ot.onStatusEvent(d=>{const m=o.current;if(!m)return;const u=pg(m,d,s);u&&(l(),r(u))}),[l,s,r]),i.useEffect(()=>{if(!n)return;const d=window.setTimeout(()=>{a(m=>!m||m.startedAt!==n.startedAt?m:(o.current=null,null))},45e3);return()=>window.clearTimeout(d)},[n]),{trackPendingLaunch:c}}function hg({sendDaemonCommand:e,trackPendingLaunch:s,onOpenSession:r,activeConv:n,ides:a,setCliViewModeOverrides:o}){const l=Pd(),c=i.useCallback(async(p,b)=>zn(e,p,b),[e]),d=i.useCallback(async(p,b)=>{if(!b.trim())return{ok:!1,error:"Choose a workspace path first."};try{const y=await e(p,"workspace_add",{path:b.trim()});return y!=null&&y.success?{ok:!0}:{ok:!1,error:(y==null?void 0:y.error)||"Could not save workspace"}}catch(y){return{ok:!1,error:y instanceof Error?y.message:"Could not save workspace"}}},[e]),m=i.useCallback(async(p,b,y)=>{var x;try{const A={ideType:b,enableCdp:!0};(x=y==null?void 0:y.workspacePath)!=null&&x.trim()&&(A.workspace=y.workspacePath.trim());const N=await e(p,"launch_ide",A);return!(N!=null&&N.success)&&(N==null?void 0:N.success)!==void 0?{ok:!1,error:(N==null?void 0:N.error)||"Could not launch IDE"}:(s({machineId:p,kind:"ide",providerType:b,workspacePath:(y==null?void 0:y.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(A){return{ok:!1,error:A instanceof Error?A.message:"Could not launch IDE"}}},[e,s]),u=i.useCallback(async(p,b,y,x)=>{var N,v,C;const A=Date.now();try{const M={cliType:y};(N=x==null?void 0:x.workspacePath)!=null&&N.trim()?M.dir=x.workspacePath.trim():x!=null&&x.workspaceId&&(M.workspaceId=x.workspaceId),(v=x==null?void 0:x.resumeSessionId)!=null&&v.trim()&&(M.resumeSessionId=x.resumeSessionId.trim()),Array.isArray(x==null?void 0:x.cliArgs)&&x.cliArgs.length>0&&(M.cliArgs=x.cliArgs),(C=x==null?void 0:x.initialModel)!=null&&C.trim()&&(M.initialModel=x.initialModel.trim());const w=await e(p,"launch_cli",M),k=(w==null?void 0:w.result)||w,F=(k==null?void 0:k.sessionId)||(k==null?void 0:k.id);return w!=null&&w.success&&F?(s({machineId:p,kind:b,providerType:y,workspacePath:(x==null?void 0:x.workspacePath)||null,resumeSessionId:(x==null?void 0:x.resumeSessionId)||null,launchedSessionId:F,startedAt:A}),{ok:!0}):w!=null&&w.success?(s({machineId:p,kind:b,providerType:y,workspacePath:(x==null?void 0:x.workspacePath)||null,resumeSessionId:(x==null?void 0:x.resumeSessionId)||null,startedAt:A}),{ok:!0}):{ok:!1,error:(w==null?void 0:w.error)||(k==null?void 0:k.error)||`Could not launch ${b.toUpperCase()} session`}}catch(M){return ml(M)?(s({machineId:p,kind:b,providerType:y,workspacePath:(x==null?void 0:x.workspacePath)||null,resumeSessionId:(x==null?void 0:x.resumeSessionId)||null,startedAt:A}),{ok:!0}):{ok:!1,error:M instanceof Error?M.message:`Could not launch ${b.toUpperCase()} session`}}},[r,e,s]),h=i.useCallback(async p=>{var b;if(l!=null&&l.listMeshes)return l.listMeshes(p);if(!p)return[];try{const y=await e(p,"list_meshes",{}),x=(y==null?void 0:y.result)??y;if((x==null?void 0:x.success)===!1)throw new Error((x==null?void 0:x.error)||"Could not load meshes");return(Array.isArray(x==null?void 0:x.meshes)?x.meshes:Array.isArray((b=x==null?void 0:x.result)==null?void 0:b.meshes)?x.result.meshes:[]).map(N=>{var v;return{id:String((N==null?void 0:N.id)||""),name:String((N==null?void 0:N.name)||(N==null?void 0:N.id)||"Untitled mesh"),repoIdentity:(N==null?void 0:N.repoIdentity)||(N==null?void 0:N.repo_identity)||null,workspace:Array.isArray(N==null?void 0:N.nodes)&&N.nodes.length>0?String(((v=N.nodes[0])==null?void 0:v.workspace)||""):null,nodesCount:Array.isArray(N==null?void 0:N.nodes)?N.nodes.length:void 0,status:(N==null?void 0:N.status)||null}}).filter(N=>N.id)}catch(y){throw console.error("List meshes failed",y),y}},[l,e]),g=i.useCallback(async(p,b,y)=>{if(!b.trim())return{ok:!1,error:"Choose a mesh first."};if(l!=null&&l.launchMeshCoordinator)return l.launchMeshCoordinator(p,b,y);const x=Date.now();try{const A={meshId:b.trim()};y.trim()&&(A.cliType=y.trim());const N=await e(p,"launch_mesh_coordinator",A),v=(N==null?void 0:N.result)??N;if((v==null?void 0:v.success)===!1||(N==null?void 0:N.success)===!1){const M=String((v==null?void 0:v.code)||(N==null?void 0:N.code)||""),w=dg((v==null?void 0:v.meshCoordinatorSetup)||(v==null?void 0:v.manualSetup)||(N==null?void 0:N.meshCoordinatorSetup)||(N==null?void 0:N.manualSetup));return{ok:!1,error:(v==null?void 0:v.error)||(N==null?void 0:N.error)||"Could not launch mesh coordinator",code:M||void 0,manualSetup:w}}const C=(v==null?void 0:v.sessionId)||(v==null?void 0:v.id);return C?r(C):s({machineId:p,kind:"cli",providerType:(v==null?void 0:v.cliType)||y.trim()||void 0,workspacePath:(v==null?void 0:v.workspace)||null,startedAt:x}),{ok:!0}}catch(A){return ml(A)?(s({machineId:p,kind:"cli",providerType:y.trim()||void 0,startedAt:x}),{ok:!0}):{ok:!1,error:A instanceof Error?A.message:"Could not launch mesh coordinator"}}},[l,r,e,s]),j=i.useCallback(async(p,b)=>{if(!p||!b)return[];try{const y=await e(p,"list_saved_sessions",{providerType:b,kind:"cli",limit:30}),x=(y==null?void 0:y.result)??y;return Array.isArray(x==null?void 0:x.sessions)?x.sessions:[]}catch(y){return console.error("List saved sessions failed",y),[]}},[e]),f=i.useCallback(async p=>{await kd({conversation:n,mode:p,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[n,a,e,o]);return{handleBrowseMachineDirectory:c,handleSaveMachineWorkspace:d,handleLaunchMachineIde:m,handleLaunchMachineProvider:u,handleListMachineMeshes:h,handleLaunchMeshCoordinator:g,handleListMachineSavedSessions:j,setActiveCliViewMode:f}}function xg(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 bg(e,s,r=Date.now()){return!e||!xg(s)?null:{tabKey:e,nonce:r}}function gg({isMobile:e,conversations:s,visibleConversations:r,groupActiveTabIds:n,focusedGroup:a,groupedConvs:o,setSearchParams:l}){const[c,d]=i.useState(null),[m,u]=i.useState(null),h=i.useMemo(()=>{var b,y;if(!e){if(c){const x=s.find(A=>A.tabKey===c);if(x)return x}return r[0]}const p=n[a];if(p){const x=s.find(A=>A.tabKey===p);if(x)return x}return((b=o[a])==null?void 0:b[0])||((y=o[0])==null?void 0:y[0])},[s,c,a,n,o,e,r]),g=i.useCallback(p=>{d(p)},[]),j=i.useCallback(p=>{d(p.tabKey),l(b=>{const y=new URLSearchParams(b),x=_f(p);return x?y.set("activeTab",x):y.delete("activeTab"),y},{replace:!0})},[l]),f=i.useCallback((p,b)=>{const y=bg(p,b);y&&u(y)},[]);return{activeConv:h,openDesktopConversation:j,requestScrollToBottom:f,scrollToBottomRequest:m,setDesktopActiveTab:g}}function yg(e){const s=e.completedKey||null,r=e.pendingKey||null;return e.shouldMarkSeen?s===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 vg(e){const s=String(e.liveState.completionMarker||""),r=String(e.liveState.seenCompletionMarker||""),n=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,o=[e.tabKey,e.historySessionId||"",s,r,n,a?"1":"0"].join(":");return{shouldMarkSeen:!!(n==="task_complete"&&a&&s&&s!==r),autoReadKey:o,completionMarker:s,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function wg({activeConv:e,isMobile:s,liveSessionInboxState:r,sendDaemonCommand:n}){const a=i.useRef(null),o=i.useRef(null),l=i.useRef(null),c=i.useRef(null),d=i.useRef(null);i.useEffect(()=>{const m=()=>{l.current&&(clearTimeout(l.current),l.current=null),c.current&&(clearTimeout(c.current),c.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),o.current=null};if(s){m(),a.current=null;return}if(!(e!=null&&e.sessionId)){m(),a.current=null;return}const u=wn(e,r),h=vg({tabKey:e.tabKey,historySessionId:Rr(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:ws(e),liveState:u}),g=h.autoReadKey,j=yg({autoReadKey:g,shouldMarkSeen:h.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!h.shouldMarkSeen){j.shouldCancelPending&&m(),a.current=g;return}if(!j.shouldSchedule)return;j.shouldCancelPending&&m();const f=()=>{if(document.visibilityState!=="visible"||a.current===g)return;a.current=g,o.current=null,l.current=null,c.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const b=h.readAt;n(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:b,completionMarker:h.completionMarker}).catch(()=>{})};if(o.current=j.nextPendingKey,document.visibilityState==="visible"){l.current=setTimeout(f,1500);const b=()=>{document.visibilityState!=="visible"&&l.current&&(clearTimeout(l.current),l.current=null)};d.current=b,document.addEventListener("visibilitychange",b);return}const p=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(f,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=p,document.addEventListener("visibilitychange",p)},[e,s,r,n]),i.useEffect(()=>()=>{l.current&&clearTimeout(l.current),c.current&&clearTimeout(c.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function ba(e){if(!e)return"";const s=String(e.workspacePath||"").trim();if(s)return s;const r=String(e.workspaceName||"").trim();return/^(?:~\/|\/|[A-Za-z]:[\\/])/.test(r)?r:""}function jg({activeConv:e,remoteDialogConv:s,remoteDialogActiveConv:r,ides:n,sendDaemonCommand:a,updateRouteChats:o,setToasts:l,setClearedTabs:c,setSearchParams:d}){var T;const[m,u]=i.useState(!1),[h,g]=i.useState([]),[j,f]=i.useState(()=>Nt()),[p,b]=i.useState(!1),[y,x]=i.useState(null),A=i.useRef(null),N=i.useMemo(()=>r||s||e,[e,r,s]),v=!!N&&nt(N)&&!tt(N),C=i.useMemo(()=>{if(!N||!v)return null;const K=N.daemonId||N.routeId||"",P=zt(N),$=ba(N);return`${K}:${P}:${N.providerSessionId||""}:${$}`},[N,v]),M=i.useMemo(()=>!N||!v?"":ba(N),[N,v]),{isCreatingChat:w,isRefreshingHistory:k,handleSwitchSession:F,handleNewChat:_,handleRefreshHistory:S}=Md({sendDaemonCommand:a,activeConv:N,chats:(T=n.find(K=>K.id===(N==null?void 0:N.routeId)))==null?void 0:T.chats,updateRouteChats:o,setToasts:l,setClearedTabs:c}),H=i.useCallback(()=>{u(!0)},[]),W=i.useCallback(()=>{u(!1)},[]),D=i.useCallback(async()=>{if(!(!N||!v||p)){b(!0);try{const K=N.daemonId||N.routeId,P=zt(N),$=ba(N),V=await a(K,"list_saved_sessions",{agentType:P,providerType:P,kind:"cli",limit:50,...N.providerSessionId?{providerSessionId:N.providerSessionId}:{},...$?{workspace:$}:{}}),Y=(V==null?void 0:V.result)??V;g(Array.isArray(Y==null?void 0:Y.sessions)?Y.sessions:[])}catch(K){console.error("Refresh saved sessions failed",K),g([])}finally{b(!1)}}},[N,p,v,a]);i.useEffect(()=>{if(!m){A.current=null;return}if(!v){A.current=null,g([]),b(!1);return}!C||p||A.current!==C&&(A.current=C,D())},[D,m,p,v,C]);const I=i.useCallback(async K=>{if(!N||!v||!K.providerSessionId||!K.workspace)return;const P=N.daemonId||N.routeId,$=zt(N);try{x(K.providerSessionId);const V=await a(P,"launch_cli",{cliType:$,dir:K.workspace,resumeSessionId:K.providerSessionId,initialModel:kc(K.summaryMetadata,"model",{preferShortValue:!0})||void 0}),Y=(V==null?void 0:V.result)??V,ge=typeof(Y==null?void 0:Y.sessionId)=="string"?Y.sessionId:typeof(Y==null?void 0:Y.id)=="string"?Y.id:"";ge&&d(fe=>{const ae=new URLSearchParams(fe);return ae.set("activeTab",ge),ae},{replace:!0}),W()}catch(V){console.error("Resume saved session failed",V)}finally{x(null)}},[W,N,v,a,d]);return{historyModalOpen:m,openHistoryModal:H,closeHistoryModal:W,historyTargetConv:N,isSavedSessionHistoryTarget:v,isHistoryCreatingChat:w,isHistoryRefreshingHistory:k,handleHistorySwitchSession:F,handleHistoryNewChat:_,handleHistoryRefresh:S,savedHistorySessions:h,savedHistoryFilters:j,setSavedHistoryFilters:f,missingWorkspaceResumePath:M,isSavedHistoryLoading:p,resumingSavedHistorySessionId:y,handleRefreshSavedHistory:D,handleResumeSavedHistorySession:I}}function kg({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:l,resolveConversationByTarget:c}){const[d,m]=i.useState(null),[u,h]=i.useState(null),g=i.useMemo(()=>{if(e||!n)return null;const y=c(n);return y&&!nt(y)&&!tt(y)?y:null},[e,n,c]),j=i.useMemo(()=>{const y=d==null?void 0:d.routeId;if(!y)return null;const x=d!=null&&d.tabKey?o.find(A=>A.tabKey===d.tabKey):a?o.find(A=>A.tabKey===a):null;return(x==null?void 0:x.routeId)===y?x:Bt(o,y)},[o,d,a]),f=i.useMemo(()=>{if(j)return l.find(y=>y.id===j.routeId)},[l,j]);i.useEffect(()=>{g&&(m({routeId:g.routeId,tabKey:$i(g)}),h(g),r({pathname:s.pathname,search:s.search},{replace:!0,state:null}))},[s.pathname,s.search,r,g]);const p=i.useCallback(y=>{y&&(m({routeId:y.routeId,tabKey:$i(y)}),h(y))},[]),b=i.useCallback(()=>{m(null),h(null)},[]);return{remoteDialogConv:j,remoteDialogIdeEntry:f,remoteDialogActiveConv:u,setRemoteDialogActiveConv:h,openRemoteDialog:p,closeRemoteDialog:b}}function Ng({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:l,resolveConversationByTarget:c,activeConv:d,sendDaemonCommand:m}){const{remoteDialogConv:u,remoteDialogIdeEntry:h,remoteDialogActiveConv:g,setRemoteDialogActiveConv:j,openRemoteDialog:f,closeRemoteDialog:p}=kg({isMobile:e,location:s,navigate:r,requestedRemoteTabTarget:n,requestedDesktopTabKey:a,conversations:o,ides:l,resolveConversationByTarget:c}),[b,y]=i.useState(!1),[x,A]=i.useState(null),N=i.useCallback(async M=>{const w=M||d;!w||!nt(w)&&!tt(w)||(A(w),y(!0))},[d]),v=i.useCallback(()=>{y(!1),A(null)},[]),C=i.useCallback(async M=>{const w=x||d;if(!w||!nt(w)&&!tt(w)){v();return}y(!1);try{const k=zt(w),F=w.routeId||w.daemonId||"";await m(F,"stop_cli",{cliType:k,targetSessionId:w.sessionId,mode:M})}catch(k){console.error("Stop CLI failed:",k)}finally{A(null)}},[d,v,x,m]);return{remoteDialogConv:u,remoteDialogIdeEntry:h,remoteDialogActiveConv:g,setRemoteDialogActiveConv:j,openRemoteDialog:f,closeRemoteDialog:p,cliStopDialogOpen:b,cliStopTargetConv:x,requestCliStop:N,cancelCliStop:v,confirmCliStop:C}}function Od({conversation:e,className:s="",onOpenNativeConversation:r,onOpenMachine:n,interactive:a=!0,meshOnly:o=!1}){var A,N;const l=cs(),c=As(e),d=o?null:Mc(e),m=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),u=!o&&e.streamSource==="agent-stream"&&!!e.agentName,h=!o&&!u&&(e.transport==="pty"||e.transport==="acp"),g=Us(e),j=Rf(e),f=(A=e.settings)==null?void 0:A.meshNodeFor,p=e.meshQueueStats,b=(N=e.settings)==null?void 0:N.meshCoordinatorFor;if(!m&&!u&&!h&&!d&&!f&&!p)return null;const y=i.useCallback(()=>{if(n){n();return}c&&l("/dashboard",{state:{openMachineId:c}})},[c,l,n]),x=i.useCallback(()=>{if(r){r();return}const v=Ed(e);v&&l(Vt(v))},[e,l,r]);return t.jsxs("div",{className:`conversation-meta-chips ${s}`.trim(),children:[m&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:x,title:j,children:[t.jsx(At,{size:12}),t.jsx("span",{children:j})]}):t.jsxs("span",{className:"conversation-meta-chip",title:j,children:[t.jsx(At,{size:12}),t.jsx("span",{children:j})]})),u&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[t.jsx(Hs,{size:12}),t.jsx("span",{children:g})]}),h&&t.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[t.jsx(Hs,{size:12}),t.jsx("span",{children:g})]}),d&&(a?t.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:y,title:d,children:[t.jsx(os,{size:12}),t.jsx("span",{children:d})]}):t.jsxs("span",{className:"conversation-meta-chip",title:d,children:[t.jsx(os,{size:12}),t.jsx("span",{children:d})]})),f&&t.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[t.jsx(os,{size:12}),t.jsx("span",{children:"Mesh Node"})]}),b&&p&&t.jsxs("span",{className:`conversation-meta-chip ${p.pending>0?"is-active":""}`,style:p.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${p.pending} pending, ${p.assigned} assigned, ${p.completed} completed, ${p.failed} failed`,children:[t.jsx(Lm,{size:12}),t.jsxs("span",{children:[p.pending," Pending"]})]})]})}function ga(e,s=!0){return(e??!0)&&s}const ei=i.memo(function({activeConv:s,clearToken:r,isCliTerminal:n,ideEntry:a,terminalRef:o,handleModalButton:l,handleRelaunch:c,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u=null,handleFocusAgent:h,isFocusingAgent:g,actionLogs:j,userName:f,scrollToBottomRequestNonce:p,isInputActive:b=!0,isVisible:y=!0}){const x=n,A=!n,N=ga(y,x),v=ga(y,A),C=ga(y),M=bd(s),w=M.status||M.modalMessage||M.modalButtons?{...s,...M.status?{status:M.status}:{},...M.modalMessage!==void 0?{modalMessage:M.modalMessage}:{},...M.modalButtons!==void 0?{modalButtons:M.modalButtons}:{}}:s;return t.jsxs(t.Fragment,{children:[t.jsx(vc,{activeConv:w,onModalButton:l}),t.jsx(Od,{conversation:w,className:"chat-pane-meta-row mx-3 mt-1",meshOnly:!0}),w.transport!=="pty"&&w.transport!=="acp"&&w.cdpConnected===!1?t.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:t.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:[t.jsx("span",{className:"text-sm",children:t.jsx(Sr,{size:14})}),t.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),t.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:c,children:"Relaunch with CDP"})]})}):null,w.transport==="pty"?t.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[t.jsx("div",{"aria-hidden":!n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:x?"visible":"hidden",pointerEvents:x?"auto":"none"},children:t.jsx(Vh,{activeConv:w,clearToken:r,terminalRef:o,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,isVisible:N,isInputActive:b&&N})}),t.jsx("div",{"aria-hidden":n,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:A?"visible":"hidden",pointerEvents:A?"auto":"none"},children:t.jsx(ao,{activeConv:w,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:h,isFocusingAgent:g,actionLogs:j,userName:f,scrollToBottomRequestNonce:p,isInputActive:b&&v,isVisible:v})})]}):t.jsx(ao,{activeConv:w,ideEntry:a,handleSendChat:d,isSendingChat:m,sendFeedbackMessage:u,handleFocusAgent:h,isFocusingAgent:g,actionLogs:j,userName:f,scrollToBottomRequestNonce:p,isInputActive:b&&C,isVisible:C})]})},(e,s)=>e.activeConv===s.activeConv&&e.isCliTerminal===s.isCliTerminal&&e.ideEntry===s.ideEntry&&e.terminalRef===s.terminalRef&&e.handleModalButton===s.handleModalButton&&e.handleRelaunch===s.handleRelaunch&&e.handleSendChat===s.handleSendChat&&e.isSendingChat===s.isSendingChat&&e.sendFeedbackMessage===s.sendFeedbackMessage&&e.handleFocusAgent===s.handleFocusAgent&&e.isFocusingAgent===s.isFocusingAgent&&e.actionLogs===s.actionLogs&&e.userName===s.userName&&e.scrollToBottomRequestNonce===s.scrollToBottomRequestNonce&&e.isInputActive===s.isInputActive&&e.isVisible===s.isVisible);function Sg({selectedConversation:e,isAcp:s,isStandalone:r,selectedIdeEntry:n,actionLogs:a,userName:o,isSendingChat:l,sendFeedbackMessage:c=null,isFocusingAgent:d,onBack:m,onOpenNativeConversation:u,onOpenMachine:h,onOpenHistory:g,onOpenRemote:j,onOpenMeshGraph:f,onStopCli:p,cliViewMode:b,onSetCliViewMode:y,handleSendChat:x,handleFocusAgent:A,handleModalButton:N,handleRelaunch:v}){var _;const C=i.useRef(null),M=nt(e)&&!s,w=M&&b==="terminal",k=!!e.daemonId&&typeof((_=e.settings)==null?void 0:_.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.length>0,F=r?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:`flex items-center justify-between gap-3 ${F} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.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:t.jsx(jo,{size:18})}),t.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:dt(e)}),t.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:t.jsx(Od,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>h(e)})})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[M&&b&&t.jsx(Ko,{mode:b,onChange:y,compact:!0}),M&&p&&t.jsx("button",{onClick:()=>{p(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:t.jsx(vt,{size:14})}),k&&f&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:t.jsx(ns,{size:14})}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:t.jsx(ko,{size:14})}),!s&&!M&&t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>j(e),type:"button",children:t.jsx(At,{size:14})})]})]}),t.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:t.jsx(ei,{activeConv:e,clearToken:0,isCliTerminal:w,ideEntry:n,terminalRef:C,handleModalButton:N,handleRelaunch:v,handleSendChat:x,isSendingChat:l,sendFeedbackMessage:c,handleFocusAgent:A,isFocusingAgent:d,actionLogs:a,userName:o})})]})}const ya={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 Cg(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Fd(){const[e,s]=i.useState("unix"),[r,n]=i.useState("powershell"),[a,o]=i.useState(!1),l=e==="unix"?"unix":r;i.useEffect(()=>{s(Cg())},[]);const c=i.useCallback(()=>{navigator.clipboard.writeText(ya[l].cmd).catch(()=>{}),o(!0),setTimeout(()=>o(!1),2e3)},[l]);return t.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:[t.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[t.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:()=>s("unix"),children:"🍎🐧 macOS / Linux"}),t.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:()=>s("windows"),children:"🪟 Windows"})]}),e==="windows"&&t.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[t.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"}),t.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"})]}),t.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:c,title:"Click to copy",children:[t.jsx("span",{className:"text-text-muted select-none",children:ya[l].prompt}),t.jsx("span",{className:"flex-1 break-all",children:ya[l].cmd}),t.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:a?"✓":"📋"})]}),t.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",t.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function Kd({section:e,onSectionChange:s}){const r=[{key:"machines",label:"Machines",icon:At},{key:"chats",label:"Chats",icon:Jt}];return t.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:t.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:r.map(({key:n,label:a,icon:o})=>{const l=e===n;return t.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 ${l?"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:l?{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:()=>s(n),type:"button","aria-pressed":l,children:[t.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${l?"text-accent-primary":"bg-transparent text-current"}`,style:l?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:t.jsx(o,{size:15})}),t.jsx("span",{children:a})]},n)})})})}function Xr({title:e,className:s=""}){return t.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${s}`,children:t.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function Ms({children:e,className:s=""}){return t.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)] ${s}`,children:e})}function cr({icon:e,title:s,subtitle:r,children:n}){return t.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:[t.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}),t.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:s}),t.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:r}),n]})}function Ig({conversation:e,onCancel:s,onConfirm:r}){const n=dt(e),a=Cs(e);return t.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:[t.jsx("div",{className:"absolute inset-0 bg-black/60 backdrop-blur-sm",onClick:s}),t.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:[t.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-border-subtle bg-[var(--surface-primary)] px-4 py-4",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base font-extrabold text-text-primary",children:"Hide this chat from the inbox?"}),t.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."})]}),t.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:s,"aria-label":"Cancel hide chat",children:t.jsx(vt,{size:16})})]}),t.jsx("div",{className:"px-4 py-4",children:t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-secondary/60 px-3.5 py-3",children:[t.jsx("div",{className:"truncate text-sm font-bold text-text-primary",children:n}),t.jsx("div",{className:"mt-1 truncate text-xs text-text-muted",children:a})]})}),t.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:[t.jsx("button",{type:"button",className:"btn btn-secondary min-h-[40px] px-4 text-sm",onClick:s,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary min-h-[40px] px-4 text-sm",onClick:r,children:"Hide tab"})]})]})]})}function Jr({item:e,type:s,getAvatarText:r,onOpenConversation:n,onRequestHideConversation:a,onOpenMeshGraph:o,onCollectChatDebugBundle:l}){var F;const c=s==="needs_attention"||s==="task_complete",d=s==="working",m=s==="earlier",u=s==="task_complete",{isReconnecting:h,isConnecting:g}=Xs(e.conversation),j=dt(e.conversation),f=Cs(e.conversation),p=Xc(e.conversation,{requiresAction:s==="needs_attention"}),b=c?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":d?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",y=c?"bg-accent-primary shadow-glow":d?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":m?"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",x=m?"text-text-secondary":"text-text-primary",A=m?"text-text-muted":"text-text-secondary",N=m?"text-text-secondary opacity-80":"text-text-muted",v=m?"text-text-muted opacity-80":"text-text-muted",C=!d&&!u,M=!!e.conversation.daemonId&&typeof((F=e.conversation.settings)==null?void 0:F.meshCoordinatorFor)=="string"&&e.conversation.settings.meshCoordinatorFor.length>0,w="text-[color:var(--status-warning)]",k=_=>{if(!l)return;_.preventDefault(),_.stopPropagation();const S=l==null?void 0:l(e.conversation);Promise.resolve(S).catch(H=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",H)})};return t.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${b}`,children:t.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[c||d?t.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,t.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[t.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${y}`,style:c?{color:"var(--accent-on-primary)"}:void 0,children:r(j)}),a&&t.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:_=>{_.preventDefault(),_.stopPropagation(),a()},"aria-label":`Hide ${j}`,title:"Hide conversation",children:[t.jsx(No,{size:11}),t.jsx("span",{children:"Hide"})]}),M&&o&&t.jsxs("button",{type:"button",className:"mobile-inbox-mesh-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:_=>{_.preventDefault(),_.stopPropagation(),o(e.conversation)},"aria-label":`Open mesh graph for ${j}`,title:"Open live repo mesh graph",children:[t.jsx(ns,{size:11}),t.jsx("span",{children:"Graph"})]})]}),t.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>n(e.conversation),onContextMenu:k,type:"button",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${x}`,children:j}),C&&t.jsx("span",{className:`text-[11px] font-medium shrink-0 ${v}`,children:yc(e.timestamp)})]}),t.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${A}`,children:[t.jsx("span",{className:"truncate",children:f}),t.jsx(Vs,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),h?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:`${w} animate-pulse`,children:"Reconnecting…"})]}):g?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:"text-text-muted",children:"Connecting…"})]}):p==="Action needed"&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{className:w,children:"Action needed"})]})]}),t.jsx("div",{className:`mt-0.5 truncate text-[13px] ${N}`,children:e.preview})]}),c&&!u&&t.jsx("span",{className:"absolute top-5 right-4 w-2 h-2 rounded-full bg-accent-primary shadow-glow"}),u&&t.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"}),d&&t.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 pl({size:e=32}){return t.jsx("div",{className:"flex flex-col items-center gap-2.5",children:t.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 Tg({section:e,attentionItems:s,unreadItems:r,workingItems:n,completedItems:a,hiddenConversations:o,machineCards:l,getAvatarText:c,actionLogs:d,sendDaemonCommand:m,onOpenConversation:u,onShowAllHidden:h,onHideConversation:g,onOpenMeshGraph:j,onOpenNewSession:f,onOpenMachine:p,onOpenSettings:b,onSectionChange:y,wsStatus:x="connected",isStandalone:A=!1,onCollectChatDebugBundle:N}){const[v,C]=i.useState(null),M=x==="disconnected"||x==="reconnecting"||x==="offline"||x==="auth_failed",w=l.length>0,k=s.length>0||r.length>0||n.length>0||a.length>0,F=e==="machines"?"Machines":"Chats",_=A?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",S=A?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",H=i.useCallback(async I=>{const T=zs(I);if(!T)return;const K=Array.isArray(I.messages)?I.messages:[],P=Ec({activeConv:I,visibleMessages:K,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:K.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),$=await m(T,"get_chat_debug_bundle",{...hs(I),delivery:"daemon_file",frontendSnapshot:P}),V=Sn($),Y=Oc(V),ge=await Bc(Y);ge==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),ot.showToast($c(V,{locatorCopyStatus:ge}),ge==="failed"?"warning":"success")},[d,m]),W=N||H,D=i.useCallback(()=>{v&&(g==null||g(v),C(null))},[v,g]);return t.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[t.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${_}`,children:t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:F}),t.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(s.length>0||r.length>0)&&t.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:[t.jsx(Dn,{size:13}),t.jsx("span",{children:s.length+r.length})]}),t.jsx("button",{onClick:b,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:t.jsx(Pn,{size:18})})]})]})}),t.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] ${S}`,children:[e==="machines"&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:M?t.jsx(cr,{icon:t.jsx(pl,{}),title:x==="offline"?"Network offline":x==="auth_failed"?"Session expired":"Reconnecting",subtitle:x==="offline"?"Waiting for network…":x==="auth_failed"?"Please log in again.":"Restoring the server connection…"}):l.length===0?t.jsx(cr,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:A?"Waiting for your daemon":"Connect your machines",subtitle:A?"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:!A&&t.jsx("div",{className:"w-full max-w-[360px] mt-4",children:t.jsx(Fd,{})})}):t.jsx(Ms,{children:l.map((I,T)=>t.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${T>0?"border-t border-border-subtle/70":""}`,onClick:()=>p(I.id),type:"button",children:[t.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:c(I.label)}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:I.label}),t.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:I.unread>0?t.jsxs("span",{className:"text-accent-primary",children:[I.unread," new"]}):I.total>0?`${I.total} chats`:"Idle"})]}),t.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:I.subtitle}),I.total>0?t.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[I.total," chat",I.total!==1?"s":"",I.unread>0?` · ${I.unread} unread`:""]}):t.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:"No active chats"})]})]},I.id))})}),e==="chats"&&s.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Xr,{title:"Needs attention",className:"mb-0"}),t.jsx(Ms,{children:s.map((I,T)=>t.jsx("div",{className:T>0?"border-t border-border-subtle/70":"",children:t.jsx(Jr,{item:I,type:"needs_attention",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:g?()=>C(I.conversation):void 0,onOpenMeshGraph:j,onCollectChatDebugBundle:W})},I.conversation.tabKey))})]}),e==="chats"&&r.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Xr,{title:"Task complete",className:"mb-0 mt-2"}),t.jsx(Ms,{children:r.map((I,T)=>t.jsx("div",{className:T>0?"border-t border-border-subtle/70":"",children:t.jsx(Jr,{item:I,type:"task_complete",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:g?()=>C(I.conversation):void 0,onOpenMeshGraph:j,onCollectChatDebugBundle:W})},I.conversation.tabKey))})]}),e==="chats"&&n.length>0&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[t.jsx(Xr,{title:"Working now",className:"mb-0 mt-2"}),t.jsx(Ms,{children:n.map((I,T)=>t.jsx("div",{className:T>0?"border-t border-border-subtle/70":"",children:t.jsx(Jr,{item:I,type:"working",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:g?()=>C(I.conversation):void 0,onOpenMeshGraph:j,onCollectChatDebugBundle:W})},I.conversation.tabKey))})]}),e==="chats"&&t.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&t.jsx(Xr,{title:"Earlier",className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?t.jsx(Ms,{children:a.map((I,T)=>t.jsx("div",{className:T>0?"border-t border-border-subtle/70":"",children:t.jsx(Jr,{item:I,type:"earlier",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:g?()=>C(I.conversation):void 0,onOpenMeshGraph:j,onCollectChatDebugBundle:W})},I.conversation.tabKey))}):k?t.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:"All caught up."}):M?t.jsx(cr,{icon:t.jsx(pl,{size:28}),title:"Connecting…",subtitle:"Waiting for server connection before loading conversations."}):w?t.jsx(cr,{icon:t.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:t.jsx(Jt,{size:20})}),title:"No conversations yet",subtitle:Zc,children:f&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:f,"aria-label":Ht,title:Ht,children:[t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),t.jsx("span",{children:Ht})]})}):t.jsx(cr,{icon:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:"No machines connected",subtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents."})]}),e==="chats"&&o.length>0&&t.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:t.jsx(Ms,{className:"mt-4 border-dashed bg-bg-secondary/20",children:t.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:"Hidden tabs"}),t.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[o.length," collapsed ",o.length===1?"conversation":"conversations"]})]}),t.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:h,children:"Restore all"})]})})})]}),e==="chats"&&f&&k&&t.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:f,"aria-label":Ht,title:Ht,children:t.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),v&&t.jsx(Ig,{conversation:v,onCancel:()=>C(null),onConfirm:D}),t.jsx(Kd,{section:e,onSectionChange:y})]})}function Ag(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 Wd(e){const s=[e.workspace||"Workspace unknown"],r=Ss(e.summaryMetadata);r&&s.push(r),(e.messageCount||0)>0&&s.push(`${e.messageCount} msgs`);const n=Ag(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:s.join(" · "),updatedLabel:n?`Updated ${n}`:"",preview:(e.preview||"").trim()}}function Vn({title:e,description:s,currentPath:r,directories:n,busy:a=!1,error:o="",confirmLabel:l="Use this folder",onClose:c,onNavigate:d,onConfirm:m}){const[u,h]=i.useState(r);i.useEffect(()=>{h(r)},[r]);const g=ig(r),j=u.trim();return t.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:t.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:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.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:c,"aria-label":"Close folder browser",children:t.jsx(vt,{size:16})})]}),t.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[t.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:()=>{!g||a||d(g)},disabled:!g||a,children:[t.jsx(jo,{size:15}),"Parent"]}),t.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("input",{type:"text",value:u,onChange:f=>h(f.target.value),onKeyDown:f=>{f.key!=="Enter"||!j||a||(f.preventDefault(),d(j))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!j||a||d(j)},disabled:!j||a,children:"Go"})]})]})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?t.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):n.length===0?t.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):t.jsx("div",{className:"p-3",children:n.map(f=>t.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(f.path),children:[t.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:t.jsx(Ns,{size:17})}),t.jsxs("span",{className:"min-w-0 flex-1",children:[t.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:f.name}),t.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:f.path})]})]},f.path))})}),t.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:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:c,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>m(j||r),disabled:!j&&!r||a,children:l})]})]})})}function ti({title:e,description:s,details:r,workspaceOptions:n,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:l="Launch",busyLabel:c="Launching…",busy:d=!1,showArgsInput:m,argsValue:u,onArgsChange:h,showModelInput:g,modelValue:j,onModelChange:f,historyProviderNode:p,onConfirm:b,onCancel:y}){const x=n==null?void 0:n.find(A=>A.key===a);return t.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:t.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:[t.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),t.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:s})]}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:y,"aria-label":"Close launch confirmation",children:t.jsx(vt,{size:16})})]}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[n&&n.length>0&&o&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Workspace"}),t.jsx("select",{value:a||"",onChange:A=>o(A.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(A=>t.jsx("option",{value:A.key,children:A.label},A.key))}),(x==null?void 0:x.description)&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:x.description})]}),p,r.map(A=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:A.label}),t.jsx("div",{className:"text-sm text-text-primary break-all",children:A.value})]},`${A.label}:${A.value}`)),g&&f&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Language Model (Optional)"}),t.jsx("input",{type:"text",value:j||"",onChange:A=>f(A.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&&h&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"CLI Arguments (Optional)"}),t.jsx("input",{type:"text",value:u||"",onChange:A=>h(A.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})]})]}),t.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:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:y,disabled:d,children:"Cancel"}),t.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:b,disabled:d,children:[t.jsx(Co,{size:14}),d?c:l]})]})]})})}function fl(e,s){return s||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function js(e){const{machine:s,currentWorkspacePath:r,currentWorkspaceId:n,includeHome:a=!0}=e,o=[];a&&o.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const d of s.workspaces||[])o.push({key:`saved:${d.id}`,label:`${d.id===s.defaultWorkspaceId?"⭐ ":""}${fl(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const l=(r==null?void 0:r.trim())||"",c=l?(s.workspaces||[]).find(d=>d.path===l):null;if(l&&!c&&o.push({key:`custom:${l}`,label:fl(l),description:l,workspaceId:null,workspacePath:l}),n){const d=`saved:${n}`;if(o.some(m=>m.key===d))return{options:o,selectedKey:d}}return c?{options:o,selectedKey:`saved:${c.id}`}:l?{options:o,selectedKey:`custom:${l}`}:{options:o,selectedKey:"__home__"}}function Mg(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Lg(e){return[Mg(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Rg(e){return e.lastLaunchedAt?En(e.lastLaunchedAt):""}function Hd(e){return{metaText:Lg(e),updatedLabel:Rg(e)}}function va(e,s,r){return e?"ide":s>0?"cli":r>0?"acp":null}function _g({selectedMachineEntry:e,cliProviders:s,acpProviders:r,machineAction:n,onBrowseDirectory:a,onListSavedSessions:o}){var st,mt,ht,yt;const l=Lr(),[c,d]=i.useState(!1),m=(((st=e.detectedIdes)==null?void 0:st.length)||0)>0,u=i.useMemo(()=>(e.workspaces||[]).map(Te=>({id:Te.id,path:Te.path,label:Te.label})),[e]),h=e.defaultWorkspaceId||null,[g,j]=i.useState(h||((mt=u[0])==null?void 0:mt.id)||""),[f,p]=i.useState(""),[b,y]=i.useState(""),[x,A]=i.useState([]),[N,v]=i.useState(!1),[C,M]=i.useState(""),[w,k]=i.useState(!1),[F,_]=i.useState(va(m,s.length,r.length)),S=i.useRef(null),[H,W]=i.useState(null),D=i.useRef("__home__"),[I,T]=i.useState("__home__"),[K,P]=i.useState(""),[$,V]=i.useState(""),[Y,ge]=i.useState(""),[fe,ae]=i.useState([]),[me,je]=i.useState(()=>Nt().textQuery),[Ne,G]=i.useState(()=>Nt().workspaceQuery),[he,pe]=i.useState(()=>Nt().modelQuery),[ye,xe]=i.useState(()=>Nt().resumableOnly),[Se,R]=i.useState(()=>Nt().sortMode),[re,Q]=i.useState(!1),[ue,ce]=i.useState(!1),de=i.useRef(null),te=i.useRef(null);i.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&l(e.id,{minFreshMs:3e4}).catch(()=>{})},[l,e]);const E=g==="__custom__"?f.trim():((ht=u.find(Te=>Te.id===g))==null?void 0:ht.path)||"",X=g==="__custom__"&&!!E&&n.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(n.message),oe=g!=="__custom__"&&((yt=u.find(Te=>Te.id===g))==null?void 0:yt.path)||"",ee=i.useMemo(()=>(e.recentLaunches||[]).map(Te=>Te.workspace),[e]),ke=i.useCallback(async Te=>{v(!0),M("");try{const Ue=await a(Te);y(Ue.path),p(Ue.path),A(Ue.directories)}catch(Ue){M(Ue instanceof Error?Ue.message:"Could not load folder")}finally{v(!1)}},[a]),Ce=i.useCallback(()=>{var Ue;j("__custom__"),k(!0);const Te=Un(e.platform,Hn(f.trim(),oe,ee,e.defaultWorkspacePath,(Ue=u.find(et=>et.id===h))==null?void 0:Ue.path,u.map(et=>et.path)));ke(Te)},[f,h,ke,ee,oe,e.platform,u]),ve=i.useCallback(Te=>{if(Te!=null&&Te.workspaceId){j(Te.workspaceId),p("");return}if(Te!=null&&Te.workspacePath){j("__custom__"),p(Te.workspacePath);return}j(""),p("")},[]),O=i.useCallback(Te=>{if(j(Te),Te==="__custom__"){Ce();return}p("")},[Ce]),Ie=i.useCallback(Te=>{j("__custom__"),p(Te)},[]),Re=i.useCallback((Te,Ue)=>{S.current=Ue,D.current=Te.selectedWorkspaceKey||"__home__",T(Te.selectedWorkspaceKey||"__home__"),P(Te.initialArgs||""),V(Te.initialModel||""),ge(""),ae([]);const et=Te.providerType?`${e.id}:${Te.providerType}`:null;if(rx(te.current,et)){const ze=Nt();je(ze.textQuery),G(ze.workspaceQuery),pe(ze.modelQuery),xe(ze.resumableOnly),R(ze.sortMode)}te.current=et,W(Te),Te.providerType&&o&&(Q(!0),o(Te.providerType).then(ze=>ae(ze||[])).catch(ze=>console.warn("Failed to load saved sessions",ze)).finally(()=>Q(!1)))},[o,e.id]),Ke=i.useMemo(()=>ed(fe,{textQuery:me,workspaceQuery:Ne,modelQuery:he,resumableOnly:ye,sortMode:Se}),[he,ye,fe,Se,me,Ne]);i.useEffect(()=>{Y&&(Ke.some(Te=>Te.providerSessionId===Y)||ge(""))},[Ke,Y]);const He=i.useCallback(()=>{S.current&&(ce(!0),S.current().finally(()=>{S.current=null,ce(!1),W(null)}))},[]),Ye=i.useCallback(()=>{S.current=null,W(null)},[]),Xe=i.useCallback(Te=>{D.current=Te,T(Te)},[]);return i.useEffect(()=>{var Te;de.current!==e.id&&(de.current=e.id,j(h||((Te=u[0])==null?void 0:Te.id)||"__custom__"),p(""),y(""),A([]),M(""),k(!1),je(Nt().textQuery),G(Nt().workspaceQuery),pe(Nt().modelQuery),xe(Nt().resumableOnly),R(Nt().sortMode),te.current=null,_(va(m,s.length,r.length)))},[r.length,s.length,h,m,e.id,u]),i.useEffect(()=>{var Te;g!=="__custom__"&&(g&&u.some(Ue=>Ue.id===g)||j(h||((Te=u[0])==null?void 0:Te.id)||"__custom__"))},[h,g,u]),i.useEffect(()=>{F==="ide"&&m||F==="cli"&&s.length>0||F==="acp"&&r.length>0||_(va(m,s.length,r.length))},[F,r.length,s.length,m]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:m,workspaceRows:u,defaultWorkspaceId:h,workspaceChoice:g,customWorkspacePath:f,browseCurrentPath:b,browseDirectories:x,browseBusy:N,browseError:C,browseDialogOpen:w,activeLauncherKind:F,launchConfirm:H,launchConfirmWorkspaceKeyRef:D,launchConfirmWorkspaceKey:I,launchConfirmArgs:K,launchConfirmModel:$,launchConfirmResumeId:Y,launchConfirmSavedSessions:fe,launchConfirmTextFilter:me,launchConfirmWorkspaceFilter:Ne,launchConfirmModelFilter:he,launchConfirmResumableOnly:ye,launchConfirmSortMode:Se,filteredLaunchConfirmSavedSessions:Ke,launchConfirmSessionsLoading:re,launchConfirmBusy:ue,resolvedWorkspacePath:E,canCreateMissingWorkspace:X,openBrowseDialog:Ce,loadBrowsePath:ke,handleWorkspaceChoiceChange:O,chooseCustomWorkspacePath:Ie,setCustomWorkspacePath:p,setBrowseDialogOpen:k,setActiveLauncherKind:_,openLaunchConfirm:Re,handleConfirmLaunch:He,closeLaunchConfirm:Ye,setWorkspaceSelectionFromOption:ve,setLaunchConfirmWorkspaceKeyAndSync:Xe,setLaunchConfirmArgs:P,setLaunchConfirmModel:V,setLaunchConfirmResumeId:ge,setLaunchConfirmTextFilter:je,setLaunchConfirmWorkspaceFilter:G,setLaunchConfirmModelFilter:pe,setLaunchConfirmResumableOnly:xe,setLaunchConfirmSortMode:R}}function Pg({selectedMachineEntry:e,selectedMachineConversations:s,selectedMachineRecentLaunches:r,cliProviders:n,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:l,machineAction:c,isStandalone:d,section:m,showBottomNav:u,onBack:h,onSectionChange:g,onOpenConversation:j,onOpenRecent:f,onOpenMachineDetails:p,onMachineUpgrade:b,onLaunchDetectedIde:y,onAddWorkspace:x,onBrowseDirectory:A,onLaunchWorkspaceProvider:N,onListSavedSessions:v}){const C=I=>I==="ide"?"IDE":I==="cli"?"CLI":"ACP",M=r.slice(0,4),w=s.slice(0,3),k=_g({selectedMachineEntry:e,cliProviders:n,acpProviders:a,machineAction:c,onBrowseDirectory:A,onListSavedSessions:v}),F=i.useMemo(()=>M.map(I=>{const{metaText:T,updatedLabel:K}=Hd(I);return{key:`recent-launch:${I.id}`,primary:I.label,secondary:T,updatedLabel:K,onClick:()=>{const{options:P,selectedKey:$}=js({machine:{workspaces:k.workspaceRows,defaultWorkspaceId:k.defaultWorkspaceId},currentWorkspacePath:I.workspace});k.openLaunchConfirm({title:I.kind==="ide"?bs("restart-ide",I.label):I.providerSessionId?Uo(I.label):bs("start-fresh",I.label),description:I.kind==="ide"?gs("restart-ide"):I.providerSessionId?zo():gs("start-fresh"),confirmLabel:I.kind==="ide"?Gs("restart-ide"):I.providerSessionId?In(!0):Gs("start-fresh"),busyLabel:I.kind==="ide"?qs("restart-ide"):I.providerSessionId?Wo(!0):qs("start-fresh"),workspaceOptions:P,selectedWorkspaceKey:$,details:[{label:"Mode",value:C(I.kind)},...I.providerType?[{label:"Provider",value:I.providerType}]:[]]},async()=>{const V=P.find(Y=>Y.key===k.launchConfirmWorkspaceKeyRef.current);k.setWorkspaceSelectionFromOption(V),await f({...I,workspace:(V==null?void 0:V.workspacePath)??null})})}}}),[k,f,M]),_=i.useMemo(()=>w.map(I=>({key:`recent-chat:${I.conversation.tabKey}`,primary:dt(I.conversation),secondary:Wh(I.conversation,{timestampLabel:I.timestamp?yc(I.timestamp):null}),unread:I.unread,onClick:()=>j(I.conversation)})),[j,w]),S=k.showAllRecent?F:F.slice(0,4),H=F.length>0,W=_.length>0,D=d?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:`flex items-center justify-between gap-3 ${D} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:t.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[t.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:h,type:"button","aria-label":"Back",children:t.jsx(jo,{size:18})}),t.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[t.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:Tt(e,{fallbackId:e.id})}),t.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}`:""]})]})]})}),t.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[W&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:_.map(I=>t.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${I.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:I.onClick,children:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:I.primary}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:I.secondary})]},I.key))})]}),H&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:S.map(I=>t.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:I.onClick,children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:I.primary}),I.updatedLabel&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:I.updatedLabel})]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:I.secondary})]},I.key))}),F.length>4&&t.jsx("div",{className:"flex justify-center px-4 pt-2",children:t.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>k.setShowAllRecent(I=>!I),children:k.showAllRecent?"Show fewer":`Show ${F.length-4} more`})})]}),(k.hasIdeOptions||n.length>0||a.length>0)&&t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Start"}),t.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:t.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:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Workspace"}),t.jsx("div",{className:"text-xs leading-relaxed text-text-secondary",children:"Pick a saved workspace or browse folders before choosing IDE, CLI, or ACP."}),t.jsx("select",{value:k.workspaceChoice,onChange:I=>k.handleWorkspaceChoiceChange(I.target.value),className:"w-full rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-primary px-3 py-3 text-sm",children:k.workspaceRows.length>0?t.jsxs(t.Fragment,{children:[k.workspaceRows.map(I=>t.jsxs("option",{value:I.id,children:[I.id===k.defaultWorkspaceId?"⭐ ":"",Bn(I.path,I.label)||I.path]},I.id)),t.jsx("option",{value:"__custom__",children:"Select workspace…"})]}):t.jsx("option",{value:"__custom__",children:"Select workspace…"})}),k.workspaceChoice==="__custom__"&&t.jsxs("div",{className:"flex flex-col gap-2.5",children:[t.jsx("div",{className:"rounded-2xl border border-border-default/80 bg-bg-primary/80 px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start gap-3",children:[t.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:t.jsx(Ns,{size:17})}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"text-[10px] font-bold uppercase tracking-[0.08em] text-text-muted mb-1",children:"Selected folder"}),t.jsx("div",{className:"text-[12px] leading-relaxed text-text-primary break-all",children:k.resolvedWorkspacePath||k.browseCurrentPath||"No folder selected yet."})]})]})}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-border-default/90 bg-bg-primary/90 text-text-secondary text-[12px] font-bold",onClick:k.openBrowseDialog,children:"Select workspace…"}),t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-xl border border-accent-primary/30 bg-accent-primary/10 text-text-primary text-[12px] font-bold disabled:opacity-40",onClick:()=>{k.resolvedWorkspacePath&&x(k.resolvedWorkspacePath)},disabled:!k.resolvedWorkspacePath||k.browseBusy,children:"Save as workspace"})]})]}),k.resolvedWorkspacePath&&t.jsx("div",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:k.resolvedWorkspacePath})]})}),t.jsxs("div",{className:"grid grid-cols-3 gap-2 px-4",children:[k.hasIdeOptions&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${k.activeLauncherKind==="ide"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>k.setActiveLauncherKind("ide"),children:"IDE"}),n.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${k.activeLauncherKind==="cli"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>k.setActiveLauncherKind("cli"),children:"CLI"}),a.length>0&&t.jsx("button",{className:`min-h-[40px] rounded-full border text-xs font-bold ${k.activeLauncherKind==="acp"?"border-accent-primary/30 bg-accent-primary/10 text-text-primary":"border-border-default/80 bg-surface-primary/90 text-text-secondary"}`,type:"button",onClick:()=>k.setActiveLauncherKind("acp"),children:"ACP"})]}),k.activeLauncherKind&&t.jsxs("div",{className:"flex flex-col gap-2.5 px-4 pt-3",children:[t.jsx("div",{className:"text-xs font-bold text-text-secondary",children:k.activeLauncherKind==="ide"?"Choose an IDE":k.activeLauncherKind==="cli"?"Choose a CLI provider":"Choose an ACP provider"}),t.jsx("div",{className:"grid grid-cols-1 gap-2",children:k.activeLauncherKind==="ide"?(e.detectedIdes||[]).slice(0,6).map(I=>t.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:T,selectedKey:K}=js({machine:{workspaces:k.workspaceRows,defaultWorkspaceId:k.defaultWorkspaceId},currentWorkspaceId:k.workspaceChoice!=="__custom__"?k.workspaceChoice:null,currentWorkspacePath:k.resolvedWorkspacePath});k.openLaunchConfirm({title:`Launch ${I.name}?`,description:"Review or change the target folder before opening this IDE.",confirmLabel:"Launch IDE",workspaceOptions:T,selectedWorkspaceKey:K,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:I.name}]},async()=>{const P=T.find($=>$.key===k.launchConfirmWorkspaceKeyRef.current);k.setWorkspaceSelectionFromOption(P),y(I.type,{workspacePath:(P==null?void 0:P.workspacePath)??null})})},children:[t.jsx("span",{className:"text-[13px] font-bold text-text-primary",children:I.name}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:k.resolvedWorkspacePath||"Use selected workspace"})]},I.type)):(k.activeLauncherKind==="cli"?n:a).map(I=>t.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 T=k.activeLauncherKind==="cli"?"cli":"acp",{options:K,selectedKey:P}=js({machine:{workspaces:k.workspaceRows,defaultWorkspaceId:k.defaultWorkspaceId},currentWorkspaceId:k.workspaceChoice!=="__custom__"?k.workspaceChoice:null,currentWorkspacePath:k.resolvedWorkspacePath});k.openLaunchConfirm({title:`Launch ${I.displayName}?`,description:"Review or change the provider workspace before starting this session.",confirmLabel:`Launch ${T.toUpperCase()}`,workspaceOptions:K,selectedWorkspaceKey:P,details:[{label:"Mode",value:T.toUpperCase()},{label:"Provider",value:I.displayName}],showArgsInput:!0,showModelInput:T==="acp",initialArgs:"",initialModel:"",providerType:I.type},async()=>{const $=K.find(V=>V.key===k.launchConfirmWorkspaceKeyRef.current);k.setWorkspaceSelectionFromOption($),N(T,I.type,{workspaceId:($==null?void 0:$.workspaceId)??null,workspacePath:($==null?void 0:$.workspacePath)??null,args:k.launchConfirmArgs,model:k.launchConfirmModel,resumeSessionId:k.launchConfirmResumeId||null})})},children:[t.jsxs("span",{className:"text-[13px] font-bold text-text-primary",children:[I.icon?`${I.icon} `:"",I.displayName]}),t.jsx("span",{className:"text-[11px] leading-relaxed text-text-muted break-all",children:k.resolvedWorkspacePath||"Use selected workspace"})]},I.type))})]}),c.message&&t.jsxs("div",{className:`mx-4 mt-2.5 p-3 rounded-xl text-xs leading-relaxed ${c.state==="error"?"text-status-error bg-status-error/10":"text-text-secondary bg-surface-primary/90"}`,children:[c.message,k.canCreateMissingWorkspace&&t.jsx("div",{className:"mt-2",children:t.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[34px] px-4 rounded-lg bg-surface-primary text-text-primary font-bold text-xs",onClick:()=>x(k.resolvedWorkspacePath,{createIfMissing:!0}),children:"Create folder"})})]})]}),t.jsxs("section",{className:"flex flex-col gap-0",children:[t.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&t.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:b,children:[t.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",l]}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),t.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:[t.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),t.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),k.browseDialogOpen&&t.jsx(Vn,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:k.browseCurrentPath,directories:k.browseDirectories,busy:k.browseBusy,error:k.browseError,confirmLabel:"Use this folder",onClose:()=>k.setBrowseDialogOpen(!1),onNavigate:I=>{k.loadBrowsePath(I)},onConfirm:I=>{k.chooseCustomWorkspacePath(I),k.setBrowseDialogOpen(!1)}}),k.launchConfirm&&t.jsx(ti,{title:k.launchConfirm.title,description:k.launchConfirm.description,details:k.launchConfirm.details,workspaceOptions:k.launchConfirm.workspaceOptions,selectedWorkspaceKey:k.launchConfirmWorkspaceKey,onWorkspaceChange:k.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:k.launchConfirm.providerType?In(!!k.launchConfirmResumeId):k.launchConfirm.confirmLabel,busyLabel:k.launchConfirm.providerType?void 0:k.launchConfirm.busyLabel,busy:k.launchConfirmBusy,showArgsInput:k.launchConfirm.showArgsInput,argsValue:k.launchConfirmArgs,onArgsChange:k.setLaunchConfirmArgs,showModelInput:k.launchConfirm.showModelInput,modelValue:k.launchConfirmModel,onModelChange:k.setLaunchConfirmModel,historyProviderNode:k.launchConfirm.providerType&&(k.launchConfirmSessionsLoading||k.launchConfirmSavedSessions.length>0)&&t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[t.jsxs("div",{className:"flex items-center justify-between mb-1",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),k.launchConfirmSessionsLoading&&t.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:Ho()}),t.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[t.jsx("input",{type:"text",value:k.launchConfirmTextFilter,onChange:I=>k.setLaunchConfirmTextFilter(I.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:k.launchConfirmBusy||k.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:k.launchConfirmWorkspaceFilter,onChange:I=>k.setLaunchConfirmWorkspaceFilter(I.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:k.launchConfirmBusy||k.launchConfirmSessionsLoading}),t.jsx("input",{type:"text",value:k.launchConfirmModelFilter,onChange:I=>k.setLaunchConfirmModelFilter(I.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:k.launchConfirmBusy||k.launchConfirmSessionsLoading}),t.jsxs("select",{value:k.launchConfirmSortMode,onChange:I=>k.setLaunchConfirmSortMode(I.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:k.launchConfirmBusy||k.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"recent",children:"Most recent"}),t.jsx("option",{value:"oldest",children:"Oldest first"}),t.jsx("option",{value:"messages",children:"Most messages"})]})]}),t.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[t.jsx("input",{type:"checkbox",checked:k.launchConfirmResumableOnly,onChange:I=>k.setLaunchConfirmResumableOnly(I.target.checked),disabled:k.launchConfirmBusy||k.launchConfirmSessionsLoading}),"Resume-ready only"]}),t.jsxs("select",{value:k.launchConfirmResumeId,onChange:I=>k.setLaunchConfirmResumeId(I.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:k.launchConfirmBusy||k.launchConfirmSessionsLoading,children:[t.jsx("option",{value:"",children:ox()}),k.filteredLaunchConfirmSavedSessions.map(I=>t.jsxs("option",{value:I.providerSessionId,disabled:!I.canResume,children:[I.title||I.providerSessionId," ",I.canResume?"":"(workspace missing)"]},I.providerSessionId))]}),!k.launchConfirmSessionsLoading&&k.launchConfirmSavedSessions.length>0&&k.filteredLaunchConfirmSavedSessions.length===0&&t.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),k.launchConfirmResumeId&&(()=>{const I=k.filteredLaunchConfirmSavedSessions.find(K=>K.providerSessionId===k.launchConfirmResumeId);if(!I)return null;const T=Wd(I);return t.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:[t.jsx("div",{className:"font-semibold text-text-primary truncate",children:T.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:T.providerSessionId}),t.jsx("div",{className:"mt-1",children:T.metaLine}),T.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:T.updatedLabel}),T.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:T.preview})]})})()]}),onConfirm:k.handleConfirmLaunch,onCancel:k.closeLaunchConfirm}),u&&t.jsx(Kd,{section:m,onSectionChange:g})]})}function mn(e){return[...e].sort((s,r)=>{const n=r.timestamp-s.timestamp;return n!==0?n:s.conversation.tabKey.localeCompare(r.conversation.tabKey)})}function Dg(e,s=[]){const r=new Map(e.map(a=>[a.conversation.tabKey,a])),n=s.map(a=>r.get(a)).filter(a=>!!a);return n.length===e.length?n:mn(e)}function Eg(e){var r;const s=((r=e.p2p)==null?void 0:r.state)||"";return s==="connected"?"Connected":s==="connecting"||s==="new"||s==="checking"?"Connecting":"Offline"}function $g(e,s){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:Ss(n.summaryMetadata)||n.workspace||void 0,workspace:n.workspace,summaryMetadata:n.summaryMetadata})):s.filter(n=>n.type!=="adhdev-daemon"&&n.daemonId===e.id).map(n=>{var l;const a=Cr(n)?"cli":Bs(n)?"acp":"ide",o=Ss(n.summaryMetadata);return{id:`${a}:${n.type}:${n.workspace||""}`,label:((l=n.activeChat)==null?void 0:l.title)||(Cr(n)?n.cliName||n.type:Bs(n)&&n.cliName||n.type),kind:a,providerType:n.type,providerSessionId:n.providerSessionId,subtitle:Bs(n)?o||n.workspace||void 0:n.workspace||void 0,workspace:n.workspace||void 0,timestamp:n.lastMessageAt||0}}).sort((n,a)=>a.timestamp-n.timestamp).map(({timestamp:n,...a})=>a)}function Bg(e,s){const r=new Map;for(const n of s){const a=As(n.conversation),o=r.get(a);o?o.push(n):r.set(a,[n])}return e.map(n=>{const a=r.get(n.id)||[],o=[...a].sort((h,g)=>g.timestamp-h.timestamp)[0]||null,l=(o==null?void 0:o.conversation)||null,c=eo(n),d=a.filter(h=>h.unread||h.requiresAction).length,m=Eg(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:l,latestTimestamp:(o==null?void 0:o.timestamp)||0,fallbackActivityAt:c,preview:l?Hh(l):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((n,a)=>{const o=n.latestTimestamp||n.fallbackActivityAt||0,l=a.latestTimestamp||a.fallbackActivityAt||0;return l!==o?l-o:n.label.localeCompare(a.label)})}function Og(e){return e==="chat"}function Qr(e,s){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}`,s)}catch{}}function Fg({conversations:e,machineEntries:s,items:r,selectedConversation:n,selectedTabKey:a,screen:o,liveSessionInboxState:l,sendDaemonCommand:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:g,onRequestedMobileSectionConsumed:j,setSelectedTabKey:f,setScreen:p,setSelectedMachineId:b,setSection:y,setMachineBackTarget:x,resetMachineAction:A}){const N=i.useRef(null),v=i.useCallback(C=>{if(!(C!=null&&C.sessionId))return;const M=wn(C,l),w=Math.max(Date.now(),ws(C),M.lastUpdated||0);Qr("mark_read:start",{tabKey:C.tabKey,sessionId:C.sessionId,displayPrimary:dt(C),inboxBucket:M.inboxBucket,unread:M.unread,lastSeenAt:M.lastSeenAt,lastUpdated:M.lastUpdated,activityAt:ws(C),readAt:w}),c(As(C)||C.routeId,"mark_session_seen",{sessionId:C.sessionId,providerSessionId:C.providerSessionId,seenAt:w,completionMarker:M.completionMarker}).then(k=>{Qr("mark_read:result",{tabKey:C.tabKey,sessionId:C.sessionId,result:k})}).catch(k=>{Qr("mark_read:error",{tabKey:C.tabKey,sessionId:C.sessionId,error:k instanceof Error?k.message:String(k)})})},[l,c]);return i.useEffect(()=>{var M;if(!n){Og(o)&&p("inbox"),f(((M=e[0])==null?void 0:M.tabKey)||null),N.current=null;return}if(o!=="chat"){N.current=null;return}const C=`${n.tabKey}:${n.sessionId||""}`;N.current!==C&&(N.current=C,v(n))},[e,v,o,n,p,f]),i.useEffect(()=>{if(!d)return;const C=e.find(M=>M.tabKey===d);C&&(f(C.tabKey),p("chat"),m==null||m())},[e,m,d,p,f]),i.useEffect(()=>{if(!u)return;const C=s.find(M=>M.id===u);C&&(b(C.id),A(),y("machines"),x("inbox"),p("machine"),h==null||h())},[s,h,u,A,x,p,y,b]),i.useEffect(()=>{g&&(y(g),p("inbox"),j==null||j())},[j,g,p,y]),i.useEffect(()=>{const C=r.filter(M=>M.inboxBucket==="task_complete"||M.unread);C.length!==0&&Qr("inbox_state",{screen:o,selectedTabKey:a,items:C.map(M=>{const w=wn(M.conversation,l);return{liveState:w,tabKey:M.conversation.tabKey,sessionId:M.conversation.sessionId,displayPrimary:dt(M.conversation),serverBucket:w.inboxBucket,computedBucket:M.inboxBucket,serverUnread:w.unread,computedUnread:M.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,activityAt:ws(M.conversation)}})})},[r,l,o,a]),{markConversationRead:v}}function Kg(e){if(!e)return"";const s=String(e);return s.includes(":")&&s.split(":")[0]||s}function hl(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Wg(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Hg({sendDaemonCommand:e,navigate:s,ides:r,conversations:n}){const[a,o]=i.useState("idle"),[l,c]=i.useState(""),[d,m]=i.useState(null),u=i.useCallback(()=>{o("idle"),c(""),m(null)},[]),h=i.useCallback(async(x,A,N)=>{var v;try{o("loading"),c(`Launching ${A}…`);const C={ideType:A,enableCdp:!0};(v=N==null?void 0:N.workspacePath)!=null&&v.trim()&&(C.workspace=N.workspacePath.trim()),await e(x,"launch_ide",C),o("done"),c(`${A} launch requested`)}catch(C){o("error"),c(C instanceof Error?C.message:"Launch IDE failed"),console.error("Launch IDE failed",C)}},[e]),g=i.useCallback(async(x,A,N)=>{if(A.trim())try{o("loading"),c(N!=null&&N.createIfMissing?"Creating folder…":"Saving workspace…");const v=await e(x,"workspace_add",{path:A.trim(),createIfMissing:(N==null?void 0:N.createIfMissing)===!0});if(v!=null&&v.success){o("done"),c(N!=null&&N.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}o("error"),c((v==null?void 0:v.error)||"Could not save workspace")}catch(v){o("error"),c(v instanceof Error?v.message:"Could not save workspace")}},[e]),j=i.useCallback(async x=>{var A,N,v,C,M,w;try{o("loading"),c("Starting daemon upgrade…");const k=await e(x,"daemon_upgrade",{});if((A=k==null?void 0:k.result)!=null&&A.alreadyLatest){o("done"),c(`Already on v${((N=k==null?void 0:k.result)==null?void 0:N.version)||"latest"}.`);return}if((v=k==null?void 0:k.result)!=null&&v.upgraded||(C=k==null?void 0:k.result)!=null&&C.success){o("done"),c(`Upgrade to v${((M=k==null?void 0:k.result)==null?void 0:M.version)||"latest"} started. Daemon is restarting…`);return}o("error"),c(((w=k==null?void 0:k.result)==null?void 0:w.error)||"Upgrade failed")}catch(k){o("error"),c(k instanceof Error?k.message:"Upgrade failed")}},[e]),f=i.useCallback(async(x,A,N,v)=>{var w,k,F;const C=Date.now(),M={machineId:x,kind:A,providerType:N,workspaceId:(v==null?void 0:v.workspaceId)||null,workspacePath:(v==null?void 0:v.workspacePath)||null,resumeSessionId:(v==null?void 0:v.resumeSessionId)||null,startedAt:C};try{o("loading"),c(`Launching ${N}…`),m(M);const _={cliType:N};(w=v==null?void 0:v.workspacePath)!=null&&w.trim()?_.dir=v.workspacePath.trim():v!=null&&v.workspaceId&&(_.workspaceId=v.workspaceId),v!=null&&v.resumeSessionId&&(_.resumeSessionId=v.resumeSessionId),(k=v==null?void 0:v.args)!=null&&k.trim()&&(_.cliArgs=v.args.trim().split(/\s+/).filter(Boolean)),(F=v==null?void 0:v.model)!=null&&F.trim()&&(_.initialModel=v.model.trim());const S=await e(x,"launch_cli",_),H=(S==null?void 0:S.result)||S,W=(H==null?void 0:H.sessionId)||(H==null?void 0:H.id);if(S!=null&&S.success&&W){m(null),o("done"),c(`${N} launched`),s(Vt(W));return}if(S!=null&&S.success){o("loading"),c(`${N} launch requested — waiting for session…`);return}m(null),o("error"),c((S==null?void 0:S.error)||(H==null?void 0:H.error)||`Could not launch ${A.toUpperCase()} workspace`)}catch(_){if(Wg(_)){o("loading"),c(`${N} launch requested — waiting for session…`);return}m(null),o("error"),c(_ instanceof Error?_.message:`Could not launch ${A.toUpperCase()} workspace`)}},[s,e]),p=i.useCallback(async(x,A)=>{try{const N=await e(x,"list_saved_sessions",{providerType:A,kind:"cli",limit:30}),v=(N==null?void 0:N.result)??N;return Array.isArray(v==null?void 0:v.sessions)?v.sessions:[]}catch(N){return console.error("Failed to list saved sessions on mobile:",N),[]}},[e]),b=i.useCallback(async(x,A)=>zn(e,x,A),[e]);i.useEffect(()=>{if(!d)return;const x=hl(d.workspacePath),A=r.find(v=>{var _,S,H,W;if(!v||v.type==="adhdev-daemon"||Kg(v.daemonId||v.id)!==d.machineId||(v.transport==="acp"?"acp":v.transport==="pty"?"cli":null)!==d.kind||String(v.agentType||v.type||"")!==d.providerType)return!1;const k=String(v.providerSessionId||"");if(d.resumeSessionId&&k)return k===d.resumeSessionId;if(x){const D=hl(v.workspace||v.runtimeWorkspaceLabel);return D?D===x:!1}return Number(v.lastUpdated||v._lastUpdate||v.timestamp||((W=(H=(S=(_=v.activeChat)==null?void 0:_.messages)==null?void 0:S.at)==null?void 0:H.call(S,-1))==null?void 0:W.timestamp)||0)>=d.startedAt-5e3});if(!A)return;const N=$d({entrySessionId:A.sessionId,entryInstanceId:A.instanceId,entryRouteId:A.id,conversations:n});N&&(m(null),o("done"),c(`${d.providerType} launched`),s(Vt(N)))},[n,r,s,d]),i.useEffect(()=>{if(!d)return;const x=window.setTimeout(()=>{m(A=>!A||A.startedAt!==d.startedAt?A:(o("error"),c("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(x)},[d]);const y=i.useCallback(async(x,A)=>{if(A.kind==="ide"&&A.providerType){await h(x,A.providerType,{workspacePath:A.workspace||null});return}(A.kind==="cli"||A.kind==="acp")&&A.providerType&&await f(x,A.kind,A.providerType,{workspacePath:A.workspace||null,resumeSessionId:A.providerSessionId||null})},[h,f]);return{machineAction:{state:a,message:l},resetMachineAction:u,handleLaunchDetectedIde:h,handleAddWorkspace:g,handleMachineUpgrade:j,handleLaunchWorkspaceProvider:f,handleListSavedSessions:p,handleBrowseDirectory:b,handleOpenRecent:y}}function Ug({conversations:e,selectedConversation:s,machineBackTarget:r,markConversationRead:n,resetMachineAction:a,setSelectedTabKey:o,setScreen:l,setSelectedMachineId:c,setSection:d,setMachineBackTarget:m}){const u=i.useCallback(y=>{o(y.tabKey),l("chat"),n(y)},[n,l,o]),h=i.useCallback(y=>{const x=e.find(A=>A.routeId===y.routeId&&A.streamSource==="native");x&&(o(x.tabKey),l("chat"),n(x))},[e,n,l,o]),g=i.useCallback(()=>{n(s),l("inbox")},[n,s,l]),j=i.useCallback((y,x="inbox")=>{c(y),a(),d("machines"),m(x),l("machine")},[a,m,l,d,c]),f=i.useCallback(y=>{const x=As(y);x&&j(x,"chat")},[j]),p=i.useCallback(()=>{a(),l(r)},[r,a,l]),b=i.useCallback(y=>{d(y),l("inbox")},[l,d]);return{openConversation:u,openNativeConversation:h,backFromConversation:g,openMachine:j,openConversationMachine:f,backFromMachine:p,changeMachineSection:b}}function Is(e,s){return e.category!==s?!1:s==="ide"?!0:e.enabled===!0}function zg(e){const s=e.trim();return s?s[0].toUpperCase():"?"}function Vg({conversations:e,hiddenConversations:s,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:l,userName:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:g,onRequestedMobileSectionConsumed:j,onOpenHistory:f,onOpenRemote:p,onStopCli:b,wsStatus:y,isConnected:x,onShowAllHiddenConversations:A,onHideConversation:N,onOpenMeshGraph:v,onOpenNewSession:C,liveSessionInboxState:M,setCliViewModeOverrides:w}){const[k,F]=i.useState(()=>{var ee;return((ee=e[0])==null?void 0:ee.tabKey)||null}),[_,S]=i.useState(()=>e[0]?"chat":"inbox"),[H,W]=i.useState("chats"),[D,I]=i.useState(null),[T,K]=i.useState("inbox"),P=i.useRef([]),$=cs(),V="0.9.81",Y=i.useMemo(()=>e.find(ee=>ee.tabKey===k)||e[0]||null,[e,k]),ge=i.useMemo(()=>Y?r.find(ee=>ee.id===Y.routeId):void 0,[r,Y]),fe=i.useMemo(()=>!Y||tt(Y)||!nt(Y)?null:Js(Y),[Y]),ae=i.useMemo(()=>r.filter(ee=>ee.type==="adhdev-daemon").sort(Ro),[r]),me=i.useMemo(()=>ae.find(ee=>ee.id===D)||null,[ae,D]),je=Fn({sendDaemonCommand:a,activeConv:Y||void 0,setActionLogs:o,isStandalone:l}),Ne=Hg({sendDaemonCommand:a,navigate:$,ides:r,conversations:e}),G=i.useMemo(()=>e.map(ee=>{const ke=_==="chat"&&(Y==null?void 0:Y.tabKey)===ee.tabKey,Ce=$n(ee,M,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ke}),ve=ws(ee),O=Yc(ee);return{conversation:ee,timestamp:ve,preview:O,unread:Ce.unread,requiresAction:Ce.requiresAction,isWorking:Ce.isWorking,inboxBucket:Ce.inboxBucket}}),[e,M,_,Y]),{markConversationRead:he}=Fg({conversations:e,machineEntries:ae,items:G,selectedConversation:Y,selectedTabKey:k,screen:_,liveSessionInboxState:M,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:m,requestedMachineId:u,onRequestedMachineConsumed:h,requestedMobileSection:g,onRequestedMobileSectionConsumed:j,setSelectedTabKey:F,setScreen:S,setSelectedMachineId:I,setSection:W,setMachineBackTarget:K,resetMachineAction:Ne.resetMachineAction}),pe=Ug({conversations:e,selectedConversation:Y,machineBackTarget:T,markConversationRead:he,resetMachineAction:Ne.resetMachineAction,setSelectedTabKey:F,setScreen:S,setSelectedMachineId:I,setSection:W,setMachineBackTarget:K}),ye=i.useMemo(()=>mn(G.filter(ee=>ee.requiresAction)),[G]),xe=i.useMemo(()=>mn(G.filter(ee=>ee.unread&&!ee.requiresAction)),[G]),Se=i.useMemo(()=>Dg(G.filter(ee=>!ee.unread&&!ee.requiresAction&&ee.isWorking),P.current),[G]);i.useEffect(()=>{P.current=Se.map(ee=>ee.conversation.tabKey)},[Se]);const R=i.useMemo(()=>mn(G.filter(ee=>!ee.unread&&!ee.requiresAction&&!ee.isWorking)),[G]),re=i.useMemo(()=>me?G.filter(ee=>As(ee.conversation)===me.id):[],[G,me]),Q=i.useMemo(()=>$g(me,r),[r,me]),ue=(me==null?void 0:me.version)||null,ce=!!me&&!!ue&&!0&&ue!==V,de=i.useMemo(()=>(me==null?void 0:me.availableProviders)||[],[me]),te=i.useMemo(()=>de.filter(ee=>Is(ee,"cli")).map(ee=>({type:ee.type,displayName:ee.displayName||ee.type,icon:ee.icon})),[de]),E=i.useMemo(()=>de.filter(ee=>Is(ee,"acp")).map(ee=>({type:ee.type,displayName:ee.displayName||ee.type,icon:ee.icon})),[de]),X=i.useMemo(()=>Bg(ae,G),[G,ae]),oe=i.useCallback(async ee=>{me&&await Ne.handleOpenRecent(me.id,ee)},[Ne,me]);return t.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:_==="chat"&&Y?t.jsx(Sg,{selectedConversation:Y,isAcp:tt(Y),isStandalone:l,selectedIdeEntry:ge,actionLogs:n,userName:c,isSendingChat:je.isSendingChat,sendFeedbackMessage:je.sendFeedbackMessage,isFocusingAgent:je.isFocusingAgent,handleModalButton:je.handleModalButton,handleRelaunch:je.handleRelaunch,onBack:pe.backFromConversation,onOpenNativeConversation:pe.openNativeConversation,onOpenMachine:pe.openConversationMachine,onOpenHistory:f,onOpenRemote:p,onOpenMeshGraph:v,onStopCli:b,cliViewMode:fe,onSetCliViewMode:async ee=>{await kd({conversation:Y,mode:ee,ides:r,sendDaemonCommand:a,setCliViewModeOverrides:w})},handleSendChat:je.handleSendChat,handleFocusAgent:je.handleFocusAgent}):_==="machine"&&me?t.jsx(Pg,{selectedMachineEntry:me,selectedMachineConversations:re,selectedMachineRecentLaunches:Q,cliProviders:te,acpProviders:E,selectedMachineNeedsUpgrade:ce,appVersion:V,machineAction:Ne.machineAction,isStandalone:l,section:H,showBottomNav:T==="inbox",onBack:pe.backFromMachine,onSectionChange:pe.changeMachineSection,onOpenConversation:pe.openConversation,onOpenRecent:oe,onOpenMachineDetails:()=>$(`/machines/${me.id}`),onMachineUpgrade:()=>Ne.handleMachineUpgrade(me.id),onLaunchDetectedIde:(ee,ke)=>Ne.handleLaunchDetectedIde(me.id,ee,ke),onAddWorkspace:(ee,ke)=>Ne.handleAddWorkspace(me.id,ee,ke),onBrowseDirectory:ee=>Ne.handleBrowseDirectory(me.id,ee),onLaunchWorkspaceProvider:(ee,ke,Ce)=>Ne.handleLaunchWorkspaceProvider(me.id,ee,ke,Ce),onListSavedSessions:ee=>Ne.handleListSavedSessions(me.id,ee)}):t.jsx(Tg,{section:H,attentionItems:ye,unreadItems:xe,workingItems:Se,completedItems:R,hiddenConversations:s,machineCards:X,getAvatarText:zg,actionLogs:n,sendDaemonCommand:a,onOpenConversation:pe.openConversation,onShowAllHidden:A,onHideConversation:N,onOpenMeshGraph:v,onOpenNewSession:C,onOpenMachine:pe.openMachine,onOpenSettings:()=>$("/settings"),onSectionChange:W,wsStatus:y,isConnected:x,isStandalone:l})})}function wa(e,s){return!!(e<4&&s&&window.innerWidth>=768)}function Gg({conversations:e,numGroups:s,onMoveTab:r,onReceiveTab:n,onOwnTabDrop:a,onClearPreviewOrder:o}){const l=i.useRef(0),[c,d]=i.useState(!1),[m,u]=i.useState(null),h=i.useCallback(()=>{l.current=0,d(!1),u(null)},[]);i.useEffect(()=>(window.addEventListener("dragend",h),window.addEventListener("drop",h),()=>{window.removeEventListener("dragend",h),window.removeEventListener("drop",h)}),[h]);const g=i.useCallback(b=>{b.dataTransfer.types.includes("text/tab-key")&&(l.current+=1,d(!0))},[]),j=i.useCallback(b=>{if(!b.dataTransfer.types.includes("text/tab-key"))return;if(b.preventDefault(),!wa(s,r)){u("merge");return}const y=b.currentTarget.getBoundingClientRect(),x=b.clientX-y.left,A=y.width/3;x<A?u("split-left"):x>A*2?u("split-right"):u("merge")},[s,r]),f=i.useCallback(()=>{l.current-=1,!(l.current>0)&&(l.current=0,d(!1),u(null))},[]),p=i.useCallback(b=>{l.current=0,d(!1);const y=b.dataTransfer.getData("text/tab-key"),x=y?e.some(N=>N.tabKey===y):!1,A=m;if(u(null),o(),!!y){if(b.preventDefault(),A==="split-left"&&wa(s,r)){r==null||r(y,"split-left");return}if(A==="split-right"&&wa(s,r)){r==null||r(y,"split-right");return}if(x){a(y);return}n==null||n(y)}},[e,m,s,r,n,a,o]);return{dragOver:c,dropAction:m,resetDragState:h,handleDragEnter:g,handleDragOver:j,handleDragLeave:f,handleDrop:p}}function qg(e,s){const r=new Set(s.map(o=>o.tabKey)),n=e.filter(o=>r.has(o)),a=s.filter(o=>!e.includes(o.tabKey)).map(o=>o.tabKey);return[...n,...a]}function Yg({conversations:e,initialActiveTabId:s,initialTabOrder:r,onActiveTabChange:n,onTabOrderChange:a}){const[o,l]=i.useState(s??null),[c,d]=i.useState(r??[]),[m,u]=i.useState(null),h=i.useRef(null),g=i.useRef(null),j=i.useRef(n),f=i.useRef(a);i.useEffect(()=>{j.current=n},[n]),i.useEffect(()=>{f.current=a},[a]),i.useEffect(()=>{s&&s!==o&&l(s)},[s,o]),i.useEffect(()=>{d(M=>{const w=qg(M,e);return w.length===M.length&&w.every((k,F)=>k===M[F])?M:w})},[e]);const p=i.useMemo(()=>{const M=m??c;if(M.length===0)return e;const w=new Map(M.map((k,F)=>[k,F]));return[...e].sort((k,F)=>{const _=w.get(k.tabKey)??999,S=w.get(F.tabKey)??999;return _-S})},[e,m,c]);i.useEffect(()=>{var w,k;if(p.length===0){o!==null&&(l(null),(w=j.current)==null||w.call(j,null));return}if(o&&p.some(F=>F.tabKey===o))return;const M=p[0].tabKey;M!==o&&(l(M),(k=j.current)==null||k.call(j,M))},[p,o]);const b=i.useMemo(()=>p.find(M=>M.tabKey===o),[p,o]),y=i.useCallback(M=>{var w;l(M),(w=j.current)==null||w.call(j,M)},[]),x=i.useCallback((M,w,k)=>{d(F=>{var W;const _=F.filter(D=>D!==M),S=_.indexOf(w);if(S<0)return F;const H=k==="left"?S:S+1;return _.splice(H,0,M),(W=f.current)==null||W.call(f,_),_}),u(null)},[]),A=i.useCallback((M,w,k)=>{const _=(c.length>0?c:e.map(W=>W.tabKey)).filter(W=>W!==M),S=_.indexOf(w);if(S<0)return;const H=k==="left"?S:S+1;_.splice(H,0,M),h.current=_,u(_)},[c,e]),N=i.useCallback(()=>{var w;const M=h.current;M&&(d(M),(w=f.current)==null||w.call(f,M))},[]),v=i.useCallback(()=>{h.current=null,u(null)},[]),C=i.useCallback(M=>{d(w=>{var F;const k=w.filter(_=>_!==M);return k.push(M),(F=f.current)==null||F.call(f,k),k})},[]);return{activeTabId:o,activeConv:b,sortedConversations:p,previewOrderRef:h,draggingTabRef:g,selectTab:y,handleTabReorder:x,updatePreviewOrder:A,commitPreviewOrder:N,clearPreviewOrder:v,moveTabToEnd:C,setDraggingTabKey:M=>{g.current=M}}}function Xg({dropAction:e,canSplit:s}){return t.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[t.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:s?1:.45},children:t.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"})}),t.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:t.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"})}),t.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:s?1:.45},children:t.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 si({conversationsCount:e,isSplitMode:s,isStandalone:r,hasRegisteredMachines:n=!1,suppressGuide:a=!1,onOpenNewSession:o}){if(a)return t.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const l=!r&&!n,c=n&&!!o,d=n?"No conversations yet":r?"Waiting for your daemon":"Connect your machines",m=n?Zc: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&&!s?t.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[t.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),t.jsxs("div",{className:"text-center max-w-lg",children:[t.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:d}),t.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:m}),c&&t.jsx("div",{className:"flex items-center justify-center mb-4",children:t.jsxs("button",{type:"button",onClick:o,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:Ht,"aria-label":Ht,children:[t.jsx(dc,{size:14}),t.jsx("span",{children:Ht})]})}),l&&t.jsx(Fd,{}),l&&t.jsx("div",{className:"mt-8",children:t.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 →"})})]})]}):t.jsx("div",{className:"text-sm text-text-muted opacity-50",children:s?"Move a tab here to view":"No active agent"})}const Ud="adhdev-tab-shortcuts";function zd(){try{return JSON.parse(localStorage.getItem(Ud)||"{}")}catch{return{}}}function Vd({enabled:e=!0,sortedTabKeys:s,onFocus:r,onSelectTab:n}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,l]=i.useState(()=>zd()),[c,d]=i.useState(null),m=i.useCallback(h=>{const g=[];return h.metaKey&&g.push(a?"⌘":"Meta"),h.ctrlKey&&g.push("Ctrl"),h.altKey&&g.push(a?"⌥":"Alt"),h.shiftKey&&g.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(g.push(h.key.length===1?h.key.toUpperCase():h.key),g.join("+"))},[a]),u=i.useCallback(h=>{l(h);try{localStorage.setItem(Ud,JSON.stringify(h))}catch{}},[]);return i.useEffect(()=>{if(!e||!c)return;const h=g=>{if(g.preventDefault(),g.stopPropagation(),g.key==="Escape"){d(null);return}const j=m(g);if(!j)return;const f={...o};for(const[p,b]of Object.entries(f))b===j&&delete f[p];f[c]=j,u(f),d(null)};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[e,c,o,u,m]),i.useEffect(()=>{if(!e)return;const h=g=>{if(!(!g.ctrlKey&&!g.metaKey&&!g.altKey)){for(const[j,f]of Object.entries(o))if(s.includes(j)&&m(g)===f){g.preventDefault(),r(),n(j);return}}};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[e,o,s,r,n,m]),{isMac:a,tabShortcuts:o,shortcutListening:c,setShortcutListening:d,saveShortcuts:u}}const ja=e=>{e.preventDefault()},Jg=i.memo(function({conv:s,isActive:r,isDraggedTab:n,isTaskCompleteUnread:a,shortcut:o,conversationKeys:l,draggingTabRef:c,onFocus:d,onSelectTab:m,onConversationActivated:u,onPreviewReorder:h,onReorderTab:g,onCommitPreviewOrder:j,onClearPreviewOrder:f,onDragStateReset:p,onDragTabKeyChange:b,onReceiveTab:y,onOpenContextMenu:x,longPressTimer:A,isGroupActive:N}){const v=Xs(s),C=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",M=v.isReconnecting,w=i.useCallback(T=>{c.current=s.tabKey,b(s.tabKey),T.dataTransfer.setData("text/tab-key",s.tabKey),T.dataTransfer.effectAllowed="move"},[s.tabKey,c,b]),k=i.useCallback(()=>{c.current=null,b(null),j(),f(),p()},[c,b,j,f,p]),F=i.useCallback(T=>{const K=c.current;if(!(!K||K===s.tabKey)&&T.dataTransfer.types.includes("text/tab-key")){T.preventDefault(),T.stopPropagation();const P=T.currentTarget.getBoundingClientRect(),$=T.clientX<P.left+P.width/2?"left":"right";h(K,s.tabKey,$)}},[s.tabKey,c,h]),_=i.useCallback(T=>{T.preventDefault(),T.stopPropagation();const K=T.dataTransfer.getData("text/tab-key");if(K&&K!==s.tabKey){const P=T.currentTarget.getBoundingClientRect(),$=T.clientX<P.left+P.width/2?"left":"right";l.includes(K)?g(K,s.tabKey,$):y&&y(K)}f()},[s.tabKey,l,g,y,f]),S=i.useCallback(T=>{T.stopPropagation(),d(),m(s.tabKey),u(s)},[s,u,d,m]),H=i.useCallback(T=>{T.preventDefault(),x(T.clientX,T.clientY,s.tabKey)},[s.tabKey,x]),W=i.useCallback(T=>{const K=T.touches[0];A.current=setTimeout(()=>{x(K.clientX,K.clientY,s.tabKey)},600)},[s.tabKey,A,x]),D=i.useCallback(()=>{A.current&&clearTimeout(A.current)},[A]),I=["adhdev-dockview-tab",C,r&&"is-active",N&&"is-group-active",M&&"is-reconnecting"].filter(Boolean).join(" ");return t.jsxs("div",{"data-tabkey":s.tabKey,className:I,draggable:!0,onDragStart:w,onDragEnd:k,onDragOver:F,onDrop:_,onClick:S,onContextMenu:H,onTouchStart:W,onTouchEnd:D,onTouchMove:D,style:{cursor:"pointer",opacity:n?.4:void 0},children:[a&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status",children:v.isGenerating?t.jsx("div",{className:"tab-spinner"}):v.isWaiting?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):M?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):v.isConnecting?t.jsx("div",{className:"tab-connecting-spinner"}):s.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("span",{className:"adhdev-dockview-tab-primary",title:dt(s),children:dt(s)}),t.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[M?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:xs(s)}):v.isConnecting?t.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[xs(s),t.jsx("span",{className:"connecting-dots"})]}):t.jsx("span",{className:"truncate",children:xs(s)}),t.jsx(Vs,{git:s.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),o&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${o}`,children:o})]})},(e,s)=>e.conv===s.conv&&e.isActive===s.isActive&&e.isDraggedTab===s.isDraggedTab&&e.isTaskCompleteUnread===s.isTaskCompleteUnread&&e.shortcut===s.shortcut&&e.conversationKeys===s.conversationKeys&&e.isGroupActive===s.isGroupActive);function Qg({conversations:e,activeTabId:s,groupIndex:r,unreadTabKeys:n,draggingTabRef:a,onFocus:o,onSelectTab:l,onConversationActivated:c,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:h,onDragStateReset:g,onDragTabKeyChange:j,onReceiveTab:f,onHideTab:p,isGroupActive:b,allowTabShortcuts:y=!0}){const[x,A]=i.useState(null),N=i.useRef(null),v=i.useRef(null),C=i.useMemo(()=>e.map(H=>H.tabKey),[e]);Ar("PaneGroupTabBar",{groupIndex:r,activeTabId:s,tabCount:e.length,ctxMenuTab:(x==null?void 0:x.tabKey)||null});const{isMac:M,tabShortcuts:w,shortcutListening:k,setShortcutListening:F,saveShortcuts:_}=Vd({enabled:y,sortedTabKeys:e.map(H=>H.tabKey),onFocus:o,onSelectTab:l});i.useEffect(()=>{if(!x)return;const H=W=>{const D=document.querySelector("[data-pane-context-menu]");D&&D.contains(W.target)||A(null)};return window.addEventListener("mousedown",H,!0),()=>window.removeEventListener("mousedown",H,!0)},[x]),i.useEffect(()=>{const H=v.current;if(!H)return;const W=D=>{Math.abs(D.deltaY)<=Math.abs(D.deltaX)||(D.preventDefault(),H.scrollLeft+=D.deltaY)};return H.addEventListener("wheel",W,{passive:!1}),()=>H.removeEventListener("wheel",W)},[]);const S=i.useCallback((H,W,D)=>{A({x:H,y:W,tabKey:D})},[]);return t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:t.jsxs("div",{ref:v,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(H=>t.jsx(Jg,{conv:H,isActive:s===H.tabKey,isDraggedTab:a.current===H.tabKey,isTaskCompleteUnread:n.has(H.tabKey),shortcut:y?w[H.tabKey]:void 0,conversationKeys:C,draggingTabRef:a,onFocus:o,onSelectTab:l,onConversationActivated:c,onPreviewReorder:d,onReorderTab:m,onCommitPreviewOrder:u,onClearPreviewOrder:h,onDragStateReset:g,onDragTabKeyChange:j,onReceiveTab:f,onOpenContextMenu:S,longPressTimer:N,isGroupActive:b},H.tabKey)),e.length===0&&t.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),x&&t.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:x.x,top:x.y},children:[y&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:ja,onClick:H=>{H.stopPropagation(),F(x.tabKey),A(null)},children:["⌨ ",w[x.tabKey]?`Change shortcut (${w[x.tabKey]})`:"Set shortcut"]}),w[x.tabKey]&&t.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:ja,onClick:()=>{const H={...w};delete H[x.tabKey],_(H),A(null)},children:"✕ Remove shortcut"})]}),p&&t.jsxs(t.Fragment,{children:[y&&t.jsx("div",{className:"border-t border-border-subtle my-1"}),t.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:ja,onClick:()=>{p(x.tabKey),A(null)},children:"🚫 Hide from Dashboard"})]})]}),y&&k&&t.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:()=>F(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:H=>H.stopPropagation(),children:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.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",")"]}),t.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),t.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function Zg({conversations:e,ides:s,clearedTabs:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:l,hasRegisteredMachines:c,userName:d,groupIndex:m,onFocus:u,isSplitMode:h,numGroups:g,onMoveTab:j,onReceiveTab:f,style:p,onActiveTabChange:b,initialActiveTabId:y,initialTabOrder:x,onTabOrderChange:A,onHideTab:N,isFocused:v,allowTabShortcuts:C=!0,onOpenNewSession:M,liveSessionInboxState:w}){const{sendCommand:k}=wt(),F=i.useRef(null),{activeTabId:_,activeConv:S,sortedConversations:H,draggingTabRef:W,selectTab:D,handleTabReorder:I,updatePreviewOrder:T,commitPreviewOrder:K,clearPreviewOrder:P,moveTabToEnd:$,setDraggingTabKey:V}=Yg({conversations:e,initialActiveTabId:y,initialTabOrder:x,onActiveTabChange:b,onTabOrderChange:A}),Y=Fn({sendDaemonCommand:a,activeConv:S,setActionLogs:o,isStandalone:l}),{dragOver:ge,dropAction:fe,resetDragState:ae,handleDragEnter:me,handleDragOver:je,handleDragLeave:Ne,handleDrop:G}=Gg({conversations:e,numGroups:g,onMoveTab:j,onReceiveTab:f,onOwnTabDrop:$,onClearPreviewOrder:P}),he=S&&!tt(S)&&Js(S)==="terminal",pe=i.useMemo(()=>S?s.find(R=>R.id===S.routeId):void 0,[s,S]),ye=i.useMemo(()=>S?n.filter(R=>R.routeId===S.tabKey):[],[n,S]),xe=i.useMemo(()=>new Set(H.filter(R=>Mp(R,w,{isOpenConversation:R.tabKey===_})).map(R=>R.tabKey)),[_,w,H]);Ar("PaneGroup",{groupIndex:m,conversationCount:e.length,activeTabId:_,dragOver:ge});const Se=i.useCallback(R=>{R.streamSource==="agent-stream"&&R.agentType&&k(R.routeId,Dc(),{agentType:R.agentType,...R.sessionId&&{targetSessionId:R.sessionId}}).catch(()=>{})},[k]);return t.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...p,outline:ge?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[t.jsx(Qg,{conversations:H,activeTabId:_,groupIndex:m,numGroups:g,unreadTabKeys:xe,draggingTabRef:W,onFocus:u,onSelectTab:D,onConversationActivated:Se,onPreviewReorder:T,onReorderTab:I,onCommitPreviewOrder:K,onClearPreviewOrder:P,onDragStateReset:ae,onDragTabKeyChange:V,onMoveTab:j,onReceiveTab:f,onHideTab:N,isGroupActive:v??!1,allowTabShortcuts:C}),t.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:me,onDragOver:je,onDragLeave:Ne,onDrop:G,children:[ge&&t.jsx(Xg,{dropAction:fe,canSplit:!!(g<4&&j)}),S?t.jsx(ei,{activeConv:S,clearToken:r[S.tabKey]||0,isCliTerminal:!!he,ideEntry:pe,terminalRef:F,handleModalButton:Y.handleModalButton,handleRelaunch:Y.handleRelaunch,handleSendChat:Y.handleSendChat,isSendingChat:Y.isSendingChat,sendFeedbackMessage:Y.sendFeedbackMessage,handleFocusAgent:Y.handleFocusAgent,isFocusingAgent:Y.isFocusingAgent,actionLogs:ye,userName:d,isInputActive:!h||!!v}):t.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:t.jsx(si,{conversationsCount:e.length,isSplitMode:h,isStandalone:l,hasRegisteredMachines:c,onOpenNewSession:M})})]})]})}function ey({containerRef:e,isSplitMode:s,numGroups:r,groupSizes:n,groupedConvs:a,clearedTabs:o,ides:l,actionLogs:c,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:h,userName:g,focusedGroup:j,focusGroup:f,moveTabToGroup:p,splitTabRelative:b,closeGroup:y,handleResizeStart:x,groupActiveTabIds:A,setGroupActiveTab:N,groupTabOrders:v,setGroupTabOrder:C,toggleHiddenTab:M,onOpenNewSession:w,allowTabShortcuts:k=!0,liveSessionInboxState:F}){return t.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${s?"flex-row":"flex-col"} overflow-hidden`,children:a.map((_,S)=>{const H=s&&n.length===r?`${n[S]}%`:void 0;return t.jsxs(kt.Fragment,{children:[s&&S>0&&t.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:W=>x(S-1,W),onDoubleClick:()=>y(S),title:"Drag to resize · Double-click to merge",children:t.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),t.jsx(Zg,{style:s?{flexBasis:H??`${100/r}%`,flexGrow:H?0:1,flexShrink:H?0:1}:void 0,conversations:_,clearedTabs:o,ides:l,actionLogs:c,sendDaemonCommand:d,setActionLogs:m,isStandalone:u,hasRegisteredMachines:h,userName:g,groupIndex:S,isFocused:s&&j===S,onFocus:()=>f(S),isSplitMode:s,numGroups:r,onMoveTab:(W,D)=>{D==="left"&&S>0?p(W,S-1):D==="right"&&S<r-1?p(W,S+1):D==="split-left"&&r<4?b(W,S,"left"):D==="split-right"&&r<4&&b(W,S,"right")},onReceiveTab:W=>p(W,S),onActiveTabChange:W=>N(S,W),initialActiveTabId:A[S],initialTabOrder:v[S],onTabOrderChange:W=>C(S,W),onHideTab:M,onOpenNewSession:w,allowTabShortcuts:k,liveSessionInboxState:F})]},S)})})}function Gd({doId:e,targetSessionId:s,connState:r,viewMode:n}){const[a,o]=i.useState(null),[l,c]=i.useState(null);i.useEffect(()=>e?ut.onScreenshot("ide-page",(u,h)=>{if(u!==e)return;const g=new FileReader;g.onload=()=>o(g.result),g.readAsDataURL(h)}):void 0,[e]),i.useEffect(()=>{r!=="connected"&&o(null)},[r]),i.useEffect(()=>{var u;return e?((u=ut.onStatus)==null?void 0:u.call(ut,(h,g)=>{h===e&&g!=null&&g.screenshotUsage&&c(g.screenshotUsage)}))||(()=>{}):void 0},[e]),i.useEffect(()=>{o(null)},[e,s]),i.useEffect(()=>{const m=e?ut.get(e):null;if(!(!m||r!=="connected"))return n!=="chat"&&s?m.startScreenshots(s):m.stopScreenshots(s),()=>{m.stopScreenshots(s)}},[n,r,s,e]);const d=i.useCallback(async(m,u)=>{const h=e?ut.get(e):null;return!h||r!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):h.sendInput(m,u,s)},[e,r,s]);return{connScreenshot:a,screenshotUsage:l,handleRemoteAction:d}}const qd="adhdev-dashboard-action-shortcuts",ty=1200,sy=[["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 ry(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function it(e,s){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return s?"⌘+⇧+Enter":"Ctrl+Shift+Enter";case"hideCurrentTab":return s?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return s?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return s?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return s?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return s?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return s?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return s?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return s?"⌘+Ctrl+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return s?"⌘+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 s?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return s?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return s?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return s?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return s?"⌘+⇧+←":"Ctrl+Shift+←";case"selectNextGroupTab":return s?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return s?"⌥+T":"Ctrl+Alt+T"}}function Yd(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:it("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:it("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:it("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:it("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:it("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:it("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:it("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:it("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:it("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:it("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:it("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:it("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:it("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:it("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:it("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:it("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:it("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:it("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:it("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:it("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:it("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:it("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:it("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:it("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:it("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:it("toggleCliView",e)}]}function fo(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const s=e.tagName;return s==="INPUT"||s==="TEXTAREA"||s==="SELECT"}function Rn(e){const s=Object.fromEntries(Yd(e).map(r=>[r.id,r.defaultShortcut]));try{const r=JSON.parse(localStorage.getItem(qd)||"{}"),n={...s,...r};for(const[a,o]of sy)n[a]===o&&(n[a]=s[a]);return n}catch{return s}}function Xd(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function ny({enabled:e=!0,onTrigger:s}){const r=ry(),[n,a]=i.useState(()=>Rn(r)),[o,l]=i.useState(null),[c,d]=i.useState([]),m=i.useRef({parts:[],timer:null}),u=i.useCallback(p=>{const b=[];return p.metaKey&&b.push(r?"⌘":"Meta"),p.ctrlKey&&b.push("Ctrl"),p.altKey&&b.push(r?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&b.push(r?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(b.push(Xd(p.key)),b.join("+"))},[r]),h=i.useCallback(p=>{a(p);try{localStorage.setItem(qd,JSON.stringify(p))}catch{}},[]);i.useEffect(()=>{const p=Rn(r),b=Object.entries(n),y=Object.entries(p);b.length===y.length&&b.every(([x,A])=>p[x]===A)||h(p)},[n,r,h]);const g=i.useCallback(()=>{typeof window<"u"&&m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current={parts:[],timer:null}},[]),j=i.useCallback(()=>{typeof window>"u"||(m.current.timer!=null&&window.clearTimeout(m.current.timer),m.current.timer=window.setTimeout(()=>{m.current={parts:[],timer:null}},ty))},[]);i.useEffect(()=>{if(!o)return;const p=b=>{if(b.preventDefault(),b.stopPropagation(),b.key==="Escape"){l(null),d([]);return}const y=u(b);if(!y)return;const A=!(b.metaKey||b.ctrlKey||b.altKey)&&/^[A-Z0-9]$/.test(y);if(c.length===0&&A){d([y]);return}const v=[...c,y].slice(0,2).join(" "),C={...n};for(const[M,w]of Object.entries(C))w===v&&delete C[M];C[o]=v,h(C),l(null),d([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[n,u,h,o,c]),i.useEffect(()=>{if(!e||o)return;const p=b=>{if(b.defaultPrevented)return;const y=u(b);if(!y)return;const x=b.metaKey||b.ctrlKey||b.altKey;if(fo(b.target))return;const A=m.current.parts,N=x?[y]:[...A.slice(-1),y].slice(-2),v=N.join(" "),C=N[N.length-1],M=Object.entries(n).filter(([,S])=>!!S),w=M.find(([,S])=>S===v);if(w){b.preventDefault(),g(),s(w[0]);return}if(M.some(([,S])=>S.startsWith(`${v} `))){b.preventDefault(),m.current.parts=N,j();return}const F=M.find(([,S])=>S===C);if(F){b.preventDefault(),g(),s(F[0]);return}if(M.some(([,S])=>S.startsWith(`${C} `))){b.preventDefault(),m.current.parts=[C],j();return}g()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[n,j,e,u,s,g,o]),i.useEffect(()=>()=>g(),[g]);const f=i.useMemo(()=>Yd(r),[r]);return{isMac:r,actionDefinitions:f,actionShortcuts:n,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:l,setShortcutListeningDraft:d,saveShortcuts:h}}function ay({isTabInPopout:e,isTabFloating:s,tabShortcut:r,actionShortcuts:n}){const a=[];return e?(s&&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})):s?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 Jd(e){return e.some(s=>s.type!=="adhdev-daemon")||e.some(s=>s.type==="adhdev-daemon"&&!!s.machine)}function xl({hasStoredLayout:e,initialDataLoaded:s,visibleConversationCount:r,ides:n}){return!e||r>0?!1:s?!Jd(n):!0}function oy({previousVisibleConversationCount:e,visibleConversationCount:s,ides:r}){return s>0||e<=0?!1:Jd(r)}const Qd=1e3,iy=4;function bl(e,s){return s?e.clientX>=s.left&&e.clientX<=s.right&&e.clientY>=s.top&&e.clientY<=s.bottom:!1}function gl(e,s,r){return Math.abs(s.clientX-e.clientX)>r||Math.abs(s.clientY-e.clientY)>r}function ly({detachDelayMs:e=Qd,stillnessThresholdPx:s=iy,onDetach:r,setTimeoutFn:n=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,l=null,c=null,d=null,m=null,u=!1;const h=()=>{m!=null&&(a(m),m=null)},g=()=>{h(),c=null},j=()=>{h(),o=null,l=null,c=null,d=null,u=!1},f=()=>{!o||!c||!d||u||m!=null||(m=n(()=>{m=null,!(!o||!c||!d||u)&&bl(d,l)&&(gl(c,d,s)||(u=!0,r({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},p=y=>{if(!(!o||u)){if(!bl(y,l)){d={clientX:y.clientX,clientY:y.clientY},g();return}(!c||gl(c,y,s))&&(h(),c={clientX:y.clientX,clientY:y.clientY}),d={clientX:y.clientX,clientY:y.clientY},f()}},b=y=>{!o||u||(y&&(d={clientX:y.clientX,clientY:y.clientY}),g())};return{startDrag:y=>{h(),o=y.panelId,l=y.selfPanelBounds??null,c=null,d={clientX:y.clientX,clientY:y.clientY},u=!1},markSelfPanel:p,markNonSelfPanel:b,markNoDropTarget:b,markDockTarget:b,endDrag:j,isDragging:()=>o!=null,hasDetached:()=>u,dispose:j}}function cy(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Zr(e){return e.isActive}function yl(e){return e.isVisible}const Zd=i.createContext(null);function Gn(){const e=i.useContext(Zd);if(!e)throw new Error("DashboardDockviewContext missing");return e}function pn(e){return dt(e)||e.tabKey}function dy(e){return`remote:${e}`}function Dt(e){return e.startsWith("remote:")}function vl(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function uy(e){e.preventDefault()}function ka(e){var n;const s=e==null?void 0:e.defaultView;if(!s)return;const r=a=>{if(a)try{a.focus({preventScroll:!0})}catch{try{a.focus()}catch{}}};try{s.focus(),r(e==null?void 0:e.body),r(e==null?void 0:e.documentElement),(n=s.requestAnimationFrame)==null||n.call(s,()=>{try{s.focus(),r(e==null?void 0:e.body)}catch{}})}catch{}}function Na(e,s){e.classList.remove(Ga.className,qa.className),e.classList.add(s==="light"?Ga.className:qa.className)}function wl(e){return e?Array.from(new Set(e.groups.map(s=>{var r,n;return(n=(r=s.element)==null?void 0:r.ownerDocument)==null?void 0:n.defaultView}).filter(s=>!!s&&s!==window))):[]}function my(e){const[,s]=i.useState(0);i.useEffect(()=>{const r=()=>s(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 py(e,s,r){var l;const n=[s];let a;for(const c of n){let d;for(const m of c){const u=e.addPanel({id:m.tabKey,component:"conversation",title:pn(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??((l=s[0])==null?void 0:l.tabKey)??null}function jl(e,s){const r=new Set(s.map(a=>a.tabKey)),n=new Map;for(const a of s)n.set(a.tabKey,(n.get(a.tabKey)||0)+1);for(const a of[...e.panels])Dt(a.id)||r.has(a.id)||e.removePanel(a);for(const a of s){const o=e.getPanel(a.tabKey);if(o){(n.get(a.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:a.tabKey,daemonId:a.daemonId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,panelId:o.id}),o.update({params:{tabKey:a.tabKey}}),o.title!==pn(a)&&o.api.setTitle(pn(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:pn(a),params:{kind:"conversation",tabKey:a.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function kl(e,s,r){var d,m;const n=r?dy(r):null;for(const u of[...e.panels])Dt(u.id)&&(!n||u.id!==n)&&e.removePanel(u);if(!r||!n)return;const a=Bt(s,r);if(!a&&e.totalPanels===0)return;const o=e.getPanel(n),l=Qc(a);if(o){o.title!==l&&o.api.setTitle(l);return}const c=(a==null?void 0:a.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((m=e.panels.find(u=>!Dt(u.id)))==null?void 0:m.id);e.addPanel({id:n,component:"remote",title:l,params:{kind:"remote",routeId:r},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function fy({params:e,api:s}){var j;const r=Gn(),n=i.useRef(null),[a,o]=i.useState(()=>Zr(s)),[l,c]=i.useState(()=>yl(s)),d=r.conversationsByTabKey.get(e.tabKey),m=Fn({sendDaemonCommand:r.sendDaemonCommand,activeConv:d,setActionLogs:r.setActionLogs,isStandalone:r.isStandalone});i.useEffect(()=>{o(Zr(s)),c(yl(s));const f=[s.onDidActiveChange(p=>o(p.isActive)),s.onDidActiveGroupChange(p=>{if(!Zr(s)&&!p.isActive){o(!1);return}o(Zr(s))}),s.onDidVisibilityChange(p=>c(p.isVisible))];return()=>{for(const p of f)p.dispose()}},[s]);const u=i.useMemo(()=>d?r.ides.find(f=>f.id===d.routeId):void 0,[r.ides,d]),h=i.useMemo(()=>d?r.actionLogs.filter(f=>f.routeId===d.tabKey):[],[r.actionLogs,d]);if(!d)return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:t.jsx(si,{conversationsCount:0,isSplitMode:!1,isStandalone:r.isStandalone,hasRegisteredMachines:r.hasRegisteredMachines,onOpenNewSession:r.onOpenNewSession,suppressGuide:r.hasDetachedConversationPanels})});const g=!tt(d)&&Js(d)==="terminal";return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:t.jsx(ei,{activeConv:d,clearToken:r.clearedTabs[d.tabKey]||0,isCliTerminal:g,ideEntry:u,terminalRef:n,handleModalButton:m.handleModalButton,handleRelaunch:m.handleRelaunch,handleSendChat:m.handleSendChat,isSendingChat:m.isSendingChat,handleFocusAgent:m.handleFocusAgent,isFocusingAgent:m.isFocusingAgent,actionLogs:h,userName:r.userName,scrollToBottomRequestNonce:((j=r.scrollToBottomRequest)==null?void 0:j.tabKey)===d.tabKey?r.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:l})})}function hy({params:e}){var d;const s=Gn(),r=i.useMemo(()=>Bt([...s.conversationsByTabKey.values()],e.routeId),[s.conversationsByTabKey,e.routeId]),n=i.useMemo(()=>s.ides.find(m=>m.id===e.routeId),[s.ides,e.routeId]),a=(r==null?void 0:r.daemonId)||((d=r==null?void 0:r.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:l,handleRemoteAction:c}=Gd({doId:a,targetSessionId:r?Pc(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?t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:t.jsx(gc,{addLog:()=>{},connState:r.connectionState||"new",connScreenshot:o,screenshotUsage:l,transportType:r.transport,onAction:c})}):t.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 xy(){const e=Gn();return t.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:t.jsx(si,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function by(e){var j,f;my(e);const s=Gn(),r=i.useCallback(p=>{"button"in p&&p.button!==0||e.api.setActive()},[e.api]);if(e.params.kind==="remote"){const p=Bt([...s.conversationsByTabKey.values()],e.params.routeId),b=((j=e.api.group.activePanel)==null?void 0:j.id)===e.api.id,y=e.api.isGroupActive;return t.jsxs("div",{className:`adhdev-dockview-tab${b?" is-active":""}${y?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(p==null?void 0:p.tabKey)||"",onMouseDown:r,onTouchStart:r,children:[t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:p!=null&&p.machineName?t.jsxs(t.Fragment,{children:[t.jsx("span",{children:"Live remote view"}),t.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),t.jsx("span",{className:"adhdev-dockview-tab-machine",children:p.machineName})]}):t.jsx("span",{children:"Live remote view"})})]})]})}const n=s.conversationsByTabKey.get(e.params.tabKey);if(!n)return t.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:t.jsx("div",{className:"adhdev-dockview-tab-copy",children:t.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const a=((f=e.api.group.activePanel)==null?void 0:f.id)===e.api.id,o=e.api.isGroupActive,l=$n(n,s.liveSessionInboxState,{isOpenConversation:a}),c=l.isReconnecting,d=l.isConnecting,m=l.isGenerating,u=l.isWaiting,h=l.unread,g=s.tabShortcuts[n.tabKey];return t.jsxs("div",{className:`adhdev-dockview-tab${a?" is-active":""}${o?" is-group-active":""}${c?" is-reconnecting":""}`,title:dt(n),"data-tab-key":e.params.tabKey,onMouseDown:r,onTouchStart:r,onContextMenu:p=>{var b;p.preventDefault(),r(p),s.openTabContextMenu({x:p.clientX,y:p.clientY,tabKey:n.tabKey,sourceDocument:((b=p.target)==null?void 0:b.ownerDocument)??document})},children:[h&&t.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),t.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:m?t.jsx("div",{className:"tab-spinner"}):u?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):c?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):d?t.jsx("div",{className:"tab-connecting-spinner"}):n.connectionState==="connected"?t.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):t.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),t.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[t.jsx("div",{className:"adhdev-dockview-tab-primary",children:dt(n)}),t.jsx("div",{className:"adhdev-dockview-tab-meta",children:c?t.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:xs(n)}):d?t.jsx("span",{className:"adhdev-dockview-tab-connecting",children:xs(n)}):t.jsx("span",{children:xs(n)})})]}),g&&t.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:g,children:g})]})}function gy({visibleConversations:e,clearedTabs:s,ides:r,actionLogs:n,sendDaemonCommand:a,setActionLogs:o,isStandalone:l,hasRegisteredMachines:c,initialDataLoaded:d,userName:m,toggleHiddenTab:u,actionShortcuts:h,registerActionHandlers:g,onActiveTabChange:j,onOpenNewSession:f,onRequestScrollToBottom:p,requestedActiveTabKey:b,requestedRemoteIdeId:y,onRequestedActiveTabConsumed:x,scrollToBottomRequest:A,liveSessionInboxState:N,layoutProfile:v}){var et,ze,at;const{theme:C}=qo(),{sendCommand:M}=wt(),w=i.useRef(null),k=i.useRef(null),F=i.useRef(null),_=i.useRef(!1),S=i.useRef(!1),H=i.useRef(!1),W=i.useRef(null),D=i.useRef([]),[I,T]=i.useState(null),[K,P]=i.useState(0),$=i.useRef(typeof window>"u"?{}:$b(v)),V=i.useMemo(()=>new Map(e.map(U=>[U.tabKey,U])),[e]),Y=i.useMemo(()=>{const U=w.current;return U?U.groups.some(z=>{try{const Z=z.model.location.type;return Z!=="floating"&&Z!=="popout"?!1:z.panels.some(ie=>V.has(ie.id))}catch{return!1}}):!1},[V,K,e]),ge=i.useCallback(()=>{var U;(U=w.current)==null||U.focus()},[]),fe=i.useCallback((U,z)=>{p==null||p(U,z)},[p]),ae=i.useCallback(U=>{const z=document,Z=U.document;for(const le of z.querySelectorAll('link[rel="stylesheet"]')){const we=Z.createElement("link");we.rel="stylesheet",we.href=le.href,le.crossOrigin&&(we.crossOrigin=le.crossOrigin),Z.head.appendChild(we)}for(const le of z.querySelectorAll("style")){const we=Z.createElement("style");we.textContent=le.textContent,Z.head.appendChild(we)}const ie=[];for(const le of z.styleSheets)try{for(const we of le.cssRules)we instanceof CSSStyleRule&&(we.selectorText===":root"||we.selectorText==="html")&&ie.push(we.cssText)}catch{}if(ie.length>0){const le=Z.createElement("style");le.textContent=ie.join(`
|
|
54
|
-
`),Z.head.appendChild(le)}const B=z.documentElement.getAttribute("data-theme");B&&Z.documentElement.setAttribute("data-theme",B),Z.documentElement.style.colorScheme=B==="light"?"light":"dark",Z.body.className=z.body.className;const q=z.documentElement.getAttribute("style");q&&Z.documentElement.setAttribute("style",q);const ne=Z.getElementById("dv-popout-window");ne instanceof HTMLElement&&(ne.classList.add("adhdev-dockview"),Na(ne,C))},[C]),me=i.useCallback(()=>{var z;const U=w.current;if(U)for(const Z of U.groups)try{const ie=(z=Z.element)==null?void 0:z.ownerDocument;if(!ie||ie===document)continue;const B=ie.getElementById("dv-popout-window");B instanceof HTMLElement&&(B.classList.add("adhdev-dockview"),Na(B,C));const q=document.documentElement.getAttribute("data-theme");q&&ie.documentElement.setAttribute("data-theme",q),ie.documentElement.style.colorScheme=q==="light"?"light":"dark",ie.body.className=document.body.className;const ne=document.documentElement.getAttribute("style");ne?ie.documentElement.setAttribute("style",ne):ie.documentElement.removeAttribute("style")}catch{}},[C]),je=i.useCallback(U=>{const z=w.current;if(!z)return;const Z=z.getPanel(U);Z&&z.addPopoutGroup(Z,{popoutUrl:"/popout.html",onDidOpen:({window:ie})=>{ae(ie),re();const B=V.get(U);ie.document.title=B?`${dt(B)} — ADHDev`:"ADHDev — Popout"}})},[V,ae]),Ne=i.useCallback(U=>{const z=w.current,Z=z==null?void 0:z.getPanel(U);if(!z||!Z)return;const ie=z.groups.filter(B=>{var q;try{return((q=B.element)==null?void 0:q.ownerDocument)===document}catch{return!0}});ie.length>0?Z.api.moveTo({group:ie[0],position:"center"}):Z.api.moveTo({position:"center"}),Z.api.setActive()},[]),G=i.useCallback(U=>{var ie;const z=w.current;if(!z)return!1;const Z=z.getPanel(U);if(!Z)return!1;try{return((ie=Z.group.element)==null?void 0:ie.ownerDocument)!==document}catch{return!1}},[]),he=i.useCallback(U=>{G(U)&&Ne(U),u(U)},[G,Ne,u]),pe=i.useCallback(U=>{const z=w.current,Z=z==null?void 0:z.getPanel(U);!z||!Z||z.addFloatingGroup(Z,{width:600,height:500})},[]),ye=i.useCallback(U=>{var Z;const z=(Z=w.current)==null?void 0:Z.getPanel(U);if(!z)return!1;try{return z.group.model.location.type==="floating"}catch{return!1}},[]),xe=i.useCallback(()=>{var z,Z;const U=(Z=(z=w.current)==null?void 0:z.activePanel)==null?void 0:Z.id;return!U||Dt(U)?null:V.has(U)?U:null},[V]),Se=i.useCallback(U=>{const z=w.current,Z=z==null?void 0:z.getPanel(U);if(!z||!Z)return;const ie=z.groups.filter(B=>{try{return B.model.location.type==="grid"}catch{return!0}});ie.length>0?Z.api.moveTo({group:ie[0],position:"center"}):Z.api.moveTo({position:"center"}),Z.api.setActive()},[]),R=i.useCallback(()=>{var q;const U=w.current;if(!U)return;const Z=U.groups.filter(ne=>{var le;try{return((le=ne.element)==null?void 0:le.ownerDocument)===document&&ne.model.location.type==="grid"}catch{return!1}})[0]||null,ie=[...U.panels];for(const ne of ie){const le=(q=ne.group.element)==null?void 0:q.ownerDocument,we=ne.group.model.location.type;le===document&&we==="grid"||(Z&&Z.id!==ne.group.id?ne.api.moveTo({group:Z,position:"center"}):ne.api.moveTo({position:"center"}))}const B=U.activePanel;B&&(B.group.model.openPanel(B),B.api.setActive()),ka(document)},[]),re=i.useCallback(()=>{var z,Z;const U=w.current;if(U)for(const ie of U.groups){const B=(z=ie.element)==null?void 0:z.ownerDocument;if(!B||B===document)continue;const q=B.getElementById("dv-popout-window");if(!(q instanceof HTMLElement))continue;let ne=null,le=B.title||"ADHDev",we="Popout workspace";const _e=ie.activePanel;if(_e)if(ne=_e.id,Dt(_e.id)){const Ae=((Z=_e.params)==null?void 0:Z.routeId)||_e.id.slice(7),Je=Bt([...V.values()],Ae);le=Qc(Je),we=Je!=null&&Je.machineName?`Remote view · ${Je.machineName}`:"Remote view"}else{const Ae=V.get(_e.id);le=Ae?dt(Ae):_e.title||_e.id,we=Ae?xs(Ae):"Dockview panel"}B.title=`${le} — ADHDev`;const De=Array.from(B.querySelectorAll("#adhdev-popout-header"));for(const Ae of De)Ae.remove();const Me=B.createElement("div");Me.id="adhdev-popout-header",B.body.appendChild(Me),Me.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(";")),Me.innerHTML=`
|
|
55
|
-
<div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
|
|
56
|
-
<div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
|
|
57
|
-
<div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${vl(le)}</div>
|
|
58
|
-
<div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${vl(we)}</div>
|
|
59
|
-
</div>
|
|
60
|
-
<div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
|
|
61
|
-
<button type="button" data-adhdev-popout-focus style="height:30px;padding:0 10px;border-radius:9px;background:var(--bg-glass);color:var(--text-secondary);font-size:11px;font-weight:600;">Dashboard</button>
|
|
62
|
-
<button type="button" data-adhdev-popout-dock style="height:30px;padding:0 10px;border-radius:9px;background:var(--surface-primary);color:var(--text-primary);font-size:11px;font-weight:700;">Dock</button>
|
|
63
|
-
</div>
|
|
64
|
-
`,q.style.top="52px",q.style.height="calc(100% - 52px)";const Ee=Me.querySelector("[data-adhdev-popout-focus]");Ee&&(Ee.onclick=()=>{window.focus()});const Oe=Me.querySelector("[data-adhdev-popout-dock]");Oe&&(Oe.disabled=!ne,Oe.style.opacity=ne?"1":"0.5",Oe.style.cursor=ne?"pointer":"default",Oe.onclick=()=>{var Ae;ne&&Ne(ne),(Ae=B.defaultView)==null||Ae.focus()})}},[V,Ne]),Q=i.useCallback(U=>{var ie;const z=w.current,Z=z==null?void 0:z.getPanel(U);if(!(!z||!Z)){Z.group.model.openPanel(Z),Z.api.setActive(),fe(U,"dockview-shortcut");try{const B=Z.group.model.location;B.type==="popout"?B.getWindow().focus():ka((ie=Z.group.element)==null?void 0:ie.ownerDocument)}catch{}}},[fe]),ue=i.useCallback(U=>{const z=w.current,Z=z==null?void 0:z.activePanel,ie=(z==null?void 0:z.activeGroup)||(Z==null?void 0:Z.group);if(!z||!Z||!ie)return;const B=ie.panels||[];if(B.length<=1)return;const q=B.findIndex(we=>we.id===Z.id);if(q<0)return;const ne=(q+U+B.length)%B.length,le=B[ne];le&&(le.group.model.openPanel(le),le.api.setActive(),Dt(le.id)||fe(le.id,"dockview-shortcut"))},[fe]),ce=i.useCallback(U=>{var Ee;const z=w.current,Z=(z==null?void 0:z.activeGroup)||((Ee=z==null?void 0:z.activePanel)==null?void 0:Ee.group);if(!z||!Z)return;const ie=z.groups||[],B=ie.find(Oe=>Oe.id===Z.id);if(!B)return;const q=B.element.getBoundingClientRect(),ne=q.left+q.width/2,le=q.top+q.height/2,we=(Oe,Ae,Je,Ze)=>Math.max(0,Math.min(Ae,Ze)-Math.max(Oe,Je)),_e=Oe=>{const Ae=Oe.element.getBoundingClientRect(),Je=Ae.left+Ae.width/2,Ze=Ae.top+Ae.height/2;let xt=0,bt=0,ct=0,pt=!1;if(U==="left"?(pt=Je<ne,xt=Math.max(0,q.left-Ae.right),bt=Math.abs(Ze-le),ct=we(q.top,q.bottom,Ae.top,Ae.bottom)):U==="right"?(pt=Je>ne,xt=Math.max(0,Ae.left-q.right),bt=Math.abs(Ze-le),ct=we(q.top,q.bottom,Ae.top,Ae.bottom)):U==="above"?(pt=Ze<le,xt=Math.max(0,q.top-Ae.bottom),bt=Math.abs(Je-ne),ct=we(q.left,q.right,Ae.left,Ae.right)):(pt=Ze>le,xt=Math.max(0,Ae.top-q.bottom),bt=Math.abs(Je-ne),ct=we(q.left,q.right,Ae.left,Ae.right)),!pt)return Number.POSITIVE_INFINITY;const We=ct>0?0:120;return xt*3+bt+We};let De=null,Me=Number.POSITIVE_INFINITY;for(const Oe of ie){if(Oe.id===B.id)continue;const Ae=_e(Oe);Number.isFinite(Ae)&&(Ae>=Me||(Me=Ae,De=Oe))}return De||void 0},[]),de=i.useCallback(U=>{var ie;const z=ce(U);if(!z)return;const Z=z.activePanel||z.panels[0];Z&&(z.model.openPanel(Z),Z.api.setActive(),Dt(Z.id)||fe(Z.id,"dockview-focus"),ka((ie=z.element)==null?void 0:ie.ownerDocument))},[ce,fe]),te=i.useCallback((U,z)=>{const Z=w.current,ie=Z==null?void 0:Z.activePanel,B=(Z==null?void 0:Z.activeGroup)||(ie==null?void 0:ie.group);if(!Z||!ie||!B)return;let q=ce(U);!q&&(z!=null&&z.createGroupIfMissing)&&(q=Z.addGroup({referenceGroup:B,direction:U})),q&&(ie.api.moveTo({group:q,position:"center"}),ie.group.model.openPanel(ie),ie.api.setActive(),Dt(ie.id)||fe(ie.id,z!=null&&z.createGroupIfMissing?"dockview-split":"dockview-move"))},[ce,fe]),{isMac:E,tabShortcuts:X,shortcutListening:oe,setShortcutListening:ee,saveShortcuts:ke}=Vd({sortedTabKeys:e.map(U=>U.tabKey),onFocus:ge,onSelectTab:Q}),Ce=i.useCallback(()=>{var Z;const U=w.current;if(!U)return;const z=U.activePanel;if(z){if(Dt(z.id)){const ie=((Z=z.params)==null?void 0:Z.routeId)||z.id.slice(7),B=Bt(e,ie);B!=null&&B.tabKey&&ee(B.tabKey);return}V.has(z.id)&&ee(z.id)}},[V,Q,ee,e]),ve=i.useCallback(U=>{const z=[];return U.metaKey&&z.push(E?"⌘":"Meta"),U.ctrlKey&&z.push("Ctrl"),U.altKey&&z.push(E?"⌥":"Alt"),U.shiftKey&&U.key.length!==1&&z.push(E?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(U.key)?null:(z.push(Xd(U.key)),z.join("+"))},[E]),O=i.useCallback(U=>{var z,Z;switch(U){case"splitActiveTabRight":te("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":te("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const ie=xe();ie&&pe(ie);return}case"popoutActiveTab":{const ie=xe();ie&&je(ie);return}case"dockActiveTab":{const ie=xe();if(!ie)return;G(ie)?Ne(ie):ye(ie)&&Se(ie);return}case"focusLeftPane":de("left");return;case"focusRightPane":de("right");return;case"focusUpPane":de("above");return;case"focusDownPane":de("below");return;case"moveActiveTabToLeftPane":te("left");return;case"moveActiveTabToRightPane":te("right");return;case"moveActiveTabToUpPane":te("above");return;case"moveActiveTabToDownPane":te("below");return;case"selectPreviousGroupTab":ue(-1);return;case"selectNextGroupTab":ue(1);return;case"setActiveTabShortcut":Ce();return;case"hideCurrentTab":{const ie=(Z=(z=w.current)==null?void 0:z.activePanel)==null?void 0:Z.id;ie&&!Dt(ie)&&he(ie);return}default:return}},[ue,Se,de,pe,xe,he,ye,G,Ne,te,je,Ce]);i.useEffect(()=>{if(!I)return;const U=I.sourceDocument,z=U.defaultView??window,Z=ie=>{const B=U.querySelector("[data-dockview-tab-context-menu]");B&&B.contains(ie.target)||T(null)};return z.addEventListener("mousedown",Z,!0),z!==window&&window.addEventListener("mousedown",()=>T(null),!0),()=>{z.removeEventListener("mousedown",Z,!0),z!==window&&window.removeEventListener("mousedown",()=>T(null),!0)}},[I]);const Ie=i.useMemo(()=>({actionLogs:n,clearedTabs:s,conversationsByTabKey:V,hasDetachedConversationPanels:Y,ides:r,isStandalone:l,hasRegisteredMachines:c,onOpenNewSession:f,liveSessionInboxState:N,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:he,userName:m,scrollToBottomRequest:A,tabShortcuts:X,openTabContextMenu:({x:U,y:z,tabKey:Z,sourceDocument:ie})=>T({x:U,y:z,tabKey:Z,sourceDocument:ie??document}),popoutTab:je,moveTabBackToMain:Ne,isTabInPopout:G,floatTab:pe,isTabFloating:ye}),[n,s,V,Y,r,l,c,f,N,a,o,he,m,A,X,je,Ne,G,pe,ye]),Re=I?ay({isTabInPopout:G(I.tabKey),isTabFloating:ye(I.tabKey),tabShortcut:X[I.tabKey],actionShortcuts:h}):[],Ke=i.useCallback(U=>{var ie;const z=w.current;if((((ie=z==null?void 0:z.activePanel)==null?void 0:ie.id)??null)===U.id){U.group.model.openPanel(U);return}U.group.model.openPanel(U),U.api.setActive()},[]),He=i.useCallback((U,z="requested-tab")=>{if(!U)return!1;const Z=w.current;if(!Z)return!1;const ie=Z.getPanel(U);return ie?(Ke(ie),fe(U,z),x==null||x(),!0):!1},[Ke,x,fe]),Ye=i.useCallback(()=>{if(H.current)return!1;const U=He(W.current,"stored-layout-restore");return U&&(H.current=!0),U},[He]),Xe=i.useCallback(()=>{var z;const U=w.current;U&&Eb(v,{activeTabId:((z=U.activePanel)==null?void 0:z.id)??null,layout:U.toJSON()})},[v]),st=i.useCallback(()=>{Bb(v,$.current)},[v]),mt=i.useCallback(U=>{var ie,B,q,ne;const z=w.current;if(!z)return{kind:"grid"};const Z=z.toJSON();for(const le of Z.floatingGroups||[])if((B=(ie=le.data)==null?void 0:ie.views)!=null&&B.includes(U)&&le.position)return{kind:"floating",position:le.position};for(const le of Z.popoutGroups||[])if((ne=(q=le.data)==null?void 0:q.views)!=null&&ne.includes(U))return{kind:"popout",position:le.position,popoutUrl:le.url};return{kind:"grid"}},[]),ht=i.useCallback(U=>{const z=w.current;if(!z)return;const Z=z.getPanel(U),ie=$.current[U];if(!Z||!ie||ie.kind==="grid")return;if(Z.group.model.location.type===ie.kind){delete $.current[U],st();return}if(ie.kind==="floating"){z.addFloatingGroup(Z,{x:ie.position.left??24,y:ie.position.top??24,width:ie.position.width,height:ie.position.height}),delete $.current[U],st();return}delete $.current[U],st()},[st]);i.useEffect(()=>(g==null||g({setShortcutForActiveTab:Ce,restoreHiddenTabToSavedLocation:ht,activateConversationTab:Q,resetAllPanelsToMain:R,activatePreviousTabInGroup:()=>ue(-1),activateNextTabInGroup:()=>ue(1),floatActiveTab:()=>{const U=xe();U&&pe(U)},popoutActiveTab:()=>{const U=xe();U&&je(U)},dockActiveTab:()=>{const U=xe();U&&(G(U)?Ne(U):ye(U)&&Se(U))},splitActiveTabRight:()=>te("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>te("below",{createGroupIfMissing:!0}),focusLeftPane:()=>de("left"),focusRightPane:()=>de("right"),focusUpPane:()=>de("above"),focusDownPane:()=>de("below"),moveActiveTabToLeftPane:()=>te("left"),moveActiveTabToRightPane:()=>te("right"),moveActiveTabToUpPane:()=>te("above"),moveActiveTabToDownPane:()=>te("below")}),()=>g==null?void 0:g(null)),[ue,Se,pe,de,xe,ye,G,te,Ne,je,g,R,ht,Q,Ce]),i.useEffect(()=>()=>{var U;(U=F.current)==null||U.call(F),F.current=null},[]);const yt=i.useCallback(U=>{var Z,ie;w.current=U.api,(Z=F.current)==null||Z.call(F),F.current=null;const z=Db(v);if(W.current=(z==null?void 0:z.activeTabId)??null,z!=null&&z.layout&&U.api.fromJSON(z.layout,{reuseExistingPanels:!1}),S.current=xl({hasStoredLayout:!!(z!=null&&z.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:r}),S.current||(jl(U.api,e),kl(U.api,e,y)),U.api.totalPanels===0&&e.length>0){const B=py(U.api,e,b);if(B){const q=U.api.getPanel(B);q&&Ke(q)}}else!S.current&&!He(b)&&Ye();if(_.current=!0,U.api.onDidActivePanelChange(B=>{var ne;if(W.current=(B==null?void 0:B.id)??null,H.current=!0,re(),B&&Dt(B.id)){const le=((ne=B.params)==null?void 0:ne.routeId)||B.id.slice(7),we=Bt(e,le);j((we==null?void 0:we.tabKey)??null),Xe();return}if(j((B==null?void 0:B.id)??null),Xe(),!B)return;const q=V.get(B.id);(q==null?void 0:q.streamSource)==="agent-stream"&&q.agentType&&M(q.routeId,Dc(),{agentType:q.agentType,...q.sessionId&&{targetSessionId:q.sessionId}}).catch(()=>{})}),U.api.onDidLayoutChange(()=>{Xe(),re(),P(B=>B+1)}),cy()){const B=Me=>({clientX:Me.clientX,clientY:Me.clientY}),q=Me=>{const Ee=Me==null?void 0:Me.getBoundingClientRect();return Ee?{left:Ee.left,right:Ee.right,top:Ee.top,bottom:Ee.bottom}:null},ne=Me=>{var Oe;const Ee=(Oe=k.current)==null?void 0:Oe.getBoundingClientRect();return Ee?Me.clientX<Ee.left||Me.clientX>Ee.right||Me.clientY<Ee.top||Me.clientY>Ee.bottom:!1},le=ly({detachDelayMs:Qd,onDetach:({panelId:Me,clientX:Ee,clientY:Oe})=>{var ct,pt;const Ae=U.api.getPanel(Me);if(!Ae)return;try{if(Ae.group.model.location.type!=="grid")return}catch{return}const Je=(ct=k.current)==null?void 0:ct.getBoundingClientRect(),Ze=(pt=Ae.group.element)==null?void 0:pt.getBoundingClientRect(),xt=Math.round(Math.min(Math.max((Ze==null?void 0:Ze.width)??600,360),720)),bt=Math.round(Math.min(Math.max((Ze==null?void 0:Ze.height)??500,260),640));U.api.addFloatingGroup(Ae,{x:Je?Math.max(0,Ee-Je.left-32):void 0,y:Je?Math.max(0,Oe-Je.top-18):void 0,width:xt,height:bt}),Ae.api.setActive(),Xe(),re(),P(We=>We+1)}}),we=[U.api.onWillDragPanel(Me=>{if(!(Me.nativeEvent.defaultPrevented||Me.nativeEvent.shiftKey)){try{if(Me.panel.group.model.location.type!=="grid")return}catch{return}le.startDrag({panelId:Me.panel.id,selfPanelBounds:q(Me.panel.group.element),...B(Me.nativeEvent)})}}),U.api.onWillShowOverlay(Me=>{if(le.hasDetached()){Me.preventDefault();return}le.markDockTarget(B(Me.nativeEvent))}),U.api.onWillDrop(Me=>{if(le.hasDetached()){Me.preventDefault(),le.endDrag();return}le.markDockTarget(B(Me.nativeEvent))}),U.api.onDidDrop(()=>le.endDrag()),U.api.onUnhandledDragOverEvent(Me=>{le.isDragging()&&le.markSelfPanel(B(Me.nativeEvent))})],_e=Me=>{if(!le.isDragging())return;const Ee=B(Me);ne(Ee)&&le.markNonSelfPanel(Ee)},De=()=>le.endDrag();window.addEventListener("dragover",_e,!0),window.addEventListener("drop",De,!0),window.addEventListener("dragend",De,!0),F.current=()=>{le.dispose();for(const Me of we)Me.dispose();window.removeEventListener("dragover",_e,!0),window.removeEventListener("drop",De,!0),window.removeEventListener("dragend",De,!0)}}U.api.onDidAddGroup(B=>{requestAnimationFrame(()=>{var q,ne;try{const le=(q=B.element)==null?void 0:q.ownerDocument;if(!le||le===document)return;(ne=le.getElementById("dv-popout-window"))==null||ne.classList.add("adhdev-dockview");const we=document.documentElement.getAttribute("data-theme");we&&le.documentElement.setAttribute("data-theme",we),le.body.className=document.body.className;const _e=document.documentElement.getAttribute("style");_e&&le.documentElement.setAttribute("style",_e)}catch{}re(),P(le=>le+1)})}),j(((ie=U.api.activePanel)==null?void 0:ie.id)??null)},[Ke,He,V,r,d,v,j,Xe,b,y,M,re,e]);i.useLayoutEffect(()=>{const U=w.current;if(!U||!_.current||S.current&&xl({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:r}))return;S.current&&(S.current=!1);const z=D.current,Z=new Set(z),ie=e.map(De=>De.tabKey),B=new Set(ie),q=oy({previousVisibleConversationCount:z.length,visibleConversationCount:e.length,ides:r});let ne=!1;for(const De of z)B.has(De)||q||($.current[De]=mt(De),ne=!0);ne&&st(),q||(jl(U,e),kl(U,e,y));const le=ie.filter(De=>!Z.has(De));let we=!1;for(const De of le){const Me=U.getPanel(De),Ee=$.current[De];if(!Me||!Ee||Ee.kind==="grid")continue;if(Me.group.model.location.type===Ee.kind){delete $.current[De],we=!0;continue}if(Ee.kind==="floating"){U.addFloatingGroup(Me,{x:Ee.position.left??24,y:Ee.position.top??24,width:Ee.position.width,height:Ee.position.height}),delete $.current[De],we=!0;continue}}if(we&&st(),D.current=ie,b&&He(b))return;!U.activePanel&&U.panels[0]&&Ke(U.panels[0]),!!(U.activePanel&&U.getPanel(U.activePanel.id))||Ye()},[Ke,He,Ye,r,d,st,mt,b,y,e]),i.useEffect(()=>{_.current&&He(b)},[He,b]),i.useEffect(()=>{const U=Z=>{const ie=Z.target;if(!ie)return;const B=ie.querySelector("[data-tab-key]")||ie.closest("[data-tab-key]");if(B){const q=B.getAttribute("data-tab-key");if(q&&Z.dataTransfer){const ne=ie.closest(".dv-tab")||B.closest(".dv-tab")||B;Z.dataTransfer.effectAllowed="move",Z.dataTransfer.setData("text/tab-key",q),ne instanceof HTMLElement&&Z.dataTransfer.setDragImage(ne,Math.max(12,Math.round(ne.clientWidth/2)),Math.max(10,Math.round(ne.clientHeight/2)))}}};window.addEventListener("dragstart",U);const z=wl(w.current);for(const Z of z)Z.addEventListener("dragstart",U);return()=>{window.removeEventListener("dragstart",U);for(const Z of z)Z.removeEventListener("dragstart",U)}},[K]),i.useEffect(()=>{var z;const U=(z=k.current)==null?void 0:z.querySelector(".adhdev-dockview");U instanceof HTMLElement&&Na(U,C),me(),re()},[re,me,C]),i.useEffect(()=>{re()},[re]),i.useEffect(()=>{const U=z=>{if(z.defaultPrevented||oe)return;const Z=ve(z);if(!Z)return;const ie=z.metaKey||z.ctrlKey||z.altKey;fo(z.target)&&!ie||Rn(E).setActiveTabShortcut!==Z||(z.preventDefault(),z.stopPropagation(),Ce())};return window.addEventListener("keydown",U,!0),()=>window.removeEventListener("keydown",U,!0)},[ve,E,oe,Ce]),i.useEffect(()=>{const U=k.current;if(!U)return;const z=Z=>{var le,we;if(!Z.isTrusted)return;const ie=(we=(le=Z.target)==null?void 0:le.closest)==null?void 0:we.call(le,".dv-scrollable");if(!ie)return;Z.preventDefault(),Z.stopPropagation();const B=Math.abs(Z.deltaX),q=Math.abs(Z.deltaY),ne=B>q?Z.deltaX:Z.deltaY;ie.dispatchEvent(new WheelEvent("wheel",{deltaY:ne,deltaMode:Z.deltaMode,bubbles:!1,cancelable:!0}))};return U.addEventListener("wheel",z,{passive:!1,capture:!0}),()=>U.removeEventListener("wheel",z,{capture:!0})},[]),i.useEffect(()=>{const U=wl(w.current);if(U.length===0)return;const z=U.map(Z=>{let ie=[],B=null;const q=()=>{B!=null&&Z.clearTimeout(B),B=null,ie=[]},ne=()=>{B!=null&&Z.clearTimeout(B),B=Z.setTimeout(()=>{B=null,ie=[]},1200)},le=_e=>{if(!_e.ctrlKey&&!_e.metaKey&&!_e.altKey)return;const De=ve(_e);if(!De)return;const Me=zd();for(const[Ee,Oe]of Object.entries(Me))if(e.some(Ae=>Ae.tabKey===Ee)&&Oe===De){_e.preventDefault(),Q(Ee);return}},we=_e=>{if(_e.defaultPrevented||oe)return;const De=ve(_e);if(!De)return;const Me=_e.metaKey||_e.ctrlKey||_e.altKey;if(fo(_e.target))return;const Ee=Rn(E),Oe=Object.entries(Ee).filter(([We,Ot])=>!!Ot&&(We==="splitActiveTabRight"||We==="splitActiveTabDown"||We==="floatActiveTab"||We==="popoutActiveTab"||We==="dockActiveTab"||We==="focusLeftPane"||We==="focusRightPane"||We==="focusUpPane"||We==="focusDownPane"||We==="moveActiveTabToLeftPane"||We==="moveActiveTabToRightPane"||We==="moveActiveTabToUpPane"||We==="moveActiveTabToDownPane"||We==="selectPreviousGroupTab"||We==="selectNextGroupTab"||We==="setActiveTabShortcut"||We==="hideCurrentTab")),Ae=Me?[De]:[...ie.slice(-1),De].slice(-2),Je=Ae.join(" "),Ze=Ae[Ae.length-1],xt=Oe.find(([,We])=>We===Je);if(xt){_e.preventDefault(),q(),O(xt[0]);return}if(Oe.some(([,We])=>We.startsWith(`${Je} `))){_e.preventDefault(),ie=Ae,ne();return}const ct=Oe.find(([,We])=>We===Ze);if(ct){_e.preventDefault(),q(),O(ct[0]);return}if(Oe.some(([,We])=>We.startsWith(`${Ze} `))){_e.preventDefault(),ie=[Ze],ne();return}q()};return Z.addEventListener("keydown",le),Z.addEventListener("keydown",we),()=>{q(),Z.removeEventListener("keydown",le),Z.removeEventListener("keydown",we)}});return()=>{for(const Z of z)Z()}},[ve,E,K,Q,oe,O,e]);const Te=C==="light"?Ga:qa,Ue=((at=(ze=(et=w.current)==null?void 0:et.activePanel)==null?void 0:ze.group.element)==null?void 0:at.ownerDocument)??document;return t.jsxs(Zd.Provider,{value:Ie,children:[t.jsx("div",{ref:k,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:t.jsx(Vu,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:fy,remote:hy},defaultTabComponent:by,watermarkComponent:xy,onReady:yt,singleTabMode:"default",tabAnimation:"smooth",theme:Te,popoutUrl:"/popout.html"})}),I&&kr.createPortal(t.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[55] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:I.x,top:I.y},children:Re.map(U=>{if(U.type==="separator")return t.jsx("div",{className:"border-t border-border-subtle my-1"},U.id);let z=t.jsx(Gm,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{};switch(U.id){case"dockInWindow":case"dockBackToGrid":z=t.jsx(Ym,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{Se(I.tabKey),T(null)};break;case"moveBackToMain":z=t.jsx(Vm,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{Ne(I.tabKey),T(null)};break;case"floatAsPanel":z=t.jsx(qm,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{pe(I.tabKey),T(null)};break;case"openInNewWindow":z=t.jsx(zm,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{je(I.tabKey),T(null)};break;case"setShortcut":Z=ie=>{ie.stopPropagation(),ee(I.tabKey),T(null)};break;case"removeShortcut":z=t.jsx(vt,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{const ie={...X};delete ie[I.tabKey],ke(ie),T(null)};break;case"hideTab":z=t.jsx(No,{size:13,className:"shrink-0 opacity-70"}),Z=()=>{he(I.tabKey),T(null)};break}return t.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 ${U.tone==="muted"?"text-text-muted":""}`,onMouseDown:uy,onClick:Z,children:[z,t.jsx("span",{className:"flex-1 min-w-0",children:U.label}),U.shortcut?t.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:U.shortcut}):null]},U.id)})}),I.sourceDocument.body),oe&&kr.createPortal(t.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:()=>ee(null),children:t.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:U=>U.stopPropagation(),children:[t.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),t.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",E?"⌘+1":"Ctrl+1",", ",E?"⌥+A":"Alt+A",")"]}),t.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),t.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),Ue.body)]})}const eu="adhdev-recent-launch-args-v1",yy=8;function tu(e){return String(e||"").trim().replace(/\s+/g," ")}function ri(e,s){return`${e.trim()}::${s.trim()}`}function ni(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(eu)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function su(e){if(!(typeof window>"u"))try{window.localStorage.setItem(eu,JSON.stringify(e))}catch{}}function ho(e,s){var o;const r=String(e||"").trim(),n=String(s||"").trim();return!r||!n?[]:((o=ni().byKey[ri(r,n)])==null?void 0:o.items)||[]}function ru(e,s,r){var u;const n=String(e||"").trim(),a=String(s||"").trim(),o=tu(r);if(!n||!a||!o)return;const l=ni(),c=ri(n,a),d=((u=l.byKey[c])==null?void 0:u.items)||[],m=[o,...d.filter(h=>h!==o)].slice(0,yy);l.byKey[c]={items:m},su(l)}function vy(e,s,r){var u;const n=String(e||"").trim(),a=String(s||"").trim(),o=tu(r);if(!n||!a||!o)return;const l=ni(),c=ri(n,a),m=(((u=l.byKey[c])==null?void 0:u.items)||[]).filter(h=>h!==o);m.length>0?l.byKey[c]={items:m}:delete l.byKey[c],su(l)}function nu(e){return!e.hasLoadedInitialResults&&!e.isLoading}function fn({title:e,description:s,action:r,children:n,className:a="",contentClassName:o=""}){return t.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${a}`.trim(),children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),s&&t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:s})]}),r?t.jsx("div",{className:"flex items-center gap-2",children:r}):null]}),n?t.jsx("div",{className:s||r?`mt-3 ${o}`.trim():o,children:n}):null]})}function wy({savedSessionsLoading:e,savedSessionsLoaded:s,savedSessionsCount:r=0}){return e?"Refreshing saved history…":s?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 au({busy:e,savedSessionsLoading:s,savedSessionsError:r,savedSessionsLoaded:n,savedSessionsCount:a=0,selectedSession:o,onRefresh:l,onOpenHistory:c,onClearSelection:d}){const m=o?Wd(o):null,u=wy({savedSessionsLoading:s,savedSessionsLoaded:n,savedSessionsCount:a});return t.jsxs(fn,{title:"Saved history",description:Ho(),action:t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||s,onClick:l,children:s?"Loading…":"Refresh"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:c,children:lx()})]}),children:[m?t.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:t.jsxs("div",{className:"flex items-start justify-between gap-2",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Selected saved history"}),t.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",children:m.title}),t.jsx("div",{className:"font-mono break-all mt-0.5",children:m.providerSessionId}),t.jsx("div",{className:"mt-1",children:m.metaLine}),m.updatedLabel&&t.jsx("div",{className:"mt-1 text-text-secondary",children:m.updatedLabel}),m.preview&&t.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:m.preview})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:d,disabled:e,children:"Clear"})]})}):t.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:u}),r&&t.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:r})]})}function ou({setup:e,providerName:s,className:r=""}){return e?t.jsxs("div",{className:`rounded-xl border border-accent/25 bg-accent/10 px-4 py-3 text-sm text-text-primary ${r}`,children:[t.jsxs("div",{className:"font-semibold",children:["Manual MCP setup required",s?` for ${s}`:""]}),e.instructions&&t.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-secondary",children:e.instructions}),t.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-[11px] text-text-muted",children:[e.serverName&&t.jsxs("span",{children:["Server: ",t.jsx("code",{children:e.serverName})]}),e.configFormat&&t.jsxs("span",{children:["Format: ",t.jsx("code",{children:e.configFormat})]}),e.configPathCommand&&t.jsxs("span",{children:["Config path: ",t.jsx("code",{children:e.configPathCommand})]}),e.requiresRestart&&t.jsx("span",{children:"Start a fresh CLI session after editing config."})]}),e.template&&t.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 jy({workspaceMode:e,activeKind:s,cliEnabled:r,ideEnabled:n,acpEnabled:a,busy:o,onSelect:l}){return e==="mesh"?null:t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:"Category"}),t.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(c=>t.jsx("button",{type:"button",className:`btn btn-sm ${s===c.id?"btn-primary":"btn-secondary"}`,onClick:()=>l(c.id),disabled:!c.enabled||o,children:c.label},c.id))})]})}function Sa(e){var n;if(!e)return null;const s=e.availableProviders||[];return s.some(a=>Is(a,"cli"))?"cli":(((n=e.detectedIdes)==null?void 0:n.length)||0)>0?"ide":s.some(a=>Is(a,"acp"))?"acp":null}function en(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function ky({machines:e,ides:s,onClose:r,onBrowseDirectory:n,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:l,onListMeshes:c,onLaunchMeshCoordinator:d,onListSavedSessions:m}){var We,Ot;const u=Lr(),h=i.useMemo(()=>[...e].sort(Ro),[e]),[g,j]=i.useState(((We=h[0])==null?void 0:We.id)||""),f=i.useMemo(()=>h.find(se=>se.id===g)||h[0],[g,h]),p=i.useMemo(()=>((f==null?void 0:f.workspaces)||[]).map(se=>({id:se.id,path:se.path,label:se.label})),[f]),b=(f==null?void 0:f.defaultWorkspaceId)||null,[y,x]=i.useState("workspace"),[A,N]=i.useState(""),[v,C]=i.useState(""),[M,w]=i.useState([]),[k,F]=i.useState(""),[_,S]=i.useState(!1),[H,W]=i.useState(null),[D,I]=i.useState(""),[T,K]=i.useState(Sa(h[0])),[P,$]=i.useState(""),[V,Y]=i.useState(""),[ge,fe]=i.useState([]),[ae,me]=i.useState(""),[je,Ne]=i.useState([]),[G,he]=i.useState(!1),[pe,ye]=i.useState(!1),[xe,Se]=i.useState(""),[R,re]=i.useState(!1),[Q,ue]=i.useState(()=>Nt()),[ce,de]=i.useState(null),[te,E]=i.useState(!1),[X,oe]=i.useState(""),[ee,ke]=i.useState(null),[Ce,ve]=i.useState(!1),[O,Ie]=i.useState(""),[Re,Ke]=i.useState([]),[He,Ye]=i.useState(!1),[Xe,st]=i.useState(""),[mt,ht]=i.useState(!1),yt=i.useRef(null),Te=i.useRef(0);i.useEffect(()=>{var se;!g&&((se=h[0])!=null&&se.id)&&j(h[0].id)},[g,h]),i.useEffect(()=>{!f||!(!f.workspaces||!f.availableProviders||!f.detectedIdes||!f.recentLaunches)||u(f.id,{minFreshMs:3e4}).catch(()=>{})},[u,f]);const Ue=i.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(se=>Is(se,"cli")),[f]),et=i.useMemo(()=>((f==null?void 0:f.availableProviders)||[]).filter(se=>Is(se,"acp")),[f]),ze=i.useMemo(()=>((f==null?void 0:f.detectedIdes)||[]).map(se=>({id:se.type,label:se.name||se.type,meta:se.running?"Detected locally":"Available to open"})),[f]),at=i.useMemo(()=>T==="cli"?Ue.map(se=>({id:se.type,label:se.displayName||se.type,meta:"CLI provider"})):T==="acp"?et.map(se=>({id:se.type,label:se.displayName||se.type,meta:"ACP provider"})):ze,[et,T,Ue,ze]),U=i.useMemo(()=>M.find(se=>se.id===k)||null,[M,k]),z=i.useMemo(()=>Ue.find(se=>se.type===P)||null,[Ue,P]),Z=i.useMemo(()=>Dd(z==null?void 0:z.meshCoordinator,{meshId:(U==null?void 0:U.id)||"",workspace:(U==null?void 0:U.workspace)||""}),[z,U]),ie=ee||Z,B=i.useCallback(async se=>{S(!0),I("");try{const Pe=await c(se);w(Pe),F(L=>{var J;return Pe.some(be=>be.id===L)?L:((J=Pe[0])==null?void 0:J.id)||""}),W(se)}catch(Pe){w([]),F(""),W(se),I(Pe instanceof Error?Pe.message:"Could not load meshes")}finally{S(!1)}},[c]);i.useEffect(()=>{var Pe;if(!f)return;if(yt.current!==f.id){yt.current=f.id,x("workspace"),N(b||((Pe=p[0])==null?void 0:Pe.id)||"__home__"),C(""),w([]),F(""),W(null),I(""),K(Sa(f)),$(""),Y(""),me(""),Ne([]),ye(!1),Se(""),ue(Nt()),oe(""),ke(null);return}N(L=>{var J;return L==="__custom__"||L==="__home__"||p.some(be=>be.id===L)?L:b||((J=p[0])==null?void 0:J.id)||"__home__"}),K(L=>L==="ide"&&ze.length>0||L==="cli"&&Ue.length>0||L==="acp"&&et.length>0?L:Sa(f))},[et.length,Ue.length,b,ze.length,f,p]),i.useEffect(()=>{!f||y!=="mesh"||H===f.id||_||B(f.id)},[B,H,_,f,y]),i.useEffect(()=>{y==="mesh"&&T!=="cli"&&Ue.length>0&&K("cli")},[T,Ue.length,y]),i.useEffect(()=>{var se;T&&(at.some(Pe=>Pe.id===P)||$(((se=at[0])==null?void 0:se.id)||""))},[T,at,P]),i.useEffect(()=>{ke(null)},[f==null?void 0:f.id,k,P,y]);const q=i.useCallback(async(se,Pe)=>{const L=Te.current+1;return Te.current=L,he(!0),Se(""),m(se,Pe).then(J=>{Te.current===L&&Ne(J)}).catch(J=>{Te.current===L&&(Ne([]),Se(J instanceof Error?J.message:"Could not load saved sessions"))}).finally(()=>{Te.current===L&&(he(!1),ye(!0))})},[m]),ne=i.useCallback((se,Pe)=>{fe(ho(se,Pe))},[]);i.useEffect(()=>{Te.current+=1,me(""),ue(Nt()),!f||!P||T==="ide"?fe([]):ne(f.id,P),ye(!1),Ne([]),Se(""),he(!1)},[T,ne,q,f,P]),i.useEffect(()=>{if(!ae)return;const se=je.find(Pe=>Pe.providerSessionId===ae);se!=null&&se.canResume||me("")},[je,ae]);const le=A==="__custom__"?v.trim():A==="__home__"?"":((Ot=p.find(se=>se.id===A))==null?void 0:Ot.path)||"",we=i.useMemo(()=>f?s.filter(se=>se.id!==f.id&&se.daemonId===f.id).map(se=>se.workspace):[],[s,f]),_e=i.useMemo(()=>((f==null?void 0:f.recentLaunches)||[]).map(se=>se.workspace),[f]),De=i.useCallback(se=>{const Pe=String(se.workspace||"").trim();if(!Pe)return;const L=p.find(J=>en(J.path)===en(Pe));if(L){N(L.id),C("");return}N("__custom__"),C(Pe)},[p]),Me=i.useCallback(se=>{const Pe=String(se.workspace||"").trim();if(!Pe)return{workspaceId:null,workspacePath:null};const L=p.find(J=>en(J.path)===en(Pe));return L?{workspaceId:L.id,workspacePath:null}:{workspaceId:null,workspacePath:Pe}},[p]),Ee=i.useMemo(()=>je.find(se=>se.providerSessionId===ae)||null,[je,ae]),Oe=i.useMemo(()=>{var Pe;if(T!=="cli"||!f||!P)return null;const se=((Pe=Ue.find(L=>L.type===P))==null?void 0:Pe.displayName)||P;return{routeId:f.id,daemonId:f.id,providerSessionId:ae||void 0,transport:"pty",mode:"chat",agentName:se,agentType:P,status:"idle",title:se,messages:[],ideType:P,workspaceName:le,workspacePath:le,displayPrimary:se,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${f.id}:${P}`,machineName:Tt(f,{fallbackId:f.id})}},[T,Ue,le,f,ae,P]),Ae=i.useCallback(()=>{var Pe;if(!f)return;N("__custom__"),ve(!0),st("");const se=Un(f.platform,Hn(v.trim(),le,we,_e,f.defaultWorkspacePath,(Pe=p.find(L=>L.id===b))==null?void 0:Pe.path,p.map(L=>L.path)));Ye(!0),n(f.id,se).then(L=>{Ie(L.path),C(L.path),Ke(L.directories)}).catch(L=>{st(L instanceof Error?L.message:"Could not load folder")}).finally(()=>Ye(!1))},[v,b,_e,we,n,le,f,p]),Je=i.useCallback(se=>{f&&(Ye(!0),st(""),n(f.id,se).then(Pe=>{Ie(Pe.path),C(Pe.path),Ke(Pe.directories)}).catch(Pe=>{st(Pe instanceof Error?Pe.message:"Could not load folder")}).finally(()=>Ye(!1)))},[n,f]),Ze=i.useCallback(async()=>{if(!f||!le)return;ht(!0),oe("");const se=await a(f.id,le);if(ht(!1),!se.ok){oe(se.error||"Could not save workspace");return}oe("Workspace saved. It will appear in the list once the machine state refreshes.")},[a,le,f]),xt=i.useCallback(async()=>{if(!f)return;if(y==="mesh"){if(!k||!P)return;E(!0),oe(""),ke(null);const L=await d(f.id,k,P);if(E(!1),!L.ok){if(L.code==="mesh_coordinator_manual_mcp_setup_required"&&L.manualSetup){ke(L.manualSetup),oe("Manual MCP setup required before this provider can act as mesh coordinator.");return}oe(L.error||"Could not start mesh coordinator");return}r();return}if(!T||!P)return;E(!0),oe("");const se=V.trim()?V.trim().split(/\s+/).filter(Boolean):[],Pe=T==="ide"?await o(f.id,P,{workspacePath:le||null}):await l(f.id,T,P,{workspaceId:A!=="__home__"&&A!=="__custom__"?A:null,workspacePath:A==="__custom__"&&le||null,resumeSessionId:T==="cli"&&ae?ae:null,cliArgs:se});if(E(!1),!Pe.ok){oe(Pe.error||"Could not start session");return}T!=="ide"&&V.trim()&&(ru(f.id,P,V),ne(f.id,P)),r()},[T,V,ne,r,o,d,l,le,f,k,ae,P,A,y]),bt=y==="mesh"?"Start mesh coordinator":T?td(T,T==="cli"&&!!ae):"Start",ct=y==="mesh"?"Starting coordinator…":T?sd(T,T==="cli"&&!!ae):"Starting…",pt=h.length>5;return f?t.jsxs(t.Fragment,{children:[t.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:t.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:[t.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:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:"Start session"}),t.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."})]}),t.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:t.jsx(vt,{size:16})})]}),t.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:[t.jsx(fn,{title:"Machine",children:pt?t.jsx("select",{"aria-label":"Machine",value:f.id,onChange:se=>j(se.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:te,children:h.map(se=>t.jsx("option",{value:se.id,children:Tt(se,{fallbackId:se.id})},se.id))}):t.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":"Machine",children:h.map(se=>{const Pe=Tt(se,{fallbackId:se.id}),L=f.id===se.id;return t.jsxs("button",{type:"button","aria-label":`Select machine ${Pe}`,"aria-pressed":L,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${L?"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:()=>j(se.id),disabled:te,title:Pe,children:[t.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${se.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),t.jsx("span",{className:"truncate",children:Pe})]},se.id)})})}),t.jsxs(fn,{title:"Workspace",description:"Start from a normal workspace, or select a repo mesh and run a mesh coordinator.",action:y==="workspace"?t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ae,disabled:te,children:"Browse…"}):void 0,children:[t.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(se=>t.jsxs("button",{type:"button",role:"radio","aria-checked":y===se.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${y===se.id?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/40 text-text-secondary hover:bg-bg-secondary/70 hover:text-text-primary"}`,onClick:()=>{x(se.id),oe(""),se.id==="mesh"&&f&&H!==f.id&&!_&&B(f.id)},disabled:te,children:[t.jsx("div",{className:"text-sm font-semibold",children:se.label}),t.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:se.desc})]},se.id))}),y==="workspace"?t.jsxs(t.Fragment,{children:[t.jsxs("select",{value:A,onChange:se=>{const Pe=se.target.value;N(Pe),Pe==="__custom__"?Ae():oe("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:te,children:[t.jsx("option",{value:"__home__",children:"Home directory"}),p.map(se=>t.jsxs("option",{value:se.id,children:[se.id===b?"⭐ ":"",Bn(se.path,se.label)||se.path]},se.id)),t.jsx("option",{value:"__custom__",children:"Custom folder…"})]}),t.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:A==="__home__"?"Launch without a workspace.":le||"Select a workspace folder."}),A==="__custom__"&&le&&t.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ae,disabled:te,children:[t.jsx(Ns,{size:14}),"Select folder"]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ze,disabled:te||mt,children:mt?"Saving…":"Save workspace"})]})]}):t.jsxs("div",{className:"space-y-3",children:[_&&t.jsx("div",{className:"text-sm text-text-muted",children:"Loading meshes…"}),!_&&D&&t.jsx("div",{className:"rounded-lg border border-status-error/25 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:D}),!_&&!D&&M.length===0&&t.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&&t.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":"Mesh",children:M.map(se=>t.jsxs("button",{type:"button",role:"radio","aria-checked":k===se.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${k===se.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>F(se.id),disabled:te,children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:se.name}),t.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[se.repoIdentity||"Repo mesh",typeof se.nodesCount=="number"?` · ${se.nodesCount} node${se.nodesCount===1?"":"s"}`:""]}),se.workspace&&t.jsxs("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:["Coordinator workspace: ",se.workspace]})]},se.id))}),U&&t.jsx("div",{className:"text-[11px] text-text-muted",children:"Mesh coordinators use the selected CLI provider and the mesh's configured coordinator workspace."})]})]}),t.jsx(jy,{workspaceMode:y,activeKind:T,cliEnabled:Ue.length>0,ideEnabled:ze.length>0,acpEnabled:et.length>0,busy:te,onSelect:K}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:T==="ide"?"Choose IDE":T==="cli"?"Choose CLI provider":"Choose ACP provider"}),t.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[at.map(se=>t.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${P===se.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>$(se.id),disabled:te,children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:se.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:se.meta})]},se.id)),at.length===0&&t.jsx("div",{className:"text-sm text-text-muted",children:"Nothing usable for this category on the selected machine. Set a custom executable path in Providers if the binary lives outside the default location."})]})]}),y==="mesh"&&ie&&t.jsx(ou,{setup:ie,providerName:(z==null?void 0:z.displayName)||(z==null?void 0:z.name)||P}),y!=="mesh"&&T!=="ide"&&t.jsxs(fn,{title:"Startup arguments",children:[t.jsx("input",{type:"text",value:V,onChange:se=>Y(se.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:te}),ge.length>0&&t.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:ge.map(se=>t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>Y(se),disabled:te,title:se,children:se},se))})]}),y!=="mesh"&&T==="cli"&&t.jsx(au,{busy:te,savedSessionsLoading:G,savedSessionsError:xe,selectedSession:Ee,onRefresh:()=>{!f||!P||q(f.id,P)},onOpenHistory:()=>{!f||!P||(re(!0),nu({hasLoadedInitialResults:pe,isLoading:G})&&q(f.id,P))},onClearSelection:()=>me("")}),X&&t.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${X.includes("saved")||X.includes("requested")||X.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:X})]}),t.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:[t.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:r,disabled:te,children:"Cancel"}),t.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:xt,disabled:te||(y==="mesh"?!k||!P||T!=="cli"||_:!T||!P||A==="__custom__"&&!le),children:[t.jsx(Co,{size:14}),te?ct:bt]})]})]})}),Ce&&t.jsx(Vn,{title:"Select workspace",description:"Pick the folder that should be used for this new session.",currentPath:O,directories:Re,busy:He,error:Xe,onClose:()=>ve(!1),onNavigate:Je,onConfirm:se=>{C(se),Ie(se),N("__custom__"),ve(!1)}}),R&&Oe&&t.jsx(Vo,{activeConv:Oe,ides:[],isCreatingChat:!1,isRefreshingHistory:G,savedSessions:je,isSavedSessionsLoading:G,isResumingSavedSessionId:ce,savedHistoryFilters:Q,missingWorkspaceResumePath:le||null,onSavedHistoryFiltersChange:ue,onClose:()=>re(!1),onNewChat:()=>{me(""),re(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!f||!P||q(f.id,P)},onResumeSavedSession:se=>{if(!f||!P||ce||!se.canResume)return;const Pe=Me(se);me(se.providerSessionId),De(se),de(se.providerSessionId),re(!1),E(!0),oe(""),l(f.id,"cli",P,{workspaceId:Pe.workspaceId,workspacePath:Pe.workspacePath,resumeSessionId:se.providerSessionId}).then(L=>{if(!L.ok){oe(L.error||"Could not resume session");return}r()}).finally(()=>{E(!1),de(L=>L===se.providerSessionId?null:L)})}})]}):null}function Ny(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function Sy(e){return((e==null?void 0:e.submodules)??[]).some(s=>s.dirty)}function iu(e){return((e==null?void 0:e.submodules)??[]).some(s=>s.outOfSync||!!s.error)}function Cy(e){return iu(e)?"degraded":Sy(e)?"dirty":"online"}function Iy(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function Nl(e){switch(e){case"online":return 0;case"dirty":return 1;case"degraded":return 2;case"wrong_branch":return 3;case"offline":return 4;case"unknown":default:return 5}}function Ca(e){return e.length===0?"unknown":e.reduce((s,r)=>Nl(r)>Nl(s)?r:s)}function Ty(e){var o,l,c,d,m;const s=new Map,r=new Map;for(const u of e){const h=(l=(o=u.git)==null?void 0:o.branch)==null?void 0:l.trim();h&&(r.set(h,(r.get(h)??0)+1),(c=u.git)!=null&&c.upstream&&s.set(h,(s.get(h)??0)+1))}const n=[...s.entries()].sort((u,h)=>{if(h[1]!==u[1])return h[1]-u[1];const g=["main","master","develop","dev"],j=g.indexOf(u[0]),f=g.indexOf(h[0]);return j!==-1||f!==-1?j===-1?1:f===-1?-1:j-f:u[0].localeCompare(h[0])});return(d=n[0])!=null&&d[0]?n[0][0]:((m=[...r.entries()].sort((u,h)=>h[1]-u[1])[0])==null?void 0:m[0])??null}function Ay(e,s){const r=[],n=e.git;return n?n.isGitRepo?(!n.branch&&n.headCommit&&r.push("Detached HEAD"),n.hasConflicts&&r.push("Merge conflicts need resolution"),n.branch&&s&&n.branch!==s&&!n.upstream&&r.push(`No upstream tracking for ${n.branch}`),e.error&&r.push(e.error),r):(r.push("Not a git repository"),r):(r.push("No git status available"),r)}function My(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function lu(e){var g;const s=Ty(e.nodes),r=[],n=[],a=[],o=new Map;for(const j of e.nodes){const f=j.git,p=(f==null?void 0:f.branch)??null,b=Cy(f),y=Ny(f)||b==="dirty",x=Ay(j,s),A={id:j.nodeId,type:x.length>0?"orphanNode":"worktreeNode",label:j.machineLabel||j.nodeId.slice(0,8),workspace:j.workspace,branch:p,machineLabel:j.machineLabel||null,health:Ca([j.health,b]),ahead:(f==null?void 0:f.ahead)??0,behind:(f==null?void 0:f.behind)??0,dirty:y,dirtyFiles:Iy(f),hasConflicts:(f==null?void 0:f.hasConflicts)??!1,activeSessionCount:((g=j.activeSessions)==null?void 0:g.length)??0,activeSessions:j.activeSessions??[],providers:j.providers??[],isOrphan:x.length>0,orphanReasons:x,error:j.error,nextStepHint:x[0],parentNodeId:null,submodulePath:null,submoduleCommit:(f==null?void 0:f.headCommit)??null,outOfSync:iu(f),source:j};if(r.push(A),p){const N=o.get(p)??[];N.push(A.id),o.set(p,N)}for(const N of(f==null?void 0:f.submodules)??[]){const v=`${A.id}::submodule::${N.path}`,C=N.path.split("/").filter(Boolean).pop()||N.path;r.push({id:v,type:"submoduleNode",label:C,workspace:N.repoPath,branch:null,machineLabel:A.machineLabel,health:My(N),ahead:0,behind:0,dirty:N.dirty,dirtyFiles:N.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],providers:[],isOrphan:!1,orphanReasons:[],error:N.error,nextStepHint:N.error||(N.outOfSync?`${N.path} is out of sync with the parent checkout`:N.dirty?`${N.path} has local changes`:`${N.path} is in sync with the parent checkout`),parentNodeId:A.id,submodulePath:N.path,submoduleCommit:N.commit,outOfSync:N.outOfSync,source:{kind:"synthetic-submodule",parentNodeId:A.id,parentWorkspace:j.workspace,submodule:N}}),n.push({id:`${A.id}--${v}`,source:A.id,target:v,type:"submoduleLink",label:N.outOfSync?"submodule out of sync":"submodule"})}}const l=s?`__branch_${s}`:null;if(l&&s){const f=(o.get(s)??[]).map(b=>r.find(y=>y.id===b)).filter(Boolean),p={id:l,type:"defaultBranchNode",label:s,workspace:e.repoIdentity,branch:s,machineLabel:"default branch",health:Ca(f.map(b=>b.health)),ahead:0,behind:0,dirty:f.some(b=>b.dirty),dirtyFiles:f.reduce((b,y)=>b+y.dirtyFiles,0),hasConflicts:f.some(b=>b.hasConflicts),activeSessionCount:f.reduce((b,y)=>b+y.activeSessionCount,0),activeSessions:f.flatMap(b=>b.activeSessions),providers:[...new Set(f.flatMap(b=>b.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:f.length>0?`${f.length} workspace(s) currently on ${s}`:"No workspaces currently checked out to the default branch",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,source:{nodeId:l,machineLabel:s,workspace:e.repoIdentity,health:Ca(f.map(b=>b.health)),providers:[],activeSessions:[]}};r.push(p);for(const b of r)if(!(b.id===l||b.type==="submoduleNode")){if(b.branch===s){n.push({id:`${l}--${b.id}`,source:l,target:b.id,type:"parentBranch",label:"checked out"});continue}if(b.branch){n.push({id:`${l}--${b.id}`,source:l,target:b.id,type:b.isOrphan?"orphanLink":"parentBranch",label:b.branch});continue}b.isOrphan&&n.push({id:`${l}--${b.id}`,source:l,target:b.id,type:"orphanLink",label:"detached"})}}for(const[j,f]of o){if(f.length<2)continue;const p=f.map(b=>r.find(y=>y.id===b)).filter(Boolean);p.sort((b,y)=>b.label.localeCompare(y.label));for(let b=1;b<p.length;b+=1)n.push({id:`wt_${p[b-1].id}--${p[b].id}`,source:p[b-1].id,target:p[b].id,type:"worktreeLink",label:b===1?`${j} peers`:void 0})}const c=r.filter(j=>j.type!=="defaultBranchNode"),d=c.filter(j=>j.isOrphan).length,m=c.filter(j=>j.hasConflicts).length,u=c.filter(j=>j.health==="offline").length,h=c.filter(j=>j.type==="submoduleNode"&&j.outOfSync).length;return d>0&&a.push(`${d} workspace(s) need attention before safe coordination`),m>0&&a.push(`${m} workspace(s) report merge conflicts`),u>0&&a.push(`${u} node(s) are currently offline`),h>0&&a.push(`${h} submodule(s) are out of sync with their parent checkout`),s||a.push("Could not infer a default branch from live mesh status"),{meshId:e.meshId,meshName:e.meshName,repoIdentity:e.repoIdentity,refreshedAt:e.refreshedAt,nodes:r,edges:n,stats:{totalNodes:c.length,onlineNodes:c.filter(j=>j.health==="online").length,dirtyNodes:c.filter(j=>j.dirty).length,orphanNodes:d,errorNodes:c.filter(j=>!!j.error||j.outOfSync).length,offlineNodes:u,totalActiveSessions:c.reduce((j,f)=>j+f.activeSessionCount,0)},warnings:a}}const Sl=380,Cl=240,Il=176,Tl=220,Ly=44;function Ry(e,s){const r=s?"border-cyan-400/70 shadow-[0_0_0_1px_rgba(34,211,238,0.35),0_24px_60px_rgba(8,145,178,0.18)]":"border-white/10 shadow-[0_18px_48px_rgba(3,7,18,0.22)]";switch(e){case"online":return`${r} bg-emerald-500/8`;case"dirty":return`${r} bg-amber-500/8`;case"degraded":return`${r} bg-rose-500/10`;case"wrong_branch":return`${r} bg-violet-500/10`;case"offline":return`${r} bg-slate-500/12`;default:return`${r} bg-slate-950/78`}}function ts(e){switch(e){case"health":return"border-white/10 bg-slate-950/60 text-slate-200";case"dirty":return"border-amber-400/25 bg-amber-500/10 text-amber-200";case"conflict":return"border-rose-400/25 bg-rose-500/10 text-rose-200";case"orphan":return"border-fuchsia-400/25 bg-fuchsia-500/10 text-fuchsia-200";case"submodule":return"border-violet-400/25 bg-violet-500/10 text-violet-200";case"meta":default:return"border-cyan-400/20 bg-cyan-500/8 text-cyan-100"}}function cu(e){switch(e){case"online":return"#34d399";case"dirty":return"#fbbf24";case"degraded":return"#fb7185";case"wrong_branch":return"#a78bfa";case"offline":return"#94a3b8";default:return"#64748b"}}function _y(e){return e.replace(/_/g," ")}function Py({data:e,selected:s}){const r=e.graphNode,n=r.type==="defaultBranchNode",a=r.type==="submoduleNode",o=n?"default branch anchor":a?r.submodulePath||"submodule checkout":r.machineLabel||r.workspace,l=r.submoduleCommit?r.submoduleCommit.slice(0,7):null;return t.jsxs("div",{className:`${a?"w-[224px]":"w-[240px]"} rounded-2xl border px-4 py-3 backdrop-blur-sm transition-all ${Ry(r.health,s)}`,children:[t.jsx(xi,{type:"target",position:bi.Top,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}}),t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"truncate text-sm font-semibold text-slate-100",children:r.label}),t.jsx("div",{className:"truncate text-[11px] text-slate-400",children:o})]}),t.jsx("span",{className:"mt-0.5 h-2.5 w-2.5 shrink-0 rounded-full",style:{backgroundColor:cu(r.health)},"aria-hidden":!0})]}),t.jsxs("div",{className:"mt-3 flex flex-wrap gap-1.5 text-[10px]",children:[t.jsx("span",{className:`rounded-full border px-2 py-0.5 capitalize ${ts("health")}`,children:_y(r.health)}),a&&t.jsx("span",{className:`rounded-full border px-2 py-0.5 ${ts("submodule")}`,children:"submodule"}),r.branch&&!a&&t.jsx("span",{className:`rounded-full border px-2 py-0.5 ${ts("meta")}`,children:r.branch}),l&&a&&t.jsx("span",{className:`rounded-full border px-2 py-0.5 ${ts("meta")}`,children:l}),r.dirty&&t.jsx("span",{className:`rounded-full border px-2 py-0.5 ${ts("dirty")}`,children:a?"local changes":`${r.dirtyFiles} dirty`}),r.outOfSync&&t.jsx("span",{className:`rounded-full border px-2 py-0.5 ${ts("conflict")}`,children:"out of sync"}),r.hasConflicts&&t.jsx("span",{className:`rounded-full border px-2 py-0.5 ${ts("conflict")}`,children:"conflicts"}),r.isOrphan&&t.jsx("span",{className:`rounded-full border px-2 py-0.5 ${ts("orphan")}`,children:"needs attention"})]}),a?t.jsxs("div",{className:"mt-3 grid grid-cols-2 gap-2 text-[11px] text-slate-300",children:[t.jsxs("div",{className:"rounded-xl border border-white/8 bg-slate-950/58 px-2.5 py-2",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.12em] text-slate-500",children:"Parent node"}),t.jsx("div",{className:"mt-1 truncate font-medium text-slate-100",children:r.machineLabel||"mesh node"})]}),t.jsxs("div",{className:"rounded-xl border border-white/8 bg-slate-950/58 px-2.5 py-2",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.12em] text-slate-500",children:"State"}),t.jsx("div",{className:"mt-1 font-medium text-slate-100",children:r.outOfSync?"Out of sync":r.dirty?"Dirty":"Synced"})]})]}):t.jsxs("div",{className:"mt-3 grid grid-cols-2 gap-2 text-[11px] text-slate-300",children:[t.jsxs("div",{className:"rounded-xl border border-white/8 bg-slate-950/58 px-2.5 py-2",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.12em] text-slate-500",children:"Sessions"}),t.jsx("div",{className:"mt-1 font-medium text-slate-100",children:r.activeSessionCount})]}),t.jsxs("div",{className:"rounded-xl border border-white/8 bg-slate-950/58 px-2.5 py-2",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-[0.12em] text-slate-500",children:"Git drift"}),t.jsxs("div",{className:"mt-1 font-medium text-slate-100",children:["+",r.ahead," / -",r.behind]})]})]}),r.nextStepHint&&t.jsx("div",{className:"mt-3 rounded-xl border border-cyan-400/15 bg-cyan-500/8 px-3 py-2 text-[10px] leading-4 text-cyan-50/90",children:r.nextStepHint}),t.jsx(xi,{type:"source",position:bi.Bottom,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const Dy={meshNode:Py};function Ia(e,s){return e.type==="defaultBranchNode"&&s.type!=="defaultBranchNode"?-1:s.type==="defaultBranchNode"&&e.type!=="defaultBranchNode"||e.type==="submoduleNode"&&s.type!=="submoduleNode"?1:s.type==="submoduleNode"&&e.type!=="submoduleNode"?-1:e.branch&&s.branch&&e.branch!==s.branch?e.branch.localeCompare(s.branch):e.branch&&!s.branch?-1:!e.branch&&s.branch?1:e.label.localeCompare(s.label)}function Ey(e){const s=[...e.nodes].sort(Ia),r=s.find(f=>f.type==="defaultBranchNode")??null,n=new Map;for(const f of s){if(f.type!=="submoduleNode"||!f.parentNodeId)continue;const p=n.get(f.parentNodeId)??[];p.push(f),n.set(f.parentNodeId,p)}const a=s.filter(f=>f.id!==(r==null?void 0:r.id)&&f.type!=="submoduleNode"),o=new Map,l=[];for(const f of a){if(f.isOrphan||!f.branch){l.push(f);continue}const p=f.branch,b=o.get(p)??[];b.push(f),o.set(p,b)}const c=[...o.entries()].sort(([f],[p])=>r!=null&&r.branch&&f===r.branch&&p!==r.branch?-1:r!=null&&r.branch&&p===r.branch&&f!==r.branch?1:f.localeCompare(p));l.length>0&&c.push(["__orphans__",[...l].sort(Ia)]),c.length===0&&c.push(["__nodes__",[]]);const d=[],m=c.length,u=Math.max(1,m-1)*Sl,h=r?0:80,g=r?Cl:0;r&&d.push({id:r.id,type:"meshNode",position:{x:u/2,y:h},data:{graphNode:r},selected:!1,draggable:!1,selectable:!0}),c.forEach(([f,p],b)=>{const y=b*Sl,x=p.length>0?p:a.length>0?a:[];let A=g;x.forEach(N=>{d.push({id:N.id,type:"meshNode",position:{x:y,y:A},data:{graphNode:N},selected:!1,draggable:!1,selectable:!0});const v=[...n.get(N.id)??[]].sort(Ia);if(v.length>0){v.forEach((C,M)=>{d.push({id:C.id,type:"meshNode",position:{x:y,y:A+Tl+M*Il},data:{graphNode:C},selected:!1,draggable:!1,selectable:!0})}),A+=Tl+v.length*Il+Ly;return}A+=Cl}),f==="__nodes__"&&a.length===0&&r&&d.push({id:`${r.id}__placeholder`,type:"meshNode",position:{x:y,y:g},data:{graphNode:{id:`${r.id}__placeholder`,type:"worktreeNode",label:"No active worktrees",workspace:e.repoIdentity,branch:r.branch,machineLabel:null,health:"unknown",ahead:0,behind:0,dirty:!1,dirtyFiles:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],providers:[],isOrphan:!1,orphanReasons:[],nextStepHint:"Waiting for worktree nodes to report live mesh status.",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,source:{nodeId:`${r.id}__placeholder`,machineLabel:null,workspace:e.repoIdentity,health:"unknown",providers:[],activeSessions:[]}}},selected:!1,draggable:!1,selectable:!1})});const j=e.edges.map(f=>({id:f.id,source:f.source,target:f.target,label:f.label,type:f.type==="worktreeLink"||f.type==="submoduleLink"?"smoothstep":"bezier",animated:f.type==="orphanLink",markerEnd:{type:Qu.ArrowClosed,width:f.type==="submoduleLink"?16:18,height:f.type==="submoduleLink"?16:18,color:Al(f)},style:{stroke:Al(f),strokeWidth:f.type==="orphanLink"?2.25:f.type==="submoduleLink"?1.7:f.type==="worktreeLink"?1.8:2,strokeDasharray:f.type==="orphanLink"?"5 4":f.type==="submoduleLink"?"4 3":void 0},labelStyle:{fill:"var(--text-secondary, #cbd5e1)",fontSize:10,fontWeight:600},labelBgStyle:{fill:"rgba(2, 6, 23, 0.86)",fillOpacity:1,stroke:"rgba(148, 163, 184, 0.2)"},labelBgPadding:[5,3],labelBgBorderRadius:6}));return{nodes:d,edges:j}}function Al(e){switch(e.type){case"parentBranch":return"#38bdf8";case"worktreeLink":return"#a78bfa";case"sessionLink":return"#34d399";case"orphanLink":return"#f97316";case"submoduleLink":return"#c084fc";default:return"#64748b"}}function du({data:e,selectedNodeId:s=null,onNodeClick:r}){const n=i.useMemo(()=>Ey(e),[e]),a=i.useMemo(()=>n.nodes.map(o=>({...o,selected:o.id===s})),[n.nodes,s]);return t.jsxs("div",{className:"relative h-full min-h-[560px] overflow-hidden rounded-2xl border border-white/10 bg-[radial-gradient(circle_at_top,_rgba(56,189,248,0.12),_rgba(15,23,42,0.98)_42%,_rgba(2,6,23,1))]",children:[t.jsxs("div",{className:"absolute left-4 top-4 z-10 flex flex-wrap gap-2 text-[11px] text-slate-200",children:[t.jsxs("span",{className:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1",children:[e.stats.totalNodes," node",e.stats.totalNodes===1?"":"s"]}),t.jsxs("span",{className:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1",children:[e.stats.totalActiveSessions," active session",e.stats.totalActiveSessions===1?"":"s"]}),e.stats.orphanNodes>0&&t.jsxs("span",{className:"rounded-full border border-orange-400/25 bg-orange-500/12 px-3 py-1 text-orange-100",children:[e.stats.orphanNodes," need attention"]})]}),t.jsxs(Gu,{nodes:a,edges:n.edges,nodeTypes:Dy,fitView:!0,fitViewOptions:{padding:.28,maxZoom:1.02},minZoom:.25,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!1,zoomOnScroll:!1,zoomOnPinch:!1,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(o,l)=>r==null?void 0:r(l.data.graphNode),className:"h-full w-full",colorMode:"dark",proOptions:{hideAttribution:!0},children:[t.jsx(qu,{className:"!bottom-4 !right-4 !bg-slate-950/85 !border !border-white/10 !rounded-xl",nodeColor:o=>cu(o.data.graphNode.health)}),t.jsx(Yu,{className:"!bottom-4 !left-4 !shadow-lg",showInteractive:!1}),t.jsx(Xu,{variant:Ju.Dots,gap:18,size:1.2,color:"rgba(148, 163, 184, 0.22)"})]})]})}function Lt({label:e,value:s}){return s==null||s===""?null:t.jsxs("div",{className:"flex justify-between gap-3 border-b border-white/6 py-0.5 text-[11px]",children:[t.jsx("span",{className:"text-slate-400",children:e}),t.jsx("span",{className:"break-all text-right font-medium text-slate-200",children:String(s)})]})}function $y({health:e}){const s={online:"bg-green-500/10 text-green-400 border-green-500/20",dirty:"bg-yellow-500/10 text-yellow-400 border-yellow-500/20",degraded:"bg-red-500/10 text-red-400 border-red-500/20",wrong_branch:"bg-purple-500/10 text-purple-400 border-purple-500/20",offline:"bg-gray-500/10 text-gray-400 border-gray-500/20",unknown:"bg-gray-500/10 text-gray-400 border-gray-500/20"};return t.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] border ${s[e]||s.unknown}`,children:e})}function By(e){var a,o,l;if(e.type==="submoduleNode")return e.submoduleCommit?e.submoduleCommit.slice(0,7):null;const s=e.source;if("kind"in s)return null;const r=(a=s.git)!=null&&a.headCommit?s.git.headCommit.slice(0,7):null,n=((l=(o=s.git)==null?void 0:o.headMessage)==null?void 0:l.trim())||null;return!r&&!n?null:[r,n].filter(Boolean).join(" · ")}function uu({node:e,onClose:s}){if(!e)return t.jsx("div",{className:"w-full max-w-full rounded-xl border border-white/10 bg-white/[0.04] p-4 text-xs text-slate-400 md:w-64",children:"Select a node to view details."});const r=e.type==="submoduleNode",n=By(e);return t.jsxs("div",{className:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-white/10 bg-white/[0.04] p-4 shadow-lg md:w-64",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("span",{className:"truncate text-xs font-semibold text-slate-100",children:e.label}),s&&t.jsx("button",{onClick:s,className:"text-xs text-slate-400 hover:text-slate-100",children:"✕"})]}),t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsx($y,{health:e.health}),r&&t.jsx("span",{className:"rounded border border-violet-500/20 bg-violet-500/10 px-1.5 py-0.5 text-[10px] text-violet-200",children:"Submodule"}),e.dirty&&t.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] bg-yellow-500/10 text-yellow-400 border border-yellow-500/20",children:"Dirty"}),e.outOfSync&&t.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] bg-red-500/10 text-red-400 border border-red-500/20",children:"Out of sync"}),e.hasConflicts&&t.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] bg-red-500/10 text-red-400 border border-red-500/20",children:"Conflict"}),e.isOrphan&&t.jsx("span",{className:"px-1.5 py-0.5 rounded text-[10px] bg-red-500/10 text-red-400 border border-red-500/20",children:"Orphan"})]}),t.jsxs("div",{className:"flex flex-col gap-0.5 mt-1",children:[t.jsx(Lt,{label:"Workspace",value:e.workspace}),t.jsx(Lt,{label:"Branch",value:e.branch}),t.jsx(Lt,{label:"HEAD",value:n}),t.jsx(Lt,{label:"Submodule path",value:e.submodulePath??null}),t.jsx(Lt,{label:"Submodule commit",value:e.submoduleCommit??null}),t.jsx(Lt,{label:"Parent node",value:r&&(e.machineLabel||e.parentNodeId)||null}),t.jsx(Lt,{label:"Ahead",value:!r&&e.ahead>0?`+${e.ahead}`:null}),t.jsx(Lt,{label:"Behind",value:!r&&e.behind>0?`-${e.behind}`:null}),t.jsx(Lt,{label:"Dirty files",value:e.dirtyFiles>0?e.dirtyFiles:null}),t.jsx(Lt,{label:"Active sessions",value:e.activeSessionCount>0?e.activeSessionCount:null}),t.jsx(Lt,{label:"Providers",value:r?null:e.providers.join(", ")||null}),t.jsx(Lt,{label:"Error",value:e.error??null})]}),e.orphanReasons.length>0&&t.jsxs("div",{className:"mt-1",children:[t.jsx("div",{className:"text-[10px] font-semibold text-red-400 mb-1",children:"Orphan reasons"}),t.jsx("ul",{className:"list-disc list-inside text-[10px] text-red-300 space-y-0.5",children:e.orphanReasons.map((a,o)=>t.jsx("li",{children:a},o))})]}),e.nextStepHint&&t.jsxs("div",{className:"mt-1 px-2 py-1.5 rounded bg-blue-500/10 border border-blue-500/20 text-[10px] text-blue-300",children:["💡 ",e.nextStepHint]})]})}const Ml=new Set(["pending","assigned"]);function Ve({label:e,tone:s="default"}){const r={default:"border-white/10 bg-white/[0.04] text-slate-200",good:"border-emerald-400/20 bg-emerald-500/10 text-emerald-200",warn:"border-amber-400/20 bg-amber-500/10 text-amber-100",danger:"border-rose-400/20 bg-rose-500/10 text-rose-100",info:"border-sky-400/20 bg-sky-500/10 text-sky-100"};return t.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${r[s]||r.default}`,children:e})}function Ft({title:e,subtitle:s,children:r,className:n=""}){return t.jsxs("section",{className:`rounded-2xl border border-white/10 bg-white/[0.04] ${n}`,children:[t.jsxs("div",{className:"border-b border-white/10 px-4 py-3",children:[t.jsx("div",{className:"text-sm font-semibold text-white",children:e}),s&&t.jsx("div",{className:"mt-1 text-xs text-slate-400",children:s})]}),t.jsx("div",{className:"px-4 py-3",children:r})]})}function qe({label:e,value:s}){return t.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-white/5 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",children:[t.jsx("span",{className:"text-slate-400",children:e}),t.jsx("span",{className:"max-w-[65%] break-all text-right text-slate-100",children:s})]})}function Kt({label:e,onClick:s,tone:r="default"}){const n={default:"border-white/10 bg-white/[0.04] text-slate-200 hover:bg-white/[0.08]",info:"border-sky-400/25 bg-sky-500/10 text-sky-100 hover:bg-sky-500/16",success:"border-emerald-400/25 bg-emerald-500/10 text-emerald-100 hover:bg-emerald-500/16"};return t.jsx("button",{type:"button",onClick:s,className:`rounded-full border px-2.5 py-1 text-[11px] transition ${n[r]||n.default}`,children:e})}function ss(e){if(!e)return null;const s=new Date(e);return Number.isNaN(s.getTime())?e:s.toLocaleString()}function Ls(e){if(!e)return null;const s=new Date(e);return Number.isNaN(s.getTime())?null:s.toLocaleString()}function Ta(e){switch(e){case"completed":return"good";case"failed":case"cancelled":return"danger";case"assigned":return"info";case"pending":return"warn";default:return"default"}}function Ll(e){switch(e){case"online":return"good";case"dirty":return"warn";case"degraded":case"offline":return"danger";case"wrong_branch":return"info";default:return"default"}}function tn(e){switch((e||"").toLowerCase()){case"idle":return"good";case"generating":case"running":return"info";case"waiting_approval":case"starting":case"pending":return"warn";case"failed":case"stopped":case"interrupted":return"danger";default:return"default"}}function Rl(e){if(!e)return"default";if(e.state==="self")return"info";if(e.transport==="direct"&&e.state==="connected")return"good";if(e.transport==="relay"&&e.state==="connected")return"info";switch(e.state){case"connected":return"good";case"connecting":return"warn";case"disconnected":case"failed":case"closed":return"danger";default:return"default"}}function Aa(e){return e?e.state==="self"?"mesh self":e.transport==="direct"&&e.state==="connected"?"mesh direct":e.transport==="relay"&&e.state==="connected"?"mesh relay":!e.reported&&e.source==="not_reported"?"mesh unknown / not reported":`mesh ${e.state}`:"mesh unknown"}function Ma(e){return e===!0?"yes":e===!1?"no":"unknown"}function _l(e,s){if(!s)return null;const r=new URLSearchParams;return e&&r.set("daemonId",e),r.set("targetSessionId",s),`/dashboard?${r.toString()}`}function Pl(e){const s=e.git;if(!s)return"No git probe";const r=(s.staged??0)+(s.modified??0)+(s.untracked??0)+(s.deleted??0)+(s.renamed??0),n=[];s.branch&&n.push(s.branch),((s.ahead??0)>0||(s.behind??0)>0)&&n.push(`↑${s.ahead??0}/↓${s.behind??0}`),r>0&&n.push(`${r} dirty`);const a=(s.submodules??[]).filter(l=>l.dirty),o=(s.submodules??[]).filter(l=>l.outOfSync||l.error);return a.length>0&&n.push(`${a.length} submodule dirty`),o.length>0&&n.push(`${o.length} submodule drift`),s.hasConflicts&&n.push("conflicts"),n.join(" · ")||"Clean"}function Oy(e){var r;const s=[];for(const n of e.nodes){const a=n.activeSessionDetails&&n.activeSessionDetails.length>0?n.activeSessionDetails:(n.activeSessions??[]).map(o=>({sessionId:o,workspace:n.workspace,isCached:!0}));for(const o of a)s.push({nodeId:n.nodeId,machineLabel:n.machineLabel,workspace:n.workspace,branch:((r=n.git)==null?void 0:r.branch)??null,nodeHealth:n.health,session:o})}return s}function La(e){const s=e.assignedNodeId||e.targetNodeId||"unbound",r=e.assignedSessionId||e.targetSessionId||"no session";return`${s} · ${r}`}function sn(e){return e.assignedNodeId||e.targetNodeId||null}function Ra(e){var s;return e.assignedSessionId||e.targetSessionId||((s=e.autoLaunch)==null?void 0:s.sessionId)||null}function _a(e){var s,r;return((s=e.nodes.find(n=>n.type!=="submoduleNode"))==null?void 0:s.id)??((r=e.nodes[0])==null?void 0:r.id)??null}function wr(e){return e?e.slice(0,7):null}function Fy(e,s){var o,l,c;const r=wr((o=e==null?void 0:e.git)==null?void 0:o.headCommit),n=((c=(l=e==null?void 0:e.git)==null?void 0:l.headMessage)==null?void 0:c.trim())||"";if(r||n)return[r,n].filter(Boolean).join(" · ");const a=s[0];return a?[wr(a.commit),a.message].filter(Boolean).join(" · "):null}function Ky(e){const s=(e==null?void 0:e.result)??e,r=(s==null?void 0:s.log)??(e==null?void 0:e.log)??s;return Array.isArray(r==null?void 0:r.entries)?r.entries:[]}function Wy({graph:e,status:s,emptyMessage:r="No live mesh graph is available for this coordinator yet.",daemonId:n=null,sendDaemonCommand:a=null}){var K,P,$,V,Y,ge,fe,ae,me,je,Ne,G,he,pe,ye,xe,Se;const o=cs(),[l,c]=i.useState(()=>_a(e)),[d,m]=i.useState(()=>{const R=_a(e);return R?{kind:"node",nodeId:R}:null}),[u,h]=i.useState("active"),[g,j]=i.useState({}),f=i.useMemo(()=>new Map(s.nodes.map(R=>[R.nodeId,R])),[s.nodes]),p=i.useMemo(()=>new Map(e.nodes.map(R=>[R.id,R])),[e.nodes]),b=((K=s.queue)==null?void 0:K.tasks)??[],y=((P=s.queue)==null?void 0:P.summary)??null,x=i.useMemo(()=>Oy(s),[s]),A=i.useMemo(()=>{const R=new Map;for(const re of x){const Q=re.session.state||re.session.lifecycle||"unknown";R.set(Q,(R.get(Q)??0)+1)}return[...R.entries()].sort((re,Q)=>Q[1]-re[1])},[x]),N=i.useMemo(()=>u==="all"?b:u==="active"?b.filter(R=>Ml.has(R.status)):b.filter(R=>!Ml.has(R.status)),[u,b]);i.useEffect(()=>{if(!l||!p.has(l)){const R=_a(e);c(R),m(R?{kind:"node",nodeId:R}:null)}},[e,p,l]);const v=l?p.get(l)??null:null,C=l?f.get(l)??null:null,M=(d==null?void 0:d.kind)==="queue"?b.find(R=>R.id===d.taskId)??null:null,w=(d==null?void 0:d.kind)==="session"?x.find(R=>R.nodeId===d.nodeId&&R.session.sessionId===d.sessionId)??null:null,k=i.useMemo(()=>x.filter(R=>R.nodeId===l),[l,x]),F=i.useMemo(()=>b.filter(R=>sn(R)===l),[b,l]),_=(w==null?void 0:w.session.workspace)||(w==null?void 0:w.workspace)||(v==null?void 0:v.workspace)||null,S=_?g[_]??null:null,H=Fy(C,(S==null?void 0:S.entries)??[]),W=i.useCallback(R=>{R&&o(Vt(R),{state:{openRemoteForTabKey:R}})},[o]),D=i.useCallback((R,re)=>{c(R),m({kind:"session",nodeId:R,sessionId:re})},[]),I=i.useCallback(R=>{c(R),m({kind:"node",nodeId:R})},[]);i.useEffect(()=>{if(!_||!n||!a)return;const R=g[_];if(R!=null&&R.loading||R&&(R.entries.length>0||R.error))return;let re=!1;return j(Q=>{var ue;return{...Q,[_]:{loading:!0,error:null,entries:((ue=Q[_])==null?void 0:ue.entries)??[]}}}),a(n,"git_log",{workspace:_,limit:5}).then(Q=>{re||j(ue=>({...ue,[_]:{loading:!1,error:null,entries:Ky(Q)}}))}).catch(Q=>{re||j(ue=>({...ue,[_]:{loading:!1,error:Q instanceof Error?Q.message:"git_log failed",entries:[]}}))}),()=>{re=!0}},[n,g,_,a]);const T=[...e.warnings??[],...s.nodes.filter(R=>R.machineStatus&&R.machineStatus!=="online").map(R=>`${R.machineLabel}: ${R.machineStatus}`)];return t.jsxs("div",{className:"flex min-h-0 flex-col gap-4 xl:flex-row",children:[t.jsxs("div",{className:"flex min-h-0 min-w-0 flex-1 flex-col gap-4",children:[t.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4",children:[t.jsx(Ft,{title:`${e.stats.totalNodes} nodes`,subtitle:"Mesh topology",children:t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx(Ve,{label:`${e.stats.totalActiveSessions} active sessions`,tone:e.stats.totalActiveSessions>0?"info":"default"}),t.jsx(Ve,{label:`${e.stats.dirtyNodes} dirty`,tone:e.stats.dirtyNodes>0?"warn":"good"}),t.jsx(Ve,{label:`${e.stats.offlineNodes} offline`,tone:e.stats.offlineNodes>0?"danger":"good"})]})}),t.jsx(Ft,{title:`${(y==null?void 0:y.active)??0} active queue`,subtitle:"Pending + assigned tasks",children:t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx(Ve,{label:`${(y==null?void 0:y.activeCounts.pending)??0} pending`,tone:"warn"}),t.jsx(Ve,{label:`${(y==null?void 0:y.activeCounts.assigned)??0} assigned`,tone:"info"}),t.jsx(Ve,{label:`${(y==null?void 0:y.historical)??0} recent history`,tone:"default"})]})}),t.jsx(Ft,{title:`${x.length} sessions`,subtitle:"Live and cached session view",children:t.jsx("div",{className:"flex flex-wrap gap-2",children:A.length===0?t.jsx(Ve,{label:"no session metadata"}):A.slice(0,3).map(([R,re])=>t.jsx(Ve,{label:`${re} ${R}`,tone:tn(R)},R))})}),t.jsx(Ft,{title:`${(($=s.ledger)==null?void 0:$.summary.recentFailures)??0} recent failures`,subtitle:"Ledger evidence",children:t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx(Ve,{label:`${((V=s.ledger)==null?void 0:V.summary.taskCompleted)??0} completed`,tone:"good"}),t.jsx(Ve,{label:`${((Y=s.ledger)==null?void 0:Y.summary.taskFailed)??0} failed`,tone:(((ge=s.ledger)==null?void 0:ge.summary.taskFailed)??0)>0?"danger":"good"}),t.jsx(Ve,{label:`${((fe=s.ledger)==null?void 0:fe.summary.sessionLaunched)??0} launched`,tone:"info"})]})})]}),t.jsxs(Ft,{title:"Mesh meaning",subtitle:"Read the graph without hidden rules.",children:[t.jsxs("div",{className:"flex flex-wrap gap-2 text-xs text-slate-300",children:[t.jsx(Ve,{label:"Anchor = inferred default branch",tone:"info"}),t.jsx(Ve,{label:"Peer link = same-branch worktree",tone:"default"}),t.jsx(Ve,{label:"Submodule link = child checkout under a parent node",tone:"warn"}),t.jsx(Ve,{label:"Node badges = health + drift + session activity",tone:"default"}),t.jsx(Ve,{label:"Mesh transport = selected-coordinator view only",tone:"info"}),t.jsx(Ve,{label:"Unknown / not reported = no live daemon↔daemon telemetry yet",tone:"warn"})]}),t.jsx("div",{className:"mt-3 text-xs text-slate-400",children:"Tap a node to inspect workspace, session, and git details. Launch readiness and mesh transport details stay in the same drill-down. Queue rows and session rows are also selectable for drill-down."})]}),T.length>0&&t.jsx("div",{className:"flex flex-wrap gap-2",children:T.map(R=>t.jsx("span",{className:"rounded-full border border-amber-400/20 bg-amber-500/10 px-3 py-1 text-xs text-amber-100",children:R},R))}),t.jsx("div",{className:"min-h-0 flex-1 rounded-[28px] border border-white/10 bg-white/[0.03] p-3 sm:p-4",style:{minHeight:420},children:e.nodes.length>0?t.jsx(du,{data:e,selectedNodeId:l,onNodeClick:R=>{c(R.id),m({kind:"node",nodeId:R.id})}}):t.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:r})})]}),t.jsxs("div",{className:"flex w-full shrink-0 flex-col gap-4 xl:w-[420px]",children:[t.jsx(Ft,{title:"Selected detail",subtitle:"Node, session, or queue item drill-down.",children:t.jsx("div",{className:"flex flex-col gap-3",children:(d==null?void 0:d.kind)==="queue"&&M?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsx(Ve,{label:M.status,tone:Ta(M.status)}),t.jsx(Ve,{label:M.id.slice(0,8),tone:"default"})]}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[sn(M)&&t.jsx(Kt,{label:"View node",onClick:()=>I(sn(M)||"")}),(()=>{const R=Ra(M);if(!R)return null;const re=x.find(Q=>Q.session.sessionId===R)??null;return t.jsxs(t.Fragment,{children:[re&&t.jsx(Kt,{label:"View session",onClick:()=>D(re.nodeId,re.session.sessionId)}),t.jsx(Kt,{label:"Open chat",tone:"info",onClick:()=>W(R)})]})})()]}),t.jsx(qe,{label:"Message",value:M.message}),t.jsx(qe,{label:"Routing",value:La(M)}),t.jsx(qe,{label:"Created",value:ss(M.createdAt)??"unknown"}),t.jsx(qe,{label:"Updated",value:ss(M.updatedAt)??"unknown"}),t.jsx(qe,{label:"Requeues",value:M.requeueCount??0}),t.jsx(qe,{label:"Auto-launch",value:M.autoLaunch?`${M.autoLaunch.status}${M.autoLaunch.providerType?` · ${M.autoLaunch.providerType}`:""}`:"none"}),(()=>{var ue,ce,de;const R=M.assignedSessionId||M.targetSessionId||((ue=M.autoLaunch)==null?void 0:ue.sessionId)||null,re=M.assignedNodeId||M.targetNodeId||((ce=M.autoLaunch)==null?void 0:ce.nodeId)||null,Q=_l(re?(de=f.get(re))==null?void 0:de.daemonId:null,R);return Q?t.jsx("a",{href:Q,className:"inline-flex w-fit items-center rounded-full border border-sky-400/30 bg-sky-500/10 px-3 py-1 text-xs font-medium text-sky-100 transition hover:bg-sky-500/20",children:"Open linked dashboard chat"}):null})(),M.cancelReason&&t.jsx(qe,{label:"Cancel reason",value:M.cancelReason}),M.requeueReason&&t.jsx(qe,{label:"Requeue reason",value:M.requeueReason})]}):(d==null?void 0:d.kind)==="session"&&w?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsx(Ve,{label:w.session.state||w.session.lifecycle||"unknown",tone:tn(w.session.state||w.session.lifecycle)}),w.session.providerType&&t.jsx(Ve,{label:w.session.providerType,tone:"info"}),w.session.isCached&&t.jsx(Ve,{label:"cached",tone:"default"})]}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx(Kt,{label:"View node",onClick:()=>I(w.nodeId)}),t.jsx(Kt,{label:"Open chat",tone:"info",onClick:()=>W(w.session.sessionId)})]}),t.jsx(qe,{label:"Session id",value:w.session.sessionId}),t.jsx(qe,{label:"Node",value:w.machineLabel}),t.jsx(qe,{label:"Workspace",value:w.workspace}),t.jsx(qe,{label:"Branch",value:w.branch??"unknown"}),t.jsx(qe,{label:"Node health",value:w.nodeHealth}),t.jsx(qe,{label:"Lifecycle",value:w.session.lifecycle??"unknown"}),w.session.surfaceKind&&t.jsx(qe,{label:"Surface",value:w.session.surfaceKind}),w.session.recoveryState&&t.jsx(qe,{label:"Recovery",value:w.session.recoveryState}),w.session.lastActivityAt&&t.jsx(qe,{label:"Last activity",value:ss(w.session.lastActivityAt)??w.session.lastActivityAt}),(()=>{var re;const R=_l((re=f.get(w.nodeId))==null?void 0:re.daemonId,w.session.sessionId);return R?t.jsx("a",{href:R,className:"inline-flex w-fit items-center rounded-full border border-sky-400/30 bg-sky-500/10 px-3 py-1 text-xs font-medium text-sky-100 transition hover:bg-sky-500/20",children:"Open dashboard chat"}):null})(),t.jsxs("div",{className:"rounded-xl border border-white/10 bg-slate-950/40 p-3",children:[t.jsx("div",{className:"mb-2 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400",children:"Git context"}),t.jsxs("div",{className:"flex flex-col gap-2 text-xs text-slate-300",children:[t.jsx("div",{children:H||"HEAD subject not present in cached mesh_status."}),(S==null?void 0:S.loading)&&t.jsx("div",{className:"text-slate-500",children:"Loading recent commits…"}),(S==null?void 0:S.error)&&t.jsxs("div",{className:"text-amber-200",children:["Recent history unavailable: ",S.error]}),((S==null?void 0:S.entries)??[]).slice(0,5).map(R=>t.jsxs("div",{className:"rounded-lg border border-white/5 bg-white/[0.03] px-2.5 py-2",children:[t.jsxs("div",{className:"font-medium text-slate-100",children:[wr(R.commit)," · ",R.message]}),t.jsxs("div",{className:"mt-1 text-[11px] text-slate-500",children:[R.authorName||"unknown author",Ls(R.committedAt)?` · ${Ls(R.committedAt)}`:""]})]},R.commit))]})]})]}):v?t.jsxs(t.Fragment,{children:[t.jsx(uu,{node:v}),C&&t.jsxs("div",{className:"rounded-xl border border-white/10 bg-slate-950/40 p-3",children:[t.jsxs("div",{className:"mb-2 flex flex-wrap items-center gap-2",children:[t.jsx(Ve,{label:C.health,tone:Ll(C.health)}),C.machineStatus&&t.jsx(Ve,{label:C.machineStatus,tone:C.machineStatus==="online"?"good":"warn"}),t.jsx(Ve,{label:`launchReady ${Ma(C.launchReady)}`,tone:C.launchReady?"good":"warn"}),t.jsx(Ve,{label:Aa(C.connection),tone:Rl(C.connection)}),C.worktreeBranch&&t.jsx(Ve,{label:C.worktreeBranch,tone:"info"})]}),t.jsxs("div",{className:"flex flex-col gap-0.5",children:[t.jsx(qe,{label:"Repo root",value:C.repoRoot??C.workspace}),t.jsx(qe,{label:"Provider(s)",value:(C.providers??[]).join(", ")||"none"}),t.jsx(qe,{label:"Provider priority",value:(C.providerPriority??[]).join(", ")||"not configured"}),t.jsx(qe,{label:"Drift",value:Pl(C)}),t.jsx(qe,{label:"HEAD",value:H??"Not available"}),t.jsx(qe,{label:"Daemon",value:C.daemonId??"unknown"}),t.jsx(qe,{label:"Machine",value:C.machineId??C.machineLabel}),t.jsx(qe,{label:"Launch ready",value:Ma(C.launchReady)}),t.jsx(qe,{label:"Mesh connection",value:Aa(C.connection)}),t.jsx(qe,{label:"Transport",value:((ae=C.connection)==null?void 0:ae.transport)??"unknown"}),t.jsx(qe,{label:"Connection source",value:((me=C.connection)==null?void 0:me.source)??"unknown"}),t.jsx(qe,{label:"Last seen",value:ss(C.lastSeenAt)??C.lastSeenAt??"not reported"}),t.jsx(qe,{label:"Updated",value:ss(C.updatedAt)??C.updatedAt??"not reported"}),((je=C.connection)==null?void 0:je.lastConnectedAt)&&t.jsx(qe,{label:"Last connected",value:ss(C.connection.lastConnectedAt)??C.connection.lastConnectedAt}),((Ne=C.connection)==null?void 0:Ne.lastCommandAt)&&t.jsx(qe,{label:"Last mesh command",value:ss(C.connection.lastCommandAt)??C.connection.lastCommandAt}),((G=C.connection)==null?void 0:G.reason)&&t.jsx(qe,{label:"Connection reason",value:C.connection.reason}),t.jsx(qe,{label:"Sessions",value:C.activeSessions.length}),C.error&&t.jsx(qe,{label:"Error",value:C.error})]}),k.length>0&&t.jsxs("div",{className:"mt-3",children:[t.jsx("div",{className:"mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400",children:"Active sessions"}),t.jsx("div",{className:"flex flex-col gap-2",children:k.map(R=>{const re=R.session.state||R.session.lifecycle||"unknown";return t.jsxs("div",{className:"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200",children:[t.jsxs("div",{className:"flex items-start justify-between gap-2",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"truncate font-medium text-slate-100",children:R.session.title||R.session.sessionId}),t.jsxs("div",{className:"mt-1 truncate text-[11px] text-slate-400",children:[R.session.providerType||"unknown provider"," · ",re]})]}),t.jsx(Ve,{label:re,tone:tn(re)})]}),t.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[t.jsx(Kt,{label:"View session",onClick:()=>D(R.nodeId,R.session.sessionId)}),t.jsx(Kt,{label:"Open chat",tone:"info",onClick:()=>W(R.session.sessionId)})]})]},`${R.nodeId}:${R.session.sessionId}`)})})]}),F.length>0&&t.jsxs("div",{className:"mt-3",children:[t.jsx("div",{className:"mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400",children:"Related queue items"}),t.jsx("div",{className:"flex flex-col gap-2",children:F.map(R=>{const re=Ra(R),Q=re?x.find(ue=>ue.session.sessionId===re)??null:null;return t.jsxs("div",{className:"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200",children:[t.jsxs("div",{className:"flex items-start justify-between gap-2",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"truncate font-medium text-slate-100",children:R.message}),t.jsx("div",{className:"mt-1 truncate text-[11px] text-slate-400",children:La(R)})]}),t.jsx(Ve,{label:R.status,tone:Ta(R.status)})]}),t.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[t.jsx(Kt,{label:"View queue detail",onClick:()=>m({kind:"queue",taskId:R.id})}),Q&&t.jsx(Kt,{label:"View session",onClick:()=>D(Q.nodeId,Q.session.sessionId)}),re&&t.jsx(Kt,{label:"Open chat",tone:"info",onClick:()=>W(re)})]})]},R.id)})})]}),t.jsxs("div",{className:"mt-3",children:[t.jsx("div",{className:"mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400",children:"Recent commits"}),t.jsxs("div",{className:"flex flex-col gap-2",children:[(S==null?void 0:S.loading)&&t.jsx("div",{className:"text-xs text-slate-500",children:"Loading recent commits…"}),(S==null?void 0:S.error)&&t.jsxs("div",{className:"text-xs text-amber-200",children:["Recent history unavailable: ",S.error]}),!(S!=null&&S.loading)&&!(S!=null&&S.error)&&((S==null?void 0:S.entries)??[]).length===0&&t.jsx("div",{className:"text-xs text-slate-500",children:"Recent commit history not available from the current mesh snapshot yet."}),((S==null?void 0:S.entries)??[]).slice(0,5).map(R=>t.jsxs("div",{className:"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200",children:[t.jsxs("div",{className:"font-medium text-slate-100",children:[wr(R.commit)," · ",R.message]}),t.jsxs("div",{className:"mt-1 text-[11px] text-slate-500",children:[R.authorName||"unknown author",Ls(R.committedAt)?` · ${Ls(R.committedAt)}`:""]})]},R.commit))]})]}),(((pe=(he=C.git)==null?void 0:he.submodules)==null?void 0:pe.length)??0)>0&&t.jsxs("div",{className:"mt-3",children:[t.jsx("div",{className:"mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400",children:"Submodules"}),t.jsx("div",{className:"flex flex-col gap-2",children:(((ye=C.git)==null?void 0:ye.submodules)??[]).map(R=>t.jsxs("div",{className:"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200",children:[t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsx("span",{className:"font-medium",children:R.path}),R.dirty&&t.jsx(Ve,{label:"dirty",tone:"warn"}),(R.outOfSync||R.error)&&t.jsx(Ve,{label:"drift",tone:"danger"})]}),t.jsx("div",{className:"mt-1 break-all text-[11px] text-slate-400",children:R.repoPath}),t.jsx("div",{className:"mt-1 text-[11px] text-slate-500",children:"Select the submodule node in the graph for its own HEAD and recent history."}),R.error&&t.jsx("div",{className:"mt-1 text-[11px] text-rose-200",children:R.error})]},`${C.nodeId}:${R.path}`))})]})]}),!C&&t.jsxs("div",{className:"rounded-xl border border-white/10 bg-slate-950/40 p-3",children:[t.jsx("div",{className:"mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400",children:"Git context"}),t.jsx("div",{className:"text-xs text-slate-300",children:H??"No daemon-owned node status is attached to this graph node."}),t.jsxs("div",{className:"mt-3",children:[t.jsx("div",{className:"mb-1 text-[11px] font-semibold uppercase tracking-[0.16em] text-slate-400",children:"Recent commits"}),t.jsxs("div",{className:"flex flex-col gap-2",children:[(S==null?void 0:S.loading)&&t.jsx("div",{className:"text-xs text-slate-500",children:"Loading recent commits…"}),(S==null?void 0:S.error)&&t.jsxs("div",{className:"text-xs text-amber-200",children:["Recent history unavailable: ",S.error]}),!(S!=null&&S.loading)&&!(S!=null&&S.error)&&((S==null?void 0:S.entries)??[]).length===0&&t.jsx("div",{className:"text-xs text-slate-500",children:"Recent commit history not available for this detached graph node yet."}),((S==null?void 0:S.entries)??[]).slice(0,5).map(R=>t.jsxs("div",{className:"rounded-lg border border-white/5 bg-white/[0.03] px-3 py-2 text-xs text-slate-200",children:[t.jsxs("div",{className:"font-medium text-slate-100",children:[wr(R.commit)," · ",R.message]}),t.jsxs("div",{className:"mt-1 text-[11px] text-slate-500",children:[R.authorName||"unknown author",Ls(R.committedAt)?` · ${Ls(R.committedAt)}`:""]})]},R.commit))]})]})]})]}):t.jsx("div",{className:"text-xs text-slate-400",children:"Select a node, session, or queue item."})})}),t.jsxs(Ft,{title:"Queue",subtitle:"Active work plus recent history from mesh_status.",children:[t.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:["active","history","all"].map(R=>t.jsx("button",{type:"button",onClick:()=>h(R),className:`rounded-full border px-3 py-1 text-xs transition ${u===R?"border-sky-400/30 bg-sky-500/10 text-sky-100":"border-white/10 bg-white/[0.03] text-slate-300 hover:bg-white/[0.06]"}`,children:R},R))}),t.jsxs("div",{className:"mb-3 grid grid-cols-2 gap-2 text-xs sm:grid-cols-4 xl:grid-cols-2",children:[t.jsxs("div",{className:"rounded-xl border border-white/5 bg-white/[0.03] px-3 py-2 text-slate-300",children:["Active ",t.jsx("span",{className:"ml-1 text-white",children:(y==null?void 0:y.active)??0})]}),t.jsxs("div",{className:"rounded-xl border border-white/5 bg-white/[0.03] px-3 py-2 text-slate-300",children:["Pending ",t.jsx("span",{className:"ml-1 text-white",children:(y==null?void 0:y.activeCounts.pending)??0})]}),t.jsxs("div",{className:"rounded-xl border border-white/5 bg-white/[0.03] px-3 py-2 text-slate-300",children:["Assigned ",t.jsx("span",{className:"ml-1 text-white",children:(y==null?void 0:y.activeCounts.assigned)??0})]}),t.jsxs("div",{className:"rounded-xl border border-white/5 bg-white/[0.03] px-3 py-2 text-slate-300",children:["History ",t.jsx("span",{className:"ml-1 text-white",children:(y==null?void 0:y.historical)??0})]})]}),t.jsx("div",{className:"max-h-[24vh] overflow-y-auto pr-1",children:N.length===0?t.jsx("div",{className:"text-xs text-slate-400",children:"No queue items for this filter."}):t.jsx("div",{className:"flex flex-col gap-2",children:N.map(R=>{const re=Ra(R),Q=re?x.find(ce=>ce.session.sessionId===re)??null:null,ue=sn(R);return t.jsxs("button",{type:"button",onClick:()=>m({kind:"queue",taskId:R.id}),className:`rounded-xl border px-3 py-2 text-left transition ${(d==null?void 0:d.kind)==="queue"&&d.taskId===R.id?"border-sky-400/30 bg-sky-500/10":"border-white/10 bg-white/[0.03] hover:bg-white/[0.06]"}`,children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"truncate text-xs font-medium text-white",children:R.message}),t.jsx("div",{className:"mt-1 truncate text-[11px] text-slate-400",children:La(R)})]}),t.jsx(Ve,{label:R.status,tone:Ta(R.status)})]}),(ue||Q||re)&&t.jsxs("div",{className:"mt-2 flex flex-wrap gap-2",children:[ue&&t.jsx("button",{type:"button",onClick:ce=>{ce.stopPropagation(),I(ue)},className:"text-[11px] text-slate-300 underline underline-offset-2 transition hover:text-white",children:"View node"}),Q&&t.jsx("button",{type:"button",onClick:ce=>{ce.stopPropagation(),D(Q.nodeId,Q.session.sessionId)},className:"text-[11px] text-slate-300 underline underline-offset-2 transition hover:text-white",children:"View session"}),re&&t.jsx("button",{type:"button",onClick:ce=>{ce.stopPropagation(),W(re)},className:"text-[11px] text-sky-200 underline underline-offset-2 transition hover:text-white",children:"Open chat"})]})]},R.id)})})})]}),t.jsx(Ft,{title:"Sessions",subtitle:"Node-level active session roster.",children:t.jsx("div",{className:"max-h-[22vh] overflow-y-auto pr-1",children:x.length===0?t.jsx("div",{className:"text-xs text-slate-400",children:"No active session metadata in this mesh snapshot."}):t.jsx("div",{className:"flex flex-col gap-2",children:x.map(R=>{const re=R.session.state||R.session.lifecycle||"unknown";return t.jsx("button",{type:"button",onClick:()=>{c(R.nodeId),m({kind:"session",nodeId:R.nodeId,sessionId:R.session.sessionId})},className:`rounded-xl border px-3 py-2 text-left transition ${(d==null?void 0:d.kind)==="session"&&d.nodeId===R.nodeId&&d.sessionId===R.session.sessionId?"border-sky-400/30 bg-sky-500/10":"border-white/10 bg-white/[0.03] hover:bg-white/[0.06]"}`,children:t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"truncate text-xs font-medium text-white",children:R.machineLabel}),t.jsxs("div",{className:"mt-1 truncate text-[11px] text-slate-400",children:[R.session.title||R.session.providerType||"unknown provider"," · ",R.branch||"no branch"]})]}),t.jsxs("div",{className:"flex flex-col items-end gap-1",children:[t.jsx(Ve,{label:re,tone:tn(re)}),t.jsx("button",{type:"button",onClick:Q=>{Q.stopPropagation(),W(R.session.sessionId)},className:"text-[11px] text-sky-200 underline underline-offset-2 transition hover:text-white",children:"Open chat"})]})]})},`${R.nodeId}:${R.session.sessionId}`)})})})}),t.jsx(Ft,{title:"Nodes",subtitle:"Health, branch, drift, and provider view per node.",children:t.jsx("div",{className:"max-h-[22vh] overflow-y-auto pr-1",children:t.jsx("div",{className:"flex flex-col gap-2",children:s.nodes.map(R=>t.jsx("button",{type:"button",onClick:()=>{c(R.nodeId),m({kind:"node",nodeId:R.nodeId})},className:`rounded-xl border px-3 py-2 text-left transition ${(d==null?void 0:d.kind)==="node"&&d.nodeId===R.nodeId?"border-sky-400/30 bg-sky-500/10":"border-white/10 bg-white/[0.03] hover:bg-white/[0.06]"}`,children:t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("div",{className:"truncate text-xs font-medium text-white",children:R.machineLabel}),t.jsx("div",{className:"mt-1 truncate text-[11px] text-slate-400",children:Pl(R)}),t.jsx("div",{className:"mt-1 truncate text-[11px] text-slate-500",children:(R.providers??[]).join(", ")||"no provider metadata"}),t.jsxs("div",{className:"mt-1 flex flex-wrap gap-1",children:[t.jsx(Ve,{label:`launchReady ${Ma(R.launchReady)}`,tone:R.launchReady?"good":"warn"}),t.jsx(Ve,{label:Aa(R.connection),tone:Rl(R.connection)})]})]}),t.jsxs("div",{className:"flex flex-col items-end gap-1",children:[t.jsx(Ve,{label:R.health,tone:Ll(R.health)}),R.machineStatus&&t.jsx(Ve,{label:R.machineStatus,tone:R.machineStatus==="online"?"good":"warn"}),R.activeSessions.length>0&&t.jsx(Ve,{label:`${R.activeSessions.length} sessions`,tone:"info"})]})]})},R.nodeId))})})}),t.jsx(Ft,{title:"Recent mesh events",subtitle:"Read-only ledger tail from mesh_status.",children:t.jsx("div",{className:"max-h-[18vh] overflow-y-auto pr-1",children:(((xe=s.ledger)==null?void 0:xe.entries)??[]).length===0?t.jsx("div",{className:"text-xs text-slate-400",children:"No recent ledger entries."}):t.jsx("div",{className:"flex flex-col gap-2",children:(((Se=s.ledger)==null?void 0:Se.entries)??[]).map(R=>t.jsxs("div",{className:"rounded-xl border border-white/10 bg-white/[0.03] px-3 py-2 text-xs text-slate-200",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("span",{className:"font-medium text-white",children:R.kind}),t.jsx("span",{className:"text-[11px] text-slate-500",children:ss(R.timestamp)??R.timestamp})]}),t.jsx("div",{className:"mt-1 truncate text-[11px] text-slate-400",children:R.nodeId||R.sessionId||R.providerType||"mesh-wide event"})]},R.id))})})})]})]})}function Hy(e){const s=(e==null?void 0:e.result)??e,r=[e==null?void 0:e.status,s==null?void 0:s.status,s,e];for(const n of r)if(n&&Array.isArray(n.nodes)&&typeof n.meshId=="string")return n;return null}function Uy({activeConv:e,sendDaemonCommand:s,onClose:r}){var N;const n=typeof((N=e.settings)==null?void 0:N.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null,a=e.daemonId??null,o=Pd(),[l,c]=i.useState(null),[d,m]=i.useState(null),[u,h]=i.useState(!1),[g,j]=i.useState(null),[f,p]=i.useState(null),b=i.useCallback(async()=>{if(!a||!n){j("This coordinator does not expose a live mesh id."),c(null),m(null);return}h(!0),j(null);try{const v=o!=null&&o.loadMeshStatus?await o.loadMeshStatus(a,n):await s(a,"mesh_status",{meshId:n}),C=Hy(v);if(!C){c(null),m(null),j("mesh_status returned an unexpected payload.");return}const M=lu(C);m(C),c(M),p(C.refreshedAt||new Date().toISOString())}catch(v){c(null),m(null),j(v instanceof Error?v.message:"Failed to load live mesh status")}finally{h(!1)}},[a,n,o,s]);i.useEffect(()=>{b()},[b]),i.useEffect(()=>{const v=C=>{C.key==="Escape"&&r()};return window.addEventListener("keydown",v),()=>window.removeEventListener("keydown",v)},[r]);const y=(l==null?void 0:l.meshName)||(d==null?void 0:d.meshName)||n||"Repo Mesh",x=f?new Date(f).toLocaleTimeString():null,A=i.useMemo(()=>u?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet.",[u]);return t.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center bg-[#030617]/[0.58] p-0 md:p-4 backdrop-blur-md",onClick:r,children:t.jsxs("div",{role:"dialog","aria-modal":"true",className:"flex h-[100dvh] w-full flex-col overflow-hidden bg-slate-950 md:h-[min(90vh,960px)] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-white/10 md:bg-slate-950/96 md:shadow-[0_28px_120px_rgba(2,6,23,0.46)]",onClick:v=>v.stopPropagation(),children:[t.jsxs("div",{className:"flex shrink-0 flex-col gap-3 border-b border-white/10 bg-slate-950/92 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",children:[t.jsx("div",{className:"min-w-0 flex-1",children:t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-sky-400/20 bg-sky-500/12 text-sky-200 shadow-[0_12px_30px_rgba(14,165,233,0.18)]",children:t.jsx(ns,{size:18})}),t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[t.jsx("h2",{className:"truncate text-lg font-semibold text-white md:text-xl",children:y}),t.jsx("span",{className:"rounded-full border border-white/10 bg-white/6 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-300",children:"Mesh observability"})]}),t.jsxs("p",{className:"mt-1 truncate text-sm text-slate-400",children:[dt(e),e.workspaceName?` · ${e.workspaceName}`:"",l!=null&&l.repoIdentity?` · ${l.repoIdentity}`:""]})]})]})}),t.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:justify-end",children:[x&&t.jsxs("span",{className:"rounded-full border border-white/10 bg-white/6 px-3 py-1.5 text-xs text-slate-300",children:["Refreshed ",x]}),t.jsx("button",{type:"button",onClick:b,disabled:u,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:u?"Refreshing…":"Refresh"}),t.jsx("button",{type:"button",onClick:r,className:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-white/10 bg-white/6 text-slate-300 transition hover:bg-white/10 hover:text-white","aria-label":"Close mesh graph",children:t.jsx(vt,{size:16})})]})]}),g&&t.jsx("div",{className:"shrink-0 border-b border-rose-400/20 bg-rose-500/12 px-4 py-2 text-sm text-rose-200 md:px-5",children:g}),t.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto bg-[linear-gradient(180deg,rgba(2,6,23,0.95),rgba(15,23,42,0.98))] px-4 py-4 md:px-5 md:py-5",children:l&&d?t.jsx(Wy,{graph:l,status:d,emptyMessage:A,daemonId:a,sendDaemonCommand:s}):t.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-white/10 bg-white/[0.03] px-6 text-center text-sm text-slate-400",children:A})})]})})}function zy(e,s){const{sendCommand:r}=wt(),[n,a]=i.useState(null),[o,l]=i.useState(!1);i.useEffect(()=>{if(!e||!s){a(null);return}l(!0),r(e,"git_remote_url",{workspace:s}).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(()=>l(!1))},[e,s,r]);const c=Vy(n);return{remoteUrl:n,githubUrl:c,loading:o}}function Vy(e){if(!e)return null;const s=e.match(/git@github\.com[:/](.+?)(?:\.git)?$/);if(s)return`https://github.com/${s[1]}`;const r=e.match(/https?:\/\/github\.com\/(.+?)(?:\.git)?$/);return r?`https://github.com/${r[1]}`:null}const mu=5e3;function Gy(e){return`git:${e}`}function qy({workspace:e,includeDiffSummary:s=!1,intervalMs:r=mu}){return{type:"subscribe",topic:"workspace.git",key:Gy(e),params:{workspace:e,includeDiffSummary:s,intervalMs:r}}}function ai(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Ts(e,s){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 s}function Yy(e){const s=ai(e);return(s==null?void 0:s.success)===!1?{status:null,error:Ts(s,"Git status request failed")}:s!=null&&s.status?{status:s.status,error:null}:{status:null,error:Ts(s,"Git status response did not include status")}}function Xy(e){const s=ai(e);return(s==null?void 0:s.success)===!1?{diffSummary:null,error:Ts(s,"Git diff summary request failed")}:s!=null&&s.diffSummary?{diffSummary:s.diffSummary,error:null}:{diffSummary:null,error:Ts(s,"Git diff summary response did not include diffSummary")}}function Pa(e){return e===void 0||typeof e=="boolean"}function Jy(e){if(!e||typeof e!="object")return!1;const s=e;return typeof s.path=="string"&&typeof s.diff=="string"&&Pa(s.binary)&&Pa(s.truncated)&&Pa(s.staged)}function Qy(e){const s=ai(e);return(s==null?void 0:s.success)===!1?{diff:null,error:Ts(s,"Git file diff request failed")}:Jy(s==null?void 0:s.diff)?{diff:s.diff,error:null}:{diff:null,error:Ts(s,"Git file diff response did not include a valid diff object")}}function Zy({daemonId:e,workspace:s,enabled:r=!0,includeDiffSummary:n=!1,intervalMs:a=mu}){const{sendCommand:o,sendData:l}=wt(),c=typeof s=="string"?s.trim():"",d=!!(r&&e&&c),[m,u]=i.useState(null),[h,g]=i.useState(null),[j,f]=i.useState(!1),[p,b]=i.useState(null),y=i.useCallback(async()=>{if(!(!d||!e||!c)){f(!0),b(null);try{const A=Yy(await o(e,"git_status",{workspace:c}));if(A.error){u(null),g(null),b(A.error);return}if(u(A.status),!n){g(null);return}const N=Xy(await o(e,"git_diff_summary",{workspace:c}));if(N.error){g(null),b(N.error);return}g(N.diffSummary)}catch(A){b(Ts(A,"Git status request failed"))}finally{f(!1)}}},[d,e,n,o,c]),x=i.useMemo(()=>c?qy({workspace:c,includeDiffSummary:n,intervalMs:a}):null,[n,a,c]);return i.useEffect(()=>{if(!d||!e||!c||!x){u(null),g(null),f(!1),b(null);return}const A=l?Xt.subscribe({sendData:l},e,x,N=>{var v,C;N.workspace===c&&(u(N.status),g(N.diffSummary??null),b(((v=N.status)==null?void 0:v.error)||((C=N.diffSummary)==null?void 0:C.error)||null),f(!1))},{retryIntervalMs:1e3}):null;return y(),()=>{A==null||A()}},[d,e,y,x,l,c]),{status:m,diffSummary:h,loading:j,error:p,refresh:y}}const e0={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},t0={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 Dl(e){return e.split("/").pop()??e}function s0(e){const s=e.lastIndexOf("/");return s>0?e.slice(0,s):""}function r0({files:e,truncated:s,onFileClick:r,selectedPath:n,className:a=""}){return e.length===0?t.jsx("p",{className:"px-3 py-2 text-xs text-text-secondary",children:"No changed files."}):t.jsxs("div",{className:`flex flex-col ${a}`,children:[t.jsx("ul",{className:"min-w-0 divide-y divide-border/30",children:e.map(o=>{const l=n===o.path,c=e0[o.status]??"?",d=t0[o.status]??"text-zinc-400",m=s0(o.path),u=Dl(o.path),h=o.staged?t.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-emerald-500 align-middle",title:"Staged"}):null;return t.jsxs("li",{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs hover:bg-surface-elevated/60 ${l?"bg-surface-elevated":""}`,onClick:()=>r==null?void 0:r(o),children:[t.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${d}`,title:o.status,children:c}),t.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[m&&t.jsxs("span",{className:"text-text-secondary",children:[m,"/"]}),t.jsx("span",{className:"text-text-primary",children:u}),o.oldPath&&t.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",Dl(o.oldPath)]}),h]}),!o.binary&&(o.insertions>0||o.deletions>0)&&t.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[o.insertions>0&&t.jsxs("span",{className:"text-emerald-500",children:["+",o.insertions]}),o.insertions>0&&o.deletions>0&&t.jsx("span",{className:"text-text-secondary",children:" "}),o.deletions>0&&t.jsxs("span",{className:"text-red-400",children:["-",o.deletions]})]}),o.binary&&t.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${o.path}-${o.staged?"S":"U"}`)})}),s&&t.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary",children:["File list truncated — run ",t.jsx("code",{className:"font-mono",children:"git status"})," locally for full output."]})]})}function n0(e,s){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"),t.jsx("div",{className:`px-3 ${r}`,children:t.jsx("code",{className:"whitespace-pre font-mono text-[11px] leading-5",children:e})},s)}function a0({diff:e,binary:s,truncated:r,loading:n,error:a,className:o=""}){const l=i.useRef(null);if(i.useEffect(()=>{l.current&&(l.current.scrollTop=0)},[e]),n)return t.jsx("div",{className:`flex items-center justify-center py-8 text-xs text-text-secondary ${o}`,children:"Loading diff…"});if(a)return t.jsx("div",{className:`px-3 py-4 text-xs text-red-400 ${o}`,children:a});if(s)return t.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"Binary file — diff not available."});if(!e)return t.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"No diff available."});const c=e.split(`
|
|
65
|
-
`);return t.jsxs("div",{ref:l,className:`overflow-auto ${o}`,children:[t.jsx("div",{className:"py-1",children:c.map((d,m)=>n0(d,m))}),r&&t.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary border-t border-border/30",children:["Diff truncated — run ",t.jsx("code",{className:"font-mono",children:"git diff"})," locally for full output."]})]})}function o0(e,s){const r=[`Branch: ${e||"unknown"}`];r.push(`Changed: ${s.files.length} file(s) +${s.totalInsertions}/-${s.totalDeletions}`);const n={};for(const a of s.files)n[a.status]||(n[a.status]=[]),n[a.status].push(a.path);for(const[a,o]of Object.entries(n))r.push(`${a}: ${o.slice(0,5).join(", ")}${o.length>5?` (+${o.length-5} more)`:""}`);return r.join(`
|
|
66
|
-
`)}function pu({daemonId:e,workspace:s,onClose:r}){const{sendCommand:n}=wt(),{status:a,diffSummary:o,loading:l,error:c,refresh:d}=Zy({daemonId:e,workspace:s,includeDiffSummary:!0}),[m,u]=i.useState(null),[h,g]=i.useState(null),[j,f]=i.useState(""),[p,b]=i.useState(!1),[y,x]=i.useState(!1),[A,N]=i.useState(null),[v,C]=i.useState(null),{githubUrl:M}=zy(e,s),w=i.useCallback(async W=>{if(!((m==null?void 0:m.path)===W.path&&!m.loading)){u({path:W.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const D=await n(e,"git_diff_file",{workspace:s,path:W.path,staged:W.staged}),I=Qy(D);if(I.error||!I.diff){u({path:W.path,diff:"",binary:!1,truncated:!1,loading:!1,error:I.error??"Failed to load diff"});return}u({path:W.path,diff:I.diff.diff,binary:I.diff.binary??!1,truncated:I.diff.truncated??!1,loading:!1,error:null})}catch(D){const I=D instanceof Error?D.message:"Failed to load diff";u({path:W.path,diff:"",binary:!1,truncated:!1,loading:!1,error:I})}}},[e,n,m,s]),k=i.useCallback(W=>{f(""),b(!1),N(null),C(null),g(W)},[]),F=i.useCallback(()=>{g(null),N(null),x(!1)},[]),_=i.useCallback(async()=>{var W,D,I;if(h){x(!0),N(null);try{let T;h==="checkpoint"?T=await n(e,"git_checkpoint",{workspace:s,message:j,includeUntracked:p}):h==="stash"?T=await n(e,"git_stash_push",{workspace:s,message:j,includeUntracked:p}):h==="stash_pop"?T=await n(e,"git_stash_pop",{workspace:s}):h==="checkout_files"&&m&&(T=await n(e,"git_checkout_files",{workspace:s,paths:[m.path]}));const K=(T==null?void 0:T.result)??T;if((K==null?void 0:K.success)===!1||K!=null&&K.error){N((K==null?void 0:K.error)??"Action failed"),x(!1);return}h==="checkpoint"?C(`Checkpoint created: ${((D=(W=K==null?void 0:K.checkpoint)==null?void 0:W.commit)==null?void 0:D.slice(0,7))??"done"}`):h==="stash"?C(`Stashed as ${((I=K==null?void 0:K.stash)==null?void 0:I.stashRef)??"stash@{0}"}`):h==="stash_pop"?C("Stash restored"):(C("File reverted"),u(null)),g(null),await d()}catch(T){N(T instanceof Error?T.message:"Action failed")}finally{x(!1)}}},[h,n,e,s,j,p,m,d]),S=!!(a!=null&&a.hasConflicts),H=a?a.staged+a.modified+a.untracked+a.deleted+a.renamed:null;return t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:W=>{W.target===W.currentTarget&&r()},children:t.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:[t.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[t.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(a==null?void 0:a.branch)??"Git Status"}),t.jsx("p",{className:"truncate text-xs text-text-secondary",children:s}),M&&t.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 ↗"})]}),t.jsx("button",{onClick:d,disabled:l,className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40",title:"Refresh",children:"↺"}),t.jsx("button",{onClick:r,className:"rounded p-1 text-text-secondary hover:text-text-primary","aria-label":"Close",children:t.jsx(vt,{className:"h-4 w-4"})})]}),a&&t.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&&t.jsxs("span",{title:a.headMessage??void 0,children:[t.jsx("span",{className:"font-mono",children:a.headCommit.slice(0,7)}),a.headMessage&&t.jsx("span",{className:"ml-1 truncate",children:a.headMessage.slice(0,60)})]}),a.ahead>0&&t.jsxs("span",{className:"text-orange-400",children:["↑",a.ahead," ahead"]}),a.behind>0&&t.jsxs("span",{className:"text-orange-400",children:["↓",a.behind," behind"]}),a.staged>0&&t.jsxs("span",{className:"text-emerald-400",children:[a.staged," staged"]}),a.modified>0&&t.jsxs("span",{children:[a.modified," modified"]}),a.untracked>0&&t.jsxs("span",{children:[a.untracked," untracked"]}),a.deleted>0&&t.jsxs("span",{className:"text-red-400",children:[a.deleted," deleted"]}),a.stashCount>0&&t.jsxs("span",{children:[a.stashCount," stashed"]}),a.hasConflicts&&t.jsx("span",{className:"font-bold text-red-400",children:"conflicts"}),H===0&&!a.error&&t.jsx("span",{className:"text-emerald-500",children:"clean"}),o&&o.files.length>0&&t.jsxs("span",{className:"text-text-secondary",children:[o.files.length," file",o.files.length!==1?"s":"",o.totalInsertions>0&&t.jsxs("span",{className:"text-emerald-500",children:[" +",o.totalInsertions]}),o.totalDeletions>0&&t.jsxs("span",{className:"text-red-400",children:[" -",o.totalDeletions]})]})]}),c&&t.jsx("div",{className:"shrink-0 border-b border-border/50 bg-red-500/10 px-4 py-2 text-xs text-red-400",children:c}),t.jsxs("div",{className:"flex min-h-0 flex-1",children:[t.jsxs("div",{className:"flex w-56 shrink-0 flex-col overflow-y-auto border-r border-border/50",children:[l&&!o&&t.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),o&&t.jsx(r0,{files:o.files,truncated:o.truncated,selectedPath:(m==null?void 0:m.path)??null,onFileClick:w}),!l&&!o&&!c&&t.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"No diff data."})]}),t.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:m?t.jsx(a0,{diff:m.diff,binary:m.binary,truncated:m.truncated,loading:m.loading,error:m.error,className:"h-full"}):t.jsx("div",{className:"flex h-full items-center justify-center text-xs text-text-secondary",children:"Select a file to view diff"})})]}),v&&t.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:[t.jsx("span",{children:v}),t.jsx("button",{onClick:()=>C(null),className:"ml-2 text-emerald-400 hover:text-text-primary",children:"×"})]}),t.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-t border-border px-4 py-2",children:[t.jsx("button",{onClick:()=>k("checkpoint"),disabled:S,title:S?"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"}),t.jsx("button",{onClick:()=>k("stash"),disabled:S,title:S?"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"}),t.jsx("button",{onClick:()=>k("stash_pop"),disabled:S||!(a!=null&&a.stashCount),title:S?"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"}),t.jsx("button",{onClick:()=>k("checkout_files"),disabled:!m,title:m?`Revert changes to ${m.path}`:"Select a file to revert",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkout selected"}),o&&o.files.length>0&&t.jsx("button",{onClick:()=>{const W=o0((a==null?void 0:a.branch)??null,o);navigator.clipboard.writeText(W),C("Copied to clipboard"),setTimeout(()=>C(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),h&&t.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:t.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[t.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[h==="checkpoint"&&"Create checkpoint commit",h==="stash"&&"Stash changes",h==="stash_pop"&&"Restore latest stash?",h==="checkout_files"&&`Revert changes to ${(m==null?void 0:m.path)??"file"}?`]}),(h==="checkpoint"||h==="stash")&&t.jsxs(t.Fragment,{children:[t.jsx("input",{type:"text",value:j,onChange:W=>f(W.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}),t.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[t.jsx("input",{type:"checkbox",checked:p,onChange:W=>b(W.target.checked)}),"Include untracked files"]})]}),A&&t.jsx("p",{className:"text-xs text-red-400",children:A}),t.jsxs("div",{className:"flex justify-end gap-2",children:[t.jsx("button",{onClick:F,disabled:y,className:"rounded px-3 py-1 text-xs text-text-secondary hover:text-text-primary border border-border/50 disabled:opacity-40",children:"Cancel"}),t.jsx("button",{onClick:_,disabled:y||(h==="checkpoint"||h==="stash")&&!j.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:y?"Working…":"Confirm"})]})]})})]})})}function i0({isMobile:e,showMobileChatMode:s,visibleConversationCount:r}){const[n,a]=i.useState(!1),[o,l]=i.useState(!1),[c,d]=i.useState(!1),[m,u]=i.useState(!1),[h,g]=i.useState(!1),[j,f]=i.useState("quickstart"),[p,b]=i.useState("workspace"),y=i.useMemo(()=>!s&&!e,[s,e]),x=i.useCallback(w=>{a(w),w&&l(!1)},[]),A=i.useCallback(w=>{l(w),w&&a(!1)},[]),N=i.useCallback(()=>{f(r===0?"quickstart":"shortcuts"),b("workspace"),d(!0),a(!1),l(!1)},[r]),v=i.useCallback(()=>{d(!1)},[]),C=i.useCallback(()=>{u(!0)},[]),M=i.useCallback(()=>{u(!1)},[]);return i.useEffect(()=>{if(!y){g(!1);return}g(!0);const w=window.setTimeout(()=>{g(!1)},1e4);return()=>window.clearTimeout(w)},[y]),{inboxOpen:n,hiddenOpen:o,shortcutHelpOpen:c,newSessionOpen:m,guideNudgeVisible:h,guideTab:j,shortcutSection:p,isDesktopDashboard:y,setGuideTab:f,setShortcutSection:b,handleInboxOpenChange:x,handleHiddenOpenChange:A,handleOpenShortcutHelp:N,closeShortcutHelp:v,openNewSession:C,closeNewSession:M}}function l0(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 c0(e){return e instanceof Error?e.message:String(e||"")}function d0(e){const s=c0(e).toLowerCase();return s.includes("button not found")||s.includes("not in approval state")||s.includes("command failed")}function u0({showMobileChatMode:e,isMobile:s,activeConv:r,wsStatus:n,isConnected:a,onOpenHistory:o,onOpenRemote:l,onStopCli:c,activeCliViewMode:d,onSetActiveCliViewMode:m,mobileChatConversations:u,hiddenConversations:h,ides:g,actionLogs:j,sendDaemonCommand:f,setActionLogs:p,setCliViewModeOverrides:b,isStandalone:y,initialDataLoaded:x,userName:A,requestedMobileTabKey:N,onRequestedMobileTabConsumed:v,requestedMachineId:C,onRequestedMachineConsumed:M,requestedMobileSection:w,onRequestedMobileSectionConsumed:k,containerRef:F,isSplitMode:_,numGroups:S,groupSizes:H,groupedConvs:W,clearedTabs:D,focusedGroup:I,focusGroup:T,moveTabToGroup:K,splitTabRelative:P,closeGroup:$,handleResizeStart:V,groupActiveTabIds:Y,setGroupActiveTab:ge,groupTabOrders:fe,setGroupTabOrder:ae,toggleHiddenTab:me,visibleConversations:je,requestedDesktopTabKey:Ne,onRequestedDesktopTabConsumed:G,onDesktopActiveTabChange:he,onRequestScrollToBottom:pe,onHideConversation:ye,onShowHiddenConversation:xe,onShowAllHiddenConversations:Se,scrollToBottomRequest:R,machineEntries:re,layoutProfile:Q,onBrowseMachineDirectory:ue,onSaveMachineWorkspace:ce,onLaunchMachineIde:de,onLaunchMachineProvider:te,onListMachineMeshes:E,onLaunchMeshCoordinator:X,onListMachineSavedSessions:oe,notifications:ee,notificationUnreadCount:ke,liveSessionInboxState:Ce,onMarkNotificationRead:ve,onMarkNotificationUnread:O,onDeleteNotification:Ie}){const Re=kt.useRef(null),{inboxOpen:Ke,hiddenOpen:He,shortcutHelpOpen:Ye,newSessionOpen:Xe,guideNudgeVisible:st,guideTab:mt,shortcutSection:ht,isDesktopDashboard:yt,setGuideTab:Te,setShortcutSection:Ue,handleInboxOpenChange:et,handleHiddenOpenChange:ze,handleOpenShortcutHelp:at,closeShortcutHelp:U,openNewSession:z,closeNewSession:Z}=i0({isMobile:s,showMobileChatMode:e,visibleConversationCount:je.length}),[ie,B]=kt.useState(null),[q,ne]=kt.useState(null),le=kt.useCallback((L,J)=>{B({daemonId:L,workspace:J})},[]),we=kt.useCallback(L=>{ne(L)},[]),_e=kt.useCallback(L=>{var J;kr.flushSync(()=>{xe(L)}),(J=Re.current)==null||J.restoreHiddenTabToSavedLocation(L.tabKey)},[xe]),De=kt.useCallback(L=>{var be;const J=u.find($e=>ro($e,L))||h.find($e=>ro($e,L));J&&(h.some($e=>$e.tabKey===J.tabKey)&&_e(J),he(J.tabKey),(be=Re.current)==null||be.activateConversationTab(J.tabKey),pe(J.tabKey,"notification-open")),ve(L.id),et(!1)},[_e,h,u,he,ve,pe]),Me=kt.useCallback(()=>{var J;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((J=Re.current)==null||J.resetAllPanelsToMain(),ze(!1))},[ze]),Ee=kt.useCallback(async L=>{var Be;if(!r)return;const J=(Be=r.modalButtons)==null?void 0:Be[L];if(!J)return;const be=zs(r);if(!be)return;const $e=J.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Le=/^(run|approve|accept|yes|allow|always|proceed|save)/.test($e);try{await f(be,"resolve_action",{button:J,action:Le?"approve":"reject",buttonIndex:L,...hs(r)})}catch(rt){d0(rt)||console.error("[Shortcut approval] Failed:",rt)}},[r,f]),{isMac:Oe,actionDefinitions:Ae,actionShortcuts:Je,shortcutListening:Ze,shortcutListeningDraft:xt,setShortcutListening:bt,setShortcutListeningDraft:ct,saveShortcuts:pt}=ny({enabled:yt&&!Ye,onTrigger:L=>{var J,be,$e,Le,Be,rt,It,ft,Zt,Pr,Dr,Er,$r,Br,Or,Fr;if(L==="openShortcutHelp"){at();return}if(L==="openNewSession"){z();return}if(L==="hideCurrentTab"){r&&ye(r);return}if(L==="toggleHiddenTabs"){ze(!He);return}if(L==="openHistoryForActiveTab"){r&&!tt(r)&&o(r);return}if(L==="openRemoteForActiveTab"){r&&!nt(r)&&!tt(r)&&l(r);return}if(L==="splitActiveTabRight"){(J=Re.current)==null||J.splitActiveTabRight();return}if(L==="splitActiveTabDown"){(be=Re.current)==null||be.splitActiveTabDown();return}if(L==="floatActiveTab"){($e=Re.current)==null||$e.floatActiveTab();return}if(L==="popoutActiveTab"){(Le=Re.current)==null||Le.popoutActiveTab();return}if(L==="dockActiveTab"){(Be=Re.current)==null||Be.dockActiveTab();return}if(L==="focusLeftPane"){(rt=Re.current)==null||rt.focusLeftPane();return}if(L==="focusRightPane"){(It=Re.current)==null||It.focusRightPane();return}if(L==="focusUpPane"){(ft=Re.current)==null||ft.focusUpPane();return}if(L==="focusDownPane"){(Zt=Re.current)==null||Zt.focusDownPane();return}if(L==="moveActiveTabToLeftPane"){(Pr=Re.current)==null||Pr.moveActiveTabToLeftPane();return}if(L==="moveActiveTabToRightPane"){(Dr=Re.current)==null||Dr.moveActiveTabToRightPane();return}if(L==="moveActiveTabToUpPane"){(Er=Re.current)==null||Er.moveActiveTabToUpPane();return}if(L==="moveActiveTabToDownPane"){($r=Re.current)==null||$r.moveActiveTabToDownPane();return}if(L==="triggerPrimaryApprovalAction"){Ee(0);return}if(L==="triggerSecondaryApprovalAction"){Ee(1);return}if(L==="triggerTertiaryApprovalAction"){Ee(2);return}if(L==="setActiveTabShortcut"){(Br=Re.current)==null||Br.setShortcutForActiveTab();return}if(L==="selectPreviousGroupTab"){(Or=Re.current)==null||Or.activatePreviousTabInGroup();return}if(L==="selectNextGroupTab"){(Fr=Re.current)==null||Fr.activateNextTabInGroup();return}!r||!nt(r)||tt(r)||L==="toggleCliView"&&m(d==="chat"?"terminal":"chat")}}),We=kt.useCallback(()=>{U(),bt(null),ct([])},[U,bt,ct]),Ot=kt.useMemo(()=>ht==="all"?Ae:Ae.filter(L=>l0(L)===ht),[Ae,ht]),se=kt.useCallback(()=>{const L=Object.fromEntries(Ae.map(J=>[J.id,""]));pt(L)},[Ae,pt]),Pe=kt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const L=Object.fromEntries(Ae.map(J=>[J.id,J.defaultShortcut]));pt(L)},[Ae,pt]);return kt.useEffect(()=>{const L=J=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?J.metaKey&&J.key.toLowerCase()==="w":J.ctrlKey&&J.key.toLowerCase()==="w")&&(J.preventDefault(),r&&ye&&ye(r))};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[r,ye]),kt.useEffect(()=>{if(!Ye||Ze)return;const L=J=>{J.key==="Escape"&&(J.preventDefault(),We())};return window.addEventListener("keydown",L,!0),()=>window.removeEventListener("keydown",L,!0)},[We,Ye,Ze]),t.jsxs(t.Fragment,{children:[!e&&t.jsx(sx,{activeConv:r,wsStatus:n,isConnected:a,conversations:je,hiddenConversations:h,onOpenHistory:o,onHideConversation:ye,onShowConversation:_e,onShowAllHidden:Se,onResetPanelsToMain:Me,notifications:ee,notificationUnreadCount:ke,onOpenNotification:De,onMarkNotificationRead:ve,onMarkNotificationUnread:O,onDeleteNotification:Ie,inboxOpen:Ke,onInboxOpenChange:et,hiddenOpen:He,onHiddenOpenChange:ze,onOpenNewSession:s?void 0:z,onOpenDashboardGuide:at,guideNudgeVisible:st,actionShortcuts:Je,onOpenRemote:()=>{!r||nt(r)||tt(r)||l(r)},onStopCli:c,activeCliViewMode:d,onSetCliViewMode:m,onOpenGitDialog:le,onOpenMeshGraph:we}),e?t.jsx(Vg,{conversations:u,hiddenConversations:h,ides:g,actionLogs:j,sendDaemonCommand:f,setActionLogs:p,setCliViewModeOverrides:b,isStandalone:y,userName:A,requestedActiveTabKey:N,onRequestedActiveTabConsumed:v,requestedMachineId:C,onRequestedMachineConsumed:M,requestedMobileSection:w,onRequestedMobileSectionConsumed:k,onOpenHistory:o,onOpenRemote:l,onStopCli:c,wsStatus:n,isConnected:a,onShowAllHiddenConversations:Se,onHideConversation:ye,onOpenMeshGraph:we,onOpenNewSession:z,liveSessionInboxState:Ce}):s?t.jsx(ey,{containerRef:F,isSplitMode:_,numGroups:S,groupSizes:H,groupedConvs:W,clearedTabs:D,ides:g,actionLogs:j,sendDaemonCommand:f,setActionLogs:p,isStandalone:y,hasRegisteredMachines:re.length>0,userName:A,focusedGroup:I,focusGroup:T,moveTabToGroup:K,splitTabRelative:P,closeGroup:$,handleResizeStart:V,groupActiveTabIds:Y,setGroupActiveTab:ge,groupTabOrders:fe,setGroupTabOrder:ae,toggleHiddenTab:me,onOpenNewSession:z,allowTabShortcuts:!1,liveSessionInboxState:Ce}):t.jsx(gy,{visibleConversations:je,clearedTabs:D,ides:g,actionLogs:j,sendDaemonCommand:f,setActionLogs:p,isStandalone:y,hasRegisteredMachines:re.length>0,initialDataLoaded:x,userName:A,toggleHiddenTab:me,actionShortcuts:Je,registerActionHandlers:L=>{Re.current=L},onActiveTabChange:he,requestedActiveTabKey:Ne,onRequestedActiveTabConsumed:G,onRequestScrollToBottom:pe,scrollToBottomRequest:R,onOpenNewSession:z,liveSessionInboxState:Ce,layoutProfile:Q}),Xe&&t.jsx(ky,{machines:re,ides:g,onClose:Z,onBrowseDirectory:ue,onSaveWorkspace:ce,onLaunchIde:de,onLaunchProvider:te,onListMeshes:E,onLaunchMeshCoordinator:X,onListSavedSessions:oe}),q&&t.jsx(Uy,{activeConv:q,sendDaemonCommand:f,onClose:()=>ne(null)}),ie&&t.jsx(pu,{daemonId:ie.daemonId,workspace:ie.workspace,onClose:()=>B(null)}),Ye&&t.jsx("div",{className:"fixed inset-0 z-[60] flex items-center justify-center",style:{background:"rgba(0,0,0,0.5)",backdropFilter:"blur(2px)"},onClick:We,children:t.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:L=>L.stopPropagation(),children:[t.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),t.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."})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:We,"aria-label":"Close dashboard guide",children:t.jsx(vt,{size:14})})]}),t.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(L=>t.jsx("button",{type:"button",className:`btn btn-sm ${mt===L.id?"btn-primary":"btn-secondary"}`,onClick:()=>Te(L.id),children:L.label},L.id))}),mt==="overview"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",Oe?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),mt==="quickstart"&&t.jsxs("div",{className:"space-y-4",children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),t.jsxs("div",{children:[t.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."]})]})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),t.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.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."]}),t.jsxs("div",{children:[t.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"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[t.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(L=>t.jsx("button",{type:"button",className:`btn btn-sm ${ht===L.id?"btn-primary":"btn-secondary"}`,onClick:()=>Ue(L.id),children:L.label},L.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:se,children:"Disable all"}),t.jsx("button",{type:"button",className:"btn btn-sm",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, var(--border-subtle, transparent))",background:"color-mix(in srgb, var(--status-error, #ef4444) 8%, var(--bg-primary, transparent))"},onClick:Pe,children:"Reset to defaults"})]})]}),t.jsx("div",{className:"space-y-2",children:Ot.map(L=>t.jsx("div",{className:`rounded-xl border px-4 py-3 ${Ze===L.id?"border-accent bg-bg-secondary/70":"border-border-subtle bg-bg-secondary/30"}`,children:t.jsxs("div",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:L.label}),t.jsx("div",{className:"text-xs text-text-secondary mt-1",children:L.description}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",t.jsx("span",{className:"font-mono",children:L.defaultShortcut})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[t.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:Ze===L.id?xt.length>0?`${xt.join(" ")} ...`:"Listening...":Je[L.id]||"Off"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{bt(L.id),ct([])},children:Ze===L.id?"Listening":"Set"}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const J={...Je};J[L.id]="",pt(J)},children:"Disable"})]})]})},L.id))}),t.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",Oe?"⌘⇧Enter, ⌘⇧→, ⌘Ctrl⇧↓":"Ctrl+Shift+Enter, Ctrl+Shift+→, Ctrl+Alt+Shift+↓",", or set your own combo. Dashboard action shortcuts are ignored while typing in text inputs."]})]})]})})]})}const Da=[{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 m0({onClose:e}){const[s,r]=i.useState(0),n=Da[s],a=s===Da.length-1;return t.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:9999,background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:o=>{o.stopPropagation()},children:[t.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:[t.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:t.jsx(vt,{size:20})}),t.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:Da.map((o,l)=>t.jsx("div",{style:{width:l===s?24:8,height:8,borderRadius:4,background:l===s?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},l))}),t.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:n.visual||n.icon}),t.jsxs("div",{style:{textAlign:"center"},children:[t.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[t.jsx("span",{children:n.icon})," ",n.title]}),t.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:n.desc}),n.code&&t.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:[t.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),n.code]}),a&&t.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 →"})]}),t.jsx("div",{className:"flex justify-end items-center mt-6",children:t.jsx("button",{onClick:()=>a?e():r(o=>o+1),className:"btn btn-primary",children:a?"Get Started →":"Next →"})})]}),t.jsx("style",{children:`
|
|
67
|
-
@keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
|
|
68
|
-
@keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
|
|
69
|
-
`})]})}function p0({hasExtensions:e,ideName:s,activeChatTab:r,extensionTabs:n,onSelectTab:a}){return e?t.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[t.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:s}),n.map(o=>{const l=r===o.tabKey,c=o.status==="waiting_approval",d=o.status==="generating";return t.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 ${l?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a(o.tabKey),children:[t.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:c?"var(--status-warning)":d?"var(--accent-primary)":"var(--text-muted)",boxShadow:d?"0 0 6px var(--accent-primary)":"none"}}),o.title,c&&t.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-[10px] font-bold ml-0.5",style:{background:"color-mix(in srgb, var(--status-warning) 13%, transparent)",color:"var(--status-warning)"},children:"!"})]},o.tabKey)})]}):null}function f0({ideData:e,allIdes:s,connectionStates:r,ideName:n,preferredTabKey:a}){const[o,l]=i.useState(()=>a||"native"),c=i.useMemo(()=>nd(s),[s]),d=i.useMemo(()=>e?Go(e,{machineNames:c,connectionStates:r,defaultConnectionState:"new"}):[],[e,c,r]),m=i.useMemo(()=>d.find(p=>p.streamSource==="native"),[d]),u=i.useMemo(()=>d.filter(p=>p.streamSource==="agent-stream"),[d]),h=i.useMemo(()=>e?Bt(d,e.id):null,[d,e]);i.useEffect(()=>{a&&l(a)},[a]),i.useEffect(()=>{if(a||!h)return;const p=h.streamSource==="native"?"native":h.tabKey;!p||o===p||o==="native"&&l(p)},[o,h,a]),i.useEffect(()=>{var p;o!=="native"&&(u.some(b=>b.tabKey===o)||l(((p=u[0])==null?void 0:p.tabKey)||"native"))},[o,u]),i.useEffect(()=>{o==="native"&&(m||u[0]&&l(u[0].tabKey))},[o,m,u]);const g=i.useMemo(()=>o==="native"&&m?m:u.find(p=>p.tabKey===o)||h||m||u[0],[o,m,h,u]),j=i.useMemo(()=>u.map(p=>({tabKey:p.tabKey,title:Jc(p)||n,status:p.status})),[u,n]),f=i.useCallback(p=>{if(p)return d.find(b=>ro(b,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[d]);return{activeChatTab:o,setActiveChatTab:l,activeConv:g,conversations:d,extensionTabs:j,hasExtensions:j.length>0,resolveConversationByTarget:f}}function h0({activeConv:e,ideEntry:s,ides:r,connectionStates:n,actionLogs:a,sendDaemonCommand:o,setActionLogs:l,isStandalone:c,userName:d,onOpenHistory:m,onConversationChange:u,onClose:h}){const[g,j]=i.useState("split"),[f,p]=i.useState(()=>is(e)?"native":e.tabKey),b=i.useRef(null),y=i.useMemo(()=>s||r.find(T=>T.id===e.routeId),[e.routeId,s,r]),x=i.useMemo(()=>lt((y==null?void 0:y.type)||""),[y==null?void 0:y.type]),{conversations:A,extensionTabs:N,hasExtensions:v}=f0({ideData:y,allIdes:r,connectionStates:n,ideName:x||"IDE",preferredTabKey:is(e)?void 0:e.tabKey}),C=i.useMemo(()=>y?Bt(A,y.id):null,[y,A]);i.useEffect(()=>{const T=b.current,K={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(b.current=K,!(T&&T.routeId===K.routeId&&T.tabKey===K.tabKey&&T.streamSource===K.streamSource)){if(is(e)){p("native");return}p(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),i.useEffect(()=>{if(f==="native"){if(A.some(T=>T.streamSource==="native"))return;(C==null?void 0:C.streamSource)==="agent-stream"&&p(C.tabKey);return}if(!A.some(T=>T.tabKey===f)){if((C==null?void 0:C.streamSource)==="agent-stream"){p(C.tabKey);return}p("native")}},[A,f,C]);const M=i.useMemo(()=>f==="native"?A.find(T=>T.streamSource==="native")||e:A.find(T=>T.tabKey===f)||e,[e,A,f]),w=bd(M),k=i.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]),F=Mr(k),_=Fn({sendDaemonCommand:o,activeConv:k,setActionLogs:l,isStandalone:c}),{connScreenshot:S,screenshotUsage:H,handleRemoteAction:W}=Gd({doId:F,targetSessionId:Pc(k),connState:k.connectionState||"new",viewMode:g}),D=i.useMemo(()=>a.filter(T=>T.routeId===k.tabKey),[a,k.tabKey]);i.useEffect(()=>{u==null||u(k)},[k,u]),i.useEffect(()=>{const T=K=>{K.key==="Escape"&&h()};return window.addEventListener("keydown",T),()=>window.removeEventListener("keydown",T)},[h]);const I=i.useCallback(T=>{T.stopPropagation()},[]);return t.jsx("div",{className:"fixed inset-0 z-[1200] flex items-center justify-center p-0 md:p-3 bg-[#030617]/[0.56] backdrop-blur-md",onClick:h,children:t.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:I,children:[t.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:[t.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[t.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:t.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:[t.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:t.jsx(At,{size:16})}),t.jsx("span",{className:"truncate",children:Do(M)||"Remote"})]})}),t.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:h,children:"Close"})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[t.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(T=>{const K=g===T;return t.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${K?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>j(T),title:T==="split"?"Split view":"Remote only",children:T==="split"?t.jsx(_m,{size:15}):t.jsx(At,{size:15})},T)})}),t.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),t.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:[t.jsx(ko,{size:14,className:"md:mr-1.5"}),t.jsx("span",{className:"hidden md:inline",children:"History"})]}),t.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:h,children:"Close"})]})]}),t.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${g==="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:[g!=="remote"&&t.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${g==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[t.jsx(p0,{hasExtensions:v,ideName:x||"IDE",activeChatTab:f,extensionTabs:N,onSelectTab:p}),t.jsx(vc,{activeConv:k,onModalButton:_.handleModalButton}),t.jsx(ao,{activeConv:k,ideEntry:y,showMetaChips:!1,handleSendChat:_.handleSendChat,isSendingChat:_.isSendingChat,sendFeedbackMessage:_.sendFeedbackMessage,handleFocusAgent:_.handleFocusAgent,isFocusingAgent:_.isFocusingAgent,actionLogs:D,userName:d})]}),t.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-black ${g==="split"?"order-1 md:order-2":""}`,children:t.jsx(gc,{addLog:()=>{},connState:k.connectionState||"new",connScreenshot:S,screenshotUsage:H,transportType:k.transport,onAction:W})})]})]})})}function x0({activeConv:e,canSaveAndStop:s=!1,onCancel:r,onStopNow:n,onSaveAndStop:a}){const o=zh(e);return t.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:[t.jsx("div",{onClick:r,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),t.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:[t.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-[var(--surface-primary)]",children:[t.jsxs("h3",{className:"m-0 text-base md:text-lg font-extrabold",children:["Stop ",o,"?"]}),t.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:s?"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."})]}),t.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s&&t.jsx("button",{onClick:a,className:"btn btn-primary w-full justify-center min-h-[42px]",children:"Stop"}),t.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"}),t.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:"Cancel"})]})]})]})}function b0({historyModal:e,remoteDialog:s,cliStopDialog:r,connectionBanner:n,toastOverlay:a,onboarding:o}){var l;return t.jsxs(t.Fragment,{children:[t.jsx(Xh,{wsStatus:n.wsStatus,showReconnected:n.showReconnected,loginUrl:n.loginUrl,onReconnect:n.onReconnect}),e.open&&e.targetConv&&t.jsx(Vo,{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}),s.conversation&&t.jsx(h0,{activeConv:s.conversation,ideEntry:s.ideEntry,ides:s.ides,connectionStates:s.connectionStates,actionLogs:s.actionLogs,sendDaemonCommand:s.sendDaemonCommand,setActionLogs:s.setActionLogs,isStandalone:s.isStandalone,userName:s.userName,onOpenHistory:s.onOpenHistory,onConversationChange:s.onConversationChange,onClose:s.onClose}),r.open&&r.targetConv&&(nt(r.targetConv)||tt(r.targetConv))&&t.jsx(x0,{activeConv:r.targetConv,canSaveAndStop:nt(r.targetConv)&&!tt(r.targetConv)&&!!((l=r.targetConv.resume)!=null&&l.supported),onCancel:r.onCancel,onStopNow:r.onStopNow,onSaveAndStop:r.onSaveAndStop}),t.jsx(rd,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),o.open&&t.jsx(m0,{onClose:o.onClose})]})}function g0({daemons:e,targetVersion:s,required:r=!1,upgradingDaemons:n,onUpgrade:a,onDismiss:o}){return e.length===0?null:t.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:[t.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:r?"var(--status-danger)":"var(--status-warning)"},children:t.jsx(Tr,{size:14})}),t.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[t.jsxs("span",{children:[r?"Daemon update required":"Update available",s?t.jsxs(t.Fragment,{children:[": ",t.jsxs("strong",{children:["v",s]})]}):null]}),e.map(l=>{const c=Tt(l,{fallbackId:l.id}),d=n[l.id],m=l.version||l.daemonVersion||"unknown",u=l.versionUpdateRequired===!0,g=Ld(l)==="preview"?"Update to preview":u?"Update now":"Upgrade";return t.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:[t.jsx("span",{className:"font-medium text-text-primary",children:c}),t.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",m]}),u&&t.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),d==="upgrading"?t.jsx("span",{className:"text-[10px] animate-pulse",style:{color:u?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):d==="done"?t.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):d==="error"?t.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(l.id),children:"retry"}):t.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(l.id),children:g})]},l.id)})]}),!r&&t.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:o,title:"Dismiss",children:t.jsx(vt,{size:16})})]})}function y0(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function v0(e){const s=e.machine;return typeof(s==null?void 0:s.cpus)!="number"||typeof(s==null?void 0:s.totalMem)!="number"||typeof(s==null?void 0:s.arch)!="string"||typeof(s==null?void 0:s.release)!="string"}function w0(e){return{metadataDaemonIds:e.map(s=>s.id),runtimeDaemonIds:e.filter(s=>v0(s)).map(s=>s.id)}}function j0(){var mi,pi,fi,hi;const{sendCommand:e}=wt(),s=Lr(),r=xd(),n=vo(),a=cs(),[o,l]=Zu(),c=o.get("activeTab"),d=((mi=n.state)==null?void 0:mi.openRemoteForTabKey)||null,m=((pi=n.state)==null?void 0:pi.openMachineId)||null,u=((fi=n.state)==null?void 0:fi.mobileSection)||null,h=Gc(),g=h.ides||[],j=h.initialLoaded??!0,{updateRouteChats:f,setToasts:p}=h,[b,y]=i.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),x=h.toasts||[],A=h.wsStatus||"connected",N=h.isConnected??!0,v=h.connectionStates||{},C=h.showReconnected||!1,{layoutProfile:M,groupAssignments:w,updateGroupAssignments:k,focusedGroup:F,updateFocusedGroup:_,focusGroup:S,groupActiveTabIds:H,updateGroupActiveTabIds:W,setGroupActiveTab:D,groupTabOrders:I,updateGroupTabOrders:T,setGroupTabOrder:K,groupSizes:P,updateGroupSizes:$,isMobile:V,hasHydratedStoredLayout:Y,hydrateStoredLayout:ge,focusConversationTab:fe}=Kb(),[ae,me]=i.useState(()=>Jo());i.useEffect(()=>Zx(me),[]);const je=i.useMemo(()=>y0({isMobile:V,mobileViewMode:ae}),[V,ae]),[Ne,G]=i.useState([]),[he,pe]=i.useState({}),[ye,xe]=i.useState({});Ar("Dashboard",{ideCount:g.length,toastCount:x.length,focusedGroup:F,groupCount:Object.keys(w).length,actionLogCount:Ne.length});const Se=i.useMemo(()=>g.filter(Ge=>Ge.type==="adhdev-daemon").sort(Ro),[g]),R=Se[0],re=!!R;i.useEffect(()=>{const{metadataDaemonIds:Ge,runtimeDaemonIds:Pt}=w0(Se);for(const Qs of Ge)s(Qs,{minFreshMs:3e4}).catch(()=>{});for(const Qs of Pt)r(Qs,{minFreshMs:3e4}).catch(()=>{})},[s,r,Se]);const Q=(R==null?void 0:R.terminalBackend)||null,ue=R?Tt(R,{fallbackId:R.id}):null,ce=(R==null?void 0:R.id)||null,de=i.useMemo(()=>pb(g,he),[g,he]),{hiddenTabs:te,autoHiddenTabs:E,autoHideTarget:X,hideTarget:oe,toggleTarget:ee,showTarget:ke,showAllTabs:Ce}=mb(),{conversations:ve,visibleConversations:O,visibleTabKeys:Ie,resolveConversationBySessionId:Re,resolveConversationByTarget:Ke}=Cb({ides:de,connectionStates:v,clearedTabs:ye,hiddenTabs:te}),He=i.useMemo(()=>new Map(ve.map(Ge=>[Ge.tabKey,Ge])),[ve]),Ye=i.useMemo(()=>ub(ve,te,E),[ve,te,E]);i.useEffect(()=>{for(const Ge of Ye)X(Ge)},[Ye,X]),jh(O,je),i.useEffect(()=>{Object.keys(he).length!==0&&pe(Ge=>fb(Ge,g))},[g,he]);const Xe=i.useMemo(()=>Ap(g),[g]),{notifications:st,unreadCount:mt}=rg({conversations:ve,liveSessionInboxState:Xe}),{handleMarkDashboardNotificationRead:ht,handleMarkDashboardNotificationUnread:yt,handleDeleteDashboardNotification:Te}=ng({notifications:st,sendDaemonCommand:e}),{containerRef:Ue,normalizedGroupAssignments:et,numGroups:ze,isSplitMode:at,groupedConvs:U,moveTabToGroup:z,closeGroup:Z,handleResizeStart:ie,splitTabRelative:B}=qb({groupAssignments:w,updateGroupAssignments:k,updateFocusedGroup:_,updateGroupActiveTabIds:W,updateGroupTabOrders:T,groupSizes:P,updateGroupSizes:$,isMobile:V,visibleConversations:O,visibleTabKeys:Ie}),{activeConv:q,openDesktopConversation:ne,requestScrollToBottom:le,scrollToBottomRequest:we,setDesktopActiveTab:_e}=gg({isMobile:V,conversations:ve,visibleConversations:O,groupActiveTabIds:H,focusedGroup:F,groupedConvs:U,setSearchParams:l});wg({activeConv:q,isMobile:V,liveSessionInboxState:Xe,sendDaemonCommand:e});const{requestedDesktopTabKey:De,requestedMobileTabKey:Me,consumeRequestedActiveTab:Ee}=Ib({isMobile:V,urlActiveTab:c,resolveConversationBySessionId:Re,setSearchParams:l}),{remoteDialogConv:Oe,remoteDialogIdeEntry:Ae,remoteDialogActiveConv:Je,setRemoteDialogActiveConv:Ze,openRemoteDialog:xt,closeRemoteDialog:bt,cliStopDialogOpen:ct,cliStopTargetConv:pt,requestCliStop:We,cancelCliStop:Ot,confirmCliStop:se}=Ng({isMobile:V,location:n,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:De,conversations:ve,ides:g,resolveConversationByTarget:Ke,activeConv:q,sendDaemonCommand:e}),{historyModalOpen:Pe,openHistoryModal:L,closeHistoryModal:J,historyTargetConv:be,isSavedSessionHistoryTarget:$e,isHistoryCreatingChat:Le,isHistoryRefreshingHistory:Be,handleHistorySwitchSession:rt,handleHistoryNewChat:It,handleHistoryRefresh:ft,savedHistorySessions:Zt,savedHistoryFilters:Pr,setSavedHistoryFilters:Dr,missingWorkspaceResumePath:Er,isSavedHistoryLoading:$r,resumingSavedHistorySessionId:Br,handleRefreshSavedHistory:Or,handleResumeSavedHistorySession:Fr}=jg({activeConv:q,remoteDialogConv:Oe,remoteDialogActiveConv:Je,ides:g,sendDaemonCommand:e,updateRouteChats:f,setToasts:p,setClearedTabs:xe,setSearchParams:l}),gu=i.useMemo(()=>O,[O]),Kr=V&&ae==="chat",yu=i.useMemo(()=>ve.filter(Ge=>Wn(te,Ge)),[ve,te]),ci=i.useCallback(Ge=>{const Pt=new URLSearchParams(o);Pt.set("activeTab",Ge),l(Pt,{replace:!0})},[o,l]),{trackPendingLaunch:vu}=fg({ides:g,conversations:ve,onOpenSession:ci}),{handleBrowseMachineDirectory:wu,handleSaveMachineWorkspace:ju,handleLaunchMachineIde:ku,handleLaunchMachineProvider:Nu,handleListMachineMeshes:Su,handleLaunchMeshCoordinator:Cu,handleListMachineSavedSessions:Iu,setActiveCliViewMode:Tu}=hg({sendDaemonCommand:e,trackPendingLaunch:vu,onOpenSession:ci,activeConv:q,ides:g,setCliViewModeOverrides:pe});hb({visibleConversations:O,clearedTabs:ye,setClearedTabs:xe,setActionLogs:G}),Tb({ides:g,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:Ke});const{isRefreshingHistory:Au,handleRefreshHistory:Mu}=Md({sendDaemonCommand:e,activeConv:q,chats:(hi=g.find(Ge=>Ge.id===(q==null?void 0:q.routeId)))==null?void 0:hi.chats,updateRouteChats:f,setToasts:p,setClearedTabs:xe});Hb({urlActiveTab:V&&!Kr?c:null,conversations:ve,resolveConversationBySessionId:Re,normalizedGroupAssignments:et,hasHydratedStoredLayout:V&&!Kr?Y:!0,hydrateStoredLayout:V&&!Kr?ge:()=>{},focusConversationTab:fe,setSearchParams:l,historyModalOpen:Pe,activeConv:q,isRefreshingHistory:Au,ides:g,handleRefreshHistory:Mu});const Lu=i.useMemo(()=>!q||!nt(q)||tt(q)?null:Js(q),[q]),{versionMismatchDaemons:Ru,hasRequiredVersionDaemons:di,targetVersion:_u,versionBannerDismissed:Pu,setVersionBannerDismissed:Du,upgradingDaemons:Eu,handleBannerUpgrade:$u}=Xb({ides:g,sendDaemonCommand:e}),ui=i.useCallback(Ge=>{ke(Ge),ne(Ge)},[ne,ke]),Bu=i.useCallback(Ge=>{oe(Ge)},[oe]);return t.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[t.jsx(Jh,{terminalBackend:Q,isStandalone:re,machineLabel:ue,machineKey:ce}),(!Pu||di)&&t.jsx(g0,{daemons:Ru,targetVersion:_u,required:di,upgradingDaemons:Eu,onUpgrade:$u,onDismiss:()=>Du(!0)}),t.jsx(u0,{showMobileChatMode:Kr,isMobile:V,activeConv:q,wsStatus:A,isConnected:N,onOpenHistory:Ge=>{Ge&&Ze(Ge),L()},onOpenRemote:xt,onStopCli:We,activeCliViewMode:Lu,onSetActiveCliViewMode:Tu,mobileChatConversations:gu,ides:g,actionLogs:Ne,sendDaemonCommand:e,setActionLogs:G,setCliViewModeOverrides:pe,isStandalone:re,initialDataLoaded:j,userName:h.userName,requestedMobileTabKey:Me,onRequestedMobileTabConsumed:Ee,requestedMachineId:m,onRequestedMachineConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},requestedMobileSection:u,onRequestedMobileSectionConsumed:()=>{a(n.pathname+n.search,{replace:!0,state:null})},containerRef:Ue,isSplitMode:at,numGroups:ze,groupSizes:P,groupedConvs:U,clearedTabs:ye,focusedGroup:F,focusGroup:S,moveTabToGroup:z,splitTabRelative:B,closeGroup:Z,handleResizeStart:ie,groupActiveTabIds:H,setGroupActiveTab:D,groupTabOrders:I,setGroupTabOrder:K,toggleHiddenTab:Ge=>ee(He.get(Ge)||{tabKey:Ge}),visibleConversations:O,hiddenConversations:yu,requestedDesktopTabKey:De,onRequestedDesktopTabConsumed:Ee,onDesktopActiveTabChange:_e,onRequestScrollToBottom:le,onHideConversation:Bu,onShowHiddenConversation:ui,onShowAllHiddenConversations:Ce,scrollToBottomRequest:we,machineEntries:Se,layoutProfile:M,onBrowseMachineDirectory:wu,onSaveMachineWorkspace:ju,onLaunchMachineIde:ku,onLaunchMachineProvider:Nu,onListMachineMeshes:Su,onLaunchMeshCoordinator:Cu,onListMachineSavedSessions:Iu,notifications:st,notificationUnreadCount:mt,liveSessionInboxState:Xe,onMarkNotificationRead:ht,onMarkNotificationUnread:yt,onDeleteNotification:Te}),t.jsx("style",{children:`
|
|
70
|
-
body { overflow: hidden; overscroll-behavior: none; }
|
|
71
|
-
`}),t.jsx(b0,{historyModal:{open:Pe,targetConv:be,ides:g,isCreatingChat:Le,isRefreshingHistory:$e?!1:Be,savedSessions:Zt,savedHistoryFilters:Pr,missingWorkspaceResumePath:Er||null,onSavedHistoryFiltersChange:Dr,isSavedSessionsLoading:$r,isResumingSavedSessionId:Br,onClose:J,onNewChat:It,onSwitchSession:rt,onRefreshHistory:$e?Or:ft,onResumeSavedSession:Fr},remoteDialog:{conversation:Oe,ideEntry:Ae,ides:g,connectionStates:v,actionLogs:Ne,sendDaemonCommand:e,setActionLogs:G,isStandalone:re,userName:h.userName,onOpenHistory:Ge=>{Ge&&Ze(Ge),L()},onConversationChange:Ze,onClose:bt},cliStopDialog:{open:ct,targetConv:pt,onCancel:Ot,onStopNow:async()=>{await se("hard")},onSaveAndStop:async()=>{await se("save")}},connectionBanner:{wsStatus:A,showReconnected:C,loginUrl:h.connectionLoginUrl,onReconnect:h.retryServerConnection},toastOverlay:{toasts:x,onDismiss:Ge=>p(Pt=>Pt.filter(Qs=>Qs.id!==Ge)),onClick:Ge=>{if(Ge.targetKey){const Pt=Ke(Ge.targetKey);Pt&&(fe(Pt.tabKey,et),ui(Pt),le(Pt.tabKey,"toast-open"))}}},onboarding:{open:b,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}y(!1)}}})]})}function k0({machineId:e,registeredMachineId:s,sendDaemonCommand:r,onNicknameSynced:n,logsEndRef:a}){const[o,l]=i.useState([]),[c,d]=i.useState(null),[m,u]=i.useState(null),[h,g]=i.useState(!1),[j,f]=i.useState(null),[p,b]=i.useState(!1),[y,x]=i.useState(""),A=i.useRef(null),N=i.useCallback(P=>{A.current=P},[]),v=i.useCallback((P,$,V=!1)=>{l(Y=>[...Y.slice(-100),{timestamp:Date.now(),level:P,message:$}]),setTimeout(()=>{var Y;return(Y=a.current)==null?void 0:Y.scrollIntoView({behavior:"smooth"})},100),V&&ot.showToast($,P==="error"||P==="warn"?"warning":"success")},[a]),C=i.useCallback(P=>{const $=P instanceof Error?P.message:String(P||"");return $.includes("P2P command timeout")||$.includes("P2P not connected")||$.includes("P2P not available")},[]),M=i.useCallback(async(P,$)=>{var V;if(!e||c)return!1;d(P),v("info",`Launching ${lt(P)}${$!=null&&$.workspace?` in ${$.workspace}`:""}...`);try{const Y={ideType:P,enableCdp:!0};(V=$==null?void 0:$.workspace)!=null&&V.trim()?Y.workspace=$.workspace.trim():$!=null&&$.useDefaultWorkspace&&(Y.useDefaultWorkspace=!0);const ge=await r(e,"launch_ide",Y);return v(ge!=null&&ge.success?"info":"error",ge!=null&&ge.success?`${lt(P)} launched`:`Failed: ${ge==null?void 0:ge.error}`,!0),!!(ge!=null&&ge.success)}catch(Y){return v("error",`Launch error: ${Y.message}`,!0),!1}finally{d(null)}},[e,c,v,r]),w=i.useCallback(async P=>{if(!e)return{success:!1};const{cliType:$,dir:V,workspaceId:Y,useDefaultWorkspace:ge,useHome:fe,argsStr:ae,model:me,resumeSessionId:je}=P;if(!$)return v("warn","Select a CLI or ACP provider first",!0),{success:!1};const Ne=ae?ae.split(/\s+/).filter(Boolean):void 0,G=(V==null?void 0:V.trim())||(Y?"(saved id)":ge?"(default workspace)":fe?"(home)":"");v("info",`Launching ${$}${G?` in ${G}`:""}${me?` (model: ${me})`:""}...`),u($);try{const he={cliType:$,cliArgs:Ne,initialModel:me||void 0};V!=null&&V.trim()?he.dir=V.trim():Y?he.workspaceId=Y:ge?he.useDefaultWorkspace=!0:fe&&(he.useHome=!0),je&&(he.resumeSessionId=je);const pe=await r(e,"launch_cli",he),ye=(pe==null?void 0:pe.result)||pe;return pe!=null&&pe.success?(v("info",`${$} launched`,!0),(ye==null?void 0:ye.launchSource)==="home"?v("info","📂 Running in home directory (explicit choice)"):(ye==null?void 0:ye.launchSource)==="defaultWorkspace"&&v("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:ye==null?void 0:ye.sessionId}):(v("error",`Failed: ${(pe==null?void 0:pe.error)||(ye==null?void 0:ye.error)}`,!0),(pe==null?void 0:pe.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&f({cliType:$,argsStr:ae,model:me}),{success:!1,sessionId:ye==null?void 0:ye.sessionId})}catch(he){return C(he)?(v("warn",`${$} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(v("error",`Launch error: ${he.message}`,!0),{success:!1})}finally{u(null)}},[e,v,C,r]),k=i.useCallback(async(P,$,V,Y)=>e?P?$.trim()?w({cliType:P,dir:$,argsStr:V,model:Y}):(f({cliType:P,argsStr:V,model:Y}),{success:!1}):(v("warn","Select a provider",!0),{success:!1}):{success:!1},[e,v,w]),F=i.useCallback(async(P,$,V)=>{if(e&&window.confirm(`Stop ${P}?
|
|
72
|
-
This will terminate the process.`))try{const Y=await r(e,"stop_cli",{cliType:P,dir:$,targetSessionId:V});Y!=null&&Y.success?v("info",`${P} stopped`,!0):v("error",`Stop failed: ${(Y==null?void 0:Y.error)||"Unknown error"}`,!0)}catch(Y){v("error",`Stop failed: ${Y.message}`,!0)}},[e,v,r]),_=i.useCallback(async P=>{try{await r(P.daemonId,"restart_ide",{ideType:P.type}),v("info",`${lt(P.type)} restart initiated`,!0)}catch($){v("error",`Restart failed: ${$.message}`,!0)}},[v,r]),S=i.useCallback(async P=>{if(window.confirm(`Stop ${lt(P.type)}?
|
|
73
|
-
This will disconnect CDP and optionally kill the process.`))try{const $=await r(P.daemonId,"stop_ide",{ideType:P.type,killProcess:!0});$!=null&&$.success?v("info",`${lt(P.type)} stopped`,!0):v("error",`Stop failed: ${($==null?void 0:$.error)||"Unknown error"}`,!0)}catch($){v("error",`Stop failed: ${$.message}`,!0)}},[v,r]),H=i.useCallback(async()=>{if(e)try{const P=await r(e,"detect_ides",{});v("info",`Found ${((P==null?void 0:P.result)||[]).length} IDE(s)`,!0)}catch(P){v("error",`Detection failed: ${P.message}`,!0)}},[e,v,r]),W=i.useCallback(async P=>{if(!e||!P.trim())return!1;g(!0);try{const $=await r(e,"workspace_add",{path:P.trim()});return $!=null&&$.success?(v("info",`Workspace added: ${P.trim()}`),!0):(v("error",($==null?void 0:$.error)||"workspace_add failed"),!1)}catch($){return v("error",$.message),!1}finally{g(!1)}},[e,v,r]),D=i.useCallback(async P=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){g(!0);try{const $=await r(e,"workspace_remove",{id:P});$!=null&&$.success?v("info","Workspace removed",!0):v("error",($==null?void 0:$.error)||"workspace_remove failed",!0)}catch($){v("error",$.message,!0)}finally{g(!1)}}},[e,v,r]),I=i.useCallback(async P=>{var $;if(e){g(!0);try{const V=await r(e,"workspace_set_default",P===null?{clear:!0}:{id:P});if(V!=null&&V.success){v("info",P?"Default workspace updated":"Default workspace cleared",!0);const Y=typeof V.defaultWorkspacePath=="string"?V.defaultWorkspacePath:"";Y&&(($=A.current)==null||$.call(A,Y))}else v("error",(V==null?void 0:V.error)||"workspace_set_default failed",!0)}catch(V){v("error",V.message,!0)}finally{g(!1)}}},[e,v,r]),T=i.useCallback(async P=>{var V;if(!e||!P.trim())return;const $=P.trim();g(!0);try{const Y=await r(e,"workspace_set_default",{path:$});Y!=null&&Y.success?(v("info","Default workspace set from history"),(V=A.current)==null||V.call(A,$)):v("error",(Y==null?void 0:Y.error)||"Could not set default (path missing on disk?)")}catch(Y){v("error",Y.message)}finally{g(!1)}},[e,v,r]),K=i.useCallback(async()=>{if(e)try{if(await r(e,"set_machine_nickname",{nickname:y}),n)try{await n({machineRuntimeId:e,registeredMachineId:s,nickname:y})}catch(P){v("warn",`Live nickname updated, but account sync failed: ${P.message}`)}v("info",`Nickname set to "${y||"(cleared)"}"`),b(!1)}catch(P){v("error",`Failed: ${P.message}`)}},[e,y,s,v,n,r]);return{logs:o,launchingIde:c,launchingAgentType:m,workspaceBusy:h,launchPick:j,setLaunchPick:f,editingNickname:p,setEditingNickname:b,nicknameInput:y,setNicknameInput:x,addLog:v,handleLaunchIde:M,runLaunchCliCore:w,handleLaunchCli:k,handleStopCli:F,handleRestartIde:_,handleStopIde:S,handleDetectIdes:H,handleWorkspaceAdd:W,handleWorkspaceRemove:D,handleWorkspaceSetDefault:I,handleWorkspaceResumePath:T,handleSaveNickname:K,setOnDefaultWorkspaceChanged:N}}function N0({machineId:e,machine:s,ideSessions:r,cliSessions:n,acpSessions:a,actions:o,sendDaemonCommand:l}){var _;const{workspaceBusy:c,handleWorkspaceAdd:d,handleWorkspaceRemove:m,handleWorkspaceSetDefault:u}=o,[h,g]=i.useState(!1),[j,f]=i.useState(""),[p,b]=i.useState([]),[y,x]=i.useState(!1),[A,N]=i.useState(""),v=i.useCallback(async S=>{x(!0),N("");try{const H=await zn(l,e,S);f(H.path),b(H.directories)}catch(H){N(H instanceof Error?H.message:"Could not load folder")}finally{x(!1)}},[e,l]),C=i.useCallback(()=>{g(!0);const S=[...r.map(W=>W.workspace),...n.map(W=>W.workspace),...a.map(W=>W.workspace)],H=Un(s.platform,Hn(S,s.defaultWorkspacePath,(s.workspaces||[]).map(W=>W.path)));v(H)},[a,n,r,v,s.defaultWorkspacePath,s.platform,s.workspaces]),M=typeof s.uptime=="number"||typeof s.freeMem=="number"||typeof s.availableMem=="number"||Array.isArray(s.loadavg)&&s.loadavg.length>0,w=s.availableMem??s.freeMem??s.totalMem,k=M&&s.totalMem>0?Math.min(100,Math.max(0,Math.round((s.totalMem-w)/s.totalMem*100))):0,F=((_=s.loadavg)==null?void 0:_[0])||0;return t.jsxs("div",{children:[t.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[t.jsx(Hr,{icon:t.jsx(cc,{size:16}),label:"Uptime",value:typeof s.uptime=="number"?Dp(s.uptime):"Waiting…"}),t.jsx(Hr,{icon:t.jsx(At,{size:16}),label:"IDEs",value:`${r.length}`}),t.jsx(Hr,{icon:t.jsx(So,{size:16}),label:"CLIs",value:`${n.length}`}),t.jsx(Hr,{icon:t.jsx(Dm,{size:16}),label:"ACPs",value:`${a.length}`})]}),t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsx("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-3",children:"Resource Usage"}),t.jsxs("div",{className:"flex gap-6",children:[t.jsx(Li,{value:M?Math.min(Math.round(F/s.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:M?`${F.toFixed(2)} avg / ${s.cpus} cores`:"Polled from machine page"}),t.jsx(Li,{value:k,max:100,label:"Memory",color:"#3b82f6",detail:M?`${sa(s.totalMem-w)} / ${sa(s.totalMem)}${s.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${sa(s.totalMem)} total`})]})]}),t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-3",children:[t.jsx(Ns,{size:14})," Workspaces"]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center mb-3",children:[t.jsx("span",{className:"text-[10px] text-text-muted",children:"Default:"}),t.jsxs("select",{className:"text-xs bg-bg-primary border border-border-subtle rounded-lg px-2 py-1 max-w-[min(100%,420px)]",disabled:c,value:s.defaultWorkspaceId||"",onChange:S=>void u(S.target.value===""?null:S.target.value),children:[t.jsx("option",{value:"",children:"(none)"}),(s.workspaces||[]).map(S=>t.jsx("option",{value:S.id,children:S.label||S.path},S.id))]}),s.defaultWorkspacePath&&t.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate max-w-[min(100%,360px)]",title:s.defaultWorkspacePath,children:s.defaultWorkspacePath})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.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:c,onClick:C,children:"Select workspace…"}),t.jsx("span",{className:"text-[11px] text-text-muted",children:"Add workspaces by selecting a folder in the explorer."})]}),(s.workspaces||[]).length>0&&t.jsx("ul",{className:"mt-3 space-y-1.5 max-h-40 overflow-y-auto",children:(s.workspaces||[]).map(S=>t.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:[t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[S.id===s.defaultWorkspaceId&&t.jsx("span",{className:"text-[10px]",children:"⭐"}),t.jsx("span",{className:"font-medium text-text-primary truncate",children:Bn(S.path,S.label)})]}),t.jsx("div",{className:"font-mono truncate text-[10px]",title:S.path,children:S.path})]}),t.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void m(S.id),children:"Remove"})]},S.id))})]}),h&&t.jsx(Vn,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:j,directories:p,busy:y,error:A,confirmLabel:"Add workspace",onClose:()=>g(!1),onNavigate:S=>{v(S)},onConfirm:S=>{(async()=>{if(!S)return;await d(S)&&g(!1)})()}})]})}function S0(e){if(!e||typeof e!="object")return null;const s=e,r=s.result&&typeof s.result=="object"?s.result:s;return!r.settings||typeof r.settings!="object"?null:{settings:r.settings,values:r.values&&typeof r.values=="object"?r.values:{}}}function C0(e,s,r){const n=[];for(const[a,o]of Object.entries(e.settings)){const l=r!=null&&r.filterSchema?r.filterSchema(o):o;if(l.length===0)continue;const c=s.find(d=>d.type===a);n.push({type:a,displayName:(c==null?void 0:c.displayName)||a,icon:(c==null?void 0:c.icon)||"",category:(c==null?void 0:c.category)||"unknown",schema:l,values:e.values[a]||{}})}return n}function Ea(e){if(!e||typeof e!="object")return!1;const s=e;return(s.sourceMode==="normal"||s.sourceMode==="no-upstream")&&typeof s.disableUpstream=="boolean"&&(s.explicitProviderDir===null||typeof s.explicitProviderDir=="string")&&typeof s.userDir=="string"&&typeof s.upstreamDir=="string"&&Array.isArray(s.providerRoots)}function El(e){if(!e||typeof e!="object")return null;if(Ea(e))return e;const s=e,r=s.result;return Ea(r)?r:Ea(s.sourceConfig)?s.sourceConfig:null}function I0(e){const s=e.trim();return s||null}const $l=["openPanel","sendMessage","readChat","newSession","listSessions","switchSession","resolveAction","listModels","setModel","listModes","setMode","focusEditor"],T0=[{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 A0({machineId:e,provider:s,sendDaemonCommand:r,onClose:n}){const[a,o]=i.useState("config"),[l,c]=i.useState("codex-cli"),[d,m]=i.useState([]),[u,h]=i.useState(""),[g,j]=i.useState([]),[f,p]=i.useState(""),b=i.useRef(null),y=i.useRef(null),x=w=>{m(k=>k.includes(w)?k.filter(F=>F!==w):[...k,w])},A=()=>m([...$l]),N=()=>m([]);i.useEffect(()=>{var w;(w=b.current)==null||w.scrollIntoView({behavior:"smooth"})},[g]),i.useEffect(()=>()=>{y.current&&clearInterval(y.current)},[]);const v=i.useCallback(()=>{y.current&&clearInterval(y.current),y.current=setInterval(async()=>{try{const w=await r(e,"provider_auto_fix_status",{providerType:s.type});(w==null?void 0:w.running)===!1&&a==="running"&&(o("done"),j(k=>[...k,`
|
|
74
|
-
✅ Auto-fix completed!`]),y.current&&clearInterval(y.current))}catch{}},3e3)},[e,s.type,r,a]),C=async()=>{if(d.length!==0){o("running"),j(["🚀 Starting auto-fix...",`Agent: ${l}`,`Scripts: ${d.join(", ")}`,u?`💬 Comment: ${u}`:"",""]),p("");try{const w=await r(e,"provider_auto_fix",{providerType:s.type,functions:d,agent:l,...u?{comment:u}:{}});w!=null&&w.success&&(w!=null&&w.started||w!=null&&w.running)?(j(k=>[...k,"✅ Agent started. Monitoring progress..."]),v()):(o("error"),p((w==null?void 0:w.error)||"Failed to start auto-fix"))}catch(w){o("error"),p((w==null?void 0:w.message)||"Connection failed")}}},M=async()=>{try{await r(e,"provider_auto_fix_cancel",{providerType:s.type}),j(w=>[...w,`
|
|
75
|
-
⚠️ Auto-fix cancelled.`]),o("done"),y.current&&clearInterval(y.current)}catch{}};return t.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:t.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:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle flex items-center justify-between",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:s.icon||"🔧"}),t.jsxs("div",{children:[t.jsxs("h2",{className:"text-[15px] font-semibold text-text-primary",children:["Auto-Fix: ",s.displayName]}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"AI agent will implement provider scripts"})]})]}),t.jsx("button",{onClick:n,className:"text-text-muted hover:text-text-primary text-lg leading-none",children:"×"})]}),t.jsxs("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:[a==="config"&&t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"AI Agent"}),t.jsx("div",{className:"flex gap-2",children:T0.map(w=>t.jsxs("button",{onClick:()=>c(w.value),className:"flex-1 px-3 py-2 rounded-lg border text-left transition-all",style:{borderColor:l===w.value?w.color+"66":"var(--border-subtle)",background:l===w.value?w.color+"0d":"transparent"},children:[t.jsx("div",{className:"text-[12px] font-semibold",style:{color:l===w.value?w.color:"var(--text-primary)"},children:w.label}),t.jsx("div",{className:"text-[10px] text-text-muted",children:w.desc})]},w.value))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider",children:"Scripts to Fix"}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:A,className:"text-[10px] text-violet-400 hover:text-violet-300",children:"All"}),t.jsx("span",{className:"text-[10px] text-text-muted",children:"|"}),t.jsx("button",{onClick:N,className:"text-[10px] text-text-muted hover:text-text-secondary",children:"None"})]})]}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:$l.map(w=>t.jsxs("button",{onClick:()=>x(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))})]}),t.jsxs("div",{children:[t.jsxs("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:["Additional Instructions ",t.jsx("span",{className:"text-text-muted font-normal",children:"(optional)"})]}),t.jsx("textarea",{value:u,onChange:w=>h(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")&&t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Agent Output"}),t.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:[g.map((w,k)=>t.jsx("div",{className:w.startsWith("✅")?"text-green-400":"",style:w.startsWith("❌")||w.startsWith("⚠")?{color:"var(--status-warning)"}:void 0,children:w},k)),a==="running"&&t.jsx("div",{className:"text-violet-400 animate-pulse mt-1",children:"● Running..."}),t.jsx("div",{ref:b})]}),f&&t.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:f})]})]}),t.jsxs("div",{className:"px-5 py-3.5 border-t border-border-subtle flex justify-between items-center",children:[t.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"]}),t.jsxs("div",{className:"flex gap-2",children:[a==="config"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:C,disabled:d.length===0,className:"machine-btn",style:{background:d.length>0?"color-mix(in srgb, var(--accent-primary) 15%, transparent)":void 0,borderColor:d.length>0?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":void 0,color:d.length>0?"#a78bfa":void 0,opacity:d.length===0?.4:1},children:"🚀 Start Fix"})]}),a==="running"&&t.jsx("button",{onClick:M,className:"machine-btn text-red-400 border-red-500/30",children:"⬛ Cancel"}),(a==="done"||a==="error")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{o("config"),j([]),p("")},className:"machine-btn",children:"← Back"}),t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"})]})]})]})]})})}function M0({machineId:e,providers:s,sendDaemonCommand:r,onClose:n,onCreated:a}){var v;const o=s.filter(C=>C.category==="ide"),[l,c]=i.useState(((v=o[0])==null?void 0:v.type)||""),[d,m]=i.useState(""),[u,h]=i.useState(""),[g,j]=i.useState(!1),[f,p]=i.useState(""),[b,y]=i.useState(!1),x=C=>{const M=C.toLowerCase().replace(/[^a-z0-9-]/g,"");m(M),(!u||u===A(d))&&h(A(M))},A=C=>C.split("-").map(M=>M.charAt(0).toUpperCase()+M.slice(1)).join(" "),N=async()=>{if(!(!d||!u||!l)){j(!0),p("");try{const C=await r(e,"provider_clone",{type:d,name:u,category:"ide",location:"user",cloneFrom:l});C!=null&&C.success||C!=null&&C.created?(y(!0),a==null||a(d)):p((C==null?void 0:C.error)||"Failed to create provider")}catch(C){p((C==null?void 0:C.message)||"Connection failed")}j(!1)}};return t.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:t.jsxs("div",{className:"w-full max-w-[480px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col overflow-hidden",onClick:C=>C.stopPropagation(),children:[t.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[t.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:"✨ Create User Provider"}),t.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:"Clone an upstream IDE provider to customize"})]}),t.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:b?t.jsxs("div",{className:"text-center py-6",children:[t.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),t.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:"Provider Created!"}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[t.jsx("code",{className:"text-violet-400",children:d})," has been created at ",t.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",d,"/"]})]}),t.jsxs("p",{className:"text-[11px] text-text-muted mt-2",children:["Run ",t.jsxs("code",{className:"text-violet-400",children:["adhdev provider fix ",d]})," or use Auto-Fix to implement scripts."]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Base Provider"}),t.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:o.map(C=>t.jsxs("button",{onClick:()=>c(C.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:l===C.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:l===C.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[t.jsx("div",{className:"text-lg",children:C.icon}),t.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:l===C.type?"#a78bfa":"var(--text-secondary)"},children:C.displayName})]},C.type))})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Provider Type (ID)"}),t.jsx("input",{value:d,onChange:C=>x(C.target.value),placeholder:"my-cursor, custom-windsurf...",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),t.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:["Lowercase, alphanumeric + hyphens only. Will be created at ",t.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",d||"...","/"]})]})]}),t.jsxs("div",{children:[t.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:"Display Name"}),t.jsx("input",{value:u,onChange:C=>h(C.target.value),placeholder:"My Custom IDE",className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]}),f&&t.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:f})]})}),t.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:b?t.jsx("button",{onClick:n,className:"machine-btn",children:"Close"}):t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:n,className:"machine-btn",children:"Cancel"}),t.jsx("button",{onClick:N,disabled:!d||!u||g,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||g?.4:1},children:g?"⏳ Creating...":"✨ Create Provider"})]})})]})})}function Bl(e){return e==="cli"||e==="acp"}function L0(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 R0(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 Ol(e){if(!e)return"No result yet";const s=e.stage||"check",r=e.ok?"OK":"Failed",n=e.message||e.path||e.command||"";return n?`${s}: ${r} — ${n}`:`${s}: ${r}`}function _0({machineId:e,providers:s,sendDaemonCommand:r}){var W;const[n,a]=i.useState([]),[o,l]=i.useState(!1),[c,d]=i.useState(null),[m,u]=i.useState("all"),[h,g]=i.useState(null),[j,f]=i.useState(!1),[p,b]=i.useState(null),[y,x]=i.useState("normal"),[A,N]=i.useState(""),[v,C]=i.useState(!1),M=i.useCallback(async()=>{if(e)try{const D=await r(e,"get_provider_source_config",{}),I=El(D);I&&(b(I),x(I.sourceMode),N(I.explicitProviderDir||""))}catch{}},[e,r]),w=i.useCallback(async()=>{if(e){l(!0);try{const D=await r(e,"get_provider_settings",{}),I=S0(D);if(I){const T=C0(I,s,{filterSchema:K=>K.filter(P=>P.key!=="enabled")});T.sort((K,P)=>K.category.localeCompare(P.category)||K.displayName.localeCompare(P.displayName)),a(T)}}catch{}l(!1)}},[e,s,r]);i.useEffect(()=>{n.length===0&&w(),p||M()},[]);const k=async(D,I,T)=>{d(`${D}.${I}`),a(K=>K.map(P=>P.type===D?{...P,values:{...P.values,[I]:T}}:P));try{const K=await r(e,"set_provider_setting",{providerType:D,key:I,value:T});K!=null&&K.success||w()}catch{w()}d(null)},F=async(D,I)=>{await k(D,"enabled",I),await w()},_=async D=>{d(`${D}.detect`);try{await r(e,"detect_provider",{providerType:D})}finally{await w(),d(null)}},S=async D=>{await k(D,"executablePath",""),await k(D,"executableArgs",""),await w()},H=async()=>{C(!0);try{const D=await r(e,"set_provider_source_config",{providerSourceMode:y,providerDir:I0(A)}),I=El(D);I?(b(I),x(I.sourceMode),N(I.explicitProviderDir||"")):await M(),await w()}catch{await M()}C(!1)};return t.jsxs("div",{children:[t.jsxs("div",{className:"flex justify-between items-center mb-4",children:[t.jsxs("div",{className:"flex gap-1 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:"Filter"}),["all","acp","cli","ide","extension"].map(D=>t.jsx("button",{onClick:()=>u(D),className:`machine-btn text-[10px] px-2 py-0.5 ${m===D?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:D.toUpperCase()},D))]}),t.jsxs("div",{className:"flex gap-1.5",children:[t.jsx("button",{onClick:()=>f(!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"}),t.jsx("button",{onClick:w,disabled:o,className:"machine-btn",children:o?"⏳ Loading...":"↻ Refresh"})]})]}),t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle mb-4",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:"Provider source config"}),t.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."})]}),t.jsx("button",{onClick:M,className:"machine-btn text-[10px]",children:"↻ Refresh source"})]}),t.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Source mode"}),t.jsxs("select",{value:y,onChange:D=>x(D.target.value),className:"machine-input text-[11px]",children:[t.jsx("option",{value:"normal",children:"normal"}),t.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),t.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[t.jsx("span",{className:"font-medium text-text-primary",children:"Explicit providerDir"}),t.jsx("input",{type:"text",value:A,onChange:D=>N(D.target.value),placeholder:"Leave blank to use ~/.adhdev/providers",className:"machine-input text-[11px]"})]}),t.jsx("button",{onClick:()=>void H(),disabled:v,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:v?"Applying…":"Apply + Reload"})]}),t.jsxs("div",{className:"mt-3 grid gap-1 text-[11px] text-text-muted",children:[t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Effective user root:"})," ",(p==null?void 0:p.userDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Upstream root:"})," ",(p==null?void 0:p.upstreamDir)||"loading…"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-primary font-medium",children:"Provider roots:"})," ",((W=p==null?void 0:p.providerRoots)==null?void 0:W.join(" → "))||"loading…"]})]})]}),m!=="all"&&n.filter(D=>D.category===m).length>1&&(()=>{const D=n.filter(P=>P.category===m),I=new Map;for(const P of D)for(const $ of P.schema){if($.type!=="boolean")continue;const V=I.get($.key),Y=!!(P.values[$.key]??$.default);V?(V.onCount+=Y?1:0,V.total+=1):I.set($.key,{label:$.label||$.key,onCount:Y?1:0,total:1})}const T=[...I.entries()].filter(([,P])=>P.total===D.length);if(T.length===0)return null;const K=async(P,$)=>{for(const V of D)await k(V.type,P,$)};return t.jsxs("div",{className:"px-4 py-3 rounded-xl bg-violet-500/[0.04] border border-violet-500/10 mb-4",children:[t.jsxs("div",{className:"text-[10px] text-violet-400 font-semibold uppercase tracking-wider mb-2",children:["Bulk — Apply to all ",m.toUpperCase()," providers (",D.length,")"]}),t.jsx("div",{className:"flex flex-wrap gap-2",children:T.map(([P,$])=>{const V=$.onCount===$.total,Y=$.onCount===0;return t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[t.jsx("span",{className:"text-text-secondary font-medium",children:$.label}),t.jsxs("span",{className:"text-[9px] text-text-muted",children:["(",$.onCount,"/",$.total,")"]}),t.jsx("button",{onClick:()=>void K(P,!0),disabled:V,className:`machine-btn text-[9px] px-1.5 py-px ${V?"opacity-40":"text-green-400 border-green-500/30"}`,children:"All ON"}),t.jsx("button",{onClick:()=>void K(P,!1),disabled:Y,className:`machine-btn text-[9px] px-1.5 py-px ${Y?"opacity-40":"text-red-400 border-red-500/30"}`,children:"All OFF"})]},P)})})]})})(),o&&n.length===0?t.jsx("div",{className:"p-10 text-center text-text-muted",children:"Loading provider settings..."}):t.jsx("div",{className:"flex flex-col gap-2",children:n.filter(D=>m==="all"||D.category===m).map(D=>t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[t.jsx("span",{className:"text-lg",children:D.icon}),t.jsx("span",{className:"font-semibold text-[13px] text-text-primary",children:D.displayName}),t.jsx("span",{className:"px-1.5 py-px rounded text-[9px] font-semibold",style:{background:D.category==="acp"?"rgba(139,92,246,0.08)":D.category==="cli"?"rgba(59,130,246,0.08)":D.category==="ide"?"rgba(34,197,94,0.08)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",color:D.category==="acp"?"#a78bfa":D.category==="cli"?"#60a5fa":D.category==="ide"?"#86efac":"var(--status-warning)"},children:D.category}),Bl(D.category)&&(()=>{const I=s.find(P=>P.type===D.type),T=(I==null?void 0:I.enabled)===!0||D.values.enabled===!0,K=(I==null?void 0:I.machineStatus)||(T?"enabled_unchecked":"disabled");return t.jsxs(t.Fragment,{children:[t.jsx("span",{className:`px-1.5 py-px rounded border text-[9px] font-semibold ${R0(K)}`,children:L0(K)}),t.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[t.jsx("button",{onClick:()=>void F(D.type,!T),disabled:c===`${D.type}.enabled`,className:`machine-btn text-[9px] px-2 py-0.5 ${T?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:T?"Disable":"Enable"}),t.jsx("button",{onClick:()=>void _(D.type),disabled:!T||c===`${D.type}.detect`,title:T?"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 ${T?"":"opacity-40 cursor-not-allowed"}`,children:"Detect"}),t.jsx("button",{onClick:()=>void S(D.type),className:"machine-btn text-[9px] px-2 py-0.5",children:"Reset command"})]})]})})(),D.category==="ide"&&t.jsx("button",{onClick:()=>g(s.find(I=>I.type===D.type)||{type:D.type,name:D.displayName,displayName:D.displayName,icon:D.icon,category:D.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"})]}),Bl(D.category)&&(()=>{const I=s.find(T=>T.type===D.type);return t.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:[t.jsxs("div",{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:"Detection:"})," ",Ol(I==null?void 0:I.lastDetection)]}),t.jsxs("div",{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:"Verification:"})," ",Ol(I==null?void 0:I.lastVerification)]}),t.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."})]})})(),t.jsx("div",{className:"flex flex-col gap-2",children:D.schema.map(I=>t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("div",{className:"text-xs font-medium text-text-primary",children:[I.label||I.key,c===`${D.type}.${I.key}`&&t.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:"saving..."})]}),I.description&&t.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:I.description})]}),t.jsx("div",{className:"shrink-0",children:I.type==="boolean"?t.jsx("button",{onClick:()=>k(D.type,I.key,!(D.values[I.key]??I.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:D.values[I.key]??I.default?"#8b5cf6":"var(--border-subtle)"},children:t.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:D.values[I.key]??I.default?21:3}})}):I.type==="number"?t.jsx("input",{type:"number",value:Number(D.values[I.key]??I.default??0)||0,min:I.min,max:I.max,onChange:T=>{const K=parseInt(T.target.value)||0;I.min!==void 0&&K<I.min||I.max!==void 0&&K>I.max||k(D.type,I.key,K)},className:"machine-input w-20 text-center text-[11px]"}):I.type==="select"&&I.options?t.jsx("select",{value:String(D.values[I.key]??I.default??""),onChange:T=>k(D.type,I.key,T.target.value),className:"machine-input text-[11px]",children:I.options.map(T=>t.jsx("option",{value:T,children:T},T))}):t.jsx("input",{type:"text",value:String(D.values[I.key]??I.default??""),onBlur:T=>k(D.type,I.key,T.target.value),className:"machine-input w-[120px] text-[11px]"})})]},I.key))})]},D.type))}),h&&t.jsx(A0,{machineId:e,provider:h,sendDaemonCommand:r,onClose:()=>g(null)}),j&&t.jsx(M0,{machineId:e,providers:s,sendDaemonCommand:r,onClose:()=>f(!1),onCreated:()=>{f(!1),w()}})]})}const P0=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function D0({count:e,since:s,category:r}){return{count:e,since:s,...r==="all"?{}:{category:r}}}function E0(e,s){return s==="all"?e:e.filter(r=>r.category===s)}function $0(e){return e.trim().toLowerCase()}function qn(e,s){const r=$0(s);return r?e.some(n=>String(n??"").toLowerCase().includes(r)):!0}function oi(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function Ys(e,s=220){const r=oi(e);return r?r.length>s?`${r.slice(0,s)}…`:r:""}function B0(e){const s=e&&typeof e=="object"&&"logs"in e?e.logs:e;if(Array.isArray(s))return{kind:s.length>0?"structured":"empty",entries:s.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 s=="string"){const r=s.trim();return{kind:r?"text":"empty",entries:[],rawText:r}}return{kind:"empty",entries:[],rawText:""}}function O0(e,s){return e.filter(r=>qn([r.level,r.message],s))}function Fl(e){return`${e.timestamp}:${e.level}:${e.message}`}function F0(e,s,r=300){if(s.entries.length>0){const n=new Map;for(const l of e.entries)n.set(Fl(l),l);for(const l of s.entries)n.set(Fl(l),l);const a=Array.from(n.values()).sort((l,c)=>l.timestamp-c.timestamp).slice(-r),o=a.reduce((l,c)=>Math.max(l,Number(c.timestamp||0)),e.lastTs);return{entries:a,kind:"structured",rawText:"",lastTs:o}}return s.kind==="text"?e.entries.length>0?e:{entries:[],kind:"text",rawText:s.rawText,lastTs:e.lastTs}:e.entries.length>0||e.rawText?e:{entries:[],kind:"empty",rawText:"",lastTs:e.lastTs}}function K0(e,s,r=120){if(s.length===0)return e;const n=new Map;for(const a of e)n.set(a.id,a);for(const a of s)n.set(a.id,a);return Array.from(n.values()).sort((a,o)=>a.ts-o.ts).slice(-r)}function W0(e,s){return e.split(`
|
|
76
|
-
`).map(r=>r.trimEnd()).filter(Boolean).filter(r=>qn([r],s))}function H0(e,s){return e.filter(r=>qn([r.level,r.category,r.stage,r.interactionId,oi(r.payload)],s))}function U0(e,s){return e.filter(r=>qn([r.kind,r.topic,r.interactionId,oi(r.payload)],s))}function Kl(e){return e==="warn"||e==="error"}function z0({daemonLogs:e,daemonRawLines:s,trace:r,webEvents:n}){return{all:e.length+s.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=>Kl(a.level)).length+r.filter(a=>Kl(a.level)).length}}function V0({daemonLogs:e,daemonRawLines:s,trace:r,webEvents:n}){const a=[];return e.length>0?a.push(["[daemon logs]",...e.map(o=>`${new Date(o.timestamp).toISOString()} ${o.level.toUpperCase()} ${o.message}`)].join(`
|
|
77
|
-
`)):s.length>0&&a.push(["[daemon logs]",...s].join(`
|
|
78
|
-
`)),r.length>0&&a.push(["[trace]",...r.map(o=>`${new Date(o.ts).toISOString()} ${o.level.toUpperCase()} ${o.category}.${o.stage} ${Ys(o.payload,500)}`.trim())].join(`
|
|
79
|
-
`)),n.length>0&&a.push(["[browser events]",...n.map(o=>`${new Date(o.ts).toISOString()} ${o.kind}${o.topic?` topic=${o.topic}`:""} ${Ys(o.payload,500)}`.trim())].join(`
|
|
80
|
-
`)),a.join(`
|
|
81
|
-
|
|
82
|
-
`)}function G0({machineId:e,sendDaemonCommand:s}){const[r,n]=i.useState([]),[a,o]=i.useState("empty"),[l,c]=i.useState(""),[d,m]=i.useState([]),[u,h]=i.useState([]),[g,j]=i.useState(null),[f,p]=i.useState(!0),[b,y]=i.useState("info"),[x,A]=i.useState("all"),[N,v]=i.useState(!0),[C,M]=i.useState(!0),[w,k]=i.useState(""),[F,_]=i.useState(""),[S,H]=i.useState(0),W=i.useRef(0),D=i.useRef(0),I=i.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),T=i.useRef([]),K=i.useCallback(()=>{const ae={entries:[],kind:"empty",rawText:"",lastTs:0};I.current=ae,W.current=0,n([]),c(""),o("empty"),v(!0)},[]),P=i.useCallback(()=>{T.current=[],D.current=0,m([]),M(!0)},[]),$=i.useCallback(ae=>{ae!==b&&(K(),y(ae))},[b,K]),V=i.useCallback(ae=>{A(me=>me===ae?me:ae)},[]),Y=i.useCallback(()=>{K(),P(),h([]),j(null),k(""),_(""),Ks.clear()},[K,P]),ge=i.useCallback(()=>{H(ae=>ae+1)},[]),fe=i.useCallback(async()=>{if(!e)return;const ae=W.current,me=D.current,[je,Ne]=await Promise.allSettled([s(e,"get_logs",{count:200,minLevel:b,since:ae}),s(e,"get_debug_trace",D0({count:120,since:me,category:x}))]);if(je.status==="fulfilled"){const G=je.value,he=(G==null?void 0:G.result)||G,pe=B0(he),ye=F0(I.current,pe,300);I.current=ye,W.current=ye.lastTs,v(!1),k((G==null?void 0:G.success)===!1?String((G==null?void 0:G.error)||"Could not load daemon logs"):""),o(ye.kind),c(ye.rawText),n(ye.entries)}else v(!1),k(je.reason instanceof Error?je.reason.message:"Could not load daemon logs");if(Ne.status==="fulfilled"){const G=Ne.value,he=(G==null?void 0:G.result)||G;if((G==null?void 0:G.success)===!1)_(String((G==null?void 0:G.error)||"Could not load daemon trace"));else if(Array.isArray(he==null?void 0:he.trace)){const pe=he.trace,ye=K0(T.current,pe,120),xe=pe.reduce((Se,R)=>Math.max(Se,Number(R.ts||0)),me);T.current=ye,xe>me&&(D.current=xe),_(""),m(ye)}else _("");M(!1)}else M(!1),_(Ne.reason instanceof Error?Ne.reason.message:"Could not load daemon trace");h(Ks.list({limit:120})),j(Date.now())},[b,e,s,x]);return i.useEffect(()=>{P()},[P,x]),i.useEffect(()=>{if(!e||(fe(),!f))return;const ae=setInterval(()=>{fe()},3e3);return()=>clearInterval(ae)},[f,fe,e,S]),{daemonLogs:r,daemonLogKind:a,daemonRawText:l,debugTrace:d,webEvents:u,lastUpdatedAt:g,autoRefresh:f,logLevel:b,traceCategory:x,daemonLoading:N,traceLoading:C,daemonFetchError:w,traceFetchError:F,setAutoRefresh:p,setLogLevel:$,setTraceCategory:V,refresh:ge,clear:Y}}function q0({daemonLoading:e,traceLoading:s,daemonFetchError:r,traceFetchError:n,daemonLogKind:a,daemonLogsCount:o,daemonRawLineCount:l,traceCount:c,webEventCount:d}){return[{id:"daemon_logs",label:"Daemon logs",status:r?"error":e?"loading":o>0||l>0?"ok":"empty",detail:r||(a==="text"?`${l} raw file-fallback line(s)`:`${o} structured line(s)`)},{id:"daemon_trace",label:"Daemon trace",status:n?"error":s?"loading":c>0?"ok":"empty",detail:n||`${c} 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 Wl(e){return e==="warn"||e==="error"}function Y0(e){const s=e.toLowerCase();return/\[(err|error)\]/i.test(e)||s.includes(" error ")||s.includes(" failed")?"error":/\[(wrn|warn|warning)\]/i.test(e)||s.includes(" warning ")||s.includes(" timeout")?"warn":/\[(dbg|debug)\]/i.test(e)?"debug":"info"}function X0(e,s){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+s}function Hl(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function J0(e){const s=Ys(e.payload,320);return s?`${e.category}.${e.stage} ${s}`:`${e.category}.${e.stage}`}function Q0(e){const s=Ys(e.payload,320),r=e.topic?` topic=${e.topic}`:"";return s?`${e.kind}${r} ${s}`:`${e.kind}${r}`}function Z0({daemonLogs:e,daemonRawLines:s,trace:r,webEvents:n}){const a=[];return e.forEach((o,l)=>{a.push({id:`daemon-log-${o.timestamp}-${l}`,source:"daemon_log",ts:Number(o.timestamp||0),severity:o.level,message:o.message,raw:o.message})}),n.forEach(o=>{a.push({id:`browser-event-${o.id}`,source:"browser_event",ts:Number(o.ts||0),severity:"info",message:Q0(o),topic:o.topic,interactionId:o.interactionId,payload:o.payload})}),r.forEach(o=>{a.push({id:`daemon-trace-${o.id}`,source:"daemon_trace",ts:Number(o.ts||0),severity:o.level,message:J0(o),category:o.category,stage:o.stage,interactionId:o.interactionId,payload:o.payload})}),s.forEach((o,l)=>{a.push({id:`raw-file-${l}`,source:"raw_file",ts:X0(o,l),severity:Y0(o),message:o,raw:o})}),a.sort((o,l)=>o.ts!==l.ts?o.ts-l.ts:Hl(o.source)-Hl(l.source))}function ev(e){return`${e.source}:${e.severity}:${e.message}`}function tv(e){const s=e.filter(n=>Wl(n.severity)).sort((n,a)=>a.ts-n.ts),r=new Map;for(const n of e){if(!Wl(n.severity))continue;const a=ev(n),o=r.get(a);o?(o.count+=1,o.firstTs=Math.min(o.firstTs,n.ts),o.lastTs=Math.max(o.lastTs,n.ts)):r.set(a,{key:a,source:n.source,severity:n.severity,message:n.message,count:1,firstTs:n.ts,lastTs:n.ts})}return{totalCount:e.length,issueCount:s.length,latestIssue:s[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 sv(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function Ul(e){const s=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",r=e.interactionId?` ix=${e.interactionId}`:"";return`${sv(e.ts)} ${e.severity.toUpperCase()} ${e.source}${s}${r} ${e.message}`.trim()}function rv({events:e,summary:s,sources:r,maxTimelineEvents:n=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${s.totalCount}`,`issue_events: ${s.issueCount}`].join(`
|
|
83
|
-
`)),a.push(["[source status]",...r.map(l=>`${l.label}: ${l.status} - ${l.detail}`)].join(`
|
|
84
|
-
`)),s.latestIssue&&a.push(["[latest issue]",Ul(s.latestIssue)].join(`
|
|
85
|
-
`)),s.repeatedPatterns.length>0&&a.push(["[top repeated patterns]",...s.repeatedPatterns.map(l=>`${l.count}x ${l.severity.toUpperCase()} ${l.source} ${l.message}`)].join(`
|
|
86
|
-
`));const o=e.slice(-n);return a.push(["[timeline]",...o.length>0?o.map(Ul):["No diagnostic events captured."]].join(`
|
|
87
|
-
`)),a.join(`
|
|
88
|
-
|
|
89
|
-
`)}function nv(e,s){return s==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):s==="info"?e.filter(r=>r.level!=="debug"):e}function av(e,s){return s==="issues"?e.filter(r=>r.level==="warn"||r.level==="error"):s==="info"?e.filter(r=>r.level!=="debug"):e}function ov({daemonLogs:e,daemonRawText:s,daemonLogKind:r,debugTrace:n,webEvents:a,traceCategory:o,quickFilter:l,searchQuery:c,daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:h}){const g=E0(n,o),j=O0(e,c),f=W0(s,c),p=H0(g,c),b=U0(a,c),y=nv(j,l),x=l==="all"?f:[],A=av(p,l),N=l==="issues"?[]:b,v=z0({daemonLogs:j,daemonRawLines:f,trace:p,webEvents:b}),C=Z0({daemonLogs:y,daemonRawLines:x,trace:A,webEvents:N}),M=tv(C),w=q0({daemonLoading:d,traceLoading:m,daemonFetchError:u,traceFetchError:h,daemonLogKind:r,daemonLogsCount:j.length,daemonRawLineCount:f.length,traceCount:p.length,webEventCount:b.length});return{filteredDaemonLogs:j,filteredDaemonRawLines:f,filteredTraceEntries:p,filteredWebEvents:b,visibleDaemonLogs:y,visibleDaemonRawLines:x,visibleTraceEntries:A,visibleWebEvents:N,quickFilterCounts:v,diagnosticEvents:C,diagnosticsSummary:M,sourceStates:w}}function iv(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function fu(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function xo(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 $a(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 ii(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function lv({event:e}){return t.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${xo(e.severity)}`,children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[t.jsx("span",{children:fu(e.ts)}),t.jsx("span",{children:e.severity.toUpperCase()}),t.jsx("span",{children:ii(e.source)}),e.category&&e.stage&&t.jsxs("span",{children:[e.category,".",e.stage]}),e.topic&&t.jsxs("span",{children:["topic=",e.topic]}),e.interactionId&&t.jsxs("span",{children:["ix=",e.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:e.message})]})}function cv({quickFilter:e,quickFilterCounts:s,searchQuery:r,autoRefresh:n,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:l,onCopyVisible:c,onToggleAutoRefresh:d,onRefresh:m,onClear:u}){return t.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),t.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${s.info})`},{id:"issues",label:`Issues (${s.issues})`},{id:"all",label:`All (${s.all})`}].map(h=>t.jsx("button",{type:"button",onClick:()=>a(h.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===h.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:h.label},h.id))}),t.jsx("input",{value:r,onChange:h=>o(h.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{onClick:l,className:"machine-btn",children:"Copy diagnostics"}),t.jsx("button",{onClick:c,className:"machine-btn",children:"Copy visible"}),t.jsx("button",{onClick:d,className:`machine-btn ${n?"text-green-500 border-green-500/30":""}`,children:n?"⏸ Pause":"▶ Resume"}),t.jsx("button",{onClick:m,className:"machine-btn",children:"↻ Refresh"}),t.jsx("button",{onClick:u,className:"machine-btn",children:"Clear"})]})]})}function dv({logLevel:e,traceCategory:s,onLogLevelChange:r,onTraceCategoryChange:n}){return t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary p-3",children:t.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("span",{className:"text-[10px] uppercase tracking-wider text-text-muted font-semibold",children:"Advanced source scope"}),["debug","info","warn","error"].map(a=>t.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))]}),t.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:P0.map(a=>t.jsx("button",{onClick:()=>n(a.value),className:`machine-btn text-[10px] px-2 py-0.5 ${s===a.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:a.label},a.value))})]})})}function uv({diagnosticsSummary:e,diagnosticEventsCount:s,sourceStates:r,searchQuery:n,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:l,traceFetchError:c}){var u,h;const d=((u=e.latestIssue)==null?void 0:u.severity)==="error"?"danger":((h=e.latestIssue)==null?void 0:h.severity)==="warn"?"warning":"good",m=l||c?"danger":o?"good":"neutral";return t.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[t.jsxs("div",{className:`rounded-xl border p-3 ${$a(e.issueCount>0?"warning":"good")}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Diagnostics timeline"}),t.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[s," visible event(s) · ",e.issueCount," issue signal(s)"]}),t.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"})]}),t.jsxs("div",{className:`rounded-xl border p-3 ${$a(d)}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[ii(e.latestIssue.source)," · ",e.latestIssue.severity.toUpperCase()]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:e.latestIssue.message}),t.jsx("div",{className:"text-[10px] text-text-muted mt-2",children:fu(e.latestIssue.ts)})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No visible warn/error signal"}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use Issues or All if you need a narrower or rawer view."})]})]}),t.jsxs("div",{className:`rounded-xl border p-3 ${$a(m)}`,children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Source status"}),t.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:l||c?"Needs attention":o?"Live polling every 3s":"Paused"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",iv(a)]}),t.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:r.map(g=>t.jsxs("div",{children:[g.label,": ",g.status]},g.id))})]})]})}function mv({patterns:e}){return e.length===0?null:t.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/[0.04] p-3",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Repeated issue patterns"}),t.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:e.map(s=>t.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-primary px-3 py-2",children:[t.jsxs("div",{className:"text-[12px] text-text-primary font-medium",children:[s.count,"× ",s.severity.toUpperCase()," · ",ii(s.source)]}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:s.message})]},s.key))})]})}function pv({streams:e,sectionsOpen:s,setSectionsOpen:r,diagnosticEvents:n,visibleDaemonLogs:a,visibleDaemonRawLines:o,visibleTraceEntries:l,visibleWebEvents:c,quickFilter:d,searchQuery:m}){return t.jsxs("div",{className:"grid gap-3",children:[t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.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:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[n.length," visible diagnostic event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:s.timeline?"Hide":"Show"})]}),s.timeline&&t.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&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&n.length===0&&t.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&t.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&t.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&n.length===0&&!e.daemonFetchError&&!e.traceFetchError&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),n.map(u=>t.jsx(lv,{event:u},u.id))]})]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.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:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),t.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${o.length} visible raw line(s) from file fallback`:`${a.length} visible structured line(s)`})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:s.daemon?"Hide":"Show"})]}),s.daemon&&t.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.daemonLoading&&a.length===0&&o.length===0&&!e.daemonFetchError&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&t.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&o.length===0&&e.daemonRawText&&t.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&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&o.map((u,h)=>t.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:u},`raw-${h}`)),e.daemonLogKind!=="text"&&a.map((u,h)=>t.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${xo(u.level)}`,children:[t.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(u.timestamp).toLocaleTimeString()}),t.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"}),t.jsx("span",{className:"break-words",children:u.message})]},`log-${h}`))]})]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.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:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[l.length," visible trace event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:s.trace?"Hide":"Show"})]}),s.trace&&t.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&&l.length===0&&!e.traceFetchError&&t.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&l.length===0&&t.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&l.length===0&&!e.traceFetchError&&t.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."}),l.map(u=>t.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${xo(u.level)}`,children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[t.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),t.jsx("span",{children:u.level.toUpperCase()}),t.jsxs("span",{children:[u.category,".",u.stage]}),u.interactionId&&t.jsxs("span",{children:["ix=",u.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Ys(u.payload,360)||"No payload"})]},u.id))]})]}),t.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[t.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:[t.jsxs("div",{children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[c.length," visible browser event(s)"]})]}),t.jsx("div",{className:"text-[11px] text-text-muted",children:s.web?"Hide":"Show"})]}),s.web&&t.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:[c.length===0&&t.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."}),c.map(u=>t.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[t.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[t.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),t.jsx("span",{children:u.kind}),u.topic&&t.jsxs("span",{children:["topic=",u.topic]}),u.interactionId&&t.jsxs("span",{children:["ix=",u.interactionId]})]}),t.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:Ys(u.payload,360)||"No payload"})]},u.id))]})]})]})}function fv({machineId:e,sendDaemonCommand:s}){const r=G0({machineId:e,sendDaemonCommand:s}),[n,a]=i.useState("info"),[o,l]=i.useState(""),[c,d]=i.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),m=i.useRef(null),u=i.useRef(!1),h=i.useMemo(()=>ov({daemonLogs:r.daemonLogs,daemonRawText:r.daemonRawText,daemonLogKind:r.daemonLogKind,debugTrace:r.debugTrace,webEvents:r.webEvents,traceCategory:r.traceCategory,quickFilter:n,searchQuery:o,daemonLoading:r.daemonLoading,traceLoading:r.traceLoading,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),[n,o,r.daemonFetchError,r.daemonLoading,r.daemonLogKind,r.daemonLogs,r.daemonRawText,r.debugTrace,r.traceCategory,r.traceFetchError,r.traceLoading,r.webEvents]);i.useEffect(()=>{if(r.autoRefresh&&h.diagnosticEvents.length>0){const f=u.current?"smooth":"instant";setTimeout(()=>{var p;(p=m.current)==null||p.scrollIntoView({behavior:f}),u.current=!0},50)}},[h.diagnosticEvents.length,r.autoRefresh]);const g=i.useCallback(async()=>{var p;const f=V0({daemonLogs:h.visibleDaemonLogs,daemonRawLines:h.visibleDaemonRawLines,trace:h.visibleTraceEntries,webEvents:h.visibleWebEvents});if(!f.trim()){ot.showToast("No visible logs to copy.","info");return}try{await((p=navigator.clipboard)==null?void 0:p.writeText(f)),ot.showToast("Copied visible logs to clipboard.","success")}catch(b){ot.showToast(b instanceof Error?b.message:"Could not copy visible logs","warning")}},[h.visibleDaemonLogs,h.visibleDaemonRawLines,h.visibleTraceEntries,h.visibleWebEvents]),j=i.useCallback(async()=>{var p;const f=rv({events:h.diagnosticEvents,summary:h.diagnosticsSummary,sources:h.sourceStates});try{await((p=navigator.clipboard)==null?void 0:p.writeText(f)),ot.showToast("Copied diagnostic bundle to clipboard.","success")}catch(b){ot.showToast(b instanceof Error?b.message:"Could not copy diagnostic bundle","warning")}},[h.diagnosticEvents,h.diagnosticsSummary,h.sourceStates]);return t.jsxs("div",{className:"space-y-4",children:[t.jsx(cv,{quickFilter:n,quickFilterCounts:h.quickFilterCounts,searchQuery:o,autoRefresh:r.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:l,onCopyDiagnostics:()=>{j()},onCopyVisible:()=>{g()},onToggleAutoRefresh:()=>r.setAutoRefresh(f=>!f),onRefresh:r.refresh,onClear:r.clear}),t.jsx(dv,{logLevel:r.logLevel,traceCategory:r.traceCategory,onLogLevelChange:r.setLogLevel,onTraceCategoryChange:r.setTraceCategory}),t.jsx(uv,{diagnosticsSummary:h.diagnosticsSummary,diagnosticEventsCount:h.diagnosticEvents.length,sourceStates:h.sourceStates,searchQuery:o,lastUpdatedAt:r.lastUpdatedAt,autoRefresh:r.autoRefresh,daemonFetchError:r.daemonFetchError,traceFetchError:r.traceFetchError}),t.jsx(mv,{patterns:h.diagnosticsSummary.repeatedPatterns}),t.jsx(pv,{streams:r,sectionsOpen:c,setSectionsOpen:d,diagnosticEvents:h.diagnosticEvents,visibleDaemonLogs:h.visibleDaemonLogs,visibleDaemonRawLines:h.visibleDaemonRawLines,visibleTraceEntries:h.visibleTraceEntries,visibleWebEvents:h.visibleWebEvents,quickFilter:n,searchQuery:o}),t.jsx("div",{ref:m})]})}function hv(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 hu(e){const s=typeof(e==null?void 0:e.runtimeRecoveryState)=="string"?String(e.runtimeRecoveryState).trim():"";return s?s==="auto_resumed"?"restored after restart":s==="resume_failed"?"restore failed":s==="host_restart_interrupted"?"host restart interrupted":s==="orphan_snapshot"?"snapshot recovered":s.replace(/_/g," "):null}function xv(e){var a;const s=[],r=[],n=[];for(const o of e||[]){const l=String((o==null?void 0:o.lifecycle)||"").trim(),c=hu((o==null?void 0:o.meta)||void 0),d=((a=o==null?void 0:o.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(l)?s.push(o):(l==="stopped"||l==="failed")&&(d||c)?r.push(o):n.push(o)}return{liveRuntimes:s,recoverySnapshots:r,inactiveRecords:n}}function bv(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Ba(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 Oa(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Fa(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function zl(e){if(!e)return"unknown";const s=Date.now()-e,r=Math.max(0,Math.round(s/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 gv(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function yv(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 vv(e){var r;const s=new Map;for(const n of e){if(!["starting","running","stopping","interrupted"].includes(n.lifecycle))continue;const a=typeof((r=n.meta)==null?void 0:r.providerSessionId)=="string"?String(n.meta.providerSessionId).trim():"";if(!a)continue;const o=`${n.providerType}::${n.workspace}::${a}`;s.set(o,(s.get(o)||0)+1)}return Array.from(s.values()).filter(n=>n>1).length}function wv({machineId:e,cliSessions:s,sendDaemonCommand:r}){const[n,a]=i.useState(""),[o,l]=i.useState(null),[c,d]=i.useState(!1),m=ob(e,{enabled:!!e,includeSessions:!0,limit:Ki,intervalMs:sh}),u=m.diagnostics,h=m.loading,g=m.applyDiagnostics,j=i.useMemo(()=>hv({diagnostics:u,loading:h,refreshing:c,error:n}),[u,h,c,n]),f=i.useMemo(()=>new Map(s.map(_=>[_.sessionId||_.id,_])),[s]),p=i.useCallback(async()=>{if(e){d(!0);try{const _=await r(e,"session_host_get_diagnostics",{includeSessions:!0,limit:Ki}),S=Oa(_);if(!(S!=null&&S.success))throw new Error((S==null?void 0:S.error)||"Could not load hosted runtime diagnostics");g(S.diagnostics||S.result||null),a("")}catch(_){const S=_ instanceof Error?_.message:"Could not load hosted runtime diagnostics";a(S)}finally{d(!1)}}},[g,e,r]);i.useEffect(()=>{!e||u||h||c||p()},[u,h,e,p,c]);const b=i.useCallback(async(_,S)=>{const H=`${_}:${S.sessionId}`;if(!(_==="session_host_stop_session"&&!window.confirm(`Stop ${S.displayName}?
|
|
90
|
-
This will terminate the hosted runtime.`))){l(H);try{const W=await r(e,_,{sessionId:S.sessionId}),D=Oa(W);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||"Session host action failed");const I=_==="session_host_resume_session"?"resumed":_==="session_host_restart_session"?"restarted":"stopped";ot.showToast(`Session host ${I}: ${S.displayName}`,"success"),await p()}catch(W){const D=W instanceof Error?W.message:"Session host action failed";ot.showToast(D,"warning"),a(D)}finally{l(W=>W===H?null:W)}}},[e,p,r]),y=i.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
|
|
91
|
-
The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){l("session_host_prune_duplicate_sessions");try{const S=await r(e,"session_host_prune_duplicate_sessions",{}),H=Oa(S);if(!(H!=null&&H.success))throw new Error((H==null?void 0:H.error)||"Duplicate prune failed");const W=H.result||{},D=Array.isArray(W.prunedSessionIds)?W.prunedSessionIds.length:0,I=typeof W.duplicateGroupCount=="number"?W.duplicateGroupCount:0;ot.showToast(`Pruned ${D} duplicate runtime(s) across ${I} group(s)`,"success"),await p()}catch(S){const H=S instanceof Error?S.message:"Duplicate prune failed";ot.showToast(H,"warning"),a(H)}finally{l(S=>S==="session_host_prune_duplicate_sessions"?null:S)}}},[e,p,r]),x=i.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((_,S)=>(S.lastActivityAt||0)-(_.lastActivityAt||0)),[u==null?void 0:u.sessions]),A=i.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:xv(x),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,x]),N=A.liveRuntimes,v=A.recoverySnapshots,C=A.inactiveRecords,M=i.useMemo(()=>vv(N),[N]),w=i.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),k=i.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(_=>_.level==="warn"||_.level==="error")||null,[u==null?void 0:u.recentLogs]),F=(_,S)=>{var V;const H=o===`session_host_resume_session:${_.sessionId}`,W=o===`session_host_restart_session:${_.sessionId}`,D=o===`session_host_stop_session:${_.sessionId}`,I=hu(_.meta),T=f.get(_.sessionId),K=_.attachedClients.length===1?"1 client":`${_.attachedClients.length} clients`,P=S==="recovery"?"Recover":"Resume",$=bv(S);return t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:_.displayName||(T==null?void 0:T.cliName)||_.providerType}),t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${yv(_.lifecycle)}`,children:_.lifecycle}),I&&t.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:I})]}),t.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:"text-text-primary/90",children:_.workspaceLabel||(T==null?void 0:T.runtimeWorkspaceLabel)||_.workspace||"No workspace"}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsx("span",{className:"font-mono text-text-primary",children:_.runtimeKey}),_.osPid?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/90",children:["pid ",_.osPid]})]}):null]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[t.jsx("span",{className:((V=_.writeOwner)==null?void 0:V.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:gv(_.writeOwner)}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[t.jsx(ac,{size:11})," ",K]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-text-primary/85",children:["active ",zl(_.lastActivityAt)]}),t.jsx("span",{className:"text-text-muted",children:"·"}),t.jsxs("span",{className:"text-sky-200",children:["Next: ",$]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[S==="recovery"&&(_.lifecycle==="interrupted"||_.lifecycle==="failed"||_.lifecycle==="stopped")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{b("session_host_resume_session",_)},children:H?`${P}ing…`:P}),t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{b("session_host_restart_session",_)},children:W?"Restarting…":"Restart"}),S==="live"&&(_.lifecycle==="running"||_.lifecycle==="starting"||_.lifecycle==="interrupted")&&t.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!o,onClick:()=>{b("session_host_stop_session",_)},children:D?"Stopping…":"Stop"})]})]})},_.sessionId)};return t.jsxs("div",{className:"px-5 py-4 rounded-xl mb-5 bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[t.jsx(os,{size:14})," Hosted Runtime Recovery"]}),t.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:ix()})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[M>0&&t.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{y()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${M})`}),t.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${j.toneClass}`,children:j.label}),t.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:h||c,children:[t.jsx(Tr,{size:13}),h||c?"Refreshing…":"Refresh"]})]})]}),n&&!u&&t.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:t.jsxs("div",{className:"flex items-start gap-2",children:[t.jsx(Sr,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),t.jsxs("div",{children:[t.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),t.jsx("div",{className:"text-amber-200/90 mt-1",children:n})]})]})}),u&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.runtimeCount})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:v.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),t.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.recentRequests.length})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[t.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),t.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:zl(u.hostStartedAt)}),t.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Fa(u.hostStartedAt)})]})]}),k&&t.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:[t.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[t.jsx(Sr,{size:13})," Latest host warning"]}),t.jsx("div",{className:"text-text-primary leading-relaxed",children:k.message}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Fa(k.timestamp),k.sessionId?` · ${k.sessionId}`:""]})]}),t.jsxs("div",{className:"mb-4 space-y-4",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[t.jsx(So,{size:14})," Live Hosted Runtimes"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Ba("live")}),N.length===0?t.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."}):t.jsx("div",{className:"space-y-2",children:N.map(_=>F(_,"live"))})]}),t.jsxs("div",{children:[t.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[t.jsx(os,{size:14})," Recovery Snapshots"]}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Ba("recovery")}),v.length===0?t.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."}):t.jsx("div",{className:"space-y-2",children:v.map(_=>F(_,"recovery"))})]}),C.length>0&&t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),t.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Ba("inactive")}),t.jsx("div",{className:"space-y-2 opacity-85",children:C.map(_=>F(_,"inactive"))})]})]}),t.jsxs("div",{children:[t.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),w.length===0?t.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."}):t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:w.map(_=>{var H;const S=x.find(W=>W.sessionId===_.sessionId);return t.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"text-text-primary font-medium",children:(S==null?void 0:S.displayName)||((H=f.get(_.sessionId))==null?void 0:H.cliName)||_.sessionId}),t.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[_.action,_.lifecycle?` · ${_.lifecycle}`:"",_.detail?` · ${_.detail}`:"",_.error?` · ${_.error}`:""]})]}),t.jsx("div",{className:`shrink-0 text-[10px] ${_.success===!1?"text-red-300":"text-text-secondary"}`,children:Fa(_.timestamp)})]},`${_.sessionId}:${_.timestamp}:${_.action}`)})})]}),t.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",t.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),n?t.jsxs("span",{className:"text-amber-200",children:[" · last error: ",n]}):null]})]})]})}function jv({machine:e,launchPick:s,actions:r}){const{runLaunchCliCore:n,setLaunchPick:a}=r;return t.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:t.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:[t.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),t.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."}),t.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?t.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(o=>t.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:s.cliType,workspaceId:o.id,argsStr:s.argsStr,model:s.model})},children:[t.jsx("span",{className:"font-medium text-text-primary block truncate",children:o.label||o.path}),t.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:o.path})]},o.id))}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),n({cliType:s.cliType,useDefaultWorkspace:!0,argsStr:s.argsStr,model:s.model})},children:"Default workspace"}),t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{a(null),n({cliType:s.cliType,useHome:!0,argsStr:s.argsStr,model:s.model})},children:"Home directory"}),t.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>a(null),children:"Cancel"})]})]})})}function Ka({icon:e,children:s}){return t.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,t.jsx("span",{children:s})]})}function Wa({children:e,className:s=""}){return t.jsx("div",{className:`rounded-2xl border border-[#ffffff0a] bg-bg-surface/70 backdrop-blur-sm p-3 ${s}`,children:e})}function kv({machineEntry:e,providers:s,recentLaunches:r,currentConversations:n,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:l}){const c=n.slice(0,6),d=r.slice(0,4),m="0.9.81",u=Ld(e),h=Ds(e,m),g=yr(e,h),j=u==="preview"?"Update to preview":"Update daemon";return t.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:[c.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Ka,{icon:t.jsx(Jt,{size:13}),children:"Current Chats"}),t.jsx(Wa,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:c.map(f=>{const p=mo(f);return t.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:()=>l(f),children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:dt(f)}),p>0&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:En(p)})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:Cs(f)})]},f.tabKey)})})})]}),d.length>0&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Ka,{icon:t.jsx(cc,{size:13}),children:"Recent Launches"}),t.jsx(Wa,{children:t.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(f=>{const{metaText:p,updatedLabel:b}=Hd(f);return t.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-[#ffffff08] border border-transparent hover:border-[#ffffff12] hover:bg-[#ffffff0c] transition-colors cursor-pointer group",onClick:()=>o(f),children:[t.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[t.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:f.label}),b&&t.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:b})]}),t.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:p})]},f.id)})})})]}),e.versionMismatch&&t.jsxs("div",{className:"flex flex-col gap-2",children:[t.jsx(Ka,{icon:t.jsx(Sr,{size:13}),children:"Daemon Update"}),t.jsx(Wa,{className:"border-amber-500/20 bg-amber-500/5",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"text-sm font-semibold text-text-primary",children:g?"Daemon update required":"Version mismatch detected"}),t.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[g?"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.",h&&t.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",h,u?` (${u})`:""]})]}),t.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:[t.jsx(Tr,{size:13}),t.jsx("span",{className:"text-sm font-medium",children:j})]})]})})]})]})}function Nv(e){return e?e.ownerType==="user"?"you control":"agent controls":"view only"}function Sv({machine:e,selectedWorkspace:s,resolvedWorkspacePath:r,customPath:n,canBrowse:a,onWorkspaceChange:o,onCustomPathChange:l,onOpenBrowseDialog:c}){return t.jsxs("div",{className:"mb-3",children:[t.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[t.jsx("select",{value:s,onChange:d=>{const m=d.target.value;if(o(m),m==="__custom__"&&a){c();return}m!=="__custom__"&&l("")},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?t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspace — launch in home)"}),(e.workspaces||[]).map(d=>t.jsxs("option",{value:d.id,children:[d.id===e.defaultWorkspaceId?"⭐ ":"",Bn(d.path,d.label)]},d.id)),t.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]}):t.jsxs(t.Fragment,{children:[t.jsx("option",{value:"",children:"(no workspaces saved — add in Overview tab)"}),t.jsx("option",{value:"__custom__",children:a?"📁 Select workspace…":"✏️ Custom path…"})]})}),s==="__custom__"&&(a?t.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:c,children:"Select workspace…"}):t.jsx("input",{type:"text",placeholder:"Enter absolute path…",value:n,onChange:d=>l(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}))]}),t.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:s==="__custom__"?r?t.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?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"font-medium text-text-secondary",children:s===e.defaultWorkspaceId?"Default workspace":"Selected workspace"}),t.jsx("span",{className:"font-mono truncate block",title:r,children:r})]}):"No workspace selected. This launches in the home directory."})]})}const Cv={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 rn(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Ha({category:e,machine:s,machineId:r,providers:n,managedEntries:a,getIcon:o,actions:l,sendDaemonCommand:c,initialWorkspaceId:d,initialWorkspacePath:m,onOpenGitDialog:u}){const h=cs(),{handleLaunchIde:g,handleStopCli:j,handleRestartIde:f,handleStopIde:p,handleDetectIdes:b,launchingIde:y,launchingAgentType:x,addLog:A}=l,[N,v]=i.useState(null),C=i.useCallback(L=>{L&&h(Vt(L))},[h]),M=Cv[e],w=e==="ide",k=e==="acp",F=i.useMemo(()=>n.filter(L=>Is(L,e)),[e,n]),_=i.useMemo(()=>new Map(F.map(L=>[L.type,L.displayName||L.type])),[F]),[S,H]=i.useState(""),[W,D]=i.useState(""),[I,T]=i.useState([]),[K,P]=i.useState(""),[$,V]=i.useState(""),[Y,ge]=i.useState([]),[fe,ae]=i.useState(!1),[me,je]=i.useState(!1),[Ne,G]=i.useState(""),[he,pe]=i.useState(!1),[ye,xe]=i.useState(()=>Nt()),[Se,R]=i.useState(null),[re,Q]=i.useState(m?"__custom__":d||s.defaultWorkspaceId||""),[ue,ce]=i.useState(m||""),[de,te]=i.useState([]),[E,X]=i.useState(!1),[oe,ee]=i.useState(""),[ke,Ce]=i.useState([]),[ve,O]=i.useState(!1),[Ie,Re]=i.useState(""),Ke=i.useRef(null),[He,Ye]=i.useState(null),Xe=i.useRef("__home__"),[st,mt]=i.useState("__home__"),[ht,yt]=i.useState(!1),Te=i.useRef(0),Ue=de.filter(L=>!a.some(J=>J.type===L&>(J.status)!=="stopped")),et=i.useRef({});i.useEffect(()=>{s.defaultWorkspaceId&&!re&&Q(s.defaultWorkspaceId)},[s.defaultWorkspaceId]),i.useEffect(()=>{if(m){Q("__custom__"),ce(m);return}d&&(Q(d),ce(""))},[d,m]),i.useEffect(()=>{w||S&&(F.some(L=>L.type===S)||(H(""),V("")))},[F,w,S]);const ze=(()=>{if(re==="__custom__")return ue.trim();if(!re)return"";const L=(s.workspaces||[]).find(J=>J.id===re);return(L==null?void 0:L.path)||""})(),at=i.useCallback(L=>{const J=et.current[L];J&&(clearTimeout(J),delete et.current[L]),te(be=>be.includes(L)?be.filter($e=>$e!==L):be)},[]),U=i.useRef(new Set),z=i.useCallback(async L=>{if(c){O(!0),Re("");try{const J=await zn(c,r,L);ee(J.path),ce(J.path),Ce(J.directories)}catch(J){Re(J instanceof Error?J.message:"Could not load folder")}finally{O(!1)}}},[r,c]),Z=i.useCallback(()=>{if(!c)return;Q("__custom__"),X(!0);const L=a.map(be=>be.workspace),J=Un(s.platform,Hn(ue.trim(),ze,m,L,s.defaultWorkspacePath,(s.workspaces||[]).map(be=>be.path)));z(J)},[ue,m,z,s.defaultWorkspacePath,s.platform,s.workspaces,a,ze,c]),ie=i.useCallback(L=>{const J=String(L.workspace||"").trim();if(!J)return;const be=(s.workspaces||[]).find($e=>rn($e.path)===rn(J));if(be){Q(be.id),ce("");return}Q("__custom__"),ce(J)},[s.workspaces]),B=i.useCallback(L=>{const J=String(L.workspace||"").trim();if(!J)return{workspaceId:null,workspacePath:"",useHome:!0};const be=(s.workspaces||[]).find($e=>rn($e.path)===rn(J));return be?{workspaceId:be.id,workspacePath:"",useHome:!1}:{workspaceId:null,workspacePath:J,useHome:!1}},[s.workspaces]),q=i.useCallback(async L=>{if(!c||!L||e!=="cli"){ge([]),ae(!1),je(!1),G("");return}const J=Te.current+1;Te.current=J,ae(!0),G("");try{const be=await c(r,"list_saved_sessions",{providerType:L,kind:"cli",limit:30});if(Te.current!==J)return;const $e=(be==null?void 0:be.result)??be;ge(Array.isArray($e==null?void 0:$e.sessions)?$e.sessions:[])}catch(be){if(Te.current!==J)return;ge([]),G(be instanceof Error?be.message:"Could not load saved sessions")}finally{Te.current===J&&(ae(!1),je(!0))}},[e,r,c]),ne=i.useMemo(()=>{if(e!=="cli"||!S)return null;const L=_.get(S)||S;return{routeId:r,daemonId:r,providerSessionId:$||void 0,transport:"pty",mode:"chat",agentName:L,agentType:S,status:"idle",title:L,messages:[],ideType:S,workspaceName:ze,workspacePath:ze,displayPrimary:L,displaySecondary:"CLI",streamSource:"native",tabKey:`machine:${r}:resume-history:${S}`}},[e,r,_,ze,$,S]),le=i.useCallback(L=>{if(e==="ide"||!L){T([]);return}T(ho(r,L))},[e,r]),we=i.useCallback((L,J)=>{e==="ide"||!L||(vy(r,L,J),T(ho(r,L)))},[e,r]);i.useEffect(()=>{Te.current+=1,V(""),le(S),je(!1),ge([]),G(""),ae(!1)},[e,le,q,S]);const _e=i.useMemo(()=>Y.find(L=>L.providerSessionId===$)||null,[Y,$]);i.useEffect(()=>{if(!$)return;const L=Y.find(J=>J.providerSessionId===$);L!=null&&L.canResume||V("")},[Y,$]);const De=i.useCallback((L,J)=>{Ke.current=J,Xe.current=L.selectedWorkspaceKey||"__home__",mt(L.selectedWorkspaceKey||"__home__"),Ye(L)},[]),Me=i.useCallback(()=>{Ke.current&&(yt(!0),Ke.current().finally(()=>{Ke.current=null,yt(!1),Ye(null)}))},[]),Ee=i.useCallback(L=>{if(!L)return;te(be=>be.includes(L)?be:[...be,L]);const J=et.current[L];J&&clearTimeout(J),et.current[L]=setTimeout(()=>{te(be=>be.includes(L)?be.filter($e=>$e!==L):be),delete et.current[L]},2e4)},[]);i.useEffect(()=>{for(const J of a)gt(J.status)!=="stopped"&&(de.includes(J.type)&&!U.current.has(J.type)&&(U.current.add(J.type),A("info",`${_.get(J.type)||J.type} launched`,!0)),at(J.type));const L=new Set(a.filter(J=>gt(J.status)!=="stopped").map(J=>J.type));U.current.forEach(J=>{!de.includes(J)&&!L.has(J)&&U.current.delete(J)})},[A,at,a,de,_]),i.useEffect(()=>()=>{Object.values(et.current).forEach(clearTimeout),et.current={}},[]);const[Oe,Ae]=i.useState({}),[Je,Ze]=i.useState(null);i.useEffect(()=>{if(!w||!r||!c)return;(async()=>{try{const J=await c(r,"get_ide_extensions",{}),be=(J==null?void 0:J.result)||J;be!=null&&be.success&&(be!=null&&be.ideExtensions)&&Ae(be.ideExtensions)}catch{}})()},[w,r,c]);const xt=L=>w?lt(L.type):e==="cli"?L.cliName:L.acpName,bt=w?s.detectedIdes||[]:[],ct=i.useCallback(async L=>{const J=(L==null?void 0:L.type)||S,be=(L==null?void 0:L.workspacePath)??ze;if(w){await g(J,be?{workspace:be}:void 0)&&Ee(J);return}const $e=await l.runLaunchCliCore({cliType:J,dir:L!=null&&L.workspaceId?void 0:be||void 0,workspaceId:(L==null?void 0:L.workspaceId)||void 0,useHome:(L==null?void 0:L.useHome)||!(L!=null&&L.workspaceId)&&!be,argsStr:(L==null?void 0:L.argsStr)??(W||void 0),model:(L==null?void 0:L.model)??(k&&K||void 0),resumeSessionId:(L==null?void 0:L.resumeSessionId)||!k&&e==="cli"&&J===S&&$||void 0});if($e.success||$e.pending){const Le=(L==null?void 0:L.argsStr)??W;!w&&(Le!=null&&Le.trim())&&(ru(r,J,Le),le(J)),Ee(J),$e.success&&$e.sessionId&&C($e.sessionId)}},[l,g,k,w,W,K,le,Ee,r,C,ze,$,S]),pt=td(w?"ide":k?"acp":"cli",!w&&!k&&!!$),We=sd(w?"ide":k?"acp":"cli",!w&&!k&&!!$),Ot=()=>{var Le;const L=w?lt(S):_.get(S)||S,J=!w&&!k&&!!$,{options:be,selectedKey:$e}=js({machine:s,currentWorkspaceId:re&&re!=="__custom__"?re:null,currentWorkspacePath:ze});De({title:J?Uo(L):bs("start-fresh",L),description:J?zo():gs("start-fresh"),confirmLabel:pt,busyLabel:We,workspaceOptions:be,selectedWorkspaceKey:$e,details:[{label:"Mode",value:M.label},{label:"Provider",value:L},...!w&&e==="cli"&&$?[{label:"Resume",value:((Le=Y.find(Be=>Be.providerSessionId===$))==null?void 0:Le.title)||$}]:[],...!w&&W.trim()?[{label:"Arguments",value:W.trim()}]:[],...k&&K.trim()?[{label:"Model",value:K.trim()}]:[]]},async()=>{const Be=be.find(rt=>rt.key===Xe.current);Be!=null&&Be.workspaceId?(Q(Be.workspaceId),ce("")):Be!=null&&Be.workspacePath?(Q("__custom__"),ce(Be.workspacePath)):(Q(""),ce("")),await ct({workspaceId:(Be==null?void 0:Be.workspaceId)??null,workspacePath:(Be==null?void 0:Be.workspacePath)??"",useHome:!(Be!=null&&Be.workspaceId)&&!(Be!=null&&Be.workspacePath)})})},se=L=>{w?p(L):j(L.type,L.workspace,L.id)},Pe=i.useCallback(async(L,J,be=!1)=>{if(L.mode===J){be&&L.sessionId&&C(L.sessionId);return}if(!c||!L.sessionId){be&&L.sessionId&&C(L.sessionId);return}try{await c(r,"set_cli_view_mode",{targetSessionId:L.sessionId,cliType:L.type,mode:J}),be&&C(L.sessionId)}catch($e){const Le=jd($e);wd($e)?console.warn(Le?"CLI view mode result was lost after send; dashboard open will trust the requested mode:":"Skipped CLI view mode switch:",$e instanceof Error?$e.message:String($e)):console.error("Failed to switch CLI view mode:",$e)}},[r,C,c]);return t.jsxs("div",{children:[t.jsxs("div",{className:`px-5 py-5 rounded-xl mb-6 bg-bg-secondary border ${M.accent} relative overflow-hidden`,children:[t.jsx("div",{className:"absolute top-0 left-0 w-full height-[1px] bg-gradient-to-r from-transparent via-[#ffffff20] to-transparent"}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-4 flex items-center gap-2",children:[t.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-accent-primary/60"}),"Select ",M.label," to Launch"]}),t.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-3",children:w?bt.length>0?bt.map(L=>{const J=a.find(rt=>(rt.type||"").toLowerCase()===(L.type||"").toLowerCase()&>(rt.status)!=="stopped"),be=L.running||!!J,$e=!!J&&J.cdpConnected,Le=de.includes(L.type||L.id||""),Be=S===(L.type||"");return t.jsxs("button",{onClick:()=>{if($e&&J){const rt=J.sessionId;rt?h(Vt(rt),{state:{openRemoteForTabKey:rt}}):h("/dashboard",{state:{openRemoteForTabKey:J.id}});return}Le||H(rt=>rt===(L.type||"")?"":L.type||"")},disabled:!!y||Le,className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${$e?"bg-green-500/10 border-green-500/20 hover:bg-green-500/20":Be?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,style:{opacity:y&&y!==L.type?.4:1},children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:o(L.type)}),be&&t.jsx("span",{className:`absolute -top-1 -right-1 w-2 h-2 rounded-full ${$e?"bg-green-500 shadow-[0_0_6px_rgba(34,197,94,0.6)]":"bg-orange-500 shadow-[0_0_6px_rgba(249,115,22,0.6)] animate-pulse"}`})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:L.name||lt(L.type)}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${$e?"text-green-400":Le?"text-orange-400":Be?"text-accent-primary":"text-text-muted"}`,children:$e?"Open Session":Le?"Starting...":Be?"Configure":"Select"})]})]},L.type)}):t.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.",t.jsxs("button",{onClick:b,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:[t.jsx(Mm,{size:14})," Scan System"]})]}):F.length>0?F.map(L=>{const J=S===L.type,be=de.includes(L.type),Le=!!a.find(Be=>Be.type===L.type&>(Be.status)!=="stopped");return t.jsxs("button",{onClick:()=>H(Be=>Be===L.type?"":L.type),className:`flex flex-col items-center justify-center p-3.5 gap-2 rounded-xl border transition-all cursor-pointer group ${J?"bg-accent-primary/10 border-accent-primary scale-[1.02] shadow-glow":"bg-bg-primary border-[#ffffff1a] hover:bg-[#ffffff0c] hover:border-[#ffffff30]"}`,children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"text-2xl drop-shadow-sm transition-transform group-hover:scale-110 block",children:L.icon}),Le&&t.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)]"})]}),t.jsxs("div",{className:"flex flex-col items-center",children:[t.jsx("span",{className:"text-xs font-semibold text-text-primary text-center",children:L.displayName}),t.jsx("span",{className:`text-[9px] mt-0.5 uppercase tracking-wider font-medium ${be?"text-orange-400":J?"text-accent-primary":"text-text-muted"}`,children:be?"Starting...":J?"Configure":"Select"})]})]},L.type)}):t.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.",t.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."})]})}),S&&(w?bt.find(L=>L.type===S):F.find(L=>L.type===S))&&t.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:[t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center justify-between",children:[t.jsx("span",{children:"Launch Settings"}),t.jsx("span",{className:"text-accent-primary font-bold",children:w?lt(S):_.get(S)||S})]}),t.jsx(Sv,{machine:s,selectedWorkspace:re,resolvedWorkspacePath:ze,customPath:ue,canBrowse:!!c,onWorkspaceChange:Q,onCustomPathChange:ce,onOpenBrowseDialog:Z}),!w&&t.jsxs("div",{className:"flex flex-col gap-3",children:[!k&&e==="cli"&&t.jsx(au,{busy:!!x||!!y||de.includes(S),savedSessionsLoading:fe,savedSessionsError:Ne,savedSessionsLoaded:me,savedSessionsCount:Y.length,selectedSession:_e,onRefresh:()=>void q(S),onOpenHistory:()=>{S&&(pe(!0),nu({hasLoadedInitialResults:me,isLoading:fe})&&q(S))},onClearSelection:()=>V("")}),t.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[k&&t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Target Model"}),t.jsx("input",{type:"text",placeholder:"Leave empty for default",value:K,onChange:L=>P(L.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"})]}),t.jsxs("div",{className:"flex flex-col gap-1.5 flex-1",children:[t.jsx("span",{className:"text-[10px] font-semibold text-text-secondary uppercase",children:"Startup Arguments"}),t.jsx("input",{type:"text",placeholder:"Optional flags...",value:W,onChange:L=>D(L.target.value),className:"px-3 py-2 rounded-md text-sm bg-bg-primary border border-[#ffffff1a] focus:border-accent-primary focus:outline-none transition-colors w-full"}),I.length>0&&t.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:I.map(L=>t.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:L,children:[t.jsx("button",{type:"button",className:"min-w-0 max-w-[220px] truncate px-2.5 py-1.5 text-left",onClick:()=>D(L),children:L}),t.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:()=>we(S,L),"aria-label":`Remove startup arguments: ${L}`,title:"Remove startup arguments",children:t.jsx(vt,{size:12})})]},L))})]})]})]}),t.jsx("div",{className:"flex justify-end mt-2",children:t.jsx("button",{onClick:Ot,disabled:!!x||!!y||de.includes(S),className:"btn btn-primary h-9 px-6 font-bold transition-all flex items-center gap-2 hover:shadow-glow hover:-translate-y-px",children:x===S||y===S?"⏳ Launching...":"▶ Launch"})})]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-2.5",children:["Running (",a.length+de.filter(L=>!a.some(J=>J.type===L&>(J.status)!=="stopped")).length,")"]}),a.length===0&&Ue.length===0?t.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"]}):t.jsxs("div",{className:"flex flex-col gap-2.5 mb-5",children:[Ue.map(L=>t.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:t.jsxs("div",{className:"flex justify-between items-center",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:o(L)}),t.jsxs("div",{children:[t.jsx("div",{className:"font-semibold text-[13px] text-text-primary",children:w?lt(L):_.get(L)||L}),t.jsx("div",{className:"text-[11px] text-text-muted",children:x===L?"Launching process...":"Waiting for process and session to register..."})]})]}),t.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:${L}`)),a.map(L=>{const J=w?L:null,be=!w&&!k?L:null,$e=gt(L.status);return t.jsxs("div",{className:"px-4.5 py-3.5 rounded-xl bg-bg-secondary border border-border-subtle",children:[t.jsxs("div",{className:"flex justify-between items-center mb-2",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:"text-lg",children:o(L.type)}),t.jsxs("div",{children:[t.jsxs("div",{className:"font-semibold text-[13px] text-text-primary",children:[xt(L),(J==null?void 0:J.version)&&t.jsxs("span",{className:"text-[10px] text-text-muted ml-1.5",children:["v",J.version]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted flex min-w-0 flex-wrap items-center gap-2",children:[t.jsx("span",{className:"truncate",children:L.workspace||"—"}),u&&L.git&&L.workspace?t.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:"Open git status",onClick:Le=>{Le.stopPropagation(),u(L.daemonId??r,L.workspace)},children:t.jsx(Vs,{git:L.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):t.jsx(Vs,{git:L.git,compact:!0,className:"max-w-[8rem] shrink-0"}),(be==null?void 0:be.mode)&&t.jsx("span",{className:be.mode==="chat"?"text-violet-400":"text-text-secondary",children:be.mode==="chat"?"Chat view":"Terminal view"})]}),be&&(be.runtimeKey||be.runtimeWriteOwner)&&t.jsxs("div",{className:"text-[10px] text-text-muted flex gap-2 mt-0.5 flex-wrap",children:[be.runtimeKey&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-text-secondary",children:"Local terminal:"}),t.jsxs("span",{className:"font-mono text-text-secondary",children:["adhdev attach ",be.runtimeKey]}),t.jsx("button",{type:"button",className:"flex items-center justify-center px-1.5 py-0.5 rounded text-[9px] bg-[#ffffff0a] hover:bg-[#ffffff14] border border-[#ffffff0a] text-text-muted hover:text-text-primary transition-colors cursor-pointer",onClick:()=>{var Le;(Le=navigator.clipboard)==null||Le.writeText(`adhdev attach ${be.runtimeKey}`),v(be.runtimeKey||null),window.setTimeout(()=>{v(Be=>Be===be.runtimeKey?null:Be)},1200)},children:N===be.runtimeKey?"Copied":"Copy"})]}),be.runtimeWriteOwner&&t.jsx("span",{style:{color:be.runtimeWriteOwner.ownerType==="user"?"var(--status-warning)":void 0},className:be.runtimeWriteOwner.ownerType!=="user"?"text-violet-400":"",children:Nv(be.runtimeWriteOwner)})]})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${$e==="stopped"?"bg-red-500/[0.08] text-red-500":$e==="generating"?"bg-orange-500/[0.08] text-orange-400":"bg-green-500/[0.08] text-green-500"}`,children:$e}),w&&t.jsxs(t.Fragment,{children:[t.jsx("button",{onClick:()=>{const Le=L.sessionId;if(Le){h(Vt(Le),{state:{openRemoteForTabKey:Le}});return}h("/dashboard",{state:{openRemoteForTabKey:L.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:t.jsx(At,{size:13})}),t.jsx("button",{onClick:()=>{const Le=L.workspace||"",{options:Be,selectedKey:rt}=js({machine:s,currentWorkspacePath:Le});De({title:bs("restart-ide",lt(L.type)),description:gs("restart-ide"),confirmLabel:Gs("restart-ide"),busyLabel:qs("restart-ide"),workspaceOptions:Be,selectedWorkspaceKey:rt,details:[{label:"Mode",value:"IDE"},{label:"Provider",value:lt(L.type)}]},async()=>{const It=Be.find(Zt=>Zt.key===Xe.current),ft=(It==null?void 0:It.workspacePath)??"";if(ft&&ft!==Le){await ct({type:L.type,workspacePath:ft});return}await f(L)})},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:t.jsx(Tr,{size:14})})]}),k&&t.jsx("button",{onClick:()=>{const Le=L.sessionId;Le&&C(Le)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"View chat",disabled:!L.sessionId,children:t.jsx(Jt,{size:14})}),be&&$e!=="stopped"&&t.jsxs(t.Fragment,{children:[be.mode&&t.jsx(Ko,{mode:be.mode,onChange:Le=>void Pe(be,Le,!1),compact:!0}),t.jsx("button",{onClick:()=>{const Le=L.sessionId;Le&&C(Le)},className:"flex items-center justify-center w-7 h-7 rounded bg-[#ffffff0a] hover:bg-[#ffffff14] disabled:opacity-50 disabled:cursor-not-allowed text-text-primary transition-colors cursor-pointer",title:"Open current view in dashboard",disabled:!L.sessionId,children:be.mode==="chat"?t.jsx(Jt,{size:14}):t.jsx(At,{size:13})})]}),$e==="stopped"?t.jsx("button",{onClick:()=>{const Le=L.workspace||"",Be=w?lt(L.type):xt(L),{options:rt,selectedKey:It}=js({machine:s,currentWorkspacePath:Le});De({title:bs("restart-stopped",Be),description:gs("restart-stopped"),confirmLabel:Gs("restart-stopped"),busyLabel:qs("restart-stopped"),workspaceOptions:rt,selectedWorkspaceKey:It,details:[{label:"Mode",value:M.label},{label:"Provider",value:Be}]},async()=>{const ft=rt.find(Zt=>Zt.key===Xe.current);await ct({type:L.type,workspaceId:(ft==null?void 0:ft.workspaceId)??null,workspacePath:(ft==null?void 0:ft.workspacePath)??"",useHome:!(ft!=null&&ft.workspaceId)&&!(ft!=null&&ft.workspacePath)})})},disabled:de.includes(L.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:de.includes(L.type)?"⏳":t.jsx(Co,{size:14})}):t.jsx("button",{onClick:()=>se(L),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:t.jsx(vt,{size:14})})]})]}),J&&J.aiAgents.length>0&&t.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:J.aiAgents.map(Le=>t.jsxs("span",{className:`px-2 py-0.5 rounded-md text-[10px] ${jn(Le.status)?"bg-orange-500/[0.08] text-orange-400":"bg-indigo-500/[0.06] text-indigo-400"}`,children:[Le.name," · ",gt(Le.status)]},Le.id))}),J&&(Oe[J.type]||[]).length>0&&c&&t.jsxs("div",{className:"mt-2 pt-2 border-t border-border-subtle",children:[t.jsx("div",{className:"text-[10px] text-text-muted font-semibold uppercase tracking-wider mb-1.5",children:"Extensions"}),t.jsx("div",{className:"flex flex-wrap gap-2",children:(Oe[J.type]||[]).map(Le=>t.jsxs("button",{disabled:Je===`${J.type}.${Le.type}`,onClick:async()=>{const Be=`${J.type}.${Le.type}`;Ze(Be);try{await c(r,"set_ide_extension",{ideType:J.type,extensionType:Le.type,enabled:!Le.enabled}),Ae(rt=>({...rt,[J.type]:(rt[J.type]||[]).map(It=>It.type===Le.type?{...It,enabled:!It.enabled}:It)}))}catch(rt){console.error("Extension toggle failed:",rt)}finally{Ze(null)}},className:`flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-medium border transition-colors duration-150 cursor-pointer ${Le.enabled?"bg-accent-primary/10 border-accent-primary/20 text-accent-primary-light":"bg-bg-glass border-border-subtle text-text-muted"}`,children:[t.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${Le.enabled?"bg-accent-primary shadow-glow":"bg-zinc-600"}`}),Le.name,t.jsx("span",{className:"text-[9px] font-normal",children:Le.enabled?"ON":"OFF"})]},Le.type))})]})]},L.id)})]}),E&&c&&t.jsx(Vn,{title:"Select workspace",description:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",currentPath:oe,directories:ke,busy:ve,error:Ie,confirmLabel:"Use this folder",onClose:()=>X(!1),onNavigate:L=>{z(L)},onConfirm:L=>{ce(L),Q("__custom__"),X(!1)}}),He&&t.jsx(ti,{title:He.title,description:He.description,details:He.details,workspaceOptions:He.workspaceOptions,selectedWorkspaceKey:st,onWorkspaceChange:L=>{Xe.current=L,mt(L)},confirmLabel:He.confirmLabel,busyLabel:He.busyLabel,busy:ht,onConfirm:Me,onCancel:()=>{Ke.current=null,Ye(null)}}),he&&ne&&t.jsx(Vo,{activeConv:ne,ides:[],isCreatingChat:!1,isRefreshingHistory:fe,savedSessions:Y,isSavedSessionsLoading:fe,isResumingSavedSessionId:Se,savedHistoryFilters:ye,missingWorkspaceResumePath:ze||null,onSavedHistoryFiltersChange:xe,onClose:()=>pe(!1),onNewChat:()=>{V(""),pe(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{q(S)},onResumeSavedSession:L=>{if(!L.canResume||Se)return;const J=B(L);V(L.providerSessionId),ie(L),R(L.providerSessionId),pe(!1),ct({type:L.providerType,workspaceId:J.workspaceId,workspacePath:J.workspacePath,useHome:J.useHome,resumeSessionId:L.providerSessionId}).finally(()=>{R(be=>be===L.providerSessionId?null:be)})}})]})}const Vl=[{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 Iv({machine:e,machineId:s,providers:r,ideSessions:n,cliSessions:a,acpSessions:o,actions:l,getIcon:c,initialCategory:d="ide",initialWorkspaceId:m,initialWorkspacePath:u,sendDaemonCommand:h,onOpenGitDialog:g}){var b;const[j,f]=i.useState(d);i.useEffect(()=>{f(d)},[d]);const p=i.useMemo(()=>({ide:n.length,cli:a.length,acp:o.length}),[n.length,a.length,o.length]);return t.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[t.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-[#ffffff0a] mb-4",children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspace Launcher"}),t.jsx("div",{className:"text-sm text-text-secondary",children:"Choose a workspace context first, then pick how you want to open it."})]}),t.jsxs("div",{className:"flex flex-col sm:flex-row items-baseline gap-4 mb-4",children:[t.jsx("div",{className:"flex bg-bg-surface p-1 rounded-lg border border-[#ffffff0a] w-fit",children:Vl.map(y=>t.jsxs("button",{type:"button",className:`flex items-center gap-2 px-4 py-1.5 rounded-md text-sm font-medium transition-all ${j===y.id?"bg-[#ffffff10] text-text-primary shadow-sm":"text-text-secondary hover:text-text-primary hover:bg-[#ffffff05]"}`,onClick:()=>f(y.id),children:[t.jsx("span",{children:y.label}),t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ${j===y.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:p[y.id]})]},y.id))}),t.jsx("div",{className:"text-xs text-text-muted italic",children:(b=Vl.find(y=>y.id===j))==null?void 0:b.helper})]}),j==="ide"&&t.jsx(Ha,{category:"ide",machine:e,machineId:s,providers:r,managedEntries:n,getIcon:c,actions:l,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:g}),j==="cli"&&t.jsx(Ha,{category:"cli",machine:e,machineId:s,providers:r,managedEntries:a,getIcon:c,actions:l,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:g}),j==="acp"&&t.jsx(Ha,{category:"acp",machine:e,machineId:s,providers:r,managedEntries:o,getIcon:c,actions:l,sendDaemonCommand:h,initialWorkspaceId:m,initialWorkspacePath:u,onOpenGitDialog:g})]})}function Tv({onNicknameSynced:e}={}){var ce,de,te,E,X,oe,ee,ke,Ce,ve;const{id:s}=em(),r=cs(),n=vo(),{sendCommand:a}=wt(),o=Lr(),l=xd(),c=Gc(),d=c.ides||[],m=c.initialLoaded??!0,u=d.find(O=>O.id===s&&O.type==="adhdev-daemon"),h=d.some(O=>O.type==="adhdev-daemon"),g=s?(ce=c.connectionRetryStatuses)==null?void 0:ce[s]:void 0,j=!!(g!=null&&g.blocked),[f,p]=i.useState("workspace"),[b,y]=i.useState(null),x=i.useCallback((O,Ie)=>{y({daemonId:O,workspace:Ie})},[]),[A,N]=i.useState("ide"),v=i.useRef(null),[C,M]=i.useState(null),w=i.useRef("__home__"),[k,F]=i.useState("__home__"),[_,S]=i.useState(!1),H=i.useRef(null);i.useEffect(()=>{!s||!u||!(!u.workspaces||!u.availableProviders||!u.detectedIdes||!u.recentLaunches)||o(s,{minFreshMs:3e4}).catch(()=>{})},[o,u,s]),i.useEffect(()=>{if(!s||!u||f!=="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")&&l(s,{minFreshMs:3e4}).catch(()=>{})},[f,l,u,s]),ab(s&&f==="overview"?[s]:[],{enabled:f==="overview",intervalMs:Qf});const W=()=>{if(h){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},D=k0({machineId:s,registeredMachineId:(u==null?void 0:u.machineId)||null,sendDaemonCommand:a,onNicknameSynced:e,logsEndRef:H});i.useEffect(()=>ot.onToast(Ie=>{c.setToasts(Ke=>{if(Ke.some(Xe=>Xe.message===Ie.message&&Ie.timestamp-Xe.timestamp<3e3))return Ke;const Ye={id:Ie.id,message:Ie.message,type:Ie.type,timestamp:Ie.timestamp,targetKey:Ie.targetKey,actions:Ie.actions};return[...Ke.slice(-4),Ye]});const Re=Ie.duration||5e3;setTimeout(()=>c.setToasts(Ke=>Ke.filter(He=>He.id!==Ie.id)),Re)}),[c]);const I=(u==null?void 0:u.availableProviders)||[],T={};for(const O of I)T[O.type]=O.icon;const K=O=>T[O]||"",P=u?{id:u.id,hostname:wc(u,{fallbackId:u.id}),platform:((de=u.machine)==null?void 0:de.platform)||"unknown",arch:((te=u.machine)==null?void 0:te.arch)||"",cpus:((E=u.machine)==null?void 0:E.cpus)||0,totalMem:((X=u.machine)==null?void 0:X.totalMem)||0,freeMem:(oe=u.machine)==null?void 0:oe.freeMem,availableMem:(ee=u.machine)==null?void 0:ee.availableMem,loadavg:(ke=u.machine)==null?void 0:ke.loadavg,uptime:(Ce=u.machine)==null?void 0:Ce.uptime,release:((ve=u.machine)==null?void 0:ve.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===s&&O.type!=="adhdev-daemon").filter(O=>!Cr(O)&&!Bs(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:Hp(O.aiAgents||(O.agents||[]).map(Ie=>({id:Ie.name,name:Ie.name,status:Ie.status,version:Ie.version}))),activeChat:O.activeChat||null,chats:O.chats||[],childSessions:O.childSessions||[],cdpConnected:O.cdpConnected||!1,daemonId:s,lastMessageAt:O.lastMessageAt})),V=d.filter(O=>O.daemonId===s&&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:s,lastMessageAt:O.lastMessageAt})),Y=d.filter(O=>O.daemonId===s&&Bs(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:s,lastMessageAt:O.lastMessageAt})),ge=u?Tt(u,{fallbackId:s}):"",fe="workspace",ae=n.state,me=ae==null?void 0:ae.initialMachineTab,je=ae==null?void 0:ae.initialWorkspaceCategory,Ne=ae==null?void 0:ae.initialWorkspaceId,G=ae==null?void 0:ae.initialWorkspacePath,he=me==="ides"||me==="clis"||me==="acps"?"workspace":me||fe,pe=me==="ides"?"ide":me==="clis"?"cli":me==="acps"?"acp":je,ye=[...$.map(O=>{var Ie;return{id:`ide:${O.type}:${O.workspace||""}`,label:((Ie=O.activeChat)==null?void 0:Ie.title)||O.type,kind:"ide",providerType:O.type,subtitle:O.workspace||void 0,workspace:O.workspace||void 0,lastLaunchedAt:O.lastMessageAt||0}}),...V.map(O=>{var Ie;return{id:`cli:${O.type}:${O.workspace||""}`,label:((Ie=O.activeChat)==null?void 0:Ie.title)||O.cliName,kind:"cli",providerType:O.type,providerSessionId:O.providerSessionId,subtitle:O.workspace||void 0,workspace:O.workspace||void 0,lastLaunchedAt:O.lastMessageAt||0}}),...Y.map(O=>{var Ie;return{id:`acp:${O.type}:${O.workspace||""}`,label:((Ie=O.activeChat)==null?void 0:Ie.title)||O.acpName,kind:"acp",providerType:O.type,providerSessionId:O.providerSessionId,subtitle:Ss(O.summaryMetadata)||O.workspace||void 0,workspace:O.workspace||void 0,lastLaunchedAt:O.lastMessageAt||0}})].sort((O,Ie)=>(Ie.lastLaunchedAt||0)-(O.lastLaunchedAt||0)),xe=((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:Ss(O.summaryMetadata)||O.workspace||void 0,workspace:O.workspace,summaryMetadata:O.summaryMetadata,lastLaunchedAt:O.lastLaunchedAt})):ye,Se=i.useMemo(()=>{var Ie;const O=((Ie=c.connectionStates)==null?void 0:Ie[s||""])||void 0;return d.filter(Re=>Re.daemonId===s&&Re.type!=="adhdev-daemon").flatMap(Re=>Go(Re,{connectionStates:s&&O?{[s]:O}:void 0,defaultConnectionState:O})).filter(Re=>!(Re.transport==="pty"&&Re.mode==="terminal")).sort((Re,Ke)=>mo(Ke)-mo(Re))},[d,c.connectionStates,s]),R=i.useCallback(O=>{const Ie=Ed(O);Ie&&r(Vt(Ie))},[r]),re=i.useCallback(()=>{v.current&&(S(!0),v.current().finally(()=>{v.current=null,S(!1),M(null)}))},[]),Q=i.useCallback(O=>{if(!P)return;const{options:Ie,selectedKey:Re}=js({machine:P,currentWorkspacePath:O.workspace}),Ke=async()=>{N(O.kind),p("workspace")};v.current=async()=>{const He=Ie.find(st=>st.key===w.current),Ye=(He==null?void 0:He.workspacePath)??null,Xe=(He==null?void 0:He.workspaceId)??null;if(O.kind==="ide"&&O.providerType){await D.handleLaunchIde(O.providerType,Ye?{workspace:Ye}:void 0);return}if((O.kind==="cli"||O.kind==="acp")&&O.providerType){await D.runLaunchCliCore({cliType:O.providerType,dir:Xe?void 0:Ye||"",workspaceId:Xe||void 0,model:O.kind==="acp"&&kc(O.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:O.providerSessionId});return}await Ke()},w.current=Re,F(Re),M({title:O.kind==="ide"?bs("restart-ide",O.label):O.providerSessionId?Uo(O.label):bs("start-fresh",O.label),description:O.kind==="ide"?gs("restart-ide"):O.providerSessionId?zo():gs("start-fresh"),confirmLabel:O.kind==="ide"?Gs("restart-ide"):O.providerSessionId?In(!0):Gs("start-fresh"),busyLabel:O.kind==="ide"?qs("restart-ide"):O.providerSessionId?Wo(!0):qs("start-fresh"),workspaceOptions:Ie,details:[{label:"Mode",value:O.kind.toUpperCase()},...O.providerType?[{label:"Provider",value:O.providerType}]:[]]})},[D,P]);if(i.useEffect(()=>{p(he)},[fe,he,s]),i.useEffect(()=>{pe&&N(pe)},[pe,s]),!P)return m?t.jsxs("div",{className:"p-10 text-center text-text-muted",children:[t.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),t.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),t.jsx("button",{onClick:W,className:"machine-btn-back",children:"← Back"})]}):t.jsx("div",{className:"p-10 text-center text-text-muted",children:t.jsx("p",{children:"⏳ Loading machine..."})});const ue=[{id:"workspace",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(At,{size:14})," Workspace"]}),count:$.length+V.length+Y.length},{id:"session-host",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(os,{size:14})," Hosted Runtimes"]})},{id:"providers",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Pn,{size:14})," Providers"]})},{id:"overview",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Rm,{size:14})," System"]})},{id:"logs",label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Tm,{size:14})," Logs"]})}];return t.jsxs("div",{className:"flex flex-col h-full",children:[t.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:[t.jsx("div",{className:"flex items-center justify-between w-full",children:t.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[t.jsx("button",{onClick:W,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:"←"}),t.jsxs("div",{className:"flex flex-col min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[D.editingNickname?t.jsxs("div",{className:"flex gap-1.5 items-center",children:[t.jsx("input",{autoFocus:!0,value:D.nicknameInput,onChange:O=>D.setNicknameInput(O.target.value),onKeyDown:O=>{O.key==="Enter"&&D.handleSaveNickname(),O.key==="Escape"&&D.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),t.jsx("button",{onClick:D.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),t.jsx("button",{onClick:()=>D.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):t.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{D.setEditingNickname(!0),D.setNicknameInput(P.machineNickname||"")},title:"Click to set nickname",children:ge}),j?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),c.retryConnection&&s&&t.jsx("button",{onClick:()=>c.retryConnection(s),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"})]}):t.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"})]}),t.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:[t.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[P.platform," · ",P.arch]}),t.jsxs("span",{children:[P.cpus," cores"]}),(u==null?void 0:u.version)&&t.jsxs("span",{children:["v",u.version]}),P.p2p.available&&t.jsxs("span",{children:["P2P ",P.p2p.state==="connected"?"connected":P.p2p.state]}),P.machineNickname&&t.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:P.hostname})]})]})]})}),t.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ue.map(O=>t.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 ${f===O.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[O.label,O.count!==void 0&&t.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${f===O.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:O.count})]},O.id))})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:t.jsx("div",{className:"max-w-7xl mx-auto h-full",children:t.jsxs("div",{className:"h-full",children:[f==="workspace"&&t.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[t.jsx(kv,{machineEntry:u,providers:I,recentLaunches:xe,currentConversations:Se,onUpgradeDaemon:async()=>{try{await a(s,"daemon_upgrade",Rd(u))}catch{}},onOpenRecent:Q,onOpenConversation:R}),t.jsx(Iv,{machine:P,machineId:s,providers:I,ideSessions:$,cliSessions:V,acpSessions:Y,actions:D,getIcon:K,initialCategory:A,initialWorkspaceId:Ne,initialWorkspacePath:G,sendDaemonCommand:a,onOpenGitDialog:x})]}),f==="providers"&&t.jsx(_0,{machineId:s,providers:I,sendDaemonCommand:a}),f==="overview"&&t.jsx(N0,{machineId:s,machine:P,ideSessions:$,cliSessions:V,acpSessions:Y,actions:D,sendDaemonCommand:a}),f==="session-host"&&t.jsx(wv,{machineId:s,cliSessions:V,sendDaemonCommand:a}),f==="logs"&&t.jsx(fv,{machineId:s,sendDaemonCommand:a})]})})}),D.launchPick&&P&&t.jsx(jv,{machine:P,launchPick:D.launchPick,actions:D}),C&&t.jsx(ti,{title:C.title,description:C.description,details:C.details,workspaceOptions:C.workspaceOptions,selectedWorkspaceKey:k,onWorkspaceChange:O=>{w.current=O,F(O)},confirmLabel:C.confirmLabel,busyLabel:C.busyLabel,busy:_,onConfirm:re,onCancel:()=>{v.current=null,M(null)}}),b&&t.jsx(pu,{daemonId:b.daemonId,workspace:b.workspace,onClose:()=>y(null)}),t.jsx(rd,{toasts:c.toasts||[],onDismiss:O=>c.setToasts(Ie=>Ie.filter(Re=>Re.id!==O)),onClickToast:O=>{O.targetKey&&r(Vt(O.targetKey))}}),t.jsx("style",{children:`
|
|
92
|
-
@keyframes toast-in {
|
|
93
|
-
from { opacity: 0; transform: translateX(40px); }
|
|
94
|
-
to { opacity: 1; transform: translateX(0); }
|
|
95
|
-
}
|
|
96
|
-
`})]})}const nn=[{value:"preserve",label:"Preserve history and runtimes",description:"Keep completed chat history and leave live runtimes alone."},{value:"stop",label:"Stop live runtimes only",description:"Release running session processes, but keep chat records/transcripts."},{value:"delete_stopped",label:"Delete stopped sessions only",description:"Clean completed/stopped chat clutter without killing live runtimes."},{value:"stop_and_delete",label:"Stop and delete sessions",description:"Stop matching runtimes, then remove their session records/transcripts."}],Av={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,sessionCleanupOnNodeRemove:"preserve"};function hn(e){var n;const s=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((n=e.policy)==null?void 0:n.providerPriority)?e.policy.providerPriority:[],r=new Set;return s.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>r.has(a)?!1:(r.add(a),!0))}function Mv(e){const s=hn(e);return s.length?{configured:!0,label:s.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"launch not ready unless an explicit provider is selected"}}function Lv(e,s){return s.filter(r=>r.status!=="assigned"?!1:(r.assignedNodeId||r.nodeId)===e.id)}function Rv(e){const s=e.assignedSessionId||e.sessionId||"unassigned session",r=e.message.length>80?`${e.message.slice(0,77)}…`:e.message;return`${s}: ${r}`}function _v(e,s){return[...Array.isArray(s==null?void 0:s.cliSessions)?s.cliSessions:[],...Array.isArray(s==null?void 0:s.acpSessions)?s.acpSessions:[],...Array.isArray(s==null?void 0:s.sessions)?s.sessions:[]].filter(n=>{var a;return((a=n==null?void 0:n.settings)==null?void 0:a.meshNodeId)===e.id||(n==null?void 0:n.workspace)===e.workspace}).map(n=>{var a;return{id:n.sessionId||n.id||n.instanceId||"unknown",provider:n.providerType||n.cliType||n.acpType||n.type||"unknown",status:n.status||((a=n.activeChat)==null?void 0:a.status)||"unknown"}})}function Ua(e){return{...Av,...(e==null?void 0:e.policy)||{}}}function Pv({meshId:e,availableCliAgents:s}){const r=s.find(a=>{const o=a.id.toLowerCase(),l=a.name.toLowerCase();return o==="hermes-cli"||o.includes("hermes")||l.includes("hermes")}),n=Dd(r==null?void 0:r.meshCoordinator,{meshId:e});return n?t.jsx(jt,{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:t.jsx(ou,{setup:n,providerName:(r==null?void 0:r.name)||"Hermes CLI"})}):null}function Dv(){var te;const{sendCommand:e}=wt(),{ides:s}=ls(),r=cs(),n=s.find(E=>E.daemonMode||E.type==="adhdev-daemon"),a=(n==null?void 0:n.id)||"",o=[];let l=[];if(n){const E=n.availableProviders||[];l=yx(E);for(const X of E)X.category==="cli"&&o.push({id:X.type||X.id,name:X.displayName||X.name||X.type,meshCoordinator:X.meshCoordinator})}const[c,d]=i.useState([]),[m,u]=i.useState(null),[h,g]=i.useState(!0),[j,f]=i.useState(null),[p,b]=i.useState(!1),[y,x]=i.useState(null),[A,N]=i.useState({}),[v,C]=i.useState([]),[M,w]=i.useState(null),[k,F]=i.useState(null),[_,S]=i.useState(!1),[H,W]=i.useState(null),[D,I]=i.useState(null),[T,K]=i.useState(!1),[P,$]=i.useState(""),[V,Y]=i.useState(""),[ge,fe]=i.useState(!1),[ae,me]=i.useState(""),[je,Ne]=i.useState([]),G=c.find(E=>E.id===m)||null,he=i.useCallback(E=>{E&&r(Vt(E),{state:{openRemoteForTabKey:E}})},[r]);i.useEffect(()=>{N(Object.fromEntries(((G==null?void 0:G.nodes)||[]).map(E=>[E.id,hn(E)])))},[G]),i.useEffect(()=>{const E=vx(l);ge&&je.length===0&&E.length>0&&Ne(E)},[ge,l,je.length]),i.useEffect(()=>{const E=new Set(((G==null?void 0:G.nodes)||[]).map(X=>X.id));M&&!E.has(M)&&w(null)},[G,M]);const pe=i.useCallback(async()=>{if(a){g(!0);try{const E=await e(a,"list_meshes");E!=null&&E.success?(d(E.meshes||[]),f(null)):f((E==null?void 0:E.error)||"Failed to load meshes")}catch(E){f((E==null?void 0:E.message)||"Failed to load meshes")}finally{g(!1)}}},[a,e]),ye=i.useCallback(async E=>{if(!a||!E){C([]);return}try{const X=await e(a,"get_mesh_queue",{meshId:E});X!=null&&X.success?C(Array.isArray(X.queue)?X.queue:[]):C([])}catch{C([])}},[a,e]);i.useEffect(()=>{pe()},[pe]),i.useEffect(()=>{ye(m)},[ye,m]);async function xe(){if(!(!a||!m))try{S(!0),W(null);const E=await e(a,"mesh_status",{meshId:m});if(E!=null&&E.success){const X=E.status||E.result||E;if(X&&typeof X=="object"){const oe=lu(X);F(oe)}else W("Invalid mesh_status response format")}else W((E==null?void 0:E.error)||"mesh_status failed")}catch(E){W((E==null?void 0:E.message)||"Failed to load mesh graph")}finally{S(!1)}}i.useEffect(()=>{m&&(F(null),W(null),I(null),xe())},[m]);async function Se(){var E;if(!(!a||!P.trim()))try{const X=await e(a,"create_mesh",{name:P.trim(),repoIdentity:V.trim()||void 0});X!=null&&X.success?(K(!1),$(""),Y(""),await pe(),u(((E=X.mesh)==null?void 0:E.id)||null)):f((X==null?void 0:X.error)||"Create failed")}catch(X){f((X==null?void 0:X.message)||"Create failed")}}async function R(E){if(!(!a||!confirm("Delete this mesh?")))try{await e(a,"delete_mesh",{meshId:E}),u(null),await pe()}catch(X){f((X==null?void 0:X.message)||"Delete failed")}}async function re(){if(!(!a||!m||!ae.trim()))try{const E=await e(a,"add_mesh_node",{meshId:m,workspace:ae.trim(),providerPriority:oo(je,l)});E!=null&&E.success?(fe(!1),me(""),Ne([]),await pe(),await ye(m)):f((E==null?void 0:E.error)||"Add node failed")}catch(E){f((E==null?void 0:E.message)||"Add node failed")}}async function Q(E){var ee;if(!a||!m)return;const X=Ua(G),oe=((ee=nn.find(ke=>ke.value===X.sessionCleanupOnNodeRemove))==null?void 0:ee.label)||"Preserve history and runtimes";if(confirm(`Remove this node?
|
|
97
|
-
|
|
98
|
-
Node removal cleanup policy: ${oe}`))try{await e(a,"remove_mesh_node",{meshId:m,nodeId:E}),M===E&&w(null),await pe(),await ye(m)}catch(ke){f((ke==null?void 0:ke.message)||"Remove node failed")}}async function ue(E){if(!a||!m)return;const X={...Ua(G),...E};try{b(!0),f(null);const oe=await e(a,"update_mesh",{meshId:m,policy:X});if((oe==null?void 0:oe.success)===!1){f(oe.error||"Policy update failed");return}await pe()}catch(oe){f((oe==null?void 0:oe.message)||"Policy update failed")}finally{b(!1)}}async function ce(E){if(!a||!m)return;const X=oo(A[E.id]||hn(E),l),oe={...E.policy||{}};delete oe.provider_priority,X.length?oe.providerPriority=X:delete oe.providerPriority;try{x(E.id),f(null);const ee=await e(a,"update_mesh_node",{meshId:m,nodeId:E.id,policy:oe});if((ee==null?void 0:ee.success)===!1){f(ee.error||"Node policy update failed");return}await pe()}catch(ee){f((ee==null?void 0:ee.message)||"Node policy update failed")}finally{x(null)}}if(!a)return t.jsx(gr,{icon:t.jsx(ns,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:t.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})});if(!G)return t.jsxs(gr,{icon:t.jsx(ns,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",actions:t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>K(!0),children:"+ Create Mesh"}),children:[j&&t.jsx($s,{variant:"error",className:"mb-4",children:j}),T&&t.jsx(jt,{title:"New Mesh",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx(Mt,{label:"Name",children:t.jsx(da,{value:P,onChange:E=>$(E.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),t.jsx(Mt,{label:"Repo Identity (optional)",children:t.jsx(da,{value:V,onChange:E=>Y(E.target.value),placeholder:"github.com/user/repo"})}),t.jsxs("div",{className:"flex gap-2",children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Se,disabled:!P.trim(),children:"Create"}),t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>K(!1),children:"Cancel"})]})]})}),h?t.jsx("div",{className:"text-sm text-text-muted p-4",children:"Loading meshes..."}):c.length===0?t.jsx(Tn,{icon:t.jsx(ns,{}),title:"No meshes",description:"Create a mesh to get started."}):t.jsx("div",{className:"flex flex-col gap-2",children:c.map(E=>t.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:()=>u(E.id),children:[t.jsx("div",{className:"font-semibold text-sm",children:E.name}),t.jsx("div",{className:"text-xs text-text-muted mt-0.5 font-mono",children:E.repoIdentity||"No repo identity"}),t.jsxs("div",{className:"text-[10px] text-text-muted mt-1",children:[E.nodes.length," node(s)"]})]},E.id))})]});const de=Ua(G);return t.jsxs(gr,{icon:t.jsx(ns,{}),title:G.name,subtitle:G.repoIdentity||"Repo Mesh",actions:t.jsxs("div",{className:"flex gap-2",children:[t.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>u(null),children:"← Back"}),t.jsx("button",{className:"btn btn-sm",style:{color:"var(--color-red-400)"},onClick:()=>R(G.id),children:"Delete"})]}),children:[j&&t.jsx($s,{variant:"error",className:"mb-4",children:j}),t.jsxs(jt,{title:"Policy",description:"Coordinator safety defaults and node-removal session cleanup behavior for this local mesh.",children:[t.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[t.jsx(Mt,{label:"Checkpoint before task",children:t.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:de.requirePreTaskCheckpoint?"yes":"no",onChange:E=>ue({requirePreTaskCheckpoint:E.target.value==="yes"}),disabled:p,children:[t.jsx("option",{value:"no",children:"No"}),t.jsx("option",{value:"yes",children:"Yes"})]})}),t.jsx(Mt,{label:"Checkpoint after task",children:t.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:de.requirePostTaskCheckpoint?"yes":"no",onChange:E=>ue({requirePostTaskCheckpoint:E.target.value==="yes"}),disabled:p,children:[t.jsx("option",{value:"yes",children:"Yes"}),t.jsx("option",{value:"no",children:"No"})]})}),t.jsx(Mt,{label:"Push approval",children:t.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:de.requireApprovalForPush?"required":"not_required",onChange:E=>ue({requireApprovalForPush:E.target.value==="required"}),disabled:p,children:[t.jsx("option",{value:"required",children:"Require approval before push"}),t.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),t.jsx(Mt,{label:"Destructive git approval",children:t.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:de.requireApprovalForDestructiveGit?"required":"not_required",onChange:E=>ue({requireApprovalForDestructiveGit:E.target.value==="required"}),disabled:p,children:[t.jsx("option",{value:"required",children:"Require approval"}),t.jsx("option",{value:"not_required",children:"Do not require approval"})]})}),t.jsx(Mt,{label:"Dirty workspace behavior",children:t.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:de.dirtyWorkspaceBehavior||"warn",onChange:E=>ue({dirtyWorkspaceBehavior:E.target.value}),disabled:p,children:[t.jsx("option",{value:"warn",children:"Warn and continue"}),t.jsx("option",{value:"block",children:"Block task"}),t.jsx("option",{value:"checkpoint_then_continue",children:"Checkpoint then continue"})]})}),t.jsx(Mt,{label:"Max parallel tasks",children:t.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:String(de.maxParallelTasks??2),onChange:E=>ue({maxParallelTasks:Number(E.target.value)}),disabled:p,children:[1,2,3,4,5,6,7,8].map(E=>t.jsx("option",{value:E,children:E},E))})})]}),t.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[t.jsx(Mt,{label:"Node removal session cleanup",hint:"Separate transcript cleanup from runtime/process cleanup. Preserve is safest when completed work may need review.",children:t.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:de.sessionCleanupOnNodeRemove||"preserve",onChange:E=>ue({sessionCleanupOnNodeRemove:E.target.value}),disabled:p,children:nn.map(E=>t.jsx("option",{value:E.value,children:E.label},E.value))})}),t.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((te=nn.find(E=>E.value===de.sessionCleanupOnNodeRemove))==null?void 0:te.description)||nn[0].description})]}),p&&t.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:"Saving policy..."})]}),t.jsxs(jt,{title:"Visualization",description:"Live mesh topology: branches, worktrees, sessions, and orphan detection.",children:[t.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-4",children:[t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500"}),"healthy"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx("span",{className:"w-2 h-2 rounded-full bg-amber-500"}),"dirty"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx("span",{className:"w-2 h-2 rounded-full bg-red-500"}),"error"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx("span",{className:"w-2 h-2 rounded-full bg-gray-500"}),"offline"]})]}),t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:xe,disabled:_,children:_?"Loading...":"Refresh Graph"})]}),H&&t.jsx("div",{className:"mb-3 text-[12px] text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:H}),k?t.jsxs("div",{className:"flex gap-4",style:{minHeight:420},children:[t.jsx("div",{className:"flex-1 rounded-xl border border-border-subtle bg-bg-secondary overflow-hidden",style:{minHeight:420},children:t.jsx(du,{data:k,onNodeClick:E=>I(X=>(X==null?void 0:X.id)===E.id?null:E),selectedNodeId:(D==null?void 0:D.id)||null})}),D&&t.jsxs("div",{className:"w-80 shrink-0 flex flex-col gap-3",children:[t.jsx(uu,{node:D,onClose:()=>I(null)}),D.type!=="submoduleNode"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/70 p-3 text-[12px] text-text-muted",children:[t.jsx("div",{className:"mb-2 text-[11px] font-semibold uppercase tracking-wide text-text-secondary",children:"Active sessions"}),D.activeSessions.length===0?t.jsx("div",{children:"No active session ids on this node."}):t.jsx("div",{className:"flex flex-col gap-2",children:D.activeSessions.map(E=>t.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-primary/60 px-3 py-2",children:[t.jsx("div",{className:"font-mono text-[11px] text-text-primary break-all",children:E}),t.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:t.jsx("button",{type:"button",className:"text-[11px] text-accent hover:underline",onClick:()=>he(E),children:"Open chat"})})]},E))})]}),t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/70 p-3 text-[12px] text-text-muted",children:[t.jsx("div",{className:"mb-2 text-[11px] font-semibold uppercase tracking-wide text-text-secondary",children:"Related active queue"}),v.filter(E=>(E.status==="pending"||E.status==="assigned")&&(E.assignedNodeId===D.id||E.targetNodeId===D.id)).length===0?t.jsx("div",{children:"No pending/assigned queue items targeting this node."}):t.jsx("div",{className:"flex flex-col gap-2",children:v.filter(E=>(E.status==="pending"||E.status==="assigned")&&(E.assignedNodeId===D.id||E.targetNodeId===D.id)).map(E=>{const X=E.assignedSessionId||E.targetSessionId||E.sessionId||null;return t.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-primary/60 px-3 py-2",children:[t.jsx("div",{className:"text-text-primary text-[11px] break-words",children:E.message}),t.jsxs("div",{className:"mt-1 font-mono text-[10px] text-text-muted",children:[E.id," · ",E.status]}),X&&t.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:t.jsx("button",{type:"button",className:"text-[11px] text-accent hover:underline",onClick:()=>he(X),children:"Open chat"})})]},E.id)})})]})]})]})]}):t.jsx("div",{className:"text-[12px] text-text-muted rounded-lg border border-border-subtle bg-bg-secondary px-3 py-3",children:_?"Loading graph...":"Refresh the graph to view mesh topology."})]}),t.jsxs(jt,{title:"Nodes",description:"Workspaces participating in this mesh.",children:[t.jsx("div",{className:"flex justify-end mb-3",children:t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>fe(!0),children:"+ Add Node"})}),ge&&t.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass",children:[t.jsxs("div",{className:"flex justify-between items-center mb-3",children:[t.jsx("h4",{className:"text-sm font-bold",children:"Add Node"}),t.jsx("button",{onClick:()=>fe(!1),className:"text-text-muted cursor-pointer bg-transparent border-none",children:t.jsx(vt,{size:16})})]}),t.jsx(Mt,{label:"Workspace Path",children:t.jsx(da,{value:ae,onChange:E=>me(E.target.value),placeholder:"/Users/dev/projects/myapp",autoFocus:!0})}),t.jsx(Mt,{label:"Provider Priority",hint:"Order used when launching without an explicit provider. Empty means fail closed unless a provider is selected explicitly.",children:t.jsx(Qi,{value:je,availableProviders:l,onChange:Ne})}),t.jsxs("div",{className:"flex gap-2 mt-3",children:[t.jsx("button",{onClick:re,disabled:!ae.trim(),className:"btn btn-primary btn-sm",children:"Add"}),t.jsx("button",{onClick:()=>fe(!1),className:"btn btn-secondary btn-sm",children:"Cancel"})]})]}),G.nodes.length===0?t.jsx(Tn,{icon:t.jsx(Ns,{}),title:"No nodes",description:"Add a workspace to this mesh."}):t.jsx("div",{className:"flex flex-col gap-2",children:G.nodes.map(E=>{const X=hn(E),oe=Mv(E),ee=Lv(E,v),ke=_v(E,n),Ce=M===E.id;return t.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary cursor-pointer transition-colors ${Ce?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`,role:"button",tabIndex:0,onClick:()=>w(Ce?null:E.id),onKeyDown:ve=>{(ve.key==="Enter"||ve.key===" ")&&(ve.preventDefault(),w(Ce?null:E.id))},children:[t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("div",{className:"text-sm font-medium",children:E.workspace.split("/").pop()}),ee.length>0&&t.jsxs("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-orange-500/15 text-orange-300 border border-orange-500/25",children:[ee.length," active task",ee.length===1?"":"s"]})]}),t.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:E.workspace}),t.jsx("div",{className:"mt-3 max-w-2xl",onClick:ve=>ve.stopPropagation(),children:t.jsxs(Mt,{label:"Provider priority",hint:"Used when launches omit an explicit provider. Empty keeps fail-closed behavior until a provider is selected manually.",children:[t.jsx(Qi,{value:A[E.id]??X,availableProviders:l,onChange:ve=>N(O=>({...O,[E.id]:ve})),disabled:y===E.id,saveButton:t.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:ve=>{ve.stopPropagation(),ce(E)},disabled:y===E.id,children:y===E.id?"Saving...":"Save policy"})}),t.jsxs("div",{className:"mt-2 text-[12px]",children:[t.jsx("span",{className:"text-text-muted",children:"Effective provider priority: "}),t.jsx("span",{className:oe.configured?"text-text-primary font-mono":"text-amber-400",children:oe.label}),oe.launchBlockedMessage&&t.jsxs("span",{className:"ml-2 text-amber-400",children:["(",oe.launchBlockedMessage,")"]})]})]})})]}),t.jsx("button",{className:"text-text-muted hover:text-red-400 transition-colors bg-transparent border-none cursor-pointer",onClick:ve=>{ve.stopPropagation(),Q(E.id)},children:t.jsx(vt,{size:14})})]}),Ce&&t.jsxs("div",{className:"mt-3 rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-[12px] text-text-muted",children:[t.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[t.jsxs("div",{children:[t.jsx("span",{className:"text-text-secondary",children:"Node ID:"})," ",t.jsx("span",{className:"font-mono",children:E.id})]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-secondary",children:"Launch ready:"})," ",t.jsx("span",{className:oe.configured?"text-green-400":"text-amber-400",children:oe.configured?"yes":"provider priority not configured"})]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-secondary",children:"Repo root:"})," ",t.jsx("span",{className:"font-mono",children:E.repoRoot||E.workspace})]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-secondary",children:"Active sessions:"})," ",ke.length]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-secondary",children:"Branch / git:"})," not loaded in standalone list view"]}),t.jsxs("div",{children:[t.jsx("span",{className:"text-text-secondary",children:"Health:"})," ",ee.length>0||ke.length>0?"active":"idle/unknown"]})]}),t.jsxs("div",{className:"mt-3",children:[t.jsx("div",{className:"text-text-secondary mb-1",children:"Active queue assignments"}),ee.length===0?t.jsx("div",{children:"No active assigned queue task for this node."}):t.jsx("ul",{className:"m-0 pl-4",children:ee.map(ve=>t.jsx("li",{className:"font-mono",children:Rv(ve)},ve.id))})]}),ke.length>0&&t.jsxs("div",{className:"mt-3",children:[t.jsx("div",{className:"text-text-secondary mb-1",children:"Active sessions"}),t.jsx("ul",{className:"m-0 pl-4",children:ke.map(ve=>t.jsxs("li",{className:"font-mono",children:[ve.provider," / ",ve.status," / ",ve.id]},ve.id))})]})]})]},E.id)})})]}),t.jsx(Pv,{meshId:G.id,availableCliAgents:o})]})}function li(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function Ev(e){if(typeof window>"u")return e;const s=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),r=li();return r&&!s.searchParams.has("token")&&s.searchParams.set("token",r),e.startsWith("http://")||e.startsWith("https://")?s.toString():`${s.pathname}${s.search}${s.hash}`}async function Wt(e,s){return await fetch(Ev(e),{credentials:"same-origin",...s})}function xu(){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 $v{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(s){if(this.adapters.has(s))return s;if(s.startsWith("standalone")){for(const r of this.adapters.keys())if(r.startsWith("standalone"))return r}return null}register(s,r){this.adapters.set(s,r),this.states.set(s,r.connectionState)}unregister(s){this.adapters.delete(s),this.states.delete(s)}setState(s,r){this.states.set(s,r)}retryConnection(s){}get(s){const r=this.resolveDaemonId(s);return r?this.adapters.get(r):void 0}getState(s){const r=this.resolveDaemonId(s);return r&&this.states.get(r)||"disconnected"}sendData(s,r){return!1}sendPtyInput(s,r,n){return!1}onScreenshot(s,r){return this.screenshotCallbacks.set(s,r),()=>{this.screenshotCallbacks.delete(s)}}emitScreenshot(s,r){this.screenshotCallbacks.forEach(n=>n(s,r))}onStatus(s){return this.statusCallbacks.add(s),()=>{this.statusCallbacks.delete(s)}}emitStatus(s,r){this.statusCallbacks.forEach(n=>n(s,r))}emitRuntimeSnapshot(s,r,n=0,a=!1,o,l){this.emitRuntimeEvent(s,{type:"runtime_snapshot",sessionId:s,seq:n,text:r,truncated:a,cols:o,rows:l})}emitSessionOutput(s,r,n){!s||typeof r!="string"||!r||this.emitRuntimeEvent(s,{type:"session_output",sessionId:s,...typeof n=="number"?{seq:n}:{},data:r})}onRuntimeEvent(s,r){const n=this.runtimeListeners.get(s)||new Set;return n.add(r),this.runtimeListeners.set(s,n),()=>{const a=this.runtimeListeners.get(s);a&&(a.delete(r),a.size===0&&this.runtimeListeners.delete(s))}}async requestRuntimeSnapshot(s,r,n){if(!r)return{success:!1,error:"sessionId is required"};const a=new URL(`/api/v1/runtime/${encodeURIComponent(r)}/snapshot`,window.location.origin);typeof(n==null?void 0:n.sinceSeq)=="number"&&a.searchParams.set("sinceSeq",String(n.sinceSeq));const o=await Wt(`${a.pathname}${a.search}`);if(!o.ok){let c=`Runtime snapshot unavailable (${o.status})`;try{const d=await o.json();d!=null&&d.error&&(c=d.error)}catch{}return{success:!1,error:c}}const l=await o.json();return this.emitRuntimeEvent(r,{type:"runtime_snapshot",sessionId:r,seq:typeof l.seq=="number"?l.seq:0,text:typeof l.text=="string"?l.text:"",truncated:!!l.truncated,cols:typeof l.cols=="number"?l.cols:void 0,rows:typeof l.rows=="number"?l.rows:void 0,force:!!(n!=null&&n.force)}),{success:!0}}emitRuntimeEvent(s,r){var n;(n=this.runtimeListeners.get(s))==null||n.forEach(a=>a(r))}}const Gt=new $v;function Bv(){if(typeof window>"u")return"ws://localhost:3847/ws";const s=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,r=li();return r?`${s}?token=${encodeURIComponent(r)}`:s}const an=Bv(),Gl=3e3,Ov=3e4;let Et=null,Fv=0;const _n=new Map;let ms=null,jr=null;function ql(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,s)}catch{}}function dr(e,s){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,s)}catch{}}function Kv(e){return e==="connected"?"connected":e}async function xn(e,s,r){const n=id(e,r||{}),a=Et;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++Fv}_${Date.now()}`;return new Promise((l,c)=>{const d=setTimeout(()=>{_n.delete(o),c(new Error(`WS command timeout: ${s}`))},3e4);_n.set(o,{resolve:m=>{clearTimeout(d),l(m)},reject:m=>{clearTimeout(d),c(m)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:s,payload:n.payload}}))})}throw new Error(`WS command channel unavailable: ${s}`)}function bo(e,s){const r=Et;if(!r||r.readyState!==WebSocket.OPEN||!s||s.type!=="subscribe"&&s.type!=="unsubscribe")return!1;try{return r.send(JSON.stringify(s)),!0}catch{return!1}}function Wv(e,s,r){const n=Et;if(!n||n.readyState!==WebSocket.OPEN)return!1;const a=id(e,{sessionId:s,targetSessionId:s,data:r});try{return n.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}class Hv{constructor(s){Qe(this,"daemonId");Qe(this,"screenshotIdeType",null);this.daemonId=s}get hasCommandChannel(){return(Et==null?void 0:Et.readyState)===WebSocket.OPEN}get connectionState(){return(Et==null?void 0:Et.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(s,r){return xn(this.daemonId,s,r)}async sendInput(s,r){return xn(this.daemonId,"cdp_remote_action",{action:s,params:r,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(s){this.screenshotIdeType=s||null,ms&&(clearInterval(ms),ms=null);const r=async()=>{if(this.hasCommandChannel)try{const n=await xn(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(n!=null&&n.success&&(n!=null&&n.base64)){const a=await fetch(`data:image/jpeg;base64,${n.base64}`).then(o=>o.blob());Gt.emitScreenshot(this.daemonId,a)}}catch{}};r(),ms=setInterval(r,2e3)}stopScreenshots(s){ms&&(clearInterval(ms),ms=null)}}let _t=null;function Uv(e){return(!_t||_t.daemonId!==e)&&(_t=new Hv(e)),_t}function zv({children:e}){const s=i.useRef(Nr()),r=Nr();s.current=r;const{setUserName:n}=ls(),a=i.useRef(n);a.current=n;const o=i.useRef(null),l=i.useRef(null),[,c]=i.useState("disconnected"),d=i.useCallback((p,b)=>{c(p),jr==null||jr(p,b)},[]),m=i.useRef(null),u=i.useRef(),h=i.useRef(Gl),g=i.useRef(!0),j=i.useRef(!1),f=i.useRef("initial_connect");return i.useEffect(()=>{g.current=!0,j.current=!1;function p(){var x,A;if(!g.current||((x=m.current)==null?void 0:x.readyState)===WebSocket.OPEN||((A=m.current)==null?void 0:A.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${an}...`),dr("connect_attempt",{url:an,reason:f.current,delayMs:h.current});let y;try{y=new WebSocket(an)}catch(N){console.error("[Standalone WS] Failed to create WebSocket:",N),b();return}m.current=y,y.onopen=()=>{if(!g.current){y.close();return}d("connected"),h.current=Gl,dr("open",{url:an,reason:f.current}),Xt.resubscribeAll({sendData:bo}),console.log("[Standalone WS] Connected")},Et=y,y.onmessage=N=>{var v,C;try{const M=JSON.parse(N.data);if((M.type==="command_result"||M.type==="error")&&M.requestId){const w=_n.get(M.requestId);w&&(_n.delete(M.requestId),M.type==="error"?w.reject(new Error(((v=M.data)==null?void 0:v.message)||"Command failed")):w.resolve(M.data));return}if(M.type==="session_output"){const w=M.sessionId||M.cliId||M.cliType;w&&Gt.emitSessionOutput(w,typeof M.data=="string"?M.data:"",typeof M.seq=="number"?M.seq:void 0);return}if(M.type==="runtime_snapshot"){Gt.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&&Xt.publish(w);return}if(M.type==="status"||M.type==="initial_state"){const w=M.data;if(!w)return;const{injectEntries:k,markLoaded:F,getIdes:_}=s.current,S=w.instanceId||"standalone",H=_().find(I=>I.id===S),W=Uv(S);Gt.register(S,W),Gt.setState(S,"connected"),d("connected",S),Gt.emitStatus(S,w);const D=Cn(w,{daemonId:S,existingDaemon:H,existingEntries:_()});ql("ws_status",{type:M.type,daemonId:S,sessions:(w.sessions||[]).map(I=>({id:I.id,parentId:I.parentId,providerType:I.providerType,kind:I.kind,transport:I.transport,unread:I.unread,inboxBucket:I.inboxBucket,lastSeenAt:I.lastSeenAt,lastUpdated:I.lastUpdated,title:I.title})),recentLaunches:(w.recentLaunches||[]).map(I=>({id:I.id,providerType:I.providerType,kind:I.kind,workspace:I.workspace,lastLaunchedAt:I.lastLaunchedAt}))}),ql("entries",{daemonId:S,entries:D.filter(I=>I.type!=="adhdev-daemon").map(I=>({id:I.id,type:I.type,unread:I.unread,inboxBucket:I.inboxBucket,lastSeenAt:I.lastSeenAt,lastUpdated:I.lastUpdated,sessionId:I.sessionId}))}),D.length>0&&k(D,{authoritativeDaemonIds:[S]}),F(),l.current!==S&&((C=o.current)==null||C.call(o),l.current=S,o.current=Xt.subscribe({sendData:bo},S,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${S}`,params:{includeSessions:!0}},I=>{if(I.topic!=="daemon.metadata")return;const T=s.current.getIdes(),K=T.find($=>$.id===S),P=Cn(I.status,{daemonId:S,existingDaemon:K,existingEntries:T,timestamp:I.timestamp});P.length>0&&s.current.injectEntries(P,{authoritativeDaemonIds:[S]}),I.userName&&a.current&&a.current(I.userName)}))}}catch(M){console.error("[Standalone WS] Parse error:",M)}},y.onclose=N=>{g.current&&(_t==null||_t.stopScreenshots(),_t&&Gt.setState(_t.daemonId,"disconnected"),d("disconnected"),m.current=null,f.current=`close:${N.code}${N.wasClean?":clean":":unclean"}`,dr("close",{code:N.code,reason:N.reason||"",wasClean:N.wasClean}),b())},y.onerror=N=>{j.current||!g.current||(f.current="error",dr("error",{message:N instanceof Event?"event":String(N),readyState:y.readyState}),console.warn("[Standalone WS] Error, will reconnect:",N))}}function b(){if(!g.current)return;clearTimeout(u.current);const y=h.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),dr("schedule_reconnect",{reason:f.current,delayMs:y}),u.current=setTimeout(()=>{h.current=Math.min(h.current*1.5,Ov),p()},y)}return p(),()=>{var y;g.current=!1,j.current=!0,(y=o.current)==null||y.call(o),o.current=null,l.current=null,clearTimeout(u.current),m.current&&(m.current.onerror=null,m.current.onclose=null,m.current.close(),m.current=null,Et=null),_t&&(_t.stopScreenshots(),Gt.unregister(_t.daemonId))}},[]),t.jsx(t.Fragment,{children:e})}function Vv({children:e}){const[s,r]=i.useState("disconnected"),[n,a]=i.useState(null);i.useEffect(()=>(jr=(l,c)=>{r(l),c&&a(c)},()=>{jr=null}),[]);const o=i.useMemo(()=>{const l=s==="connected",c=Kv(s),d={};return n&&(d[n]=c),d.standalone=c,{wsStatus:s,isConnected:l,connectionStates:d}},[s,n]);return t.jsx(bm,{connectionOverrides:o,children:t.jsx(zv,{children:e})})}const bu="adhdev_standalone_font_preferences",ks={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Yn=[{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"}],Ir=[{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"}],Gv=new Set(Yn.map(e=>e.id)),qv=new Set(Ir.map(e=>e.id));function Ut(e){const s=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:bn("chat",s.chat),code:bn("code",s.code),terminal:bn("terminal",s.terminal)}}function bn(e,s){const r=ks[e],n=s&&typeof s=="object"&&!Array.isArray(s)?s:{},a=typeof n.preset=="string"?n.preset.trim():"",o=typeof n.customFamily=="string"?n.customFamily.trim():"";return(e==="chat"?Gv:qv).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:r:{preset:a}:r}function gn(e,s){var a;const r=bn(e,s);if(r.preset==="custom"&&r.customFamily)return r.customFamily;const n=e==="chat"?Yn:Ir;return((a=n.find(o=>o.id===r.preset))==null?void 0:a.family)||n[0].family}function Yv(e){const s=Ut(e),r=gn("chat",s.chat),n=gn("code",s.code),a=gn("terminal",s.terminal);return{"--chat-font-family":r,"--chat-code-font-family":n,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function fs(e,s=document.documentElement){const r=Ut(e),n=Yv(r);s.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(n))s.style.setProperty(a,o);return r}function go(e){const s=Ut(e);try{localStorage.setItem(bu,JSON.stringify(s))}catch{}return s}function Xv(){try{const e=localStorage.getItem(bu);if(e)return Ut(JSON.parse(e))}catch{}return ks}function Jv(){return fs(Xv())}function ur(e,s){var n;const r=e==="chat"?Yn:Ir;return((n=r.find(a=>a.id===s))==null?void 0:n.label)||r[0].label}const Qv=[{id:"dashboard",path:"/dashboard",icon:t.jsx(nc,{}),label:"Dashboard"},{id:"machine",path:"/machines",icon:t.jsx(os,{}),label:"Burrow"},{id:"mesh",path:"/mesh",icon:t.jsx(Hs,{}),label:"Mesh"},{id:"settings",path:"/settings",icon:t.jsx(Pn,{}),label:"Settings"}];function Zv({children:e}){const s=cs(),r=vo(),n=i.useMemo(()=>Qv.map(o=>({...o,active:r.pathname.startsWith(o.path),onSelect:()=>s(o.path)})),[r.pathname,s]),a=i.useMemo(()=>[{id:"docs",label:t.jsxs(t.Fragment,{children:[t.jsx("span",{children:"Docs"}),t.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:t.jsx(oc,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:"Docs"},{id:"about",label:"About",icon:t.jsx(ic,{}),active:r.pathname==="/about",onSelect:()=>s("/about"),title:"About"}],[r.pathname,s]);return t.jsx(Lx,{brand:({collapsed:o})=>t.jsxs(t.Fragment,{children:[t.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!o&&t.jsx("span",{children:"ADHDev"})]}),navItems:n,footerItems:a,footerInfo:({collapsed:o})=>o?null:t.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.81"]}),footerActions:({collapsed:o,toggleCollapsed:l})=>t.jsxs("div",{className:`nav-item cursor-pointer ${o?"justify-center py-2.5 px-0":"mt-1"}`,onClick:l,title:o?"Expand sidebar":"Collapse sidebar",children:[t.jsx("span",{className:"nav-icon text-base",children:o?"›":"‹"}),!o&&t.jsx("span",{className:"text-xs",children:"Collapse"})]}),children:e})}const ew=[{icon:t.jsx(os,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:t.jsx(Jt,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:t.jsx(lc,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:t.jsx(At,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:t.jsx(Hs,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:t.jsx(oc,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],tw=[{icon:t.jsx(Pm,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:t.jsx(nc,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:t.jsx(Dn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:t.jsx(Im,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:t.jsx(ac,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:t.jsx(Am,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],sw=[{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 rw(){return t.jsxs(gr,{icon:t.jsx(ic,{className:"text-text-primary"}),title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",widthClassName:"max-w-5xl",actions:t.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","0.9.81"]}),children:[t.jsx(jt,{children:t.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[t.jsxs("div",{className:"max-w-2xl",children:[t.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:"Self-hosted edition"}),t.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."}),t.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."})]}),t.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[t.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 ↗"}),t.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 ↗"}),t.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 ↗"})]})]})}),t.jsx(jt,{title:"Included in standalone",description:"The local-first feature set available without the cloud control plane.",children:t.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:ew.map(e=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[t.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[t.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]}),t.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),t.jsx(jt,{title:"Built-in inventory",description:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",children:t.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:ld.map(e=>`${e.icon} ${e.name}`)},{label:"Extensions",items:dd.map(e=>`${e.icon} ${e.name}`)},{label:"CLI agents",items:cd.map(e=>`${e.icon} ${e.name}`)}].map(e=>t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[t.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:e.label}),t.jsx("div",{className:"flex flex-col gap-1.5",children:e.items.map(s=>t.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:s},s))})]},e.label))})}),t.jsx(jt,{title:"Cloud-only extras",description:"Capabilities that need the hosted control plane or team infrastructure.",children:t.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:tw.map(e=>t.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[t.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[t.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]}),t.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:e.desc})]},e.title))})}),t.jsx(jt,{title:"Self-hosted vs Cloud",description:"The product split at a glance.",children:t.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:t.jsxs("table",{className:"w-full text-[13px]",children:[t.jsx("thead",{children:t.jsxs("tr",{className:"bg-bg-secondary",children:[t.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:"Feature"}),t.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:"Selfhost"}),t.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:"Cloud"})]})}),t.jsx("tbody",{children:sw.map((e,s)=>t.jsxs("tr",{className:s%2===0?"bg-bg-glass":"bg-transparent",children:[t.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:e.feature}),t.jsx("td",{className:"px-4 py-2.5 text-center",children:e.selfhost?t.jsx("span",{className:"text-emerald-500",children:"✓"}):t.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),t.jsx("td",{className:"px-4 py-2.5 text-center",children:t.jsx("span",{className:"text-emerald-500",children:"✓"})})]},e.feature))})]})})}),t.jsx(Tn,{icon:t.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:t.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[t.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:"Compare Cloud ↗"}),t.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[t.jsx(Um,{size:14,className:"mr-1"}),"Discord ↗"]})]})})]})}function za(e,s,r){return{...e,[s]:r}}function Va({surface:e,title:s,description:r,value:n,options:a,onChange:o}){return t.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-text-primary",children:s}),t.jsx("div",{className:"text-xs text-text-muted mt-1",children:r})]}),t.jsxs("div",{className:"flex flex-col gap-2",children:[t.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:l=>{const c=l.target.value;o(c==="custom"?{preset:"custom",customFamily:n.customFamily||""}:{preset:c})},children:a.map(l=>t.jsx("option",{value:l.id,children:l.label},l.id))}),n.preset==="custom"&&t.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:l=>o({preset:"custom",customFamily:l.target.value})}),t.jsxs("div",{className:"text-[11px] text-text-muted",children:[t.jsx("span",{className:"font-medium text-text-secondary",children:"Resolved stack:"})," ",t.jsx("span",{className:"font-mono break-all",children:gn(e,n)})]})]})]})}function nw({value:e,savedValue:s,saving:r=!1,error:n,notice:a,onChange:o,onSave:l,onResetToSaved:c,onResetToDefaults:d}){const m=JSON.stringify(e)!==JSON.stringify(s);return t.jsxs("div",{className:"flex flex-col gap-4",children:[t.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&&t.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&&t.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}),t.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[t.jsx(Va,{surface:"chat",title:"Chat text",description:"Assistant/user prose, markdown text, thought cards, and system notes.",value:e.chat,options:Yn,onChange:u=>o(za(e,"chat",u))}),t.jsx(Va,{surface:"code",title:"Code blocks",description:"Markdown code fences, inline code, and preformatted command output.",value:e.code,options:Ir,onChange:u=>o(za(e,"code",u))}),t.jsx(Va,{surface:"terminal",title:"Terminal",description:"Terminal transcript cards and tool/command rows in chat mode.",value:e.terminal,options:Ir,onChange:u=>o(za(e,"terminal",u))})]}),t.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-sm font-medium text-text-primary",children:"Live preview"}),t.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",ur("chat",e.chat.preset)," · Code: ",ur("code",e.code.preset)," · Terminal: ",ur("terminal",e.terminal.preset)]})]}),t.jsxs("div",{className:"text-[11px] text-text-muted",children:["Defaults: ",ur("chat",ks.chat.preset)," / ",ur("code",ks.code.preset)]})]}),t.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:t.jsxs("div",{className:"chat-container-content",children:[t.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:t.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[t.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[t.jsx("span",{className:"chat-sender",children:"Hermes"}),t.jsx("span",{className:"chat-time",children:"now"})]}),t.jsxs("div",{className:"chat-markdown",children:[t.jsxs("p",{children:["Readable prose, ",t.jsx("strong",{children:"bold text"}),", and ",t.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),t.jsx("pre",{children:t.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),t.jsxs("div",{className:"chat-msg-tool",children:[t.jsx("span",{className:"tool-icon",children:"▸"}),t.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),t.jsxs("div",{className:"chat-msg-terminal",children:[t.jsx("div",{className:"chat-msg-header",children:"Terminal"}),t.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",onClick:l,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"}),t.jsx("button",{type:"button",onClick:c,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"}),t.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 aw(){const{ides:e}=ls(),s=e.find(G=>G.type==="adhdev-daemon"),r=(s==null?void 0:s.detectedIdes)||[],{sendCommand:n}=wt(),{userName:a}=ls(),[o,l]=i.useState(a||""),[c,d]=i.useState(null),[m,u]=i.useState(null),[h,g]=i.useState(ks),[j,f]=i.useState(!1),[p,b]=i.useState(""),[y,x]=i.useState(""),[A,N]=i.useState("127.0.0.1"),[v,C]=i.useState(""),[M,w]=i.useState(""),[k,F]=i.useState(""),[_,S]=i.useState(""),[H,W]=i.useState(""),[D,I]=i.useState(!1),T=async()=>{const he=await(await Wt("/auth/session")).json();d(he)},K=async()=>{const he=await(await Wt("/api/v1/standalone/preferences")).json();u(he),N(he.standaloneBindHost);const pe=Ut(he.standaloneFontPreferences);g(pe),fs(pe),go(pe)};i.useEffect(()=>{a!==void 0&&l(a)},[a]),i.useEffect(()=>{Promise.all([T(),K()]).catch(G=>{S(G instanceof Error?G.message:String(G))})},[]),i.useEffect(()=>{fs(h)},[h]);const P=G=>{const he=G.target.value.trim();s!=null&&s.id&&he!==a&&n(s.id,"set_user_name",{userName:he}).catch(console.error)},[$,V]=i.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),Y=G=>{V(G);try{localStorage.setItem("adhdev_sound",G?"1":"0")}catch{}},ge=async()=>{b(""),x(""),f(!0);try{const G=Ut(h),he=await Wt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:G})}),pe=await he.json();if(!he.ok)throw new Error((pe==null?void 0:pe.error)||"Failed to save standalone font preferences");const ye=Ut(pe.standaloneFontPreferences);u(pe),g(ye),fs(ye),go(ye),x("Standalone chat fonts saved for this self-hosted dashboard.")}catch(G){b(G instanceof Error?G.message:String(G))}finally{f(!1)}},fe=()=>{const G=Ut(m==null?void 0:m.standaloneFontPreferences);b(""),x(""),g(G),fs(G)},ae=()=>{b(""),x(""),g(ks),fs(ks)},me=async()=>{S(""),W(""),I(!0);try{const G=await Wt("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:A})}),he=await G.json();if(!G.ok)throw new Error((he==null?void 0:he.error)||"Failed to save standalone network preference");u(he),N(he.standaloneBindHost),W(he.standaloneBindHost==="0.0.0.0"?"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.":"Default standalone network mode set to localhost only. Restart standalone to apply it.")}catch(G){S(G instanceof Error?G.message:String(G))}finally{I(!1)}},je=async()=>{if(S(""),W(""),M.trim().length<4){S("Password must be at least 4 characters.");return}if(M!==k){S("New password and confirmation do not match.");return}I(!0);try{const G=await Wt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,newPassword:M})}),he=await G.json();if(!G.ok)throw new Error((he==null?void 0:he.error)||"Failed to save password");d(he),await K(),C(""),w(""),F(""),W(c!=null&&c.hasPasswordAuth?"Standalone password updated.":"Standalone password enabled."),xu()}catch(G){S(G instanceof Error?G.message:String(G))}finally{I(!1)}},Ne=async()=>{S(""),W(""),I(!0);try{const G=await Wt("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,clear:!0})}),he=await G.json();if(!G.ok)throw new Error((he==null?void 0:he.error)||"Failed to clear password");d(he),await K(),C(""),w(""),F(""),W("Standalone password disabled.")}catch(G){S(G instanceof Error?G.message:String(G))}finally{I(!1)}};return t.jsxs(gr,{icon:t.jsx(Pn,{className:"text-text-primary"}),title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",widthClassName:"max-w-5xl",children:[t.jsx($s,{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."}),(c==null?void 0:c.publicHostWarning)&&t.jsx($s,{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."}),t.jsx(jt,{title:"Daemon",description:"Connection health and local endpoints for the self-hosted runtime.",children:t.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[t.jsx("span",{className:"text-text-muted",children:"Version"}),t.jsxs("span",{className:"font-mono text-xs",children:["v","0.9.81"]}),t.jsx("span",{className:"text-text-muted",children:"Status"}),t.jsx("span",{className:s?"text-green-400":"text-yellow-400",children:s?"● Running":"○ Not connected"}),t.jsx("span",{className:"text-text-muted",children:"Current bind"}),t.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.currentBindHost)||(c==null?void 0:c.boundHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Default bind"}),t.jsx("span",{className:"font-mono text-xs",children:(m==null?void 0:m.standaloneBindHost)||"127.0.0.1"}),t.jsx("span",{className:"text-text-muted",children:"Auth"}),t.jsx("span",{className:"text-xs",children:c!=null&&c.hasPasswordAuth?"Password enabled":c!=null&&c.hasTokenAuth?"Token enabled":"No auth configured"})]})}),t.jsx(jt,{title:"Network Access",description:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.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."}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[t.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:[t.jsx("input",{type:"radio",name:"standalone-bind-host",checked:A==="127.0.0.1",onChange:()=>N("127.0.0.1")}),t.jsxs("span",{children:[t.jsx("span",{className:"block font-medium text-text-primary",children:"Localhost only"}),t.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."})]})]}),t.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:[t.jsx("input",{type:"radio",name:"standalone-bind-host",checked:A==="0.0.0.0",onChange:()=>N("0.0.0.0")}),t.jsxs("span",{children:[t.jsx("span",{className:"block font-medium text-text-primary",children:"All interfaces"}),t.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."})]})]})]}),t.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[t.jsx("button",{type:"button",onClick:()=>{me()},disabled:D,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:D?"Saving…":"Save default network mode"}),t.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)||(c==null?void 0:c.boundHost)||"127.0.0.1","."]})]})]})}),t.jsx(jt,{title:"Dashboard Security",description:"Self-hosted-only password protection for browsers using this standalone dashboard.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:c!=null&&c.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."}),_&&t.jsx($s,{variant:"error",children:_}),H&&t.jsx($s,{variant:"success",children:H}),t.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[t.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:c!=null&&c.hasPasswordAuth?"Current password":"Current password (not needed for first setup)",value:v,onChange:G=>C(G.target.value)}),t.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:c!=null&&c.hasPasswordAuth?"New password":"New standalone password",value:M,onChange:G=>w(G.target.value)}),t.jsx("input",{type:"password",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors md:col-span-2",placeholder:"Confirm new password",value:k,onChange:G=>F(G.target.value)})]}),t.jsxs("div",{className:"flex flex-wrap gap-2",children:[t.jsx("button",{type:"button",onClick:()=>{je()},disabled:D,className:"rounded-lg bg-accent text-white px-3 py-2 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:D?"Saving…":c!=null&&c.hasPasswordAuth?"Update password":"Enable password"}),(c==null?void 0:c.hasPasswordAuth)&&t.jsx("button",{type:"button",onClick:()=>{Ne()},disabled:D,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"})]})]})}),t.jsx(jt,{title:"Detected IDEs",description:"Editors discovered by the local daemon on this machine.",children:r.length===0?t.jsx("p",{className:"text-sm text-text-muted",children:"No IDEs detected. Start an IDE to see it here."}):t.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(G=>t.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("span",{className:`w-2 h-2 rounded-full ${G.running?"bg-green-400":"bg-text-muted/30"}`}),t.jsx("span",{className:"text-sm font-medium",children:G.name})]}),t.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:G.type})]},G.type))})}),t.jsx(jt,{title:"Machine",description:"The local burrow exposed by your standalone daemon.",children:t.jsx(Fx,{ides:e,emptyMessage:"Daemon not connected. Run 'adhdev-standalone' to start."})}),t.jsx(jt,{title:"Appearance",description:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",children:t.jsxs("div",{className:"flex flex-col gap-4",children:[t.jsxs("div",{children:[t.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:"Mode"}),t.jsx(Ux,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),t.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."}),t.jsx(Qx,{})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Fonts"}),t.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:"Standalone-only typography overrides for chat text, markdown code, and terminal output."}),t.jsx(nw,{value:h,savedValue:Ut(m==null?void 0:m.standaloneFontPreferences),saving:j,error:p,notice:y,onChange:g,onSave:()=>{ge()},onResetToSaved:fe,onResetToDefaults:ae})]}),t.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[t.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Mobile"}),t.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."}),t.jsx(tb,{})]})]})}),t.jsx(jt,{title:"Notifications",description:"Browser prompts and local sound cues for agent activity.",children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsx($x,{}),t.jsx(ps,{label:t.jsxs("span",{className:"flex items-center gap-1.5",children:[t.jsx(Hm,{size:15})," Sound Effects"]}),description:"Play a sound when agent completes or needs approval",checked:$,onChange:Y})]})}),t.jsx(jt,{title:"Profile",description:"How your name appears in local chat threads and dashboard views.",children:t.jsx("div",{className:"flex flex-col gap-3",children:t.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:[t.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[t.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[t.jsx(Cm,{size:16,className:"text-text-secondary"})," Display Name"]}),t.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:"Your name shown in chat threads and on the team dashboard."})]}),t.jsx("input",{type:"text",className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-1.5 text-sm w-48 text-right focus:border-accent focus:outline-none transition-colors",placeholder:"Anonymous",value:o,onChange:G=>l(G.target.value),onBlur:P,onKeyDown:G=>{G.key==="Enter"&&G.currentTarget.blur()}})]})})})]})}Ax();Xx();Jv();const ow=sc({baseUrl:"",getToken:li});function iw({children:e}){const[s,r]=i.useState(null),[n,a]=i.useState(!0),[o,l]=i.useState(""),[c,d]=i.useState(""),[m,u]=i.useState(!1),h=async()=>{a(!0),d("");try{const f=await(await Wt("/auth/session")).json();r(f)}catch(j){d(j instanceof Error?j.message:String(j))}finally{a(!1)}};i.useEffect(()=>{h()},[]),i.useEffect(()=>{if(!s||s.required&&!s.authenticated)return;let j=!1;return(async()=>{try{const f=await Wt("/api/v1/standalone/preferences");if(!f.ok)return;const p=await f.json();if(j)return;const b=Ut(p.standaloneFontPreferences);fs(b),go(b)}catch{}})(),()=>{j=!0}},[s==null?void 0:s.authenticated,s==null?void 0:s.required]);const g=async j=>{j.preventDefault(),u(!0),d("");try{const f=await Wt("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:o})}),p=await f.json();if(!f.ok)throw new Error((p==null?void 0:p.error)||"Login failed");r(p),l(""),xu()}catch(f){d(f instanceof Error?f.message:String(f))}finally{u(!1)}};return n?t.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:"Loading standalone dashboard…"}):s?!s.required||s.authenticated?t.jsx(t.Fragment,{children:e}):t.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:t.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:[t.jsxs("div",{children:[t.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Standalone sign-in"}),t.jsx("p",{className:"text-sm text-text-muted mt-1",children:s.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."})]}),s.hasPasswordAuth?t.jsxs("form",{className:"flex flex-col gap-3",onSubmit:g,children:[t.jsx("input",{type:"password",value:o,onChange:j=>l(j.target.value),className:"bg-bg-primary border border-border-strong rounded-lg px-3 py-2.5 text-sm focus:border-accent focus:outline-none transition-colors",placeholder:"Enter standalone password",autoFocus:!0}),t.jsx("button",{type:"submit",disabled:m||!o,className:"rounded-lg bg-accent text-white px-3 py-2.5 text-sm font-medium disabled:opacity-50 disabled:cursor-not-allowed",children:m?"Signing in…":"Unlock dashboard"})]}):t.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."}),c&&t.jsx("div",{className:"rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300",children:c})]})}):t.jsxs("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:["Failed to load standalone auth status: ",c||"unknown error"]})}function Yl(){const{ides:e,initialLoaded:s}=ls();if(!s)return t.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?t.jsx(Ya,{to:`/machines/${r.id}`,replace:!0}):t.jsx(Ya,{to:"/dashboard",replace:!0})}function lw(){const e=i.useMemo(()=>({sendCommand:xn,sendData:bo,sendPtyInput:Wv}),[]);return t.jsx(tm,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:t.jsx(vm,{client:ow,children:t.jsx(iw,{children:t.jsx(Vv,{children:t.jsx(jm,{value:e,children:t.jsx(Zv,{children:t.jsxs(sm,{children:[t.jsx(es,{path:"/dashboard",element:t.jsx(j0,{})}),t.jsx(es,{path:"/machine",element:t.jsx(Yl,{})}),t.jsx(es,{path:"/machines/:id",element:t.jsx(Tv,{})}),t.jsx(es,{path:"/machines",element:t.jsx(Yl,{})}),t.jsx(es,{path:"/about",element:t.jsx(rw,{})}),t.jsx(es,{path:"/settings",element:t.jsx(aw,{})}),t.jsx(es,{path:"/mesh",element:t.jsx(Dv,{})}),t.jsx(es,{path:"*",element:t.jsx(Ya,{to:"/dashboard",replace:!0})})]})})})})})})})}Oh({connectionManager:Gt});rm(document.getElementById("root")).render(t.jsx(lw,{}));
|