@adhdev/daemon-standalone 1.0.30-rc.2 → 1.0.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,11 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-DiXj2eIR.js","assets/vendor-DyCWA2YZ.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
2
- var Hh=Object.defineProperty;var Fh=(e,t,n)=>t in e?Hh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var nt=(e,t,n)=>Fh(e,typeof t!="symbol"?t+"":t,n);import{r as l,j as s,u as Ne,M as $i,a as Bh,b as Wh,c as Oh,t as Uh,d as Gh,i as Ct,e as qh,f as un,R as Pt,T as si,g as Mr,h as ni,k as ri,D as zh,E as Kh,l as Vh,C as Yh,m as Jh,B as Qh,n as Xh,o as Zh,p as ef,H as _r,P as Es,q as tf,s as sf,v as nf,w as $l,x as rf,y as af,z as Hi,A as of,F as lf,G as cf,I as df,J as _s,N as ai,K as uf}from"./vendor-DyCWA2YZ.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const i of o.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(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 r(a){if(a.ep)return;a.ep=!0;const o=n(a);fetch(a.href,o)}})();function pf(e={}){const t=Math.max(1,Math.floor(e.capacity||200)),n=[];return{record(r){const a={id:`webdbg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,ts:Date.now(),...r,payload:r.payload?{...r.payload}:{}};return n.push(a),n.length>t&&n.splice(0,n.length-t),a},list(r={}){const a=Math.max(1,Math.floor(r.limit||100));return n.filter(o=>!r.interactionId||o.interactionId===r.interactionId).filter(o=>!r.topic||o.topic===r.topic).filter(o=>!r.kind||o.kind===r.kind).slice(-a).map(o=>({...o,payload:o.payload?{...o.payload}:{}}))},clear(){n.splice(0,n.length)}}}const Ln=pf();function Hl(e){const t={};for(const n of e)n.transport&&(t[n.transport]=(t[n.transport]||0)+1);return{count:e.length,ids:e.map(n=>n.id),statuses:e.map(n=>String(n.status||"unknown")),transports:t}}function mf(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function Fl(e){return Array.isArray(e)?[...e]:[]}function tu(e,t){if(!e)return t??null;const n=Object.prototype.hasOwnProperty.call(e,"messages"),r=Object.prototype.hasOwnProperty.call(e,"activeModal"),a=typeof e.id=="string"?e.id.trim():"",o=typeof(t==null?void 0:t.id)=="string"?t.id.trim():"",i=!!a&&!!o&&a!==o;return t?{...t,...e,messages:n?Fl(e.messages):i?[]:t.messages,activeModal:r?e.activeModal??null:t.activeModal,inputContent:e.inputContent??t.inputContent}:{...e,...n?{messages:Fl(e.messages)}:{},...r?{activeModal:e.activeModal??null}:{}}}function ir(e,t){const n=mf(e.providerName,e.providerType)?e.providerName:void 0;return{...e,parentId:e.parentId??(t==null?void 0:t.parentSessionId)??null,providerSessionId:e.providerSessionId??(t==null?void 0:t.providerSessionId),providerName:n??(t==null?void 0:t.providerName)??(t==null?void 0:t.cliName)??(t==null?void 0:t.type)??e.providerName??e.providerType,title:e.title??(t==null?void 0:t.title)??n??(t==null?void 0:t.providerName)??e.providerName??e.providerType,workspace:e.workspace??(t==null?void 0:t.workspace)??null,mode:e.mode??(t==null?void 0:t.mode),capabilities:e.capabilities??(t==null?void 0:t.sessionCapabilities)??(t==null?void 0:t.capabilities)??[],cdpConnected:e.cdpConnected??(t==null?void 0:t.cdpConnected),activeChat:tu(e.activeChat,t==null?void 0:t.activeChat),activeInteractivePrompt:Object.prototype.hasOwnProperty.call(e,"activeInteractivePrompt")?e.activeInteractivePrompt??null:(t==null?void 0:t.activeInteractivePrompt)??null,controlValues:e.controlValues??(t==null?void 0:t.controlValues),providerControls:e.providerControls??(t==null?void 0:t.providerControls),summaryMetadata:e.summaryMetadata??(t==null?void 0:t.summaryMetadata),runtimeWriteOwner:e.runtimeWriteOwner??(t==null?void 0:t.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(t==null?void 0:t.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(t==null?void 0:t.lastMessagePreview),lastMessageRole:e.lastMessageRole??(t==null?void 0:t.lastMessageRole),lastMessageAt:e.lastMessageAt??(t==null?void 0:t.lastMessageAt),lastMessageHash:e.lastMessageHash??(t==null?void 0:t.lastMessageHash),unread:e.unread??(t==null?void 0:t.unread),lastSeenAt:e.lastSeenAt??(t==null?void 0:t.lastSeenAt),inboxBucket:e.inboxBucket??(t==null?void 0:t.inboxBucket),completionMarker:e.completionMarker??(t==null?void 0:t.completionMarker),seenCompletionMarker:e.seenCompletionMarker??(t==null?void 0:t.seenCompletionMarker),surfaceHidden:e.surfaceHidden??(t==null?void 0:t.surfaceHidden),muted:e.muted??(t==null?void 0:t.muted),resume:e.resume??(t==null?void 0:t.resume),runtimeKey:e.runtimeKey??(t==null?void 0:t.runtimeKey),runtimeDisplayName:e.runtimeDisplayName??(t==null?void 0:t.runtimeDisplayName),runtimeWorkspaceLabel:e.runtimeWorkspaceLabel??(t==null?void 0:t.runtimeWorkspaceLabel),settings:e.settings??(t==null?void 0:t.settings)}}function su(e,t,n){if(!(t!=null&&t.length))return(n==null?void 0:n.preserveMissing)===!1&&Array.isArray(t)?t:e;if(!(e!=null&&e.length))return t;const r=t.map(a=>{const o=e.find(i=>i.id===a.id);return o?ir(a,o):a});if((n==null?void 0:n.preserveMissing)!==!1){const a=new Set(t.map(o=>o.id));for(const o of e)a.has(o.id)||r.push(o)}return r}function Bl(e){return!!e&&typeof e=="object"&&"text"in e}function Fi(e,t){const n=(t==null?void 0:t.joiner)??" ",r=(t==null?void 0:t.normalizeWhitespace)??!1;let a="";return typeof e=="string"?a=e:Array.isArray(e)?a=e.map(o=>typeof o=="string"?o:Bl(o)?String(o.text||""):"").join(n):Bl(e)?a=String(e.text||""):a=String(e||""),r?a.replace(/\s+/g," ").trim():a}function Rn(e){return Fi(e,{normalizeWhitespace:!0})}function hf(e){let t="";for(let n=0;n<e.length;n++){const r=e[n],a=e.charCodeAt(n);if(!(a<=31&&r!==`
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-BZj_X5zy.js","assets/vendor-cL4V2vaO.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
2
+ var Hh=Object.defineProperty;var Fh=(e,t,n)=>t in e?Hh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var nt=(e,t,n)=>Fh(e,typeof t!="symbol"?t+"":t,n);import{r as l,j as s,u as Ne,M as $i,a as Bh,b as Wh,c as Oh,t as Uh,d as Gh,i as Ct,e as qh,f as un,R as Pt,T as si,g as Mr,h as ni,k as ri,D as zh,E as Kh,l as Vh,C as Yh,m as Jh,B as Qh,n as Xh,o as Zh,p as ef,H as _r,P as Es,q as tf,s as sf,v as nf,w as $l,x as rf,y as af,z as Hi,A as of,F as lf,G as cf,I as df,J as _s,N as ai,K as uf}from"./vendor-cL4V2vaO.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const i of o.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(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 r(a){if(a.ep)return;a.ep=!0;const o=n(a);fetch(a.href,o)}})();function pf(e={}){const t=Math.max(1,Math.floor(e.capacity||200)),n=[];return{record(r){const a={id:`webdbg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,ts:Date.now(),...r,payload:r.payload?{...r.payload}:{}};return n.push(a),n.length>t&&n.splice(0,n.length-t),a},list(r={}){const a=Math.max(1,Math.floor(r.limit||100));return n.filter(o=>!r.interactionId||o.interactionId===r.interactionId).filter(o=>!r.topic||o.topic===r.topic).filter(o=>!r.kind||o.kind===r.kind).slice(-a).map(o=>({...o,payload:o.payload?{...o.payload}:{}}))},clear(){n.splice(0,n.length)}}}const Ln=pf();function Hl(e){const t={};for(const n of e)n.transport&&(t[n.transport]=(t[n.transport]||0)+1);return{count:e.length,ids:e.map(n=>n.id),statuses:e.map(n=>String(n.status||"unknown")),transports:t}}function mf(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function Fl(e){return Array.isArray(e)?[...e]:[]}function tu(e,t){if(!e)return t??null;const n=Object.prototype.hasOwnProperty.call(e,"messages"),r=Object.prototype.hasOwnProperty.call(e,"activeModal"),a=typeof e.id=="string"?e.id.trim():"",o=typeof(t==null?void 0:t.id)=="string"?t.id.trim():"",i=!!a&&!!o&&a!==o;return t?{...t,...e,messages:n?Fl(e.messages):i?[]:t.messages,activeModal:r?e.activeModal??null:t.activeModal,inputContent:e.inputContent??t.inputContent}:{...e,...n?{messages:Fl(e.messages)}:{},...r?{activeModal:e.activeModal??null}:{}}}function ir(e,t){const n=mf(e.providerName,e.providerType)?e.providerName:void 0;return{...e,parentId:e.parentId??(t==null?void 0:t.parentSessionId)??null,providerSessionId:e.providerSessionId??(t==null?void 0:t.providerSessionId),providerName:n??(t==null?void 0:t.providerName)??(t==null?void 0:t.cliName)??(t==null?void 0:t.type)??e.providerName??e.providerType,title:e.title??(t==null?void 0:t.title)??n??(t==null?void 0:t.providerName)??e.providerName??e.providerType,workspace:e.workspace??(t==null?void 0:t.workspace)??null,mode:e.mode??(t==null?void 0:t.mode),capabilities:e.capabilities??(t==null?void 0:t.sessionCapabilities)??(t==null?void 0:t.capabilities)??[],cdpConnected:e.cdpConnected??(t==null?void 0:t.cdpConnected),activeChat:tu(e.activeChat,t==null?void 0:t.activeChat),activeInteractivePrompt:Object.prototype.hasOwnProperty.call(e,"activeInteractivePrompt")?e.activeInteractivePrompt??null:(t==null?void 0:t.activeInteractivePrompt)??null,controlValues:e.controlValues??(t==null?void 0:t.controlValues),providerControls:e.providerControls??(t==null?void 0:t.providerControls),summaryMetadata:e.summaryMetadata??(t==null?void 0:t.summaryMetadata),runtimeWriteOwner:e.runtimeWriteOwner??(t==null?void 0:t.runtimeWriteOwner),runtimeAttachedClients:e.runtimeAttachedClients??(t==null?void 0:t.runtimeAttachedClients),lastMessagePreview:e.lastMessagePreview??(t==null?void 0:t.lastMessagePreview),lastMessageRole:e.lastMessageRole??(t==null?void 0:t.lastMessageRole),lastMessageAt:e.lastMessageAt??(t==null?void 0:t.lastMessageAt),lastMessageHash:e.lastMessageHash??(t==null?void 0:t.lastMessageHash),unread:e.unread??(t==null?void 0:t.unread),lastSeenAt:e.lastSeenAt??(t==null?void 0:t.lastSeenAt),inboxBucket:e.inboxBucket??(t==null?void 0:t.inboxBucket),completionMarker:e.completionMarker??(t==null?void 0:t.completionMarker),seenCompletionMarker:e.seenCompletionMarker??(t==null?void 0:t.seenCompletionMarker),surfaceHidden:e.surfaceHidden??(t==null?void 0:t.surfaceHidden),muted:e.muted??(t==null?void 0:t.muted),resume:e.resume??(t==null?void 0:t.resume),runtimeKey:e.runtimeKey??(t==null?void 0:t.runtimeKey),runtimeDisplayName:e.runtimeDisplayName??(t==null?void 0:t.runtimeDisplayName),runtimeWorkspaceLabel:e.runtimeWorkspaceLabel??(t==null?void 0:t.runtimeWorkspaceLabel),settings:e.settings??(t==null?void 0:t.settings)}}function su(e,t,n){if(!(t!=null&&t.length))return(n==null?void 0:n.preserveMissing)===!1&&Array.isArray(t)?t:e;if(!(e!=null&&e.length))return t;const r=t.map(a=>{const o=e.find(i=>i.id===a.id);return o?ir(a,o):a});if((n==null?void 0:n.preserveMissing)!==!1){const a=new Set(t.map(o=>o.id));for(const o of e)a.has(o.id)||r.push(o)}return r}function Bl(e){return!!e&&typeof e=="object"&&"text"in e}function Fi(e,t){const n=(t==null?void 0:t.joiner)??" ",r=(t==null?void 0:t.normalizeWhitespace)??!1;let a="";return typeof e=="string"?a=e:Array.isArray(e)?a=e.map(o=>typeof o=="string"?o:Bl(o)?String(o.text||""):"").join(n):Bl(e)?a=String(e.text||""):a=String(e||""),r?a.replace(/\s+/g," ").trim():a}function Rn(e){return Fi(e,{normalizeWhitespace:!0})}function hf(e){let t="";for(let n=0;n<e.length;n++){const r=e[n],a=e.charCodeAt(n);if(!(a<=31&&r!==`
3
3
  `&&r!==" ")&&!(a>=127&&a<=159)&&!(a>=8203&&a<=8207||a>=8234&&a<=8238||a===8288||a===65279)&&a!==65533){if(a===65038||a===65039){const o=t.length>0?t[t.length-1]:"";if(!o||o===`
4
4
  `||o===" "||o===" ")continue}t+=r}}return t}function Wl(e){var n,r;let t=0;return e.activeChat!==void 0&&(t+=4),e.activeInteractivePrompt!==void 0&&(t+=2),(n=e.childSessions)!=null&&n.length&&(t+=2),e.workspace&&(t+=1),e.machine&&(t+=1),(r=e.agents)!=null&&r.length&&(t+=1),t}function nu(e,t,n){if(n.type!=="adhdev-daemon")return n;const r={...n},a=t.version??n.version??e.version,o=t.serverVersion??e.serverVersion??n.serverVersion,i=t.versionMismatch===!0||e.versionMismatch===!0,c=t.versionUpdateRequired===!0||e.versionUpdateRequired===!0,u=t.versionUpdateReason??e.versionUpdateReason??n.versionUpdateReason;return a&&(r.version=a),o&&(r.serverVersion=o),u&&(r.versionUpdateReason=u),a&&o&&a===o?(delete r.versionMismatch,delete r.serverVersion,delete r.versionUpdateRequired,delete r.versionUpdateReason,r):((t.versionMismatch===!0||i&&a&&o&&a!==o)&&(r.versionMismatch=!0),c&&(r.versionUpdateRequired=!0),r)}function ff(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function oo(e){if(!e||typeof e!="object")return"";const t=e,n=ff(Rn(t.content).slice(0,512));return[String(t.id||""),String(t._localId||""),String(t._turnKey||""),String(t.index??""),String(t.role||""),String(t.receivedAt??t.timestamp??""),n].join(":")}function bf(e,t){if(!Array.isArray(e))return e;if(t!=null&&t.has(e))return{count:e.length,sharedRef:!0};let n=2166136261;for(const r of e){const a=oo(r);for(let o=0;o<a.length;o+=1)n^=a.charCodeAt(o),n=Math.imul(n,16777619)>>>0}return{count:e.length,hash:n.toString(16).padStart(8,"0"),first:oo(e[0]),last:oo(e[e.length-1])}}function oi(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function ii(e,t,n){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(oi(e)&&oi(t)){const i=e.messages;Array.isArray(i)&&i===t.messages&&n.add(i)}if(Array.isArray(e)&&Array.isArray(t)){const i=Math.min(e.length,t.length);for(let c=0;c<i;c+=1)ii(e[c],t[c],n);return}const r=e,a=t,o=new Set([...Object.keys(r),...Object.keys(a)]);for(const i of o)i!=="messages"&&ii(r[i],a[i],n)}function ur(e,t){return Array.isArray(e)?e.map(n=>ur(n,t)):!e||typeof e!="object"?e:oi(e)?Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[a])=>r.localeCompare(a)).map(([r,a])=>[r,r==="messages"?bf(a,t):ur(a,t)])):Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,ur(r,t)]))}function gf(e,t){try{const n=new WeakSet;return ii(e,t,n),JSON.stringify(ur(e,n))===JSON.stringify(ur(t,n))}catch{return!1}}function li(e,t,n){return gf(e,t)?(e._lastUpdate=n,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function ru(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function xf(e,t,n){t[n]!==void 0&&(e[n]=t[n])}function Ol(e,t,n,r){var u;const a=(u=t.chats)!=null&&u.length?t.chats:e.chats,o=su(e.childSessions,t.childSessions,{preserveMissing:r}),i=tu(t.activeChat,e.activeChat),c=t.workspace||e.workspace;return nu(e,t,{...e,...t,chats:a,childSessions:o,activeChat:i,workspace:c,_lastUpdate:n})}function vf(e,t,n){var a,o;const r={};t.status&&t.status!==e.status&&(r.status=t.status),t.cdpConnected!==void 0&&(r.cdpConnected=t.cdpConnected),t.childSessions!==void 0&&(r.childSessions=su(e.childSessions,t.childSessions,{preserveMissing:n})),(a=t.chats)!=null&&a.length&&!((o=e.chats)!=null&&o.length)&&(r.chats=t.chats),t.workspace&&(r.workspace=t.workspace);for(const i of["title","providerSessionId","parentSessionId","sessionKind","sessionCapabilities","controlValues","providerControls","summaryMetadata","activeInteractivePrompt","lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash","lastUpdated","unread","lastSeenAt","inboxBucket","completionMarker","seenCompletionMarker","surfaceHidden","muted","runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients","version","serverVersion","versionUpdateReason","versionUpdateRequired","updateCommand","updatePolicy","updateChannel","releaseChannel"])xf(r,t,i);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(r.machineNickname=t.machineNickname),t.versionMismatch===!0&&(r.versionMismatch=!0),r}function yf(e,t,n,r){const a=vf(e,t,r),o=Object.keys(a).length>0?nu(e,t,{...e,...a,_lastUpdate:n}):{...e,_lastUpdate:n};return li(e,o,n)}function wf(e){const t=new Set(e.map(o=>o.id)),n=new Set,r=new Set,a=new Set;for(const o of e){const i=ru(o);i&&n.add(i),i&&o.type!=="adhdev-daemon"&&r.add(i),i&&o.type==="adhdev-daemon"&&o._sessionListAuthoritative&&a.add(i)}return{incomingIds:t,incomingDaemonIds:n,daemonIdsWithSessionEntries:r,daemonIdsWithAuthoritativeSessionList:a}}function kf(e,t,n,r,a,o){return!a.has(t)||!o.has(t)||r.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?n>1e4:e.transport==="cdp-page"?n>3e4:!1}function Sf(e,t,n,r,a){return e.transport?n.has(t)&&!r.has(t)?!0:a.has(t):!1}function Cf(e,t,n){var d,m;const r=Date.now(),a=new Set((n==null?void 0:n.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(f=>({...f,_lastUpdate:r}));const o=new Map;for(const f of t)o.set(f.id,f);const{incomingIds:i,incomingDaemonIds:c,daemonIdsWithSessionEntries:u,daemonIdsWithAuthoritativeSessionList:p}=wf(e);for(const f of e){const g=o.get(f.id);if(!g){o.set(f.id,{...f,_lastUpdate:r});continue}const S=Wl(f),h=Wl(g),x=ru(f),y=!a.has(x);if(S>h){const v=Ol(g,f,r,y);o.set(f.id,li(g,v,r));continue}if(S<h){o.set(f.id,yf(g,f,r,y));continue}const b=v=>typeof v=="number"&&Number.isFinite(v),C=b(f.timestamp)&&b(g.timestamp),j=C?f.timestamp:f.timestamp||r,k=C?g.timestamp:g._lastUpdate||g.timestamp||0;if(j>=k){const v=Ol(g,f,r,y);o.set(f.id,li(g,v,r));continue}(d=f.chats)!=null&&d.length&&!((m=g.chats)!=null&&m.length)&&o.set(f.id,{...g,chats:f.chats})}for(const[f,g]of o){const S=g.daemonId||f.split(":")[0];if(!c.has(S))continue;if(a.has(S)&&p.has(S)&&!i.has(f)){o.delete(f);continue}const h=r-(g._lastUpdate||g.timestamp||0);kf(g,S,h,i,a,u)&&o.delete(f)}for(const[f,g]of o){const S=g.daemonId||f.split(":")[0];if(Sf(g,S,c,u,o))continue;r-(g._lastUpdate||g.timestamp||0)>3e5&&g.status!=="online"&&o.delete(f)}return Array.from(o.values())}function jf(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}const au=l.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}),ou=l.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function Nf({children:e,connectionOverrides:t}){const[n,r]=l.useState([]),[a,o]=l.useState(!1),[i,c]=l.useState([]),[u,p]=l.useState(void 0),d=l.useRef(n);l.useEffect(()=>{d.current=n},[n]);const m=l.useCallback((y,b)=>{r(C=>{let j=!1;const k=C.map(v=>v.id!==y||v.chats===b?v:(j=!0,{...v,chats:b}));return j?k:C})},[]),f=l.useCallback((y,b)=>{r(C=>{const j=C.length===0?y:Cf(y,C,b),k=!jf(C,j);return k&&Ln.record({kind:"dashboard.entries_applied",payload:{incoming:Hl(y),next:Hl(j)}}),k?j:C})},[]),g=l.useCallback(()=>o(!0),[]),S=l.useMemo(()=>({injectEntries:f,markLoaded:g,getIdes:()=>d.current}),[f,g]),h=t,x=l.useMemo(()=>({ides:n,updateRouteChats:m,initialLoaded:a,toasts:i,setToasts:c,wsStatus:(h==null?void 0:h.wsStatus)??"connected",isConnected:(h==null?void 0:h.isConnected)??!0,connectionStates:(h==null?void 0:h.connectionStates)??{},connectionTransports:(h==null?void 0:h.connectionTransports)??{},showReconnected:(h==null?void 0:h.showReconnected)??!1,retryConnection:h==null?void 0:h.retryConnection,retryServerConnection:h==null?void 0:h.retryServerConnection,connectionLoginUrl:h==null?void 0:h.connectionLoginUrl,isP2PActive:(h==null?void 0:h.isP2PActive)??!1,p2pStates:(h==null?void 0:h.p2pStates)??{},userRole:h==null?void 0:h.userRole,connectionRetryStatuses:h==null?void 0:h.connectionRetryStatuses,userName:u,setUserName:p}),[n,m,a,i,h==null?void 0:h.wsStatus,h==null?void 0:h.isConnected,h==null?void 0:h.connectionStates,h==null?void 0:h.connectionTransports,h==null?void 0:h.showReconnected,h==null?void 0:h.retryConnection,h==null?void 0:h.retryServerConnection,h==null?void 0:h.connectionLoginUrl,h==null?void 0:h.isP2PActive,h==null?void 0:h.p2pStates,h==null?void 0:h.userRole,h==null?void 0:h.connectionRetryStatuses,u]);return s.jsx(ou.Provider,{value:S,children:s.jsx(au.Provider,{value:x,children:e})})}function As(){return l.useContext(au)}function yr(){return l.useContext(ou)}function iu(e){const{baseUrl:t,getToken:n,onUnauthorized:r}=e;function a(c){return c.startsWith("http")?c:`${t}${c.startsWith("/")?"":"/"}${c}`}function o(c){const u=n==null?void 0:n(),p=a(c),d=c.startsWith("http")?new URL(p):new URL(p,typeof window<"u"?window.location.origin:"http://localhost");return u&&d.searchParams.set("token",u),!c.startsWith("http")&&!t?`${d.pathname}${d.search}${d.hash}`:d.toString()}async function i(c,u={}){const p={"Content-Type":"application/json",...u.headers||{}},d=n==null?void 0:n();d&&(p.Authorization=`Bearer ${d}`);const m=a(c),f=new AbortController,g=setTimeout(()=>f.abort(),15e3);try{const S=await fetch(m,{...u,headers:p,signal:f.signal});if(S.status===401)throw r==null||r(),new Error("Unauthorized");if(!S.ok){const h=await S.json().catch(()=>({error:S.statusText}));throw new Error(h.error||`API Error: ${S.status}`)}return S.json()}finally{clearTimeout(g)}}return{getDaemons:()=>i("/api/v1/daemons"),getDaemonStatus:c=>i(`/api/v1/daemons/${c}/status`),sendCommand:(c,u,p={})=>i(`/api/v1/daemons/${c}/command`,{method:"POST",body:JSON.stringify({type:u,payload:p})}),execTerminal:(c,u,p)=>i(`/api/v1/daemons/${c}/terminal`,{method:"POST",body:JSON.stringify({command:u,name:p})}),sendAgentMessage:(c,u,p)=>i(`/api/v1/shortcuts/${c}/chat`,{method:"POST",body:JSON.stringify({agentType:u,message:p})}),getAgentStatus:c=>i(`/api/v1/shortcuts/${c}/status`),approveAgent:(c,u,p)=>i(`/api/v1/shortcuts/${c}/approve`,{method:"POST",body:JSON.stringify({agentType:u,action:p?"approve":"reject"})}),getMuxState:c=>i(`/api/v1/mux/${encodeURIComponent(c)}/state`),getMuxSocketInfo:c=>i(`/api/v1/mux/${encodeURIComponent(c)}/socket-info`),controlMux:(c,u,p={})=>i(`/api/v1/mux/${encodeURIComponent(c)}/control`,{method:"POST",body:JSON.stringify({type:u,payload:p})}),getMuxEventsUrl:c=>o(`/api/v1/mux/${encodeURIComponent(c)}/events`),getRuntimeEventsUrl:c=>o(`/api/v1/runtime/${encodeURIComponent(c)}/events`),request:i}}const Af=iu({baseUrl:"http://localhost:3847"}),Tf=l.createContext(Af);function Mf({client:e,children:t}){return s.jsx(Tf.Provider,{value:e,children:t})}const Df={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},lu=l.createContext(Df);function If({value:e,children:t}){return s.jsx(lu.Provider,{value:e,children:t})}function St(){return l.useContext(lu)}function cu(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function Pf(e){const t=cu(e);if(!t||t.error!=="untrusted_external_provider")return null;const n=t.provider&&typeof t.provider=="object"?t.provider:null;return{providerType:typeof(n==null?void 0:n.type)=="string"?n.type:null,sourceName:typeof(n==null?void 0:n.sourceName)=="string"?n.sourceName:null,description:typeof t.hint=="string"?t.hint:void 0}}function Lf(e){const[t,n]=l.useState(null),r=l.useCallback(async(i,c)=>{const u=m=>e(i,"launch_cli",{...c,...m}),p=await u({}),d=Pf(p);return d?new Promise(m=>{n({providerType:d.providerType||String(c.cliType??"?"),sourceName:d.sourceName,description:d.description,retry:()=>u({confirmExternalUntrusted:!0}),resolve:f=>{f.cancelled?m({success:!1,error:"user_cancelled_untrusted_launch"}):m(f.response)}})}):p},[e]),a=l.useCallback(async()=>{const i=t;if(i){n(null);try{const c=await i.retry(),u=cu(c);u!=null&&u.success?i.resolve({ok:!0,response:c}):i.resolve({ok:!1,error:(u==null?void 0:u.error)||"launch failed after confirm",response:c})}catch(c){i.resolve({ok:!1,error:(c==null?void 0:c.message)||String(c)})}}},[t]),o=l.useCallback(()=>{const i=t;i&&(n(null),i.resolve({ok:!1,cancelled:!0}))},[t]);return{launchCli:r,pending:t,confirm:a,cancel:o}}function Rf({providerType:e,sourceName:t,description:n,onConfirm:r,onCancel:a}){const{t:o}=Ne("common"),i=l.useRef(null);return l.useEffect(()=>{var c;(c=i.current)==null||c.focus()},[]),l.useEffect(()=>{const c=u=>{u.key==="Escape"&&a()};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[a]),s.jsx("div",{role:"dialog","aria-modal":"true","aria-label":o("machine.confirmExternal.dialogAria"),className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",onClick:a,style:{pointerEvents:"auto"},children:s.jsxs("div",{className:"bg-[var(--surface-primary)] text-text-primary border border-amber-500/40 rounded-lg shadow-xl max-w-lg w-full",onClick:c=>c.stopPropagation(),children:[s.jsxs("div",{className:"px-4 py-3 border-b border-border-subtle flex items-center gap-2",children:[s.jsx("span",{"aria-hidden":!0,className:"text-amber-400 text-base",children:"⚠"}),s.jsx("h2",{className:"text-sm font-semibold",children:o("machine.confirmExternal.title")})]}),s.jsxs("div",{className:"px-4 py-3 text-[12px] flex flex-col gap-3",children:[s.jsxs("p",{children:["You're about to activate ",s.jsx("span",{className:"font-mono",children:e}),t?s.jsxs(s.Fragment,{children:[" from ",s.jsx("span",{className:"font-mono",children:t})]}):null,"."]}),s.jsx("p",{className:"text-text-secondary",children:n??o("machine.confirmExternal.description")}),s.jsx("p",{className:"text-text-secondary",children:o("machine.confirmExternal.proceedWarning")})]}),s.jsxs("div",{className:"px-4 py-2 border-t border-border-subtle flex justify-end gap-2",children:[s.jsx("button",{ref:i,type:"button",onClick:a,className:"px-3 py-1 text-sm rounded border border-border-default hover:bg-surface-secondary",children:o("machine.confirmExternal.cancel")}),s.jsx("button",{type:"button",onClick:r,className:"px-3 py-1 text-sm rounded bg-amber-500 text-black font-semibold hover:opacity-90",children:o("machine.confirmExternal.activate")})]})]})})}const du=l.createContext(null);function Ef({sendDaemonCommand:e,children:t}){const n=Lf(e),r=l.useMemo(()=>({launchCli:n.launchCli}),[n.launchCli]);return s.jsxs(du.Provider,{value:r,children:[t,n.pending&&s.jsx(Rf,{providerType:n.pending.providerType,sourceName:n.pending.sourceName,description:n.pending.description,onConfirm:n.confirm,onCancel:n.cancel})]})}function $a(){const e=l.useContext(du);return e||{launchCli:async()=>{throw new Error("useLaunchCli must be used inside <LaunchCliProvider>")}}}function uu(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function _f(e,t,n){return Number(e.receivedAt||n[ba(e)]||0)||0}function pu(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function $f(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function Kn(e,t){if(!e)return t;try{return(e.startsWith("file://")?new URL(e).pathname:e).split(/[\\/]/).filter(Boolean).pop()||t}catch{return e.split(/[\\/]/).filter(Boolean).pop()||t}}function io(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 Hf(e){let t=5381;for(let n=0;n<e.length;n++)t=(t<<5)+t^e.charCodeAt(n),t|=0;return(t>>>0).toString(36)}function ba(e,t){const n=e,r=Fi(e.content,{joiner:`
5
5
  `}),a=[e.id?`id:${e.id}`:"",n._localId?`local:${n._localId}`:"",n._turnKey?`turn:${n._turnKey}`:"",e.bubbleId?`bubble:${e.bubbleId}`:"",e.providerUnitKey?`unit:${e.providerUnitKey}`:"",typeof e.index=="number"?`msgIndex:${e.index}`:"",typeof e.sequence=="number"?`seq:${e.sequence}`:""].filter(Boolean);if(a.length>0)return a.join("|");const o=e.receivedAt||e.timestamp||0;return[e.role?`role:${e.role}`:"role:",`chash:${Hf(r)}`,o?`ts:${o}`:""].filter(Boolean).join("|")}function Ff(e){let t=2166136261;for(const n of e){const r=String(n||"");for(let a=0;a<r.length;a+=1)t^=r.charCodeAt(a),t=Math.imul(t,16777619)>>>0;t^=255,t=Math.imul(t,16777619)>>>0}return t.toString(16).padStart(8,"0")}function Bf(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function mu(e){return e?Ff([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),Bf(e.content)]):""}const Bi=200,Wf=80,Ul=650,Vn=new Map;function ga(e,t){if(!e)return!1;const n=String(e.messageFingerprint||"");return n?n===String(t||""):!0}function Of(e,t){if(!Array.isArray(e)||e.length===0)return"0:empty";const n=String(t||"").trim();if(n)return`${e.length}:${n}`;const r=e[e.length-1];return`${e.length}:${mu(r)}`}function Uf(e,t,n,r){return e||!t?!1:ga(n,r)}function Gf({scrollTop:e,scrollHeight:t,clientHeight:n,topThresholdPx:r=Wf,bottomThresholdPx:a=Bi}){const o=Math.max(0,Number(e)||0),i=Math.max(0,Number(t)||0),c=Math.max(0,Number(n)||0);return Math.max(0,i-c)<=0?{showTop:!1,showBottom:!1}:{showTop:o>r,showBottom:Math.max(0,i-o-c)>a}}function qf(e){return Gf({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function lr(e,t=Bi){return!!e&&e.fromBottom>=t}function zf(e,t){return ga(e,t)?!lr(e):!0}function Kf({hasSelection:e,userScrolledUp:t,hasChatContentChanged:n=!0}){return!(e||t||!n)}function Vf({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:n}){return e?!1:n||!t}function lo(e,t){const n=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(n)?n:t.top}const et={size:18};function hu({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"3",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"3",y:"14",width:"7",height:"7",rx:"1"}),s.jsx("rect",{x:"14",y:"14",width:"7",height:"7",rx:"1"})]})}function Wi({size:e=et.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polyline",{points:"15 18 9 12 15 6"})})}function Os({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),s.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),s.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),s.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function fu({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"9",cy:"7",r:"4"}),s.jsx("path",{d:"M22 21v-2a4 4 0 0 0-3-3.87"}),s.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}function Yf({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),s.jsx("circle",{cx:"12",cy:"7",r:"4"})]})}function Jf({size:e=et.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 2l-2 2m-7.61 7.61a5.5 5.5 0 1 1-7.778 7.778 5.5 5.5 0 0 1 7.777-7.777zm0 0L15.5 7.5m0 0l3 3L22 7l-3-3m-3.5 3.5L19 4"})})}function bu({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4 19.5A2.5 2.5 0 0 1 6.5 17H20"}),s.jsx("path",{d:"M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"}),s.jsx("line",{x1:"9",y1:"7",x2:"16",y2:"7"}),s.jsx("line",{x1:"9",y1:"11",x2:"14",y2:"11"})]})}function gu({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}),s.jsx("rect",{x:"8",y:"2",width:"8",height:"4",rx:"1"}),s.jsx("line",{x1:"8",y1:"10",x2:"16",y2:"10"}),s.jsx("line",{x1:"8",y1:"14",x2:"14",y2:"14"}),s.jsx("line",{x1:"8",y1:"18",x2:"12",y2:"18"})]})}function xu({size:e=et.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polyline",{points:"20 6 9 17 4 12"})})}function Ha({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"3"}),s.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})}function Oi({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),s.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})}function Qf({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"}),s.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function Xf({size:e=et.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"})})}function bn({size:e=et.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}function xs({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Ui({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),s.jsx("polyline",{points:"14 2 14 8 20 8"}),s.jsx("line",{x1:"8",y1:"13",x2:"16",y2:"13"}),s.jsx("line",{x1:"8",y1:"17",x2:"13",y2:"17"})]})}function En({size:e=et.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}function Fa({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function pn({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),s.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),s.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function wr({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M12 22v-5"}),s.jsx("path",{d:"M9 8V2"}),s.jsx("path",{d:"M15 8V2"}),s.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function os({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"5",r:"2"}),s.jsx("circle",{cx:"5",cy:"19",r:"2"}),s.jsx("circle",{cx:"19",cy:"19",r:"2"}),s.jsx("line",{x1:"12",y1:"7",x2:"5",y2:"17"}),s.jsx("line",{x1:"12",y1:"7",x2:"19",y2:"17"}),s.jsx("line",{x1:"5",y1:"19",x2:"19",y2:"19"})]})}function Zf({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polygon",{points:"12 2 2 7 12 12 22 7 12 2"}),s.jsx("polyline",{points:"2 12 12 17 22 12"}),s.jsx("polyline",{points:"2 17 12 22 22 17"})]})}function vu({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function Gi({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M17.94 17.94A10.94 10.94 0 0 1 12 20C5 20 1 12 1 12a21.8 21.8 0 0 1 5.06-5.94"}),s.jsx("path",{d:"M9.9 4.24A10.93 10.93 0 0 1 12 4c7 0 11 8 11 8a21.77 21.77 0 0 1-2.16 3.19"}),s.jsx("path",{d:"M14.12 14.12a3 3 0 1 1-4.24-4.24"}),s.jsx("line",{x1:"1",y1:"1",x2:"23",y2:"23"})]})}function yu({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("polyline",{points:"12 6 12 12 16 14"})]})}function eb({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"20",x2:"18",y2:"10"}),s.jsx("line",{x1:"12",y1:"20",x2:"12",y2:"4"}),s.jsx("line",{x1:"6",y1:"20",x2:"6",y2:"14"})]})}function qi({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"4 17 10 11 4 5"}),s.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})}function tb({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function wu({size:e=et.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function zi({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function Mt({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),s.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function sb({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"}),s.jsx("path",{d:"M12 15l-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"}),s.jsx("path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"}),s.jsx("path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"})]})}function nb({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"8",width:"18",height:"12",rx:"2"}),s.jsx("path",{d:"M12 2v6"}),s.jsx("circle",{cx:"8.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"15.5",cy:"14",r:"1.5",fill:"currentColor",stroke:"none"})]})}function rb({size:e=et.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"})})}function ab({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"9",y:"10",width:"6",height:"12",rx:"1"}),s.jsx("path",{d:"M12 2c-1.5 2-3 3.5-3 5a3 3 0 0 0 6 0c0-1.5-1.5-3-3-5z"})]})}function Un({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),s.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}function ku({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M8.7 3A6 6 0 0 1 18 8c0 3 .6 5 1.4 6.5"}),s.jsx("path",{d:"M17 17H3s3-2 3-9a5.98 5.98 0 0 1 .6-2.6"}),s.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"}),s.jsx("line",{x1:"2",y1:"2",x2:"22",y2:"22"})]})}function ob({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"5"}),s.jsx("line",{x1:"12",y1:"1",x2:"12",y2:"3"}),s.jsx("line",{x1:"12",y1:"21",x2:"12",y2:"23"}),s.jsx("line",{x1:"4.22",y1:"4.22",x2:"5.64",y2:"5.64"}),s.jsx("line",{x1:"18.36",y1:"18.36",x2:"19.78",y2:"19.78"}),s.jsx("line",{x1:"1",y1:"12",x2:"3",y2:"12"}),s.jsx("line",{x1:"21",y1:"12",x2:"23",y2:"12"}),s.jsx("line",{x1:"4.22",y1:"19.78",x2:"5.64",y2:"18.36"}),s.jsx("line",{x1:"18.36",y1:"5.64",x2:"19.78",y2:"4.22"})]})}function ib({size:e=et.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"})})}function lb({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",ry:"2"}),s.jsx("line",{x1:"8",y1:"21",x2:"16",y2:"21"}),s.jsx("line",{x1:"12",y1:"17",x2:"12",y2:"21"})]})}function Su({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),s.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function cb({size:e=et.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}function db({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),s.jsx("path",{d:"M19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07"})]})}function ub({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M14.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),s.jsx("path",{d:"M9.5 10c-.83 0-1.5-.89-1.5-2s.67-2 1.5-2 1.5.89 1.5 2-.67 2-1.5 2z"}),s.jsx("path",{d:"M19.35 6.07A16.03 16.03 0 0 0 15 4a.84.84 0 0 0-.46.33 11 11 0 0 0-.74 1.5 15.68 15.68 0 0 0-3.6 0 11.23 11.23 0 0 0-.74-1.5A.84.84 0 0 0 9 4a16.03 16.03 0 0 0-4.35 2.07A16.8 16.8 0 0 0 2 15a16.22 16.22 0 0 0 4 3c.12.08.27.06.37-.04a11.14 11.14 0 0 0 1.2-1.92.35.35 0 0 0-.18-.46 10.4 10.4 0 0 1-1.63-.78.36.36 0 0 1 .03-.6 6.8 6.8 0 0 0 .32-.24.36.36 0 0 1 .37-.04c2.2.98 4.6.98 6.8 0a.36.36 0 0 1 .37.04c.1.08.21.16.32.24a.36.36 0 0 1 .03.6 10.4 10.4 0 0 1-1.63.78.35.35 0 0 0-.18.46c.39.67.8 1.3 1.2 1.92a.37.37 0 0 0 .37.04 16.22 16.22 0 0 0 4-3 16.8 16.8 0 0 0-2.65-8.93z"})]})}function pb({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"7",width:"15",height:"14",rx:"2"}),s.jsx("path",{d:"M13 2h9v9"}),s.jsx("path",{d:"M22 2L13 11"})]})}function mb({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"9 14 4 9 9 4"}),s.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}function hb({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}),s.jsx("line",{x1:"6",y1:"8",x2:"6.01",y2:"8"}),s.jsx("line",{x1:"10",y1:"8",x2:"10.01",y2:"8"}),s.jsx("line",{x1:"14",y1:"8",x2:"14.01",y2:"8"}),s.jsx("line",{x1:"18",y1:"8",x2:"18.01",y2:"8"}),s.jsx("line",{x1:"6",y1:"12",x2:"6.01",y2:"12"}),s.jsx("line",{x1:"10",y1:"12",x2:"10.01",y2:"12"}),s.jsx("line",{x1:"14",y1:"12",x2:"14.01",y2:"12"}),s.jsx("line",{x1:"18",y1:"12",x2:"18.01",y2:"12"}),s.jsx("line",{x1:"7",y1:"16",x2:"17",y2:"16"})]})}function fb({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"6",width:"13",height:"13",rx:"2"}),s.jsx("path",{d:"M9 6V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2"})]})}function bb({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),s.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"21"}),s.jsx("line",{x1:"3",y1:"12",x2:"12",y2:"12"})]})}function gb({size:e=et.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("line",{x1:"2",y1:"12",x2:"22",y2:"12"}),s.jsx("path",{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"})]})}const Cu="adhdev_chat_activity_visible",Gl=new Set(["hidden","debug","internal"]),ql=new Set(["visible","user","chat"]),xb=new Set(["debug","trace","internal"]),vb=new Set(["tool_call","terminal_command","runtime_activity"]),yb=new Set(["runtime_status","provider_chrome","control"]),wb=new Set(["thought","tool","terminal"]);function ju(e){const t=e.meta;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function kn(e){return typeof e=="string"?e.trim().toLowerCase():""}function co(e,t,n){return e[n]??(t==null?void 0:t[n])}function zl(e,t,n){const r=e;return n.some(a=>r[a]===!0||(t==null?void 0:t[a])===!0)}function kb(e,t){const n=kn(e.kind);return n||(t==="tool"?"tool":"standard")}function uo(e,t,n){const r=ju(e),a=typeof(r==null?void 0:r.label)=="string"?r.label.trim():"";return a||(t==="terminal"||n==="terminal_command"?"Terminal":t==="tool"||n==="tool_call"?"Tool":t==="thought"?"Thought":n==="runtime_activity"?"Runtime":"Activity")}function Sb(e){const t=e.content;return Array.isArray(t)&&t.some(n=>!!n&&typeof n=="object"&&n.type!=="text")}function Ki(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal"};const t=ju(e),n=kn(e.role),r=kb(e,n),a=kn(co(e,t,"visibility")),o=kn(e.transcriptVisibility??(t==null?void 0:t.transcriptVisibility)??a),i=kn(co(e,t,"audience")),c=kn(co(e,t,"source")),u=Gl.has(a)||Gl.has(o)||xb.has(i)||zl(e,t,["internal","isInternal","debug","statusOnly","controlOnly"]),p=ql.has(a)||ql.has(o)||i==="chat"||zl(e,t,["userFacing"]),d=wb.has(r)||vb.has(c);if(u)return{surface:d?"activity":"internal",isUserFacing:!1,isActivityFacing:d,isInternal:!d,role:n,kind:r,label:uo(e,r,c)};if(p)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:n,kind:r,label:uo(e,r,c)};if((n==="system"||r==="system")&&Sb(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:n,kind:r,label:"Chat"};if(yb.has(c)||n==="system"||r==="system")return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:n,kind:r,label:"Internal"};if(d)return{surface:"activity",isUserFacing:!1,isActivityFacing:!0,isInternal:!1,role:n,kind:r,label:uo(e,r,c)};const m=(n==="user"||n==="human"||n==="assistant")&&(r==="standard"||r==="");return{surface:m?"chat":"internal",isUserFacing:m,isActivityFacing:!1,isInternal:!m,role:n,kind:r,label:m?"Chat":"Internal"}}function Cb(e){return(Array.isArray(e)?e:[]).filter(t=>Ki(t).isUserFacing)}function Nu(e){return(Array.isArray(e)?e:[]).filter(t=>Ki(t).isActivityFacing)}function Au(e){const t=e.content;return typeof t=="string"?t:(()=>{try{return JSON.stringify(t??"")}catch{return String(t??"")}})()}function jb(e){return`${String(e.role||"")}::${Au(e)}`}function Nb(e){if(e.length<2)return e;const t=[];let n="";for(const r of e){const a=jb(r);Au(r).trim().length>0&&a===n||(t.push(r),n=a)}return t}function Ab(e,t,n){return!n||t.length===0?e:[...e,...t].sort((r,a)=>{const o=Number(r.receivedAt??r.timestamp??0)||0,i=Number(a.receivedAt??a.timestamp??0)||0;if(o!==i)return o-i;const c=Number(r.index??0)||0,u=Number(a.index??0)||0;return c-u})}function Kl(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(Cu))==="1"}catch{return!1}}function Tb({text:e}){const{t}=Ne("common"),[n,r]=l.useState(!1),a=l.useCallback(()=>{navigator.clipboard.writeText(e).catch(()=>{}),r(!0),setTimeout(()=>r(!1),1500)},[e]);return s.jsx("button",{type:"button",onClick:a,"aria-label":t("chat.copyMessage"),className:"chat-copy-btn",children:n?s.jsx(xu,{size:11}):s.jsx(gu,{size:11})})}const Tu=[Bh,{singleTilde:!1}],Mu=[Tu,Wh,Oh],Mb=[Tu];function $r(e,t,n){return s.jsxs("div",{className:"rounded-md border border-border-subtle p-2 text-sm",role:"note",children:[s.jsx("span",{className:"font-medium",children:e}),t?s.jsx("span",{className:"ml-1 break-all",children:t}):null,n?s.jsx("div",{className:"mt-1 opacity-80",style:{whiteSpace:"pre-wrap"},children:n}):null]})}function Vl(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):pu(e)?s.jsx($i,{remarkPlugins:Mu,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}const Db=l.memo(function({content:t,renderAsPreformatted:n,renderAsMarkdown:r}){return n?s.jsx("pre",{className:"chat-preformatted",children:t}):r?s.jsx($i,{remarkPlugins:Mu,children:t}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:t})});function Yn({parts:e,renderAsPreformatted:t}){return s.jsx("div",{className:"flex flex-col gap-2",children:e.map((n,r)=>{if(n.type==="text")return s.jsx("div",{children:Vl(String(n.text||""),t)},`text-${r}`);if(n.type==="image"){const a=io(n),o=n.alt||n.description||Kn(n.uri,"image");return a?s.jsx("img",{src:a,alt:o,className:"max-w-full rounded-md border border-border-subtle"},`image-${r}`):s.jsx("div",{children:$r("Image",o,n.mimeType)},`image-fallback-${r}`)}if(n.type==="audio"){const a=io(n);return a?s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx("audio",{controls:!0,src:a,className:"max-w-full"}),n.transcript?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:n.transcript}):null]},`audio-${r}`):s.jsx("div",{children:$r("Audio",Kn(n.uri,"audio"),n.transcript||n.mimeType)},`audio-fallback-${r}`)}if(n.type==="video"){const a=io(n),o=n.title||n.name||n.alt||Kn(n.uri,"video"),i=[n.transcript,n.description,n.mimeType].filter(Boolean).join(`
6
6
  `);return s.jsxs("div",{className:"flex flex-col gap-1",children:[a?s.jsx("video",{controls:!0,src:a,poster:n.posterUri,className:"max-w-full rounded-md border border-border-subtle"}):$r("Video",o,i),a&&i?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:i}):null]},`video-${r}`)}if(n.type==="resource_link"){const a=n.title||n.name||Kn(n.uri,"resource"),o=[n.description,n.mimeType].filter(Boolean).join(`
7
7
  `);return s.jsxs("div",{className:"flex flex-col gap-1",children:[n.uri?s.jsx("a",{href:n.uri,target:"_blank",rel:"noreferrer",download:!0,className:"underline break-all",children:a}):$r("Resource",a,o),n.uri&&o?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:o}):null]},`resource-link-${r}`)}if(n.type==="resource"&&n.resource){const a=Kn(n.resource.uri,"resource");if(n.resource.text)return s.jsxs("div",{className:"rounded-md border border-border-subtle p-2",children:[s.jsx("div",{className:"text-[11px] opacity-70 mb-1",children:a}),Vl(n.resource.text,!0)]},`resource-${r}`);if(n.resource.uri)return s.jsx("a",{href:n.resource.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:a},`resource-uri-${r}`)}return null})})}const Ib=l.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx($i,{remarkPlugins:Mb,children:t.text}),s.jsx("span",{className:"action-time",children:uu(t.timestamp)})]})},(e,t)=>e.log===t.log);function Yl(e){const t=e.meta;return[mu(e),e.kind||"",e.senderName||"",e.bubbleId||"",e.bubbleState||"",e.visibility||"",e.transcriptVisibility||"",e.audience||"",e.source||"",e.userFacing===void 0?"":String(e.userFacing),e.internal===void 0?"":String(e.internal),e.isInternal===void 0?"":String(e.isInternal),e.debug===void 0?"":String(e.debug),t?String(t.label??""):"",t?String(t.isRunning??""):"",t?String(t.renderMode??""):""].join("")}const Pb=l.memo(function({message:t,receivedAt:n,agentName:r,userName:a,isCliMode:o,isTextExpanded:i,onToggleTextExpanded:c}){var w,A,T;const u=(t.role||"").toLowerCase(),p=u==="user"||u==="human",d=t.kind||(u==="tool"?"tool":"standard"),m=Ki(t),f=$f(t.content)?t.content:null,g=!!(f!=null&&f.some(I=>I.type!=="text")),S=Fi(t.content,{joiner:`
8
- `});if(m.isActivityFacing&&d!=="thought"&&d!=="tool"&&d!=="terminal"){const I=m.label||"Activity";return s.jsxs("div",{className:"self-start chat-msg-activity","data-chat-activity-row":"true",children:[s.jsxs("div",{className:"chat-msg-activity-meta","aria-label":"Activity message",children:[s.jsx("span",{className:"activity-dot"}),s.jsx("span",{children:I})]}),g&&f?s.jsx("div",{className:"chat-msg-activity-body",children:s.jsx(Yn,{parts:f,renderAsPreformatted:!1})}):s.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:S})]})}if(d==="thought"){const I=typeof((w=t.meta)==null?void 0:w.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought","data-chat-activity-row":m.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(rb,{size:13}),s.jsx("span",{children:I})]}),s.jsx("div",{className:"chat-msg-body",children:S})]})}if(d==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool","data-chat-activity-row":m.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-tool-meta","aria-label":"Tool message",children:[s.jsx("span",{className:"tool-icon",children:"⏺"}),s.jsx("span",{className:"tool-label",children:"Tool"})]}),g&&f?s.jsx("div",{className:"tool-text w-full",children:s.jsx(Yn,{parts:f,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:S})]});if(d==="terminal"){const I=(A=t.meta)!=null&&A.isRunning?"⏳":"✅",P=typeof((T=t.meta)==null?void 0:T.label)=="string"?t.meta.label:"Ran command";return s.jsxs("div",{className:"self-start chat-msg-terminal","data-chat-activity-row":m.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:I}),s.jsx("span",{children:P})]}),g&&f?s.jsx("div",{className:"chat-msg-body",children:s.jsx(Yn,{parts:f,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:S})]})}if(d==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:g&&f?s.jsx(Yn,{parts:f,renderAsPreformatted:!1}):S.slice(0,100)});const h=t.meta,y=(typeof(h==null?void 0:h.renderMode)=="string"?h.renderMode.trim():"")==="preformatted",b=S,C=!1,j=b,k=y,v=!p&&!k&&pu(j),N=["chat-message-row",p?"chat-message-row-user self-end":"chat-message-row-assistant self-start"].join(" ");return s.jsx("div",{className:N,children:(b||g||p)&&s.jsxs("div",{className:`chat-bubble ${p?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${b||g?"mb-1.5":"mb-0"}`,children:[s.jsx("span",{className:"chat-sender",children:p?a||"You":t.senderName||r}),s.jsxs("span",{className:"chat-bubble-header-end",children:[(b||g)&&s.jsx(Tb,{text:S}),n!=null&&s.jsx("span",{className:"chat-time",children:uu(n)})]})]}),(b||g)&&s.jsx("div",{className:"chat-markdown",children:g&&f?s.jsx(Yn,{parts:f,renderAsPreformatted:k}):s.jsx(Db,{content:j,renderAsPreformatted:k,renderAsMarkdown:v})}),C]})})},(e,t)=>(e.message===t.message||Yl(e.message)===Yl(t.message))&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded),Lb=l.forwardRef(function({messages:t,actionLogs:n,agentName:r="Agent",userName:a,isCliMode:o=!1,isWorking:i=!1,contextKey:c="",receivedAtMap:u={},lastMessageHash:p,showActivityMessages:d=!1,emptyState:m,onLoadMore:f,isLoadingMore:g,hasMoreHistory:S,hiddenLiveCount:h=0,loadError:x,scrollToBottomRequestNonce:y,isVisible:b=!0},C){const{t:j}=Ne("common"),k=l.useRef(null),v=l.useRef(null),N=l.useRef(null),w=l.useRef(0),A=l.useRef(""),T=l.useRef(""),I=l.useRef(!1),P=l.useRef(null),D=l.useRef(!1),_=l.useRef(null),W=l.useRef(!1),[$,E]=l.useState(new Set),[B,L]=l.useState({showTop:!1,showBottom:!1}),R=l.useRef(!1),M=l.useRef(!1),F=l.useRef(b),K=l.useRef(b),J=l.useRef(null);K.current=b;const V=()=>{const de=k.current;return de?de.scrollHeight-de.scrollTop-de.clientHeight<Bi:!0},Y=l.useCallback(()=>{const de=k.current,H=de?qf(de):{showTop:!1,showBottom:!1};L(he=>he.showTop===H.showTop&&he.showBottom===H.showBottom?he:H)},[]),se=l.useCallback((de="auto")=>{var he;const H=k.current;H&&(H.scrollTo({top:H.scrollHeight,behavior:de}),(he=H.ownerDocument.defaultView)==null||he.requestAnimationFrame(()=>Y()))},[Y]),ie=l.useCallback((de="auto")=>{var he;const H=k.current;H&&(H.scrollTo({top:0,behavior:de}),(he=H.ownerDocument.defaultView)==null||he.requestAnimationFrame(()=>Y()))},[Y]),Z=l.useCallback(()=>{var ye;const de=k.current,H=(ye=window.getSelection)==null?void 0:ye.call(window);if(!de||!H||H.rangeCount===0||H.isCollapsed){W.current=!1;return}const he=H.anchorNode,fe=H.focusNode;W.current=!!(he&&fe&&de.contains(he)&&de.contains(fe))},[]),O=l.useMemo(()=>{const de=Cb(t),H=Nu(t);return Nb(Ab(de,H,d))},[t,d]),ee=O.length===t.length?p:void 0,G=Of(O,ee),le=l.useCallback(()=>{const de=k.current;if(!de||!c||!K.current)return;const H={top:de.scrollTop,fromBottom:Math.max(0,de.scrollHeight-de.scrollTop-de.clientHeight),messageFingerprint:G};J.current={contextKey:c,snapshot:H},Vn.set(c,H)},[c,G]),je=l.useCallback((de="auto")=>{P.current!=null&&cancelAnimationFrame(P.current),P.current=requestAnimationFrame(()=>{P.current=null,se(de)})},[se]),ge=l.useCallback(()=>{R.current=!1,D.current=!0,M.current=!0,_.current!=null&&window.clearTimeout(_.current),_.current=window.setTimeout(()=>{D.current=!1,_.current=null},Ul)},[]);l.useEffect(()=>{const de=!I.current,H=T.current!==c;if(T.current=c,de||H){I.current=!0;const fe=c?Vn.get(c):null,ye=!!fe&&ga(fe,G);R.current=ye?lr(fe):!1,D.current=zf(fe,G),W.current||(ye?requestAnimationFrame(()=>{const Pe=k.current;Pe&&(lo(Pe,fe),R.current=lr(fe),Y(),M.current=!0)}):je("auto")),w.current=O.length,A.current=G;return}O.length>w.current;const he=G!==A.current;Kf({hasSelection:W.current,userScrolledUp:R.current,hasChatContentChanged:he})&&je("auto"),w.current=O.length,A.current=G},[G,c,O.length,je,Y]),l.useEffect(()=>{y&&(ge(),W.current||je("auto"))},[ge,je,y]),l.useEffect(()=>{const de=F.current;de&&!b&&le(),K.current=b,F.current=b;const H=c?Vn.get(c):null;if(Uf(de,b,H,G)){if(!H)return;R.current=lr(H),D.current=!1,W.current||requestAnimationFrame(()=>{const he=k.current;he&&(lo(he,H),Y())});return}},[b,c,G,ge,le,je,Y]),l.useEffect(()=>()=>{const de=J.current;de&&Vn.set(de.contextKey,de.snapshot),P.current!=null&&cancelAnimationFrame(P.current),_.current!=null&&window.clearTimeout(_.current)},[]),l.useEffect(()=>{const de=v.current,H=k.current;if(!de||!H)return;const he=()=>{_.current!=null&&window.clearTimeout(_.current),_.current=window.setTimeout(()=>{D.current=!1,_.current=null},Ul)},fe=new ResizeObserver(()=>{Y();const ye=D.current;Vf({hasSelection:W.current,userScrolledUp:R.current,contextAutoScrollActive:ye})&&(je("auto"),ye&&he())});return fe.observe(de),H!==de&&fe.observe(H),()=>{fe.disconnect(),_.current!=null&&(window.clearTimeout(_.current),_.current=null)}},[je,c,Y]),l.useImperativeHandle(C,()=>({scrollToBottom:(de="smooth")=>{se(de)}}),[se]),l.useEffect(()=>{const de=k.current;if(!de)return;let H;const he=()=>{le(),clearTimeout(H),H=setTimeout(()=>{R.current=!V(),Y()},50)};return de.addEventListener("scroll",he,{passive:!0}),()=>{de.removeEventListener("scroll",he),clearTimeout(H)}},[le,Y]),l.useEffect(()=>(document.addEventListener("selectionchange",Z),()=>document.removeEventListener("selectionchange",Z)),[Z]);const Ce=l.useRef(0),ue=l.useRef(!1);l.useEffect(()=>{const de=k.current;if(!de||!ue.current||Ce.current===0)return;const H=de.scrollHeight-Ce.current;H>0&&(de.scrollTop=H),Y(),le(),Ce.current=0,ue.current=!1},[O.length,le,Y]),l.useEffect(()=>{if(M.current||!c)return;const de=Vn.get(c),H=k.current;if(!(!de||!H)){if(!ga(de,G)){se("auto"),M.current=!0;return}lo(H,de),R.current=lr(de),Y(),M.current=!0}},[c,G,O.length,se,Y]);const z=()=>{const de=k.current;de&&(Ce.current=de.scrollHeight),ue.current=!0,f==null||f()},U=()=>{R.current=!0,ie("smooth"),le()},q=()=>{ge(),se("smooth"),le()},Q=l.useMemo(()=>{const de=O.map((ye,Pe)=>({type:"message",data:ye,index:Pe,ts:_f(ye,Pe,u)}));if(!n||n.length===0)return de;const H=[...n].sort((ye,Pe)=>ye.timestamp-Pe.timestamp).map((ye,Pe)=>({type:"action",data:ye,index:Pe,ts:ye.timestamp})),he=[];let fe=0;for(const ye of de){for(;fe<H.length&&ye.ts>0&&H[fe].ts<ye.ts;)he.push(H[fe++]);he.push(ye)}for(;fe<H.length;)he.push(H[fe++]);return he},[O,n,u]),me=h>0||!!S,Ae=h>0?h>80?j("chatList.showEarlierMessagesHidden",{count:Math.min(h,80),total:h}):j("chatList.showEarlierMessages",{count:Math.min(h,80)}):x?j("chatList.loadErrorRetry",{error:x}):j("chatList.loadOlderMessages");return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:k,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:v,className:"chat-container-content",children:[g&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:j("chatList.loadingOlderMessages")}),me&&!g&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:z,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${x&&h===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:Ae})}),Q.length===0&&!me&&(m||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:j("chatList.waitingForMessages")})),Q.map(de=>{if(de.type==="action"){const He=de.data;return s.jsx(Ib,{log:He},`action-${de.index}`)}const H=de.data;de.index;const he=ba(H),fe=H.receivedAt||u[he],ye=`${c}-${he}`,Pe=$.has(ye);return s.jsx(Pb,{message:H,receivedAt:fe,agentName:r,userName:a,isCliMode:o,isTextExpanded:Pe,onToggleTextExpanded:()=>E(He=>{const ke=new Set(He);return Pe?ke.delete(ye):ke.add(ye),ke})},`msg-${he}`)}),i&&s.jsx("div",{className:"self-start chat-typing-wrapper",children:s.jsxs("div",{className:"typing-indicator",children:[s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:j("chatList.agentGenerating")})]})}),s.jsx("div",{className:"min-h-10",ref:N})]})}),(B.showTop||B.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":j("chatList.jumpToTop"),children:[B.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:U,"aria-label":j("chatList.jumpToOldestMessages"),title:j("chatList.jumpToTop"),children:j("chatList.top")}),B.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:q,"aria-label":j("chatList.jumpToLatestMessages"),title:j("chatList.jumpToBottom"),children:j("chatList.latest")})]})]})}),Rb=l.memo(Lb,(e,t)=>e.messages===t.messages&&e.actionLogs===t.actionLogs&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isWorking===t.isWorking&&e.contextKey===t.contextKey&&e.receivedAtMap===t.receivedAtMap&&e.lastMessageHash===t.lastMessageHash&&e.showActivityMessages===t.showActivityMessages&&e.emptyState===t.emptyState&&e.onLoadMore===t.onLoadMore&&e.isLoadingMore===t.isLoadingMore&&e.hasMoreHistory===t.hasMoreHistory&&e.hiddenLiveCount===t.hiddenLiveCount&&e.loadError===t.loadError&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isVisible===t.isVisible),Eb="modulepreload",_b=function(e){return"/"+e},Jl={},$b=function(t,n,r){let a=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),c=(i==null?void 0:i.nonce)||(i==null?void 0:i.getAttribute("nonce"));a=Promise.allSettled(n.map(u=>{if(u=_b(u),u in Jl)return;Jl[u]=!0;const p=u.endsWith(".css"),d=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const m=document.createElement("link");if(m.rel=p?"stylesheet":Eb,p||(m.as="script"),m.crossOrigin="",m.href=u,c&&m.setAttribute("nonce",c),document.head.appendChild(m),p)return new Promise((f,g)=>{m.addEventListener("load",f),m.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${u}`)))})}))}function o(i){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=i,window.dispatchEvent(c),!c.defaultPrevented)throw i}return a.then(i=>{for(const c of i||[])c.status==="rejected"&&o(c.reason);return t().catch(o)})};let Ql=!1;const Du=l.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:n,fontSize:r=13,readOnly:a=!1,sizingMode:o="measured"},i)=>{const c=l.useRef(null),[u,p]=l.useState(null),d=l.useRef([]),m=l.useRef(!1),f=l.useRef(!1),g=l.useRef(!1),S=l.useRef(!1),h=()=>{const x=c.current;if(x){m.current&&(x.clear(),m.current=!1);for(const y of d.current)x.write(y.data,y.onProcessed);d.current=[],f.current&&(x.fit(),f.current=!1),g.current&&(x.bumpResize(),g.current=!1),S.current&&(x.scrollToTop(),S.current=!1)}};return l.useImperativeHandle(i,()=>({write:(x,y)=>{c.current?c.current.write(x,y):d.current.push({data:x,onProcessed:y})},clear:()=>{c.current?c.current.clear():(d.current=[],m.current=!0)},reset:()=>{c.current&&typeof c.current.reset=="function"?c.current.reset():(d.current=[],m.current=!0)},resize:(x,y)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(x,y)},fit:()=>{c.current?c.current.fit():f.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():g.current=!0},scrollToTop:()=>{c.current?c.current.scrollToTop():S.current=!0},getSelection:()=>{var x,y;return((y=(x=c.current)==null?void 0:x.getSelection)==null?void 0:y.call(x))||""},getVisibleText:()=>{var x,y;return((y=(x=c.current)==null?void 0:x.getVisibleText)==null?void 0:y.call(x))||""}}),[]),l.useEffect(()=>{u&&h()},[u]),l.useEffect(()=>{let x=!1;return $b(()=>import("./terminal-DiXj2eIR.js"),__vite__mapDeps([0,1,2])).then(y=>{Ql||(Ql=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),x||p(()=>y.GhosttyTerminalView)}).catch(y=>{console.error("[CliTerminal] failed to load terminal renderer",y)}),()=>{x=!0}},[]),u?s.jsx(u,{ref:c,onInput:e,onViewportMetrics:t,onScrollMetrics:n,fontSize:r,readOnly:a,sizingMode:o,className:"w-full h-full rounded-lg overflow-hidden"}):s.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});Du.displayName="CliTerminal";function Wt(...e){return Uh(Gh(e))}const Hb={lg:"rounded-lg",xl:"rounded-xl","2xl":"rounded-2xl"},Fb={none:"",sm:"p-3",md:"px-4 py-3.5",lg:"px-5 py-4"},Ls=l.forwardRef(function({radius:t="xl",padding:n="md",className:r,...a},o){return s.jsx("div",{ref:o,className:Wt("border border-border-subtle bg-bg-secondary",Hb[t],Fb[n],r),...a})});function Hr({label:e,value:t,sub:n,icon:r}){return s.jsxs(Ls,{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[s.jsx("span",{className:"text-base flex items-center",children:r}),s.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:e})]}),s.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:t}),n&&s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:n})]})}function Xl({value:e,max:t,label:n,color:r="#8b5cf6",detail:a,compact:o=!1}){const i=t>0?Math.min(Math.round(e/t*100),100):0,c=i>85?"#ef4444":i>60?"var(--status-warning)":r;return o?s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-0.5",children:[s.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide font-semibold",children:n}),s.jsxs("span",{className:"text-[10px] text-text-secondary font-semibold",children:[i,"%"]})]}),s.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${i}%`,background:c}})})]}):s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-1.5",children:[s.jsx("span",{className:"text-[11px] text-text-secondary font-medium",children:n}),s.jsxs("span",{className:"text-[13px] text-text-primary font-bold",children:[i,"%"]})]}),s.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${i}%`,background:`linear-gradient(90deg, ${c}, ${c}cc)`}})}),a&&s.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:a})]})}function Bb({cursorPos:e,viewportRef:t,imgRef:n}){var b;if(!e||!n.current)return null;const r=n.current,a=r.getBoundingClientRect(),o=(b=t.current)==null?void 0:b.getBoundingClientRect();if(!o)return null;const i=r.naturalWidth||a.width,c=r.naturalHeight||a.height,u=i/c,p=a.width/a.height;let d,m,f,g;u>p?(d=a.width,m=a.width/u,f=0,g=(a.height-m)/2):(m=a.height,d=a.height*u,f=(a.width-d)/2,g=0);const S=a.left-o.left+f+d*e.nx,h=a.top-o.top+g+m*e.ny,x=Math.max(8,Math.min(o.width-8,S)),y=Math.max(8,Math.min(o.height-8,h));return s.jsxs("div",{style:{position:"absolute",left:x-8,top:y-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[s.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:5,top:5,width:6,height:6,borderRadius:"50%",background:"#3b82f6",boxShadow:"0 0 8px rgba(59,130,246,0.6)"}})]})}function Wb({inputMode:e,onToggleInputMode:t,isImeOpen:n,setIsImeOpen:r,isMenuOpen:a,setIsMenuOpen:o,imeText:i,setImeText:c,handleImeSubmit:u,isConnActive:p,zoom:d,isMobile:m,mobileFillZoom:f,onZoomOut:g,onZoomReset:S,onZoomIn:h,transportType:x,screenshotUsage:y,lastActionStatus:b}){const{t:C}=Ne("common");return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:j=>j.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[s.jsxs("div",{onClick:t,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[s.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),s.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:C(e==="mouse"?"remote.mouse":"remote.touch")})]}),s.jsxs("div",{className:"relative",children:[s.jsx("div",{onClick:()=>{r(j=>!j),o(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${n?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⌨️"})}),n&&s.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:s.jsx("input",{type:"text",placeholder:C("remote.typeAndEnter"),value:i,autoFocus:!0,onTouchStart:j=>j.stopPropagation(),onChange:j=>c(j.target.value),onKeyDown:j=>{u(j)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),s.jsx("div",{className:"relative",children:s.jsx("div",{onClick:()=>{o(j=>!j),r(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⚙️"})})}),s.jsx("div",{className:"w-px h-[18px] bg-white/10"}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:p?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[s.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:p?"#22c55e":"#eab308",boxShadow:p?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),s.jsx("span",{className:"text-[8px] font-extrabold",style:{color:p?"#22c55e":"#eab308"},children:C(p?"remote.connected":"remote.ws")})]}),d>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(d*100),"%"]}),x==="direct"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:C("remote.directP2PTitle"),children:C("remote.direct")}),x==="relay"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:C("remote.turnRelayTitle"),children:C("remote.relay")}),y&&y.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:y.budgetExhausted?"#ef4444":"#c4b5fd",background:y.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:C("remote.dailyTurnTitle"),children:y.budgetExhausted?C("remote.turnBlocked"):C("remote.turnUsage",{used:y.dailyUsedMinutes,budget:y.dailyBudgetMinutes})}),b&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:b})]})]}),a&&s.jsxs("div",{onTouchStart:j=>j.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[s.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:C("remote.settings")}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:[C("remote.zoom")," ",d<=(m?f:1)+.01?C(m?"remote.fill":"remote.fit"):`${Math.round(d*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:j=>{j.stopPropagation(),g()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),s.jsx("button",{onClick:j=>{j.stopPropagation(),S()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:C(m?"remote.fill":"remote.fit")}),s.jsx("button",{onClick:j=>{j.stopPropagation(),h()},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 Ob({waitingLabel:e,waitingHint:t,transportType:n}){const{t:r}=Ne("common");return s.jsxs("div",{className:"text-center flex flex-col items-center gap-3 px-6",children:[s.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center border border-white/10 bg-white/[0.04] shadow-[0_10px_30px_rgba(0,0,0,0.35)]",style:{animation:"remote-float 2.8s ease-in-out infinite"},children:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-8 h-8 opacity-90"})}),s.jsx("div",{className:"text-white/85 text-[13px] font-semibold tracking-wide",children:e}),s.jsx("div",{className:"text-[11px] text-white/40",children:t}),n==="relay"&&s.jsx("div",{className:"text-[10px] font-medium",style:{color:"var(--status-warning)",opacity:.8},children:r("remote.waitingState.turnRelayActive")})]})}function Ub(){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 Zl(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 Dr(e,t){const n=l.useRef(null),r=l.useRef(0);l.useEffect(()=>{if(!Ub())return;r.current+=1;const a=n.current;if(!a){console.debug(`[render-trace] ${e}#${r.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(t).map(([i,c])=>[i,Zl(c)]))}),n.current=t;return}const o=Object.keys({...a,...t}).filter(i=>!Object.is(a[i],t[i]));o.length>0&&console.debug(`[render-trace] ${e}#${r.current}`,{changed:o,snapshot:Object.fromEntries(o.map(i=>[i,Zl(t[i])]))}),n.current=t})}function Gb({containerRef:e,viewportRef:t,imgRef:n,inputMode:r,setInputMode:a,minZoom:o,zoomRef:i,panXRef:c,panYRef:u,setPanX:p,setPanY:d,setZoom:m,lastWheelTimeRef:f,onAction:g,setLastActionStatus:S,spawnRippleFromNormalized:h,clampPan:x,isMobile:y,mobileFillZoom:b}){const[C,j]=l.useState(null),k=l.useRef(null),v=l.useRef(null),N=l.useRef(null),w=l.useRef(!1),A=l.useRef(null),T=l.useRef(0),I=l.useRef(null),P=l.useRef(1),D=l.useRef({x:0,y:0}),_=l.useRef(!1),W=l.useRef(r),$=l.useRef(g),E=30,B=550,L=18,R=60,M=400,F=12,K=()=>{if(k.current)return;const Y={nx:.5,ny:.5};k.current=Y,j(Y)};return l.useEffect(()=>{W.current=r,r==="mouse"&&K()},[r]),l.useEffect(()=>{$.current=g},[g]),l.useEffect(()=>{const Y=e.current;if(!Y)return;const se=le=>{if(!n.current)return null;const je=n.current.getBoundingClientRect();return!je.width||!je.height?null:{nx:Math.max(0,Math.min(1,(le.clientX-je.left)/je.width)),ny:Math.max(0,Math.min(1,(le.clientY-je.top)/je.height))}},ie=(le,je)=>{if(!n.current)return{dnx:0,dny:0};const ge=n.current,Ce=ge.getBoundingClientRect(),ue=ge.naturalWidth||Ce.width,z=ge.naturalHeight||Ce.height,U=ue/z,q=Ce.width/Ce.height;let Q,me;return U>q?(Q=Ce.width,me=Ce.width/U):(me=Ce.height,Q=Ce.height*U),{dnx:le/Q,dny:je/me}},Z=(le,je,ge)=>{if(ge<=1.05)return;const Ce=-(le-.5)*100,ue=-(je-.5)*100,z=x(Ce,ue,ge);(Math.abs(z.x-c.current)>.1||Math.abs(z.y-u.current)>.1)&&(p(z.x),d(z.y),c.current=z.x,u.current=z.y)},O=le=>{const je=t.current;if(je&&le.target instanceof Node&&je.contains(le.target))le.preventDefault();else return;if(le.touches.length===1){const ge=le.touches[0];v.current={x:ge.clientX,y:ge.clientY,time:Date.now()},N.current={x:ge.clientX,y:ge.clientY},_.current||(w.current=!1),A.current=setTimeout(()=>{if(!w.current&&!_.current)if(w.current=!0,W.current==="mouse"){const Ce=k.current||{nx:.5,ny:.5};S("Right Click"),h(Ce.nx,Ce.ny,"right"),$.current("input_click",{...Ce,button:"right"}).catch(()=>{})}else{const Ce=se(ge);Ce&&(S("Right Click"),h(Ce.nx,Ce.ny,"right"),$.current("input_click",{...Ce,button:"right"}).catch(()=>{}))}},500);return}if(le.touches.length===2){A.current&&clearTimeout(A.current),w.current=!0,_.current=!0;const ge=le.touches[1].clientX-le.touches[0].clientX,Ce=le.touches[1].clientY-le.touches[0].clientY;I.current=Math.sqrt(ge*ge+Ce*Ce),P.current=i.current,D.current={x:(le.touches[0].clientX+le.touches[1].clientX)/2,y:(le.touches[0].clientY+le.touches[1].clientY)/2}}},ee=le=>{const je=t.current;if(je&&le.target instanceof Node&&je.contains(le.target)&&le.preventDefault(),le.touches.length===1&&N.current){const ge=le.touches[0],Ce=ge.clientX-N.current.x,ue=ge.clientY-N.current.y;if(!w.current&&v.current){const z=ge.clientX-v.current.x,U=ge.clientY-v.current.y;Math.sqrt(z*z+U*U)>8&&(w.current=!0,A.current&&clearTimeout(A.current))}if(w.current)if(W.current==="mouse"){const z=ie(Ce,ue),U=k.current||{nx:.5,ny:.5},q=Math.max(0,Math.min(1,U.nx+z.dnx)),Q=Math.max(0,Math.min(1,U.ny+z.dny));k.current={nx:q,ny:Q},j({nx:q,ny:Q}),S(`Cursor: ${Math.round(q*100)}%, ${Math.round(Q*100)}%`),Z(q,Q,i.current);const me=Date.now();me-f.current>=30&&(f.current=me,$.current("input_mouseMoved",{nx:q,ny:Q}).catch(()=>{}))}else if(i.current>1){const z=t.current;if(z){const U=z.clientWidth,q=z.clientHeight,Q=c.current+Ce/U*100,me=u.current+ue/q*100,Ae=x(Q,me,i.current);p(Ae.x),d(Ae.y),c.current=Ae.x,u.current=Ae.y}}else{const z=se(ge);if(z){const U=Date.now();U-f.current>=40&&(f.current=U,S("Scroll"),$.current("input_wheel",{nx:z.nx,ny:z.ny,deltaX:Math.round(-Ce*2.5),deltaY:Math.round(-ue*2.5)}).catch(()=>{}))}}N.current={x:ge.clientX,y:ge.clientY};return}if(le.touches.length===2&&I.current!==null){const ge=le.touches[1].clientX-le.touches[0].clientX,Ce=le.touches[1].clientY-le.touches[0].clientY,z=Math.sqrt(ge*ge+Ce*Ce)/I.current,U=(le.touches[0].clientX+le.touches[1].clientX)/2,q=(le.touches[0].clientY+le.touches[1].clientY)/2,Q=U-D.current.x,me=q-D.current.y,Ae=Math.abs(z-1)>.03;if(W.current==="mouse"){if(Ae){const de=Math.max(o,Math.min(5,P.current*z));m(de),i.current=de}else if(Math.abs(Q)>2||Math.abs(me)>2){const de=k.current||{nx:.5,ny:.5},H=Date.now();H-f.current>=30&&(f.current=H,S("Scroll"),$.current("input_wheel",{nx:de.nx,ny:de.ny,deltaX:Math.round(-Q*3),deltaY:Math.round(-me*3)}).catch(()=>{}))}}else{const de=Math.max(o,Math.min(5,P.current*z));m(de),i.current=de;const H=t.current;if(H&&de>1){const he=H.clientWidth,fe=H.clientHeight,ye=c.current+Q/he*100,Pe=u.current+me/fe*100,He=x(ye,Pe,de);p(He.x),d(He.y),c.current=He.x,u.current=He.y}}D.current={x:U,y:q}}},G=le=>{var je;if(A.current&&clearTimeout(A.current),I.current=null,le.touches.length===1&&_.current){const ge=le.touches[0];v.current={x:ge.clientX,y:ge.clientY,time:Date.now()},N.current={x:ge.clientX,y:ge.clientY},w.current=!0;return}if(le.touches.length===0){if(_.current){_.current=!1,w.current=!1;return}if(le.changedTouches.length===1){const ge=le.changedTouches[0],Ce=Date.now(),ue=Ce-(((je=v.current)==null?void 0:je.time)||0),z=v.current?ge.clientX-v.current.x:0,U=v.current?ge.clientY-v.current.y:0,q=Math.sqrt(z*z+U*U);if(W.current==="mouse"){if(ue<E||ue>B||q>L){w.current=!1;return}const Q=k.current||se(ge);Q&&(S(`Click: ${Math.round(Q.nx*100)}%, ${Math.round(Q.ny*100)}%`),h(Q.nx,Q.ny,"left"),$.current("input_click",{...Q}).catch(()=>{}))}else{if(w.current){w.current=!1;return}if(ue<R||ue>M||q>F){w.current=!1;return}const Q=se(ge);if(!Q)return;Ce-T.current<300?(S("Double tap"),h(Q.nx,Q.ny,"double"),$.current("input_click",{...Q,clickCount:2}).catch(()=>{}),T.current=0):(S(`Tap: ${Math.round(Q.nx*100)}%, ${Math.round(Q.ny*100)}%`),h(Q.nx,Q.ny,"left"),$.current("input_click",{...Q}).catch(()=>{}),T.current=Ce)}}w.current=!1}};return Y.addEventListener("touchstart",O,{passive:!1}),Y.addEventListener("touchmove",ee,{passive:!1}),Y.addEventListener("touchend",G,{passive:!1}),()=>{Y.removeEventListener("touchstart",O),Y.removeEventListener("touchmove",ee),Y.removeEventListener("touchend",G),A.current&&clearTimeout(A.current)}},[e,t,n,o,i,c,u,p,d,m,f,S,h,x]),{cursorPos:C,cursorPosRef:k,handleToggleInputMode:()=>{a(Y=>{const se=Y==="touch"?"mouse":"touch";return se==="mouse"&&K(),se})},handleZoomReset:()=>{const Y=y?b:1;m(Y),i.current=Y,p(0),d(0),c.current=0,u.current=0}}}function Iu({onAction:e,addLog:t,connState:n,connScreenshot:r,screenshotUsage:a,transportType:o}){const i=l.useRef(null),c=l.useRef(null),u=l.useRef(null),[p,d]=l.useState(null),[m,f]=l.useState(""),[,g]=l.useState(!1),[S,h]=l.useState([]),x=l.useRef(0),[y,b]=l.useState(!1),[C,j]=l.useState(!1),k=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[v,N]=l.useState(k?"mouse":"touch"),[w,A]=l.useState(1),T=l.useRef(!1),[I,P]=l.useState(1),[D,_]=l.useState(0),[W,$]=l.useState(0);Dr("RemoteView",{connState:n,hasScreenshot:!!r,inputMode:v,zoom:I,panX:D,panY:W,isMenuOpen:y,isImeOpen:C});const E=l.useRef(0),B=l.useRef(I),L=l.useRef(D),R=l.useRef(W);l.useEffect(()=>{B.current=I},[I]),l.useEffect(()=>{L.current=D},[D]),l.useEffect(()=>{R.current=W},[W]),l.useEffect(()=>{var ue;(ue=i.current)==null||ue.focus()},[]);const M=n==="connected",F=r,K=M?"Connected. Waiting for first frame...":n==="connecting"?"Connecting to Host...":"Reconnecting to Host...",J=M?"The remote stream is warming up":"Waiting for the remote stream to catch up";l.useEffect(()=>{if(!k||T.current||!F)return;const ue=u.current,z=c.current;if(!ue||!z)return;const U=()=>{const q=z.clientWidth,Q=z.clientHeight,me=ue.naturalWidth,Ae=ue.naturalHeight;if(!me||!Ae||!q||!Q)return;const de=Math.min(q/me,Q/Ae),he=Math.max(q/me,Q/Ae)/de;he>1.01&&(A(he),P(he),B.current=he),T.current=!0};ue.complete&&ue.naturalWidth?U():ue.addEventListener("load",U,{once:!0})},[F,k]);const V=.5;l.useEffect(()=>{I<=V&&(_(0),$(0))},[I,V]);const Y=(ue,z,U)=>{if(U<=V)return{x:0,y:0};const q=(U-1)/(2*U)*100,Q=(U-1)/(2*U)*100;return{x:Math.max(-q,Math.min(q,ue)),y:Math.max(-Q,Math.min(Q,z))}},se=(ue,z)=>{if(!u.current)return null;const U=u.current.getBoundingClientRect();return!U.width||!U.height?null:{nx:Math.max(0,Math.min(1,(ue-U.left)/U.width)),ny:Math.max(0,Math.min(1,(z-U.top)/U.height))}},ie=(ue,z,U)=>{const q=c.current;if(!q)return;const Q=q.getBoundingClientRect(),me=++x.current;h(Ae=>[...Ae,{id:me,x:ue-Q.left,y:z-Q.top,type:U}]),setTimeout(()=>h(Ae=>Ae.filter(de=>de.id!==me)),600)},Z=(ue,z,U)=>{const q=u.current,Q=c.current;if(!q||!Q)return;const me=q.getBoundingClientRect(),Ae=Q.getBoundingClientRect(),de=q.naturalWidth||me.width,H=q.naturalHeight||me.height,he=de/H,fe=me.width/me.height;let ye,Pe,He,ke;he>fe?(ye=me.width,Pe=me.width/he,He=0,ke=(me.height-Pe)/2):(Pe=me.height,ye=me.height*he,He=(me.width-ye)/2,ke=0);const pe=me.left-Ae.left+He+ye*ue,st=me.top-Ae.top+ke+Pe*z,De=++x.current;h(_e=>[..._e,{id:De,x:pe,y:st,type:U}]),setTimeout(()=>h(_e=>_e.filter(ae=>ae.id!==De)),600)},O=async ue=>{var U;const z=se(ue.clientX,ue.clientY);if(z){d(`Click: ${Math.round(z.nx*100)}%, ${Math.round(z.ny*100)}%`),ie(ue.clientX,ue.clientY,"left"),(U=i.current)==null||U.focus();try{const q=await e("input_click",{nx:z.nx,ny:z.ny});q!=null&&q.success||t(`❌ Click failed: ${q==null?void 0:q.error}`)}catch(q){t(`❌ Click error: ${q.message||q}`)}}},ee=async(ue,z,U,q=0)=>{try{await e("input_key",{type:U?"char":"keyDown",key:ue,code:z,text:U?ue:void 0,unmodifiedText:U?ue:void 0,modifiers:q})}catch(Q){t(`❌ Key error: ${Q.message||Q}`)}},G=async ue=>{if(ue.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(ue.key)&&ue.preventDefault();let U=0;ue.altKey&&(U|=1),ue.ctrlKey&&(U|=2),ue.metaKey&&(U|=4),ue.shiftKey&&(U|=8),d(`Key: ${ue.key}`),await ee(ue.key,ue.code,ue.key.length===1,U)},le=async ue=>{if(ue.key==="Enter"){if(ue.nativeEvent.isComposing)return;if(m){const z=m;f(""),d(`IME Sent: ${z}`);try{const U=await e("input_type",{text:z});U!=null&&U.success||t(`❌ IME error: ${U==null?void 0:U.error}`)}catch(U){t(`❌ IME error: ${U.message}`)}}else d("Key: Enter"),await ee("Enter","Enter",!1)}};l.useEffect(()=>{const ue=i.current;if(!ue)return;const z=U=>{var q;if((q=u.current)!=null&&q.contains(U.target)){U.preventDefault();const Q=Date.now();if(Q-E.current<40)return;E.current=Q;const me=se(U.clientX,U.clientY);if(!me)return;d(`Scroll: ${Math.round(U.deltaY)}`),e("input_wheel",{nx:me.nx,ny:me.ny,deltaX:Math.round(U.deltaX),deltaY:Math.round(U.deltaY)}).catch(()=>{})}};return ue.addEventListener("wheel",z,{passive:!1}),()=>ue.removeEventListener("wheel",z)},[e]);const{cursorPos:je,handleToggleInputMode:ge,handleZoomReset:Ce}=Gb({containerRef:i,viewportRef:c,imgRef:u,inputMode:v,setInputMode:N,minZoom:V,zoomRef:B,panXRef:L,panYRef:R,setPanX:_,setPanY:$,setZoom:P,lastWheelTimeRef:E,onAction:e,setLastActionStatus:d,spawnRippleFromNormalized:Z,clampPan:Y,isMobile:k,mobileFillZoom:w});return s.jsxs("div",{ref:i,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:G,onContextMenu:ue=>ue.preventDefault(),onFocus:()=>g(!0),onBlur:()=>g(!1),tabIndex:0,children:[s.jsxs("div",{ref:c,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[F?s.jsx("img",{ref:u,src:F,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${I}) translate(${D}%, ${W}%)`,transformOrigin:"center center",cursor:v==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:O,onContextMenu:ue=>ue.preventDefault(),onDragStart:ue=>ue.preventDefault()}):s.jsx(Ob,{waitingLabel:K,waitingHint:J,transportType:o}),v==="mouse"&&F&&s.jsx(Bb,{cursorPos:je,viewportRef:c,imgRef:u}),S.map(ue=>{const U={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[ue.type];return s.jsxs("div",{style:{position:"absolute",left:ue.x,top:ue.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${U}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),s.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${U}, 0.9)`,boxShadow:`0 0 12px rgba(${U}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},ue.id)})]}),s.jsx(Wb,{inputMode:v,onToggleInputMode:ge,isImeOpen:C,setIsImeOpen:j,isMenuOpen:y,setIsMenuOpen:b,imeText:m,setImeText:f,handleImeSubmit:le,isConnActive:M,zoom:I,isMobile:k,mobileFillZoom:w,onZoomOut:()=>P(ue=>Math.max(.5,ue-.25)),onZoomReset:Ce,onZoomIn:()=>P(ue=>Math.min(5,ue+.25)),transportType:o,screenshotUsage:a,lastActionStatus:p}),s.jsx("style",{children:`
8
+ `});if(m.isActivityFacing&&d!=="thought"&&d!=="tool"&&d!=="terminal"){const I=m.label||"Activity";return s.jsxs("div",{className:"self-start chat-msg-activity","data-chat-activity-row":"true",children:[s.jsxs("div",{className:"chat-msg-activity-meta","aria-label":"Activity message",children:[s.jsx("span",{className:"activity-dot"}),s.jsx("span",{children:I})]}),g&&f?s.jsx("div",{className:"chat-msg-activity-body",children:s.jsx(Yn,{parts:f,renderAsPreformatted:!1})}):s.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:S})]})}if(d==="thought"){const I=typeof((w=t.meta)==null?void 0:w.label)=="string"?t.meta.label:"Thought";return s.jsxs("div",{className:"self-start chat-msg-thought","data-chat-activity-row":m.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx(rb,{size:13}),s.jsx("span",{children:I})]}),s.jsx("div",{className:"chat-msg-body",children:S})]})}if(d==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool","data-chat-activity-row":m.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-tool-meta","aria-label":"Tool message",children:[s.jsx("span",{className:"tool-icon",children:"⏺"}),s.jsx("span",{className:"tool-label",children:"Tool"})]}),g&&f?s.jsx("div",{className:"tool-text w-full",children:s.jsx(Yn,{parts:f,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:S})]});if(d==="terminal"){const I=(A=t.meta)!=null&&A.isRunning?"⏳":"✅",P=typeof((T=t.meta)==null?void 0:T.label)=="string"?t.meta.label:"Ran command";return s.jsxs("div",{className:"self-start chat-msg-terminal","data-chat-activity-row":m.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:I}),s.jsx("span",{children:P})]}),g&&f?s.jsx("div",{className:"chat-msg-body",children:s.jsx(Yn,{parts:f,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:S})]})}if(d==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:g&&f?s.jsx(Yn,{parts:f,renderAsPreformatted:!1}):S.slice(0,100)});const h=t.meta,y=(typeof(h==null?void 0:h.renderMode)=="string"?h.renderMode.trim():"")==="preformatted",b=S,C=!1,j=b,k=y,v=!p&&!k&&pu(j),N=["chat-message-row",p?"chat-message-row-user self-end":"chat-message-row-assistant self-start"].join(" ");return s.jsx("div",{className:N,children:(b||g||p)&&s.jsxs("div",{className:`chat-bubble ${p?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${b||g?"mb-1.5":"mb-0"}`,children:[s.jsx("span",{className:"chat-sender",children:p?a||"You":t.senderName||r}),s.jsxs("span",{className:"chat-bubble-header-end",children:[(b||g)&&s.jsx(Tb,{text:S}),n!=null&&s.jsx("span",{className:"chat-time",children:uu(n)})]})]}),(b||g)&&s.jsx("div",{className:"chat-markdown",children:g&&f?s.jsx(Yn,{parts:f,renderAsPreformatted:k}):s.jsx(Db,{content:j,renderAsPreformatted:k,renderAsMarkdown:v})}),C]})})},(e,t)=>(e.message===t.message||Yl(e.message)===Yl(t.message))&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded),Lb=l.forwardRef(function({messages:t,actionLogs:n,agentName:r="Agent",userName:a,isCliMode:o=!1,isWorking:i=!1,contextKey:c="",receivedAtMap:u={},lastMessageHash:p,showActivityMessages:d=!1,emptyState:m,onLoadMore:f,isLoadingMore:g,hasMoreHistory:S,hiddenLiveCount:h=0,loadError:x,scrollToBottomRequestNonce:y,isVisible:b=!0},C){const{t:j}=Ne("common"),k=l.useRef(null),v=l.useRef(null),N=l.useRef(null),w=l.useRef(0),A=l.useRef(""),T=l.useRef(""),I=l.useRef(!1),P=l.useRef(null),D=l.useRef(!1),_=l.useRef(null),W=l.useRef(!1),[$,E]=l.useState(new Set),[B,L]=l.useState({showTop:!1,showBottom:!1}),R=l.useRef(!1),M=l.useRef(!1),F=l.useRef(b),K=l.useRef(b),J=l.useRef(null);K.current=b;const V=()=>{const de=k.current;return de?de.scrollHeight-de.scrollTop-de.clientHeight<Bi:!0},Y=l.useCallback(()=>{const de=k.current,H=de?qf(de):{showTop:!1,showBottom:!1};L(he=>he.showTop===H.showTop&&he.showBottom===H.showBottom?he:H)},[]),se=l.useCallback((de="auto")=>{var he;const H=k.current;H&&(H.scrollTo({top:H.scrollHeight,behavior:de}),(he=H.ownerDocument.defaultView)==null||he.requestAnimationFrame(()=>Y()))},[Y]),ie=l.useCallback((de="auto")=>{var he;const H=k.current;H&&(H.scrollTo({top:0,behavior:de}),(he=H.ownerDocument.defaultView)==null||he.requestAnimationFrame(()=>Y()))},[Y]),Z=l.useCallback(()=>{var ye;const de=k.current,H=(ye=window.getSelection)==null?void 0:ye.call(window);if(!de||!H||H.rangeCount===0||H.isCollapsed){W.current=!1;return}const he=H.anchorNode,fe=H.focusNode;W.current=!!(he&&fe&&de.contains(he)&&de.contains(fe))},[]),O=l.useMemo(()=>{const de=Cb(t),H=Nu(t);return Nb(Ab(de,H,d))},[t,d]),ee=O.length===t.length?p:void 0,G=Of(O,ee),le=l.useCallback(()=>{const de=k.current;if(!de||!c||!K.current)return;const H={top:de.scrollTop,fromBottom:Math.max(0,de.scrollHeight-de.scrollTop-de.clientHeight),messageFingerprint:G};J.current={contextKey:c,snapshot:H},Vn.set(c,H)},[c,G]),je=l.useCallback((de="auto")=>{P.current!=null&&cancelAnimationFrame(P.current),P.current=requestAnimationFrame(()=>{P.current=null,se(de)})},[se]),ge=l.useCallback(()=>{R.current=!1,D.current=!0,M.current=!0,_.current!=null&&window.clearTimeout(_.current),_.current=window.setTimeout(()=>{D.current=!1,_.current=null},Ul)},[]);l.useEffect(()=>{const de=!I.current,H=T.current!==c;if(T.current=c,de||H){I.current=!0;const fe=c?Vn.get(c):null,ye=!!fe&&ga(fe,G);R.current=ye?lr(fe):!1,D.current=zf(fe,G),W.current||(ye?requestAnimationFrame(()=>{const Pe=k.current;Pe&&(lo(Pe,fe),R.current=lr(fe),Y(),M.current=!0)}):je("auto")),w.current=O.length,A.current=G;return}O.length>w.current;const he=G!==A.current;Kf({hasSelection:W.current,userScrolledUp:R.current,hasChatContentChanged:he})&&je("auto"),w.current=O.length,A.current=G},[G,c,O.length,je,Y]),l.useEffect(()=>{y&&(ge(),W.current||je("auto"))},[ge,je,y]),l.useEffect(()=>{const de=F.current;de&&!b&&le(),K.current=b,F.current=b;const H=c?Vn.get(c):null;if(Uf(de,b,H,G)){if(!H)return;R.current=lr(H),D.current=!1,W.current||requestAnimationFrame(()=>{const he=k.current;he&&(lo(he,H),Y())});return}},[b,c,G,ge,le,je,Y]),l.useEffect(()=>()=>{const de=J.current;de&&Vn.set(de.contextKey,de.snapshot),P.current!=null&&cancelAnimationFrame(P.current),_.current!=null&&window.clearTimeout(_.current)},[]),l.useEffect(()=>{const de=v.current,H=k.current;if(!de||!H)return;const he=()=>{_.current!=null&&window.clearTimeout(_.current),_.current=window.setTimeout(()=>{D.current=!1,_.current=null},Ul)},fe=new ResizeObserver(()=>{Y();const ye=D.current;Vf({hasSelection:W.current,userScrolledUp:R.current,contextAutoScrollActive:ye})&&(je("auto"),ye&&he())});return fe.observe(de),H!==de&&fe.observe(H),()=>{fe.disconnect(),_.current!=null&&(window.clearTimeout(_.current),_.current=null)}},[je,c,Y]),l.useImperativeHandle(C,()=>({scrollToBottom:(de="smooth")=>{se(de)}}),[se]),l.useEffect(()=>{const de=k.current;if(!de)return;let H;const he=()=>{le(),clearTimeout(H),H=setTimeout(()=>{R.current=!V(),Y()},50)};return de.addEventListener("scroll",he,{passive:!0}),()=>{de.removeEventListener("scroll",he),clearTimeout(H)}},[le,Y]),l.useEffect(()=>(document.addEventListener("selectionchange",Z),()=>document.removeEventListener("selectionchange",Z)),[Z]);const Ce=l.useRef(0),ue=l.useRef(!1);l.useEffect(()=>{const de=k.current;if(!de||!ue.current||Ce.current===0)return;const H=de.scrollHeight-Ce.current;H>0&&(de.scrollTop=H),Y(),le(),Ce.current=0,ue.current=!1},[O.length,le,Y]),l.useEffect(()=>{if(M.current||!c)return;const de=Vn.get(c),H=k.current;if(!(!de||!H)){if(!ga(de,G)){se("auto"),M.current=!0;return}lo(H,de),R.current=lr(de),Y(),M.current=!0}},[c,G,O.length,se,Y]);const z=()=>{const de=k.current;de&&(Ce.current=de.scrollHeight),ue.current=!0,f==null||f()},U=()=>{R.current=!0,ie("smooth"),le()},q=()=>{ge(),se("smooth"),le()},Q=l.useMemo(()=>{const de=O.map((ye,Pe)=>({type:"message",data:ye,index:Pe,ts:_f(ye,Pe,u)}));if(!n||n.length===0)return de;const H=[...n].sort((ye,Pe)=>ye.timestamp-Pe.timestamp).map((ye,Pe)=>({type:"action",data:ye,index:Pe,ts:ye.timestamp})),he=[];let fe=0;for(const ye of de){for(;fe<H.length&&ye.ts>0&&H[fe].ts<ye.ts;)he.push(H[fe++]);he.push(ye)}for(;fe<H.length;)he.push(H[fe++]);return he},[O,n,u]),me=h>0||!!S,Ae=h>0?h>80?j("chatList.showEarlierMessagesHidden",{count:Math.min(h,80),total:h}):j("chatList.showEarlierMessages",{count:Math.min(h,80)}):x?j("chatList.loadErrorRetry",{error:x}):j("chatList.loadOlderMessages");return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:k,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:v,className:"chat-container-content",children:[g&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:j("chatList.loadingOlderMessages")}),me&&!g&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:z,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${x&&h===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:Ae})}),Q.length===0&&!me&&(m||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:j("chatList.waitingForMessages")})),Q.map(de=>{if(de.type==="action"){const He=de.data;return s.jsx(Ib,{log:He},`action-${de.index}`)}const H=de.data;de.index;const he=ba(H),fe=H.receivedAt||u[he],ye=`${c}-${he}`,Pe=$.has(ye);return s.jsx(Pb,{message:H,receivedAt:fe,agentName:r,userName:a,isCliMode:o,isTextExpanded:Pe,onToggleTextExpanded:()=>E(He=>{const ke=new Set(He);return Pe?ke.delete(ye):ke.add(ye),ke})},`msg-${he}`)}),i&&s.jsx("div",{className:"self-start chat-typing-wrapper",children:s.jsxs("div",{className:"typing-indicator",children:[s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:j("chatList.agentGenerating")})]})}),s.jsx("div",{className:"min-h-10",ref:N})]})}),(B.showTop||B.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":j("chatList.jumpToTop"),children:[B.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:U,"aria-label":j("chatList.jumpToOldestMessages"),title:j("chatList.jumpToTop"),children:j("chatList.top")}),B.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:q,"aria-label":j("chatList.jumpToLatestMessages"),title:j("chatList.jumpToBottom"),children:j("chatList.latest")})]})]})}),Rb=l.memo(Lb,(e,t)=>e.messages===t.messages&&e.actionLogs===t.actionLogs&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isWorking===t.isWorking&&e.contextKey===t.contextKey&&e.receivedAtMap===t.receivedAtMap&&e.lastMessageHash===t.lastMessageHash&&e.showActivityMessages===t.showActivityMessages&&e.emptyState===t.emptyState&&e.onLoadMore===t.onLoadMore&&e.isLoadingMore===t.isLoadingMore&&e.hasMoreHistory===t.hasMoreHistory&&e.hiddenLiveCount===t.hiddenLiveCount&&e.loadError===t.loadError&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isVisible===t.isVisible),Eb="modulepreload",_b=function(e){return"/"+e},Jl={},$b=function(t,n,r){let a=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),c=(i==null?void 0:i.nonce)||(i==null?void 0:i.getAttribute("nonce"));a=Promise.allSettled(n.map(u=>{if(u=_b(u),u in Jl)return;Jl[u]=!0;const p=u.endsWith(".css"),d=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const m=document.createElement("link");if(m.rel=p?"stylesheet":Eb,p||(m.as="script"),m.crossOrigin="",m.href=u,c&&m.setAttribute("nonce",c),document.head.appendChild(m),p)return new Promise((f,g)=>{m.addEventListener("load",f),m.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${u}`)))})}))}function o(i){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=i,window.dispatchEvent(c),!c.defaultPrevented)throw i}return a.then(i=>{for(const c of i||[])c.status==="rejected"&&o(c.reason);return t().catch(o)})};let Ql=!1;const Du=l.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:n,fontSize:r=13,readOnly:a=!1,sizingMode:o="measured"},i)=>{const c=l.useRef(null),[u,p]=l.useState(null),d=l.useRef([]),m=l.useRef(!1),f=l.useRef(!1),g=l.useRef(!1),S=l.useRef(!1),h=()=>{const x=c.current;if(x){m.current&&(x.clear(),m.current=!1);for(const y of d.current)x.write(y.data,y.onProcessed);d.current=[],f.current&&(x.fit(),f.current=!1),g.current&&(x.bumpResize(),g.current=!1),S.current&&(x.scrollToTop(),S.current=!1)}};return l.useImperativeHandle(i,()=>({write:(x,y)=>{c.current?c.current.write(x,y):d.current.push({data:x,onProcessed:y})},clear:()=>{c.current?c.current.clear():(d.current=[],m.current=!0)},reset:()=>{c.current&&typeof c.current.reset=="function"?c.current.reset():(d.current=[],m.current=!0)},resize:(x,y)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(x,y)},fit:()=>{c.current?c.current.fit():f.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():g.current=!0},scrollToTop:()=>{c.current?c.current.scrollToTop():S.current=!0},getSelection:()=>{var x,y;return((y=(x=c.current)==null?void 0:x.getSelection)==null?void 0:y.call(x))||""},getVisibleText:()=>{var x,y;return((y=(x=c.current)==null?void 0:x.getVisibleText)==null?void 0:y.call(x))||""}}),[]),l.useEffect(()=>{u&&h()},[u]),l.useEffect(()=>{let x=!1;return $b(()=>import("./terminal-BZj_X5zy.js"),__vite__mapDeps([0,1,2])).then(y=>{Ql||(Ql=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),x||p(()=>y.GhosttyTerminalView)}).catch(y=>{console.error("[CliTerminal] failed to load terminal renderer",y)}),()=>{x=!0}},[]),u?s.jsx(u,{ref:c,onInput:e,onViewportMetrics:t,onScrollMetrics:n,fontSize:r,readOnly:a,sizingMode:o,className:"w-full h-full rounded-lg overflow-hidden"}):s.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});Du.displayName="CliTerminal";function Wt(...e){return Uh(Gh(e))}const Hb={lg:"rounded-lg",xl:"rounded-xl","2xl":"rounded-2xl"},Fb={none:"",sm:"p-3",md:"px-4 py-3.5",lg:"px-5 py-4"},Ls=l.forwardRef(function({radius:t="xl",padding:n="md",className:r,...a},o){return s.jsx("div",{ref:o,className:Wt("border border-border-subtle bg-bg-secondary",Hb[t],Fb[n],r),...a})});function Hr({label:e,value:t,sub:n,icon:r}){return s.jsxs(Ls,{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[s.jsx("span",{className:"text-base flex items-center",children:r}),s.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:e})]}),s.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:t}),n&&s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:n})]})}function Xl({value:e,max:t,label:n,color:r="#8b5cf6",detail:a,compact:o=!1}){const i=t>0?Math.min(Math.round(e/t*100),100):0,c=i>85?"#ef4444":i>60?"var(--status-warning)":r;return o?s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-0.5",children:[s.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide font-semibold",children:n}),s.jsxs("span",{className:"text-[10px] text-text-secondary font-semibold",children:[i,"%"]})]}),s.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${i}%`,background:c}})})]}):s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-1.5",children:[s.jsx("span",{className:"text-[11px] text-text-secondary font-medium",children:n}),s.jsxs("span",{className:"text-[13px] text-text-primary font-bold",children:[i,"%"]})]}),s.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${i}%`,background:`linear-gradient(90deg, ${c}, ${c}cc)`}})}),a&&s.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:a})]})}function Bb({cursorPos:e,viewportRef:t,imgRef:n}){var b;if(!e||!n.current)return null;const r=n.current,a=r.getBoundingClientRect(),o=(b=t.current)==null?void 0:b.getBoundingClientRect();if(!o)return null;const i=r.naturalWidth||a.width,c=r.naturalHeight||a.height,u=i/c,p=a.width/a.height;let d,m,f,g;u>p?(d=a.width,m=a.width/u,f=0,g=(a.height-m)/2):(m=a.height,d=a.height*u,f=(a.width-d)/2,g=0);const S=a.left-o.left+f+d*e.nx,h=a.top-o.top+g+m*e.ny,x=Math.max(8,Math.min(o.width-8,S)),y=Math.max(8,Math.min(o.height-8,h));return s.jsxs("div",{style:{position:"absolute",left:x-8,top:y-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[s.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:5,top:5,width:6,height:6,borderRadius:"50%",background:"#3b82f6",boxShadow:"0 0 8px rgba(59,130,246,0.6)"}})]})}function Wb({inputMode:e,onToggleInputMode:t,isImeOpen:n,setIsImeOpen:r,isMenuOpen:a,setIsMenuOpen:o,imeText:i,setImeText:c,handleImeSubmit:u,isConnActive:p,zoom:d,isMobile:m,mobileFillZoom:f,onZoomOut:g,onZoomReset:S,onZoomIn:h,transportType:x,screenshotUsage:y,lastActionStatus:b}){const{t:C}=Ne("common");return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:j=>j.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[s.jsxs("div",{onClick:t,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[s.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),s.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:C(e==="mouse"?"remote.mouse":"remote.touch")})]}),s.jsxs("div",{className:"relative",children:[s.jsx("div",{onClick:()=>{r(j=>!j),o(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${n?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⌨️"})}),n&&s.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:s.jsx("input",{type:"text",placeholder:C("remote.typeAndEnter"),value:i,autoFocus:!0,onTouchStart:j=>j.stopPropagation(),onChange:j=>c(j.target.value),onKeyDown:j=>{u(j)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),s.jsx("div",{className:"relative",children:s.jsx("div",{onClick:()=>{o(j=>!j),r(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⚙️"})})}),s.jsx("div",{className:"w-px h-[18px] bg-white/10"}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:p?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[s.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:p?"#22c55e":"#eab308",boxShadow:p?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),s.jsx("span",{className:"text-[8px] font-extrabold",style:{color:p?"#22c55e":"#eab308"},children:C(p?"remote.connected":"remote.ws")})]}),d>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(d*100),"%"]}),x==="direct"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:C("remote.directP2PTitle"),children:C("remote.direct")}),x==="relay"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:C("remote.turnRelayTitle"),children:C("remote.relay")}),y&&y.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:y.budgetExhausted?"#ef4444":"#c4b5fd",background:y.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:C("remote.dailyTurnTitle"),children:y.budgetExhausted?C("remote.turnBlocked"):C("remote.turnUsage",{used:y.dailyUsedMinutes,budget:y.dailyBudgetMinutes})}),b&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:b})]})]}),a&&s.jsxs("div",{onTouchStart:j=>j.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[s.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:C("remote.settings")}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:[C("remote.zoom")," ",d<=(m?f:1)+.01?C(m?"remote.fill":"remote.fit"):`${Math.round(d*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:j=>{j.stopPropagation(),g()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),s.jsx("button",{onClick:j=>{j.stopPropagation(),S()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:C(m?"remote.fill":"remote.fit")}),s.jsx("button",{onClick:j=>{j.stopPropagation(),h()},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 Ob({waitingLabel:e,waitingHint:t,transportType:n}){const{t:r}=Ne("common");return s.jsxs("div",{className:"text-center flex flex-col items-center gap-3 px-6",children:[s.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center border border-white/10 bg-white/[0.04] shadow-[0_10px_30px_rgba(0,0,0,0.35)]",style:{animation:"remote-float 2.8s ease-in-out infinite"},children:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-8 h-8 opacity-90"})}),s.jsx("div",{className:"text-white/85 text-[13px] font-semibold tracking-wide",children:e}),s.jsx("div",{className:"text-[11px] text-white/40",children:t}),n==="relay"&&s.jsx("div",{className:"text-[10px] font-medium",style:{color:"var(--status-warning)",opacity:.8},children:r("remote.waitingState.turnRelayActive")})]})}function Ub(){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 Zl(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 Dr(e,t){const n=l.useRef(null),r=l.useRef(0);l.useEffect(()=>{if(!Ub())return;r.current+=1;const a=n.current;if(!a){console.debug(`[render-trace] ${e}#${r.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(t).map(([i,c])=>[i,Zl(c)]))}),n.current=t;return}const o=Object.keys({...a,...t}).filter(i=>!Object.is(a[i],t[i]));o.length>0&&console.debug(`[render-trace] ${e}#${r.current}`,{changed:o,snapshot:Object.fromEntries(o.map(i=>[i,Zl(t[i])]))}),n.current=t})}function Gb({containerRef:e,viewportRef:t,imgRef:n,inputMode:r,setInputMode:a,minZoom:o,zoomRef:i,panXRef:c,panYRef:u,setPanX:p,setPanY:d,setZoom:m,lastWheelTimeRef:f,onAction:g,setLastActionStatus:S,spawnRippleFromNormalized:h,clampPan:x,isMobile:y,mobileFillZoom:b}){const[C,j]=l.useState(null),k=l.useRef(null),v=l.useRef(null),N=l.useRef(null),w=l.useRef(!1),A=l.useRef(null),T=l.useRef(0),I=l.useRef(null),P=l.useRef(1),D=l.useRef({x:0,y:0}),_=l.useRef(!1),W=l.useRef(r),$=l.useRef(g),E=30,B=550,L=18,R=60,M=400,F=12,K=()=>{if(k.current)return;const Y={nx:.5,ny:.5};k.current=Y,j(Y)};return l.useEffect(()=>{W.current=r,r==="mouse"&&K()},[r]),l.useEffect(()=>{$.current=g},[g]),l.useEffect(()=>{const Y=e.current;if(!Y)return;const se=le=>{if(!n.current)return null;const je=n.current.getBoundingClientRect();return!je.width||!je.height?null:{nx:Math.max(0,Math.min(1,(le.clientX-je.left)/je.width)),ny:Math.max(0,Math.min(1,(le.clientY-je.top)/je.height))}},ie=(le,je)=>{if(!n.current)return{dnx:0,dny:0};const ge=n.current,Ce=ge.getBoundingClientRect(),ue=ge.naturalWidth||Ce.width,z=ge.naturalHeight||Ce.height,U=ue/z,q=Ce.width/Ce.height;let Q,me;return U>q?(Q=Ce.width,me=Ce.width/U):(me=Ce.height,Q=Ce.height*U),{dnx:le/Q,dny:je/me}},Z=(le,je,ge)=>{if(ge<=1.05)return;const Ce=-(le-.5)*100,ue=-(je-.5)*100,z=x(Ce,ue,ge);(Math.abs(z.x-c.current)>.1||Math.abs(z.y-u.current)>.1)&&(p(z.x),d(z.y),c.current=z.x,u.current=z.y)},O=le=>{const je=t.current;if(je&&le.target instanceof Node&&je.contains(le.target))le.preventDefault();else return;if(le.touches.length===1){const ge=le.touches[0];v.current={x:ge.clientX,y:ge.clientY,time:Date.now()},N.current={x:ge.clientX,y:ge.clientY},_.current||(w.current=!1),A.current=setTimeout(()=>{if(!w.current&&!_.current)if(w.current=!0,W.current==="mouse"){const Ce=k.current||{nx:.5,ny:.5};S("Right Click"),h(Ce.nx,Ce.ny,"right"),$.current("input_click",{...Ce,button:"right"}).catch(()=>{})}else{const Ce=se(ge);Ce&&(S("Right Click"),h(Ce.nx,Ce.ny,"right"),$.current("input_click",{...Ce,button:"right"}).catch(()=>{}))}},500);return}if(le.touches.length===2){A.current&&clearTimeout(A.current),w.current=!0,_.current=!0;const ge=le.touches[1].clientX-le.touches[0].clientX,Ce=le.touches[1].clientY-le.touches[0].clientY;I.current=Math.sqrt(ge*ge+Ce*Ce),P.current=i.current,D.current={x:(le.touches[0].clientX+le.touches[1].clientX)/2,y:(le.touches[0].clientY+le.touches[1].clientY)/2}}},ee=le=>{const je=t.current;if(je&&le.target instanceof Node&&je.contains(le.target)&&le.preventDefault(),le.touches.length===1&&N.current){const ge=le.touches[0],Ce=ge.clientX-N.current.x,ue=ge.clientY-N.current.y;if(!w.current&&v.current){const z=ge.clientX-v.current.x,U=ge.clientY-v.current.y;Math.sqrt(z*z+U*U)>8&&(w.current=!0,A.current&&clearTimeout(A.current))}if(w.current)if(W.current==="mouse"){const z=ie(Ce,ue),U=k.current||{nx:.5,ny:.5},q=Math.max(0,Math.min(1,U.nx+z.dnx)),Q=Math.max(0,Math.min(1,U.ny+z.dny));k.current={nx:q,ny:Q},j({nx:q,ny:Q}),S(`Cursor: ${Math.round(q*100)}%, ${Math.round(Q*100)}%`),Z(q,Q,i.current);const me=Date.now();me-f.current>=30&&(f.current=me,$.current("input_mouseMoved",{nx:q,ny:Q}).catch(()=>{}))}else if(i.current>1){const z=t.current;if(z){const U=z.clientWidth,q=z.clientHeight,Q=c.current+Ce/U*100,me=u.current+ue/q*100,Ae=x(Q,me,i.current);p(Ae.x),d(Ae.y),c.current=Ae.x,u.current=Ae.y}}else{const z=se(ge);if(z){const U=Date.now();U-f.current>=40&&(f.current=U,S("Scroll"),$.current("input_wheel",{nx:z.nx,ny:z.ny,deltaX:Math.round(-Ce*2.5),deltaY:Math.round(-ue*2.5)}).catch(()=>{}))}}N.current={x:ge.clientX,y:ge.clientY};return}if(le.touches.length===2&&I.current!==null){const ge=le.touches[1].clientX-le.touches[0].clientX,Ce=le.touches[1].clientY-le.touches[0].clientY,z=Math.sqrt(ge*ge+Ce*Ce)/I.current,U=(le.touches[0].clientX+le.touches[1].clientX)/2,q=(le.touches[0].clientY+le.touches[1].clientY)/2,Q=U-D.current.x,me=q-D.current.y,Ae=Math.abs(z-1)>.03;if(W.current==="mouse"){if(Ae){const de=Math.max(o,Math.min(5,P.current*z));m(de),i.current=de}else if(Math.abs(Q)>2||Math.abs(me)>2){const de=k.current||{nx:.5,ny:.5},H=Date.now();H-f.current>=30&&(f.current=H,S("Scroll"),$.current("input_wheel",{nx:de.nx,ny:de.ny,deltaX:Math.round(-Q*3),deltaY:Math.round(-me*3)}).catch(()=>{}))}}else{const de=Math.max(o,Math.min(5,P.current*z));m(de),i.current=de;const H=t.current;if(H&&de>1){const he=H.clientWidth,fe=H.clientHeight,ye=c.current+Q/he*100,Pe=u.current+me/fe*100,He=x(ye,Pe,de);p(He.x),d(He.y),c.current=He.x,u.current=He.y}}D.current={x:U,y:q}}},G=le=>{var je;if(A.current&&clearTimeout(A.current),I.current=null,le.touches.length===1&&_.current){const ge=le.touches[0];v.current={x:ge.clientX,y:ge.clientY,time:Date.now()},N.current={x:ge.clientX,y:ge.clientY},w.current=!0;return}if(le.touches.length===0){if(_.current){_.current=!1,w.current=!1;return}if(le.changedTouches.length===1){const ge=le.changedTouches[0],Ce=Date.now(),ue=Ce-(((je=v.current)==null?void 0:je.time)||0),z=v.current?ge.clientX-v.current.x:0,U=v.current?ge.clientY-v.current.y:0,q=Math.sqrt(z*z+U*U);if(W.current==="mouse"){if(ue<E||ue>B||q>L){w.current=!1;return}const Q=k.current||se(ge);Q&&(S(`Click: ${Math.round(Q.nx*100)}%, ${Math.round(Q.ny*100)}%`),h(Q.nx,Q.ny,"left"),$.current("input_click",{...Q}).catch(()=>{}))}else{if(w.current){w.current=!1;return}if(ue<R||ue>M||q>F){w.current=!1;return}const Q=se(ge);if(!Q)return;Ce-T.current<300?(S("Double tap"),h(Q.nx,Q.ny,"double"),$.current("input_click",{...Q,clickCount:2}).catch(()=>{}),T.current=0):(S(`Tap: ${Math.round(Q.nx*100)}%, ${Math.round(Q.ny*100)}%`),h(Q.nx,Q.ny,"left"),$.current("input_click",{...Q}).catch(()=>{}),T.current=Ce)}}w.current=!1}};return Y.addEventListener("touchstart",O,{passive:!1}),Y.addEventListener("touchmove",ee,{passive:!1}),Y.addEventListener("touchend",G,{passive:!1}),()=>{Y.removeEventListener("touchstart",O),Y.removeEventListener("touchmove",ee),Y.removeEventListener("touchend",G),A.current&&clearTimeout(A.current)}},[e,t,n,o,i,c,u,p,d,m,f,S,h,x]),{cursorPos:C,cursorPosRef:k,handleToggleInputMode:()=>{a(Y=>{const se=Y==="touch"?"mouse":"touch";return se==="mouse"&&K(),se})},handleZoomReset:()=>{const Y=y?b:1;m(Y),i.current=Y,p(0),d(0),c.current=0,u.current=0}}}function Iu({onAction:e,addLog:t,connState:n,connScreenshot:r,screenshotUsage:a,transportType:o}){const i=l.useRef(null),c=l.useRef(null),u=l.useRef(null),[p,d]=l.useState(null),[m,f]=l.useState(""),[,g]=l.useState(!1),[S,h]=l.useState([]),x=l.useRef(0),[y,b]=l.useState(!1),[C,j]=l.useState(!1),k=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[v,N]=l.useState(k?"mouse":"touch"),[w,A]=l.useState(1),T=l.useRef(!1),[I,P]=l.useState(1),[D,_]=l.useState(0),[W,$]=l.useState(0);Dr("RemoteView",{connState:n,hasScreenshot:!!r,inputMode:v,zoom:I,panX:D,panY:W,isMenuOpen:y,isImeOpen:C});const E=l.useRef(0),B=l.useRef(I),L=l.useRef(D),R=l.useRef(W);l.useEffect(()=>{B.current=I},[I]),l.useEffect(()=>{L.current=D},[D]),l.useEffect(()=>{R.current=W},[W]),l.useEffect(()=>{var ue;(ue=i.current)==null||ue.focus()},[]);const M=n==="connected",F=r,K=M?"Connected. Waiting for first frame...":n==="connecting"?"Connecting to Host...":"Reconnecting to Host...",J=M?"The remote stream is warming up":"Waiting for the remote stream to catch up";l.useEffect(()=>{if(!k||T.current||!F)return;const ue=u.current,z=c.current;if(!ue||!z)return;const U=()=>{const q=z.clientWidth,Q=z.clientHeight,me=ue.naturalWidth,Ae=ue.naturalHeight;if(!me||!Ae||!q||!Q)return;const de=Math.min(q/me,Q/Ae),he=Math.max(q/me,Q/Ae)/de;he>1.01&&(A(he),P(he),B.current=he),T.current=!0};ue.complete&&ue.naturalWidth?U():ue.addEventListener("load",U,{once:!0})},[F,k]);const V=.5;l.useEffect(()=>{I<=V&&(_(0),$(0))},[I,V]);const Y=(ue,z,U)=>{if(U<=V)return{x:0,y:0};const q=(U-1)/(2*U)*100,Q=(U-1)/(2*U)*100;return{x:Math.max(-q,Math.min(q,ue)),y:Math.max(-Q,Math.min(Q,z))}},se=(ue,z)=>{if(!u.current)return null;const U=u.current.getBoundingClientRect();return!U.width||!U.height?null:{nx:Math.max(0,Math.min(1,(ue-U.left)/U.width)),ny:Math.max(0,Math.min(1,(z-U.top)/U.height))}},ie=(ue,z,U)=>{const q=c.current;if(!q)return;const Q=q.getBoundingClientRect(),me=++x.current;h(Ae=>[...Ae,{id:me,x:ue-Q.left,y:z-Q.top,type:U}]),setTimeout(()=>h(Ae=>Ae.filter(de=>de.id!==me)),600)},Z=(ue,z,U)=>{const q=u.current,Q=c.current;if(!q||!Q)return;const me=q.getBoundingClientRect(),Ae=Q.getBoundingClientRect(),de=q.naturalWidth||me.width,H=q.naturalHeight||me.height,he=de/H,fe=me.width/me.height;let ye,Pe,He,ke;he>fe?(ye=me.width,Pe=me.width/he,He=0,ke=(me.height-Pe)/2):(Pe=me.height,ye=me.height*he,He=(me.width-ye)/2,ke=0);const pe=me.left-Ae.left+He+ye*ue,st=me.top-Ae.top+ke+Pe*z,De=++x.current;h(_e=>[..._e,{id:De,x:pe,y:st,type:U}]),setTimeout(()=>h(_e=>_e.filter(ae=>ae.id!==De)),600)},O=async ue=>{var U;const z=se(ue.clientX,ue.clientY);if(z){d(`Click: ${Math.round(z.nx*100)}%, ${Math.round(z.ny*100)}%`),ie(ue.clientX,ue.clientY,"left"),(U=i.current)==null||U.focus();try{const q=await e("input_click",{nx:z.nx,ny:z.ny});q!=null&&q.success||t(`❌ Click failed: ${q==null?void 0:q.error}`)}catch(q){t(`❌ Click error: ${q.message||q}`)}}},ee=async(ue,z,U,q=0)=>{try{await e("input_key",{type:U?"char":"keyDown",key:ue,code:z,text:U?ue:void 0,unmodifiedText:U?ue:void 0,modifiers:q})}catch(Q){t(`❌ Key error: ${Q.message||Q}`)}},G=async ue=>{if(ue.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(ue.key)&&ue.preventDefault();let U=0;ue.altKey&&(U|=1),ue.ctrlKey&&(U|=2),ue.metaKey&&(U|=4),ue.shiftKey&&(U|=8),d(`Key: ${ue.key}`),await ee(ue.key,ue.code,ue.key.length===1,U)},le=async ue=>{if(ue.key==="Enter"){if(ue.nativeEvent.isComposing)return;if(m){const z=m;f(""),d(`IME Sent: ${z}`);try{const U=await e("input_type",{text:z});U!=null&&U.success||t(`❌ IME error: ${U==null?void 0:U.error}`)}catch(U){t(`❌ IME error: ${U.message}`)}}else d("Key: Enter"),await ee("Enter","Enter",!1)}};l.useEffect(()=>{const ue=i.current;if(!ue)return;const z=U=>{var q;if((q=u.current)!=null&&q.contains(U.target)){U.preventDefault();const Q=Date.now();if(Q-E.current<40)return;E.current=Q;const me=se(U.clientX,U.clientY);if(!me)return;d(`Scroll: ${Math.round(U.deltaY)}`),e("input_wheel",{nx:me.nx,ny:me.ny,deltaX:Math.round(U.deltaX),deltaY:Math.round(U.deltaY)}).catch(()=>{})}};return ue.addEventListener("wheel",z,{passive:!1}),()=>ue.removeEventListener("wheel",z)},[e]);const{cursorPos:je,handleToggleInputMode:ge,handleZoomReset:Ce}=Gb({containerRef:i,viewportRef:c,imgRef:u,inputMode:v,setInputMode:N,minZoom:V,zoomRef:B,panXRef:L,panYRef:R,setPanX:_,setPanY:$,setZoom:P,lastWheelTimeRef:E,onAction:e,setLastActionStatus:d,spawnRippleFromNormalized:Z,clampPan:Y,isMobile:k,mobileFillZoom:w});return s.jsxs("div",{ref:i,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:G,onContextMenu:ue=>ue.preventDefault(),onFocus:()=>g(!0),onBlur:()=>g(!1),tabIndex:0,children:[s.jsxs("div",{ref:c,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[F?s.jsx("img",{ref:u,src:F,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${I}) translate(${D}%, ${W}%)`,transformOrigin:"center center",cursor:v==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:O,onContextMenu:ue=>ue.preventDefault(),onDragStart:ue=>ue.preventDefault()}):s.jsx(Ob,{waitingLabel:K,waitingHint:J,transportType:o}),v==="mouse"&&F&&s.jsx(Bb,{cursorPos:je,viewportRef:c,imgRef:u}),S.map(ue=>{const U={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[ue.type];return s.jsxs("div",{style:{position:"absolute",left:ue.x,top:ue.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${U}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),s.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${U}, 0.9)`,boxShadow:`0 0 12px rgba(${U}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},ue.id)})]}),s.jsx(Wb,{inputMode:v,onToggleInputMode:ge,isImeOpen:C,setIsImeOpen:j,isMenuOpen:y,setIsMenuOpen:b,imeText:m,setImeText:f,handleImeSubmit:le,isConnActive:M,zoom:I,isMobile:k,mobileFillZoom:w,onZoomOut:()=>P(ue=>Math.max(.5,ue-.25)),onZoomReset:Ce,onZoomIn:()=>P(ue=>Math.min(5,ue+.25)),transportType:o,screenshotUsage:a,lastActionStatus:p}),s.jsx("style",{children:`
9
9
  @keyframes slideUp {
10
10
  from { opacity: 0; transform: translateY(6px); }
11
11
  to { opacity: 1; transform: translateY(0); }
@@ -55,7 +55,7 @@ ${JSON.stringify(t,null,2)}
55
55
  `),me=((Ae=Q[0])==null?void 0:Ae.slice(0,80))||"(empty)";return s.jsxs("div",{className:"border border-border-default rounded overflow-hidden bg-surface-secondary",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2.5 py-1.5 hover:bg-bg-glass-hover transition-colors text-left",onClick:()=>G(z),children:[s.jsx("span",{className:"text-[10px] text-text-muted w-3",children:q?"▾":"▸"}),s.jsx("span",{className:"font-mono text-accent-primary w-20 shrink-0 text-[11px]",children:z}),!q&&s.jsx("span",{className:"text-text-secondary truncate font-mono text-[11px]",children:me}),s.jsxs("span",{className:"ml-auto text-text-muted text-[10px] shrink-0",children:[Q.length,"L"]})]}),q&&s.jsx("pre",{className:"px-3 pb-2.5 pt-1 font-mono text-[11px] text-text-secondary whitespace-pre-wrap break-all bg-bg-secondary max-h-40 overflow-y-auto border-t border-border-default",children:U||"(empty)"})]},z)})})]}),s.jsx(Ur,{}),O.nativeSource&&s.jsxs("div",{children:[s.jsx(yn,{children:"State History"}),s.jsx("div",{className:"text-text-muted text-[11px] italic px-1",children:"N/A (native-source provider — no state-machine rules)"})]}),!O.nativeSource&&O.stateHistory&&O.stateHistory.length>0&&s.jsxs("div",{children:[s.jsxs(yn,{children:["State History (",O.stateHistory.length,")"]}),s.jsx("div",{className:"space-y-px",children:[...O.stateHistory].reverse().slice(0,20).map((z,U)=>s.jsxs("div",{className:"rounded px-2 py-1 hover:bg-bg-glass-hover transition-colors",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:`font-mono text-[11px] font-semibold px-1.5 py-0.5 rounded shrink-0 ${ko(z.stateId)}`,children:z.stateId}),s.jsx("span",{className:"text-text-secondary text-[11px] shrink-0 tabular-nums",children:Zn(z.at)}),z.durationMs>0&&s.jsxs("span",{className:"text-text-muted text-[11px]",children:["held ",s.jsx("span",{className:"text-text-secondary",children:Ec(z.durationMs)})]}),z.reason&&s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-mono shrink-0 ${cS[String(z.reason)]??"text-text-secondary bg-bg-glass border border-border-default"}`,children:String(z.reason)}),z.debounceKind&&String(z.debounceKind)!=="none"&&s.jsxs("span",{className:"text-text-muted text-[10px] font-mono",children:["debounce:",String(z.debounceKind)]}),z.matchedStateId&&String(z.matchedStateId)!==z.stateId&&s.jsxs("span",{className:"text-text-muted text-[10px] font-mono",children:["eval→",s.jsx("span",{className:"text-text-secondary",children:String(z.matchedStateId)})]})]}),z.matchedRules&&z.matchedRules.length>0&&s.jsxs("div",{className:"flex items-start gap-1 flex-wrap mt-0.5 ml-1 pl-1 border-l border-border-default",children:[z.matchedRules.slice(0,3).map((q,Q)=>s.jsx("span",{className:"font-mono text-[10px] text-accent-primary bg-accent-primary/20 border border-accent px-1.5 py-0.5 rounded break-all",children:typeof q=="string"?q:JSON.stringify(q)},Q)),z.matchedRules.length>3&&s.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",z.matchedRules.length-3," more"]})]})]},U))})]}),s.jsx(Ur,{}),(()=>{const z=O.messages??O.committedMessages??[];if(z.length===0)return null;const U=z.filter(me=>me.role==="user").length,q=z.filter(me=>me.role==="assistant").length,Q=[...z].reverse().find(me=>me.role==="assistant");return s.jsxs("div",{children:[s.jsxs(yn,{children:["Transcript (",z.length," — ",U,"u / ",q,"a)"]}),Q&&s.jsxs("div",{className:"bg-surface-secondary border border-border-default rounded-md p-2.5 text-[11px]",children:[s.jsxs("div",{className:"text-text-muted mb-1 text-[10px]",children:["Last assistant ",Q.receivedAt?Zn(Q.receivedAt):""]}),s.jsxs("div",{className:"text-text-secondary font-mono whitespace-pre-wrap line-clamp-4 break-all",children:[Q.content.slice(0,400),Q.content.length>400?"…":""]})]})]})})(),O.specPath&&s.jsx("div",{className:"text-[10px] text-text-muted font-mono truncate border-t border-border-default pt-2 mt-1",title:O.specPath,children:O.specPath}),s.jsxs("div",{children:[s.jsxs("button",{type:"button",className:"text-[11px] text-text-secondary hover:text-text-primary transition-colors flex items-center gap-1.5",onClick:()=>d(z=>!z),children:[s.jsx("span",{className:"text-text-muted",children:p?"▾":"▸"}),s.jsxs("span",{children:["Raw screen (",O.screen?O.screen.split(`
56
56
  `).length:0," lines)"]})]}),p&&s.jsx("pre",{className:"mt-1.5 px-3 py-2 font-mono text-[11px] text-text-secondary whitespace-pre bg-bg-secondary rounded-md border border-border-default max-h-64 overflow-auto",children:O.screen||"(empty)"})]})]})]})]})})}function mS({activeConv:e,clearToken:t=0,terminalRef:n,handleSendChat:r,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:i=!0,isInputActive:c=!0}){var Be;const{t:u}=Ne("common");As();const{sendPtyInput:p}=St(),[d,m]=l.useState(!1),f=l.useRef(!1);f.current=d;const[g,S]=l.useState("Runtime terminal unavailable"),[h,x]=l.useState(!1),[y,b]=l.useState(null),[C,j]=l.useState(!1),[k,v]=l.useState(!1),[N,w]=l.useState(1),[A,T]=l.useState(!1),[I,P]=l.useState(!1),[D,_]=l.useState(!1),[W,$]=l.useState(!1),[E,B]=l.useState(!1),[L,R]=l.useState({width:0,height:0}),[M,F]=l.useState({width:0,height:0}),[K,J]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[V,Y]=l.useState(null),se=l.useRef(null),ie=l.useRef(null),Z=l.useRef(!1),O=l.useRef(!1),ee=l.useRef(i),G=l.useRef(0),le=l.useRef(!1),je=l.useRef(""),ge=l.useRef(null),Ce=l.useRef(!1),ue=l.useRef(!1),z=l.useRef(null),U=l.useRef(null),q=l.useRef(null),Q=32*1024,me=()=>{var ce,xe,Se,Fe;return((xe=(ce=se.current)==null?void 0:ce.ownerDocument)==null?void 0:xe.defaultView)||((Fe=(Se=ie.current)==null?void 0:Se.ownerDocument)==null?void 0:Fe.defaultView)||window},Ae=ce=>{const xe=me();return{ownerWindow:xe,frameId:xe.requestAnimationFrame(ce)}},de=()=>{const ce=z.current;if(ce){try{ce.ownerWindow.cancelAnimationFrame(ce.frameId)}catch{}z.current=null}},H=()=>{const ce=U.current;if(ce){try{ce.ownerWindow.clearTimeout(ce.timeoutId)}catch{}U.current=null}},he=()=>{const ce=q.current;if(ce){try{ce.ownerWindow.clearTimeout(ce.timeoutId)}catch{}q.current=null}},fe=()=>{i&&z.current===null&&(z.current=Ae(()=>{te()}))},ye=e.tabKey,Pe=e.sessionId||"",He=e.daemonId||((Be=e.routeId)==null?void 0:Be.split(":")[0])||e.routeId||"",ke=rl(e),pe=d?ke?dp:o:g,st=d&&o||null,De=Gk,_e=qk,ae=.05,we=()=>{const ce=M.width,xe=M.height;if(!Number.isFinite(L.width)||L.width<=0||!Number.isFinite(L.height)||L.height<=0||!Number.isFinite(ce)||ce<=0||!Number.isFinite(xe)||xe<=0)return 1;const Se=L.width/ce,Fe=L.height/xe;return Number(Math.min(_e,Math.max(De,Math.min(Se,Fe))).toFixed(2))},Me=we(),qe=Z.current&&N>Me,ve=Number.isFinite(M.width)&&M.width>0?Math.max(L.width,Math.round(M.width*N)):L.width,$e=Number.isFinite(M.height)&&M.height>0?Math.max(L.height,Math.round(M.height*N)):L.height,lt=()=>{Ae(()=>{const ce=ie.current;ce&&(ce.scrollLeft=0,ce.scrollTop=ce.scrollHeight-ce.clientHeight)})},at=()=>{var ce,xe;G.current=0,le.current=!1,je.current="",ge.current=null,Ce.current=!1,ue.current=!1,Z.current||(O.current=!1,w(1)),z.current!==null&&de(),m(!1),S("Runtime terminal unavailable"),he(),H(),b(null),Y(null),T(!1),x(!1),j(!1),v(!1),(xe=(ce=n.current)==null?void 0:ce.reset)==null||xe.call(ce)},bt=()=>{var ce,xe;G.current=0,le.current=!1,je.current="",ge.current=null,Ce.current=!1,ue.current=!1,z.current!==null&&de(),m(!0),S(""),he(),H(),b(null),Y(null),T(!1),x(!1),j(!1),v(!1),(xe=(ce=n.current)==null?void 0:ce.reset)==null||xe.call(ce)},X=()=>{ue.current&&(ue.current=!1,Ae(()=>{var ce,xe;(xe=(ce=n.current)==null?void 0:ce.scrollToTop)==null||xe.call(ce)}))},te=()=>{if(z.current=null,!i)return;const ce=je.current;if(!ce)return;const xe=ce.slice(0,Q);je.current=ce.slice(xe.length);const Se=n.current;if(!Se){je.current=xe+je.current,fe();return}Se.write(xe,()=>{if(je.current.length>0){fe();return}X()})},oe=ce=>{ce&&(je.current+=ce,fe())},be=(ce,xe=0,Se,Fe,Je={})=>{var Oe,yt,zt,wt;const ct=!!Je.force;!ct&&xe>0&&G.current>=xe||!ct&&xe===0&&le.current||(G.current=xe,xe>0&&j(!0),m(!0),S(""),typeof Se=="number"&&typeof Fe=="number"&&Se>0&&Fe>0&&((yt=(Oe=n.current)==null?void 0:Oe.resize)==null||yt.call(Oe,Se,Fe)),je.current="",(wt=(zt=n.current)==null?void 0:zt.reset)==null||wt.call(zt),ce?oe(ce):X())};l.useEffect(()=>{at()},[Pe]),l.useEffect(()=>{var xe;if(!Pe)return;const ce=((xe=jt.onRuntimeEvent)==null?void 0:xe.call(jt,Pe,Se=>{if(!(!Se||Se.sessionId!==Pe)){if(Se.type==="runtime_snapshot"){if(!i){ge.current={text:Se.text||"",seq:Se.seq||0,cols:Se.cols,rows:Se.rows,force:!!Se.force};return}be(Se.text||"",Se.seq||0,Se.cols,Se.rows,{force:!!Se.force});return}if(Se.type==="session_output"){le.current=!0,typeof Se.seq=="number"&&(G.current=Math.max(G.current,Se.seq),Se.seq>0&&j(!0)),f.current||m(!0),f.current||S(""),typeof Se.data=="string"&&oe(Se.data);return}if(Se.type==="session_cleared"){if(!i){Ce.current=!0,je.current="",ge.current=null;return}bt();return}if(Se.type==="session_io_error"){const Fe=typeof Se.error=="string"&&Se.error?Se.error:typeof Se.reason=="string"&&Se.reason?Se.reason:"unknown error";m(!1),S(`Runtime input failed: ${Fe}`);return}}},He))||(()=>{});return()=>{ce()}},[He,Pe,n,i]);const re=async(ce={})=>{var xe;if(!He||!Pe)return{success:!1,error:"daemonId and sessionId are required"};ce.preserveStatus||S(ce.loadingMessage||"Loading runtime terminal...");try{const Se=await((xe=jt.requestRuntimeSnapshot)==null?void 0:xe.call(jt,He,Pe,{sinceSeq:ce.sinceSeq,force:ce.force}));return Se&&Se.success===!1?(ce.preserveStatus||(m(!1),S(`Runtime terminal unavailable: ${Se.error}`)),Se):Se||{success:!0}}catch(Se){const Fe=(Se==null?void 0:Se.message)||String(Se);return ce.preserveStatus||(m(!1),S(`Runtime terminal unavailable: ${Fe}`)),{success:!1,error:Fe}}},Te=async ce=>{var ct,Oe;const xe=((ct=se.current)==null?void 0:ct.ownerDocument)||document,Se=xe.defaultView||window,Fe=(Oe=Se.navigator)==null?void 0:Oe.clipboard;if(Fe!=null&&Fe.writeText&&Se.isSecureContext)try{return await Fe.writeText(ce),!0}catch{}let Je=null;try{return Je=xe.createElement("textarea"),Je.value=ce,Je.setAttribute("readonly","true"),Je.style.position="fixed",Je.style.left="-9999px",Je.style.top="0",xe.body.appendChild(Je),Je.focus(),Je.select(),xe.execCommand("copy")}catch{return!1}finally{Je==null||Je.remove()}},Ee=ce=>{H(),Y(ce);const xe=me();U.current={ownerWindow:xe,timeoutId:xe.setTimeout(()=>{U.current=null,Y(Se=>Se===ce?null:Se)},2200)}},Ie=ce=>{he(),b(ce);const xe=me();q.current={ownerWindow:xe,timeoutId:xe.setTimeout(()=>{q.current=null,b(Se=>Se===ce?null:Se)},2200)}},ze=async()=>{var Je,ct,Oe,yt;const ce=((ct=(Je=n.current)==null?void 0:Je.getSelection)==null?void 0:ct.call(Je))||"",xe=((yt=(Oe=n.current)==null?void 0:Oe.getVisibleText)==null?void 0:yt.call(Oe))||"",Se=ce.trimEnd()||xe.trimEnd();if(!Se){Ee("Nothing to copy");return}if(!await Te(Se)){Ee("Copy failed");return}Ee(ce.trimEnd()?"Copied selection":"Copied visible terminal")},Ke=ce=>{if(!d||!i)return;((p==null?void 0:p(He,Pe,ce))??!1)||Ee("Terminal input failed")},Qe=ce=>{Ke(Kk({ctrl:I,alt:D,shift:W},ce)),P(!1),_(!1),$(!1)},Ue=async()=>{if(h)return;x(!0),b("Loading older terminal output..."),ue.current=!0;const ce=await re({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:d});if(x(!1),(ce==null?void 0:ce.success)===!1){ue.current=!1,b(`Older terminal output unavailable: ${ce.error}`);return}v(!0),Ie("Older terminal output loaded"),Ae(()=>{var xe;(xe=n.current)==null||xe.bumpResize()})};l.useEffect(()=>{var xe,Se;if(!Pe)return;He&&((xe=jt.getState)==null?void 0:xe.call(jt,He))==="connected"&&re();const ce=(Se=jt.onStateChange)==null?void 0:Se.call(jt,(Fe,Je)=>{Fe!==He||Je!=="connected"||re()});return()=>{ce==null||ce()}},[He,Pe,n]),l.useEffect(()=>{t&&at()},[t,ye,n]),l.useEffect(()=>{var Fe,Je;const ce=se.current,xe=(Je=(Fe=ce==null?void 0:ce.ownerDocument)==null?void 0:Fe.defaultView)==null?void 0:Je.ResizeObserver;if(!ce||!xe)return;const Se=new xe(ct=>{const Oe=ct[0];if(!Oe)return;const{width:yt,height:zt}=Oe.contentRect;R(wt=>{const es=Math.round(yt),Ot=Math.round(zt);return wt.width===es&&wt.height===Ot?wt:{width:es,height:Ot}})});return Se.observe(ce),()=>Se.disconnect()},[]),l.useEffect(()=>{if(Z.current)return;const ce=we();!Number.isFinite(ce)||ce<=0||w(xe=>O.current?ce<xe-ae?ce:xe:(O.current=!0,ce))},[M.height,M.width,L.height,L.width]),l.useEffect(()=>{qe&&lt()},[qe,$e,ve]),l.useEffect(()=>{var Se;const ce=ee.current;if(ee.current=i,!i)return;ce||v(!1),Ce.current&&(Ce.current=!1,bt());const xe=ge.current;xe&&(ge.current=null,be(xe.text,xe.seq,xe.cols,xe.rows,{force:!!xe.force})),He&&Pe&&((Se=jt.getState)==null?void 0:Se.call(jt,He))==="connected"&&re(),je.current&&z.current===null&&fe(),Ae(()=>{var Fe;(Fe=n.current)==null||Fe.bumpResize()})},[He,i,Pe]),l.useEffect(()=>()=>{z.current!==null&&de(),H(),he()},[]),l.useEffect(()=>{const ce=Fe=>{var ct;const Je=Fe.detail;Je!=null&&Je.sessionId&&Je.sessionId!==Pe||d&&((ct=n.current)==null||ct.bumpResize())},xe=me(),Se=xe===window?[window]:[window,xe];for(const Fe of Se)Fe.addEventListener("adhdev:fit-cli-terminal",ce);return()=>{for(const Fe of Se)Fe.removeEventListener("adhdev:fit-cli-terminal",ce)}},[d,Pe,n]);const tt=d&&C&&!k&&(K.atTop||!K.canScroll)||h||!!y;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:se,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[tt&&s.jsxs("div",{className:"absolute left-3 top-3 z-10 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-medium text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{Ue()},disabled:!Pe||h,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:u(h?"terminal.loadingOlder":"terminal.loadOlderOutput")}),y&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:y})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[V&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:V}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>B(ce=>!ce),title:"Spec debug — inspect current state, sections, and transition history",children:u("terminal.debug")}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{ze()},disabled:!d,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:u("terminal.copy")}),s.jsxs("div",{className:"relative",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>T(ce=>!ce),disabled:!d,"aria-label":u(A?"terminal.closeControlKeys":"terminal.openControlKeys"),"aria-expanded":A,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),A&&s.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":u("terminal.openControlKeys"),className:"absolute right-0 top-10 w-72 rounded-2xl border border-white/10 bg-[#0b0d12]/95 p-3 text-white/85 shadow-2xl shadow-black/40 backdrop-blur-md",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Terminal keys"}),s.jsx("button",{type:"button",className:"rounded-full px-2 py-0.5 text-[11px] text-white/55 transition-colors hover:bg-white/10 hover:text-white/85",onClick:()=>T(!1),"aria-label":u("terminal.closeControlKeys"),children:"×"})]}),s.jsx("div",{className:"mb-2 grid grid-cols-3 gap-1.5",children:[["Ctrl",I,P],["Alt",D,_],["Shift",W,$]].map(([ce,xe,Se])=>s.jsx("button",{type:"button","aria-pressed":xe,className:`h-9 rounded-lg border text-[12px] font-semibold transition-colors ${xe?"border-sky-400/50 bg-sky-400/25 text-white":"border-white/10 bg-white/[0.06] hover:bg-white/[0.12]"}`,onClick:()=>Se(Fe=>!Fe),children:ce},ce))}),s.jsx("div",{className:"my-2 h-px bg-white/10"}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Qe("Escape"),children:"Esc"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Qe("Tab"),children:"Tab"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Qe("Enter"),children:"Enter"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Qe("ArrowUp"),"aria-label":"Arrow up",children:"↑"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Qe("ArrowLeft"),"aria-label":"Arrow left",children:"←"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Qe("ArrowDown"),"aria-label":"Arrow down",children:"↓"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>Qe("ArrowRight"),"aria-label":"Arrow right",children:"→"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Ke(""),title:"Send SIGINT (Ctrl-C)",children:"Ctrl-C"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Qe("Space"),children:"Space"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Qe("Backspace"),children:"Bksp"})]})]})]}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{Z.current=!0,w(ce=>{const xe=Math.max(Me,Number((ce-.1).toFixed(2)));return xe>Me&&lt(),xe})},title:"Shrink terminal viewport",children:"-"}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{Z.current=!0,w(ce=>{const xe=Math.min(_e,Number((ce+.1).toFixed(2)));return xe>Me&&lt(),xe})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:ie,className:qe?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:s.jsx("div",{style:{width:ve>0?`${ve}px`:"100%",height:$e>0?`${$e}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:M.width>0?`${M.width}px`:"100%",height:M.height>0?`${M.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:N},children:s.jsx(Du,{ref:n,readOnly:!d||!i,sizingMode:"measured",onViewportMetrics:F,onScrollMetrics:J,onInput:ce=>{!d||(p==null||p(He,Pe,ce))}})})})}),!d&&s.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:g})]}),s.jsx(Ju,{contextKey:e.tabKey,panelLabel:kt(e),isSending:a,isBusy:!!ke,statusMessage:pe,inlineStatusMessage:st,onSend:async ce=>ke?!1:r(ce),isActive:c&&i,showControlsToggle:!1,animateVisibility:!1}),E&&s.jsx(pS,{activeConv:e,onClose:()=>B(!1)})]})}const hS=5e3,fS=12e3;function bS(e){return e==="disconnected"||e==="reconnecting"}function gS({wsStatus:e,showReconnected:t,loginUrl:n,onReconnect:r,reconnectDelayMs:a=hS,reconnectActionDelayMs:o=fS}){const{t:i}=Ne(),c=bS(e),[u,p]=l.useState(()=>!c||a<=0),[d,m]=l.useState(()=>!c||o<=0),f=l.useRef(!1);l.useEffect(()=>{if(!c){p(!1);return}if(f.current=!1,a<=0){f.current=!0,p(!0);return}p(!1);const v=setTimeout(()=>{f.current=!0,p(!0)},a);return()=>clearTimeout(v)},[a,c]),l.useEffect(()=>{if(!c){m(!1);return}if(o<=0){m(!0);return}m(!1);const v=setTimeout(()=>{m(!0)},o);return()=>clearTimeout(v)},[o,c]);const g=c?u:e==="offline"||e==="auth_failed",S=!!(r&&e!=="auth_failed"&&(!c||d)),h=l.useMemo(()=>!t||e!=="connected"?!1:a<=0||f.current,[a,t,e]),x=e==="auth_failed"?"red":e==="offline"?"orange":"accent",y={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},b={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},C={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},j="fixed left-1/2 top-[calc(env(safe-area-inset-top,0px)+64px)] sm:top-[calc(env(safe-area-inset-top,0px)+16px)] z-[var(--z-toast)] flex items-center justify-center pointer-events-none",k={transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[g&&s.jsx("div",{className:j,style:k,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-3 py-2.5 sm:px-4 sm:py-3 text-[13px] font-semibold flex flex-wrap items-center gap-x-2.5 gap-y-2 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:y[x],border:b[x],color:C[x]},children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),s.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&i("connection.networkOffline"),e==="disconnected"&&i("connection.reconnecting"),e==="reconnecting"&&i("connection.reconnecting"),e==="auth_failed"&&(n?s.jsxs(s.Fragment,{children:[i("connection.sessionExpired")," ",s.jsx("a",{href:n,className:"text-inherit underline",children:i("connection.logInAgain")})]}):i("connection.connectionFailed"))]}),S&&s.jsx("button",{type:"button",className:"basis-full sm:basis-auto mx-auto sm:mx-0 sm:ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>r==null?void 0:r(),disabled:e==="offline",children:i("connection.reconnectNow")})]})}),h&&s.jsx("div",{className:j,style:k,children:s.jsxs("div",{className:"pointer-events-none rounded-2xl border px-4 py-2 text-xs font-semibold flex items-center gap-2 justify-center bg-gradient-to-r from-green-500/[0.12] to-green-500/[0.04] text-green-400 border-green-500/15 shadow-[0_18px_40px_rgba(2,6,23,0.2)] backdrop-blur-xl animate-[fadeIn_0.3s_ease]",children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-4 h-4"}),i("connection.connected")]})})]})}function _p({mode:e,onChange:t,compact:n=!1}){const{t:r}=Ne("common"),a=n?14:15;return s.jsx("button",{type:"button",onClick:()=>t(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:r(e==="chat"?"cliView.switchToTerminal":"cliView.switchToChat"),children:e==="chat"?s.jsx(qi,{size:a}):s.jsx(bn,{size:a})})}function xS(e){if(!e||e.isGitRepo===!1||e.reason==="not_git_repo")return null;if(e.hasConflicts)return`${e.branch||"Git"} · conflicts${e.changedFiles>0?` ${e.changedFiles}`:""}`;const t=[e.branch||"Git"];return e.changedFiles>0&&t.push(`±${e.changedFiles}`),e.ahead>0&&t.push(`↑${e.ahead}`),e.behind>0&&t.push(`↓${e.behind}`),t.length===1&&e.dirty&&t.push("dirty"),t.join(" ")}function vS(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 yS(e){switch(e){case"conflict":return"border-status-error/40 bg-status-error/10 text-status-error";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-status-online/40 bg-status-online/10 text-status-online"}}function Ca({git:e,className:t="",compact:n=!1}){const r=xS(e),a=vS(e);if(!r||!a)return null;const o=[e!=null&&e.branch?`Branch: ${e.branch}`:null,e!=null&&e.changedFiles?`Changed files: ${e.changedFiles}`:null,e!=null&&e.ahead?`Ahead: ${e.ahead}`:null,e!=null&&e.behind?`Behind: ${e.behind}`:null,e!=null&&e.hasConflicts?"Conflicts detected":null,e!=null&&e.error?`Git error: ${e.error}`:null].filter(Boolean);return s.jsxs("span",{className:`inline-flex min-w-0 max-w-[12rem] items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold leading-none ${yS(a)} ${t}`.trim(),title:o.join(" · ")||r,"data-git-tone":a,children:[s.jsx("span",{"aria-hidden":"true",children:"⑂"}),s.jsx("span",{className:"truncate",children:r})]})}function wS({wsStatus:e,isConnected:t,daemonCount:n,p2pStates:r={}}){if(e!=="connected")return{tone:"disconnected",titleKey:"connection.disconnected",subtitleKey:null};const a=Object.values(r),o=a.filter(c=>c==="connected").length,i=a.filter(c=>c==="connecting"||c==="new"||c==="checking").length;return n>0&&i>0&&o===0?{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:"connection.connectingToMachine"}:t?{tone:"connected",titleKey:"connection.connected",subtitleKey:null}:{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:null}}function _c({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function $c({notification:e,shortcutIndex:t,onOpen:n,onMarkRead:r,onMarkUnread:a,onDelete:o}){const{t:i}=Ne(),c=Ba(e.updatedAt),u=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${u?"is-attention":""}`.trim(),children:[s.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 flex-col items-start text-left",onClick:n,children:[s.jsx("span",{className:"dashboard-header-inbox-item-title",children:e.title}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[t?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",t]}):null,[e.type==="needs_attention"?i("notification.actionNeeded"):i("notification.taskComplete"),c].filter(Boolean).join(" · ")]}),e.preview?s.jsx("span",{className:"dashboard-header-inbox-item-meta dashboard-header-inbox-item-preview",children:e.preview}):null]}),s.jsxs("div",{className:"ml-3 flex shrink-0 items-center gap-1.5",children:[u?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),r()},children:i("notification.markRead")}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),a()},children:i("notification.markUnread")}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),o()},children:i("notification.delete")})]})]})}function kS({activeConv:e,wsStatus:t,isConnected:n,conversations:r,onOpenHistory:a,onOpenRemote:o,onStopCli:i,activeCliViewMode:c,onSetCliViewMode:u,onHideConversation:p,hiddenConversations:d=[],onShowConversation:m,onShowAllHidden:f,onResetPanelsToMain:g,inboxOpen:S,onInboxOpenChange:h,hiddenOpen:x,onHiddenOpenChange:y,onOpenNewSession:b,onOpenDashboardGuide:C,guideNudgeVisible:j=!1,actionShortcuts:k,notifications:v,notificationUnreadCount:N,onOpenNotification:w,onMarkNotificationRead:A,onMarkNotificationUnread:T,onDeleteNotification:I,onOpenGitDialog:P,onOpenMeshGraph:D}){var q;const{t:_}=Ne(),{ides:W,p2pStates:$={}}=As(),E=!!e&&ht(e)&&!pt(e),B=!!e&&pt(e),L=!!(e!=null&&e.daemonId)&&!!((q=e==null?void 0:e.coordinator)!=null&&q.meshId),R=c||(e?rp(e)?"terminal":"chat":null),[M,F]=l.useState(!1),[K,J]=l.useState(!1),V=l.useRef(null),Y=l.useRef(null),se=l.useRef(null),ie=W.filter(Q=>Q.type==="adhdev-daemon"),Z=wS({wsStatus:t,isConnected:n,daemonCount:ie.length,p2pStates:$}),O=_(Z.titleKey),ee=Z.subtitleKey?_(Z.subtitleKey):null,G=Z.tone==="connected"?"#22c55e":Z.tone==="limited"?"#eab308":"#ef4444",le=Z.tone==="connected"?"0 0 4px #22c55e80":Z.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",je=l.useMemo(()=>v.filter(Q=>!Q.readAt),[v]),ge=l.useMemo(()=>v.filter(Q=>!!Q.readAt),[v]),Ce=l.useMemo(()=>je.slice(0,9),[je]),ue=N;l.useEffect(()=>{if(!S)return;const Q=me=>{var Ae;(Ae=Y.current)!=null&&Ae.contains(me.target)||h(!1)};return document.addEventListener("mousedown",Q),()=>document.removeEventListener("mousedown",Q)},[S,h]),l.useEffect(()=>{if(!x)return;const Q=me=>{var Ae;(Ae=se.current)!=null&&Ae.contains(me.target)||y(!1)};return document.addEventListener("mousedown",Q),()=>document.removeEventListener("mousedown",Q)},[x,y]),l.useEffect(()=>{if(!x&&!S)return;const Q=me=>{if(!me.altKey)return;const Ae=me.code.match(/^Digit([1-9])$/);if(!Ae)return;const de=Number(Ae[1])-1,H=x?d[de]:void 0,he=S?Ce[de]:void 0;if(!(!H&&!he)){if(me.preventDefault(),me.stopPropagation(),H){m==null||m(H),y(!1);return}he&&(w(he),h(!1))}};return window.addEventListener("keydown",Q,!0),()=>window.removeEventListener("keydown",Q,!0)},[d,x,S,Ce,y,h,w,m]),l.useEffect(()=>{const Q=d.length;if(V.current===null){V.current=Q;return}Q>V.current&&J(!0),V.current=Q},[d.length]);const z=()=>J(!1),U=Q=>{if(!Q)return;const me=r.find(Ae=>Ae.tabKey===Q);me&&(p==null||p(me))};return s.jsxs("div",{className:"dashboard-header",children:[s.jsx("div",{className:"flex items-center gap-3",children:s.jsx("div",{className:"header-title-block",children:s.jsxs("div",{className:"header-title-row",children:[s.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[s.jsx(bn,{size:18}),s.jsx("span",{className:"header-title-desktop",children:_("dashboard.header.title")}),s.jsx("span",{className:"header-title-mobile",children:e?kt(e):_("dashboard.header.title")}),s.jsx("span",{title:O,"aria-label":O,className:"header-title-status-dot",style:{background:G,boxShadow:le}}),s.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:s.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:G,boxShadow:le}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[ee&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",ee]}),b&&s.jsx("button",{type:"button",onClick:b,className:"btn btn-secondary btn-sm ml-2",title:`${_("paneGroup.newSession")}${k!=null&&k.openNewSession?` (${k.openNewSession})`:""}`,"aria-label":_("paneGroup.newSession"),children:s.jsx(zi,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[C&&s.jsxs("button",{type:"button",onClick:C,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:_("dashboard.header.guide"),"aria-label":_("dashboard.header.guideOpen"),children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),j&&s.jsx("span",{children:_("dashboard.header.guideShort")})]}),e&&(E||B||!pt(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:$n(e)||kt(e),children:kt(e)}),P&&e.git&&e.daemonId&&e.workspacePath?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:_("dashboard.header.openGitStatus"),onClick:()=>P(e.daemonId,e.workspacePath),children:s.jsx(Ca,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(Ca,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),L&&D&&s.jsxs("button",{type:"button",onClick:()=>D(e),className:"btn btn-secondary btn-sm dashboard-header-mesh-button",title:_("dashboard.header.openMeshGraph"),children:[s.jsx(os,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:_("dashboard.header.meshGraph")})]}),(E||B)&&i&&s.jsxs(s.Fragment,{children:[E&&u&&R&&s.jsx(_p,{mode:R,onChange:u,compact:!0}),s.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:_(B?"dashboard.header.stopAcpSession":"dashboard.header.stopCliProcess"),style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(Mt,{size:14})})]}),!pt(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:_("dashboard.header.chatHistory"),children:s.jsx(Ui,{size:14})}),!E&&!pt(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:_("dashboard.header.remoteControl"),children:s.jsx(xs,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:Y,children:[s.jsxs("div",{className:`dashboard-header-hidden${M?" is-drop-target":""}${K?" hidden-spawn-flash":""}${(d??[]).some(kr)?" hidden-generating-spin":""}`,onAnimationEnd:z,ref:se,onDragEnter:Q=>{Q.dataTransfer.types.includes("text/tab-key")&&(Q.preventDefault(),F(!0))},onDragOver:Q=>{Q.dataTransfer.types.includes("text/tab-key")&&(Q.preventDefault(),Q.dataTransfer.dropEffect="move",F(!0))},onDragLeave:Q=>{Q.currentTarget.contains(Q.relatedTarget)||F(!1)},onDrop:Q=>{const me=Q.dataTransfer.getData("text/tab-key");Q.preventDefault(),F(!1),U(me)},children:[s.jsxs("button",{type:"button",onClick:()=>y(!x),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`${_("dashboard.hidden.title")}${k!=null&&k.toggleHiddenTabs?` (${k.toggleHiddenTabs})`:""}. ${_("dashboard.hidden.dragHint")}`,children:[s.jsx(Gi,{size:16}),d.length>0&&s.jsx("span",{className:`dashboard-header-hidden-badge${K?" hidden-badge-pop":""}`,children:d.length})]}),x&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:_("dashboard.hidden.title")}),s.jsx(_c,{value:k==null?void 0:k.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[g&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:g,children:_("dashboard.hidden.resetPanels")}),d.length>0&&f&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{f(),y(!1)},children:_("dashboard.hidden.restoreAll")})]})]}),e&&p&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>p(e),children:[s.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[s.jsx("span",{className:"dashboard-header-hidden-current-label",children:_("dashboard.hidden.hideCurrentTab")}),s.jsx(_c,{value:k==null?void 0:k.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:kt(e)})]}),d.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:d.map(Q=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{m==null||m(Q),y(!1)},children:[s.jsxs("span",{className:"dashboard-header-inbox-item-title",children:[kr(Q)&&s.jsx("span",{className:"tab-spinner dashboard-header-inbox-item-spinner","aria-label":_("dashboard.header.generating")}),kt(Q)]}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[d.indexOf(Q)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",d.indexOf(Q)+1]}):null,$n(Q)]})]},Q.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:_("dashboard.hidden.empty")})]})]}),s.jsxs("button",{type:"button",onClick:()=>h(!S),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:_("dashboard.header.activityInbox"),children:[s.jsx(Un,{size:16}),ue>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:ue})]}),S&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[je.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:_("dashboard.inbox.unread")}),je.map(Q=>s.jsx($c,{notification:Q,shortcutIndex:Ce.indexOf(Q)>=0?Ce.indexOf(Q)+1:void 0,onOpen:()=>w(Q),onMarkRead:()=>A(Q.id),onMarkUnread:()=>T(Q.id),onDelete:()=>I(Q.id)},Q.id))]}),ge.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:_("dashboard.inbox.read")}),ge.map(Q=>s.jsx($c,{notification:Q,onOpen:()=>w(Q),onMarkRead:()=>A(Q.id),onMarkUnread:()=>T(Q.id),onDelete:()=>I(Q.id)},Q.id))]}),v.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:_("dashboard.inbox.empty")})]})]})]})]})}function qt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function SS(e,t){return String(e||"")!==String(t||"")}function CS(e,t={}){const n=String(t.textQuery||"").trim().toLowerCase(),r=String(t.workspaceQuery||"").trim().toLowerCase(),a=String(t.modelQuery||"").trim().toLowerCase(),o=!!t.resumableOnly;return!n&&!r&&!a&&!o?e:e.filter(i=>!(o&&!i.canResume||n&&![i.title,i.preview].map(u=>String(u||"").toLowerCase()).join(`
57
57
  `).includes(n)||r&&!String(i.workspace||"").toLowerCase().includes(r)||a&&!Gu(i.summaryMetadata).map(u=>u.toLowerCase()).join(`
58
- `).includes(a)))}function jS(e,t="recent"){const n=e.slice();return n.sort((r,a)=>{if(t==="oldest")return(Number(r.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(t==="messages"){const o=(Number(a.messageCount)||0)-(Number(r.messageCount)||0);if(o!==0)return o}return(Number(a.lastMessageAt)||0)-(Number(r.lastMessageAt)||0)}),n}function $p(e,t={}){return jS(CS(e,t),t.sortMode||"recent")}function Si(e,t){return typeof e=="function"?e(t??!1?"launch.resumeSavedHistory":"launch.startFresh"):e?"Resume saved history":"Start fresh"}function Hp(e,t){return typeof e=="function"?e(t??!1?"launch.resumingSavedHistory":"launch.startingFresh"):e?"Resuming saved history…":"Starting fresh…"}function NS(e){return e?e("launch.startFresh"):"Start fresh"}function AS(e){return e?e("launch.hostedRuntimeRecoveryDescription"):"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function TS(e){return e?e("launch.openSavedHistory"):"Open saved history"}function MS(e){return e?e("launch.savedHistoryTitle"):"Saved History"}function ll(e){return e?e("launch.savedHistoryHelper"):"Use saved history when you want continuity in the same provider conversation."}function DS(e){return e?e("launch.savedHistoryEmpty"):"No saved history found yet."}function IS(e){return e?e("launch.refreshSavedHistory"):"Refresh saved history"}function PS(e){return e?e("launch.refreshingSavedHistory"):"Refreshing saved history…"}function ja(e,t,n){if(typeof e=="function"){const o=t,i=n;return o==="start-fresh"?e("launch.startFreshWith",{label:i}):e("launch.restart",{label:i})}const r=e,a=t;return r==="start-fresh"?`Start fresh with ${a}?`:`Restart ${a}?`}function Na(e,t){if(typeof e=="function"){const r=t;return e(r==="start-fresh"?"launch.startFreshReview":r==="restart-ide"?"launch.restartIdeReview":"launch.restartStoppedReview")}const n=e;return n==="start-fresh"?"Review the provider and target folder before starting fresh.":n==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Aa(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartFresh":"launch.confirmRestart"):e==="start-fresh"?"Start fresh":"Restart"}function Ta(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartingFresh":"launch.confirmRestarting"):e==="start-fresh"?"Starting fresh…":"Restarting…"}function Fp(e,t){return typeof e=="function"?e("launch.resumeWith",{label:t}):`Resume saved history with ${e}?`}function Bp(e){return e?e("launch.resumeReview"):"Review or change the target workspace before resuming saved history."}function LS(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 Wp({activeConv:e,ides:t,isCreatingChat:n,isRefreshingHistory:r,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:u,onSavedHistoryFiltersChange:p,onClose:d,onNewChat:m,onSwitchSession:f,onRefreshHistory:g,onResumeSavedSession:S}){var P;const{t:h}=Ne("common"),x=t.find(D=>D.id===e.routeId),y=(x==null?void 0:x.chats)||[],b=(P=x==null?void 0:x.activeChat)==null?void 0:P.id,C=ht(e)&&!pt(e),[j,k]=l.useState(()=>qt()),v=c||j,N=String(u||"").trim(),w=D=>{if(p){p(D);return}k(D)},A=l.useMemo(()=>a.map(D=>{const _=String(D.workspace||"").trim();return D.canResume||_||!N?D:{...D,workspace:N,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[N,a]),T=l.useMemo(()=>$p(A,{textQuery:v.textQuery,workspaceQuery:v.workspaceQuery,modelQuery:v.modelQuery,resumableOnly:v.resumableOnly,sortMode:v.sortMode}),[A,v.modelQuery,v.resumableOnly,v.sortMode,v.textQuery,v.workspaceQuery]),I=s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:d,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:C?MS(h):h("historyModal.chatHistory")}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Xk(e)}),C&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:ll(h)})]}),s.jsx("button",{onClick:d,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(Mt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!C&&s.jsx("button",{onClick:m,disabled:n,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:h(n?"historyModal.creating":"historyModal.startNewChat")}),C?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:v.textQuery,onChange:D=>w({...v,textQuery:D.target.value}),placeholder:h("historyModal.searchPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:v.workspaceQuery,onChange:D=>w({...v,workspaceQuery:D.target.value}),placeholder:h("historyModal.filterWorkspace"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:v.modelQuery,onChange:D=>w({...v,modelQuery:D.target.value}),placeholder:h("historyModal.filterModel"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:v.sortMode,onChange:D=>w({...v,sortMode:D.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:h("historyModal.sortRecent")}),s.jsx("option",{value:"oldest",children:h("historyModal.sortOldest")}),s.jsx("option",{value:"messages",children:h("historyModal.sortMessages")})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:v.resumableOnly,onChange:D=>w({...v,resumableOnly:D.target.checked})}),h("historyModal.resumeReadyOnly")]})]}),T.map(D=>{const _=e.providerSessionId===D.providerSessionId,W=_||!D.canResume||!!i,$=D.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{W||!S||S(D)},disabled:W,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${_?"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:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${_?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:D.title||h("historyModal.untitledSession")}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:D.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:LS(D.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:D.preview||h("historyModal.noSavedPreview")}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[D.workspace||h("historyModal.workspaceUnknown"),$?h("historyModal.selectedWorkspaceSuffix"):"",mn(D.summaryMetadata)?` · ${mn(D.summaryMetadata)}`:"",D.messageCount>0?` · ${h("historyModal.msgCount",{count:D.messageCount})}`:""]}),s.jsx("div",{className:"shrink-0",children:_?h("historyModal.statusActive"):D.canResume?$?h("historyModal.statusResumeSelectedWorkspace"):i===D.providerSessionId?h("historyModal.statusResuming"):h("historyModal.statusResume"):h("historyModal.statusMissingWorkspace")})]})]},D.id)})]}):y.map(D=>s.jsxs("div",{onClick:()=>{f(e.routeId,D.id),d()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${b===D.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${b===D.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:D.title||h("historyModal.untitledSession")}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[D.id.substring(0,12),"..."]}),b===D.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:h("historyModal.statusActive")})]})]},D.id)),(C&&!o&&T.length===0||!C&&y.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(ab,{size:32})}),s.jsx("div",{className:"text-[13px]",children:C?a.length>0?h("historyModal.noMatchingHistory"):DS(h):h("historyModal.noRecentChats")})]}),C&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:PS(h)})})]}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:s.jsx("button",{onClick:g,disabled:r||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:r||o?h("historyModal.refreshing"):s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Fa,{size:13})," ",C?IS(h):h("historyModal.refreshHistory")]})})})]})]});return typeof document>"u"?I:un.createPortal(I,document.body)}const Hc={success:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",labelKey:"toast.label.success"},warning:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",labelKey:"toast.label.warning"},info:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",labelKey:"toast.label.info"}};function Op({toasts:e,onDismiss:t,onClickToast:n}){const{t:r}=Ne();return s.jsx("div",{className:"fixed right-4 top-[calc(env(safe-area-inset-top,0px)+64px)] z-[var(--z-toast)] flex flex-col gap-2 pointer-events-none sm:top-[calc(env(safe-area-inset-top,0px)+16px)]",children:e.map(a=>{const o=Hc[a.type]||Hc.info;return s.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var i;(i=a.actions)!=null&&i.length||n&&n(a)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${o.accent}, color-mix(in srgb, ${o.accent} 55%, transparent))`}}),s.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),t(a.id)},"aria-label":r("toast.dismiss"),children:s.jsx(Mt,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:o.chipBg,color:o.chipText,border:`1px solid color-mix(in srgb, ${o.accent} 22%, transparent)`},children:r(o.labelKey)})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:a.message}),a.actions&&a.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:a.actions.map((i,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:u=>{u.stopPropagation(),i.onClick(),t(a.id)},children:i.label},c))})]})]},a.id)})})}const RS=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function ES(e){const t=e.workspace||"";if(!t)return"";const n=t.split(/[/\\]/).filter(Boolean);return n.length>0?n[n.length-1]:t}function _S(e,t){return Up(e)||t}function Up(e){var a,o,i;const t=(o=(a=e.summaryMetadata)==null?void 0:a.items)==null?void 0:o.find(c=>(c==null?void 0:c.id)==="model"),n=((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim();if(n)return n;const r=(i=e.controlValues)==null?void 0:i.model;return typeof r=="string"&&r.trim()?r.trim():""}function $S(e){return Up(e)||void 0}function HS(e){return e.sessionId||e.instanceId||e.agentType}function Gp(e=[]){const t={};for(const n of e)n.type==="adhdev-daemon"&&(t[n.id]=is(n,{fallbackId:n.id}));return t}function qp(e,t={}){var r;const n=e.daemonId||((r=e.id)==null?void 0:r.split(":")[0])||e.id;return{machineName:tw(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[n]||t.defaultConnectionState||"new":t.defaultConnectionState}}function cl(e,t={}){return FS(e,qp(e,t))}function FS(e,t={}){var f,g,S,h,x,y,b,C,j;const n=[],r=t.machineName,a=t.connectionState,o=ES(e),i=e.workspace||"",c=iw(e.type,{agentName:e.cliName}),u=ht(e)||pt(e)?c:Bt(e.type),p=_S(e,u),d=Array.isArray(e.childSessions)?e.childSessions.map(k=>{var v,N,w;return{sessionId:k.id,instanceId:k.id,providerSessionId:k.providerSessionId,activeChatId:(v=k.activeChat)==null?void 0:v.id,transport:k.transport,sessionCapabilities:k.capabilities,agentType:k.providerType,agentName:k.providerName||Bt(k.providerType),model:$S(k),status:k.status,title:k.title,lastMessagePreview:k.lastMessagePreview,lastMessageRole:k.lastMessageRole,lastMessageAt:k.lastMessageAt,lastMessageHash:k.lastMessageHash,messages:((N=k.activeChat)==null?void 0:N.messages)||[],activeModal:((w=k.activeChat)==null?void 0:w.activeModal)||void 0,unread:k.unread,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,inboxBucket:k.inboxBucket,completionMarker:k.completionMarker,surfaceHidden:k.surfaceHidden,muted:k.muted,git:k.git,settings:k.settings,coordinator:k.coordinator,messageInput:k.messageInput}}):[],m=RS(e);if(m){const k=e.sessionId||e.instanceId,v=(f=e.settings)==null?void 0:f.meshCoordinatorFor,N=((g=e.settings)==null?void 0:g.meshNodeFor)||!((S=e.settings)!=null&&S.meshCoordinatorFor)&&((h=e.settings)==null?void 0:h.launchedByCoordinator),w=v?" (Coordinator)":N?" (Mesh Node)":"",A=c+w,T=(x=e.activeChat)==null?void 0:x.activeModal,I=T&&Array.isArray(T.buttons)&&T.buttons.length>0,P=lw(e.activeChat,[{status:e.status,activeModal:(y=e.activeChat)==null?void 0:y.activeModal}],e.agents||[]),D=e.activeChat||{title:"",messages:[]};let _=D.title&&String(D.title).trim()?String(D.title).trim():"";const W=(b=e.activeChat)==null?void 0:b.id,$=e.chats;if(W&&Array.isArray($)&&$.length>0){const J=$.find(V=>V.id===W||V.id&&String(V.id)===String(W));J!=null&&J.title&&String(J.title).trim()&&(_=String(J.title).trim())}const E=(ht(e)||pt(e),e.type),B=(ht(e)||pt(e))&&ic(_,A,E)?"":_,L=D.messages||[],R=typeof W=="string"?W.trim():"",M=(ht(e)||pt(e))&&R===String(e.type||"").trim(),F=R&&!M?R:e.providerSessionId,K=e.coordinator||(typeof((C=e.settings)==null?void 0:C.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:k,providerSessionId:e.providerSessionId,historySessionId:F,nativeSessionId:k,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:ht(e)&&e.mode||"chat",agentName:A,agentType:E,status:P,title:B,messages:L,resume:e.resume,hostIdeType:!ht(e)&&!pt(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||B||(ht(e)?e.mode==="chat"?A:`Terminal${w}`:A),displaySecondary:p,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:I?T.buttons:void 0,modalMessage:I?T.message:void 0,streamSource:"native",tabKey:ho(k,e.id),machineName:r,connectionState:a,settings:e.settings,coordinator:K,messageInput:e.messageInput})}if(m&&(ht(e)||pt(e)))return n;for(const k of d){const v=k.activeModal&&Array.isArray(k.activeModal.buttons)&&k.activeModal.buttons.length>0,N=cw(k),w=HS(k),A=`${e.id}:${w}`,T=k.title&&String(k.title).trim()||"",I=ic(T,k.agentName,k.agentType)?"":T,P=k.messages||[];if(!(k.transport==="cdp-webview"||!!k.sessionId||!!k.providerSessionId||P.length>0||v||!!I||!["idle","panel_hidden","disconnected","not_monitored"].includes(N)))continue;const _=k.coordinator||(typeof((j=k.settings)==null?void 0:j.meshCoordinatorFor)=="string"&&k.settings.meshCoordinatorFor?{meshId:k.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:k.sessionId||k.instanceId,providerSessionId:k.providerSessionId,historySessionId:k.activeChatId||k.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:k.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:k.sessionCapabilities,mode:"chat",agentName:k.agentName,agentType:k.agentType,status:N,title:I,messages:P,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:k.git||e.git,displayPrimary:o||I||k.agentName||u,displaySecondary:k.model&&k.model.trim()?k.model.trim():`${u} · ${k.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:k.lastMessagePreview,lastMessageRole:k.lastMessageRole,lastMessageAt:k.lastMessageAt,lastMessageHash:k.lastMessageHash,lastUpdated:k.lastUpdated||e.lastUpdated,inboxBucket:k.inboxBucket,completionMarker:k.completionMarker,modalButtons:v?k.activeModal.buttons:void 0,modalMessage:v?k.activeModal.message:void 0,streamSource:"agent-stream",tabKey:ho(k.sessionId||k.instanceId,A),machineName:r,connectionState:a,settings:k.settings,coordinator:_,messageInput:k.messageInput})}return n.length===0&&n.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:i,git:e.git,displayPrimary:o||u,displaySecondary:p,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:ho(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),n}function zp(e){return String(e.type||e.id||"").trim()}function Ma(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function BS(e,t){const n=(t||"").trim();if(!n)return[];const r=(e||[]).find(a=>a.type===n);return Ma(r==null?void 0:r.modelOptions)}function WS(e,t){const n=(t||"").trim();if(!n)return[];const r=(e||[]).find(a=>a.type===n);return Ma(r==null?void 0:r.thinkingLevelOptions)}function Kp(e){const t=new Map;for(const n of e||[])n!=null&&n.type&&t.set(n.type,{models:Ma(n.modelOptions),thinking:Ma(n.thinkingLevelOptions)});return t}function OS(e){var t;return e.category!=="cli"||!zp(e)||e.enabled===!1?!1:e.machineStatus?e.machineStatus==="detected":((t=e.lastDetection)==null?void 0:t.ok)===!0||e.installed===!0||!!e.detectedPath}function Hn(e){var r;const t=new Set,n=[];for(const a of e||[]){if(!OS(a))continue;const o=zp(a);if(!o||t.has(o))continue;t.add(o);const i=String(a.displayName||a.name||o),c=a.detectedPath||((r=a.lastDetection)==null?void 0:r.path)||null;n.push({type:o,label:i,icon:a.icon,statusLabel:c?`Detected at ${c}`:"Detected on this machine",detectedPath:c,...Array.isArray(a.modelOptions)&&a.modelOptions.length?{modelOptions:a.modelOptions}:{},...Array.isArray(a.thinkingLevelOptions)&&a.thinkingLevelOptions.length?{thinkingLevelOptions:a.thinkingLevelOptions}:{}})}return n}function Fn(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],n=new Set,r=[];for(const a of t){const o=typeof a=="string"?a.trim():"";!o||n.has(o)||(n.add(o),r.push(o))}return r}function jr(e){return e.map(t=>t.type)}function US(e,t){const n=Fn(e),r=t.trim();return!r||n.includes(r)?n:[...n,r]}function GS(e,t){return Fn(e).filter(n=>n!==t)}function Fc(e,t,n){const r=Fn(e),a=r.indexOf(t);if(a<0)return r;const o=r.filter(c=>c!==t);if(n==="top")return[t,...o];if(n==="bottom")return[...o,t];const i=n==="up"?Math.max(0,a-1):Math.min(o.length,a+1);return o.splice(i,0,t),o}function Bc({direction:e}){return s.jsx("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e==="up"?s.jsx("polyline",{points:"18 15 12 9 6 15"}):s.jsx("polyline",{points:"6 9 12 15 18 9"})})}function qS({value:e,availableProviders:t,onChange:n,disabled:r=!1,saveButton:a}){const{t:o}=Ne("common"),[i,c]=l.useState(""),u=l.useMemo(()=>new Map(t.map(g=>[g.type,g])),[t]),p=l.useMemo(()=>Fn(e),[e]),d=p.filter(g=>!u.has(g)).length,m=t.filter(g=>!p.includes(g.type)),f=()=>{i&&(n(US(p,i)),c(""))};return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[s.jsx("div",{className:"flex flex-col gap-2",children:p.length===0?s.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:"No provider priority configured. Launches without an explicit CLI provider will fail closed."}):p.map((g,S)=>{const h=u.get(g),x=!!h;return s.jsxs("div",{className:`flex flex-col gap-2 rounded-md border border-border-subtle px-3 py-2 sm:flex-row sm:items-center sm:justify-between ${x?"bg-bg-primary":"bg-bg-primary/40"}`,children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",S+1]}),(h==null?void 0:h.icon)&&s.jsx("span",{"aria-hidden":"true",children:h.icon}),s.jsx("span",{className:`font-mono text-[12px] ${x?"text-text-primary":"text-text-muted"}`,children:g}),x?s.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:o("settings.providerPriority.available")}):s.jsx("span",{className:"rounded border border-amber-500/25 bg-amber-500/10 px-1.5 py-px text-[9px] font-semibold text-amber-400",children:o("settings.providerPriority.notOnMachine")})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:h?`${h.label} · ${h.statusLabel}`:"Kept in order; skipped at launch until detected here."})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move up",disabled:r||S===0,title:"Move up",onClick:()=>n(Fc(p,g,"up")),children:s.jsx(Bc,{direction:"up"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move down",disabled:r||S===p.length-1,title:"Move down",onClick:()=>n(Fc(p,g,"down")),children:s.jsx(Bc,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:r,onClick:()=>n(GS(p,g)),children:o("settings.providerPriority.remove")})]})]},g)})}),s.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[s.jsxs("label",{className:"flex-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:o("settings.providerPriority.addCliLabel")}),s.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:i,onChange:g=>c(g.target.value),disabled:r||m.length===0,children:[s.jsx("option",{value:"",children:m.length?"Select provider…":"No additional detected CLI providers"}),m.map(g=>s.jsxs("option",{value:g.type,children:[g.label," (",g.type,")"]},g.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:r||!i,onClick:f,children:o("settings.providerPriority.addProvider")}),a]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Launches use this order, top to bottom.",d>0?` ${d} provider${d===1?"":"s"} not detected here — kept in order, skipped until available.`:""]})]})}function zS(e){const t=e.split(":");return t.length>=3&&(t[1]==="ide"||t[1]==="cli"||t[1]==="acp")?{daemonId:t[0],targetSessionId:t.slice(2).join(":")||void 0}:{daemonId:e}}function Vp(e,t){const n=zS(e);return{daemonId:n.daemonId,payload:{...t,...n.targetSessionId&&!t.targetSessionId?{targetSessionId:n.targetSessionId}:{}}}}const Yp=[{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:"🏄"}],Jp=[{id:"antigravity-cli",name:"Antigravity CLI",icon:"🪐"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"hermes-cli",name:"Hermes",icon:"⚕️"},{id:"kimi",name:"Kimi",icon:"🌙"},{id:"opencode",name:"OpenCode CLI",icon:"◆"}],Qp=[{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:"🟠"}],KS=Yp,VS=Jp,YS=Qp;function JS({icon:e,title:t,subtitle:n,badge:r,actions:a,className:o}){return s.jsxs("div",{className:Wt("dashboard-header",o),children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"header-title flex items-center gap-2",children:[s.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,r&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[r.count!==void 0?r.count:""," ",r.text]})]}),n&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:n})]}),a&&s.jsx("div",{className:"flex gap-2",children:a})]})}function Lr({icon:e,title:t,subtitle:n,badge:r,actions:a,widthClassName:o="max-w-6xl",contentClassName:i,children:c}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(JS,{icon:e,title:t,subtitle:n,badge:r,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Wt("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const Ci="adhdev:themechange";function QS(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function jn(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Nn(e){return e==="system"?QS():e}function Xp(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function ia(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(Ci,{detail:{preference:e,theme:t}}))}function XS(){const e=jn(),t=Nn(e);Xp(t),ia(e,t)}function qs(){const[e,t]=l.useState(jn),[n,r]=l.useState(()=>Nn(jn()));l.useEffect(()=>{Xp(n)},[n]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=u=>{if(e==="system"){const p=u.matches?"light":"dark";r(p),ia("system",p)}};return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[e]),l.useEffect(()=>{const i=u=>{const p=u.detail||{},d=p.preference,m=p.theme;t(d==="dark"||d==="light"||d==="system"?d:jn()),r(m==="dark"||m==="light"?m:Nn(jn()))},c=u=>{if(u.key!=="theme")return;const p=jn(),d=Nn(p);t(p),r(d)};return window.addEventListener(Ci,i),window.addEventListener("storage",c),()=>{window.removeEventListener(Ci,i),window.removeEventListener("storage",c)}},[]);const a=l.useCallback(i=>{const c=Nn(i);t(i),r(c);try{localStorage.setItem("theme",i)}catch{}ia(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",u=Nn(c);r(u);try{localStorage.setItem("theme",c)}catch{}return ia(c,u),c})},[]);return{theme:n,preference:e,setPreference:a,cycleTheme:o,isDark:n==="dark"}}const Wc={dark:"Dark",light:"Light",system:"System"};function ZS({collapsed:e}){const{preference:t,cycleTheme:n}=qs(),r=t==="dark"?s.jsx(ib,{size:16}):t==="light"?s.jsx(ob,{size:16}):s.jsx(lb,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:n,title:`Theme: ${Wc[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:r}),!e&&s.jsx("span",{className:"text-xs",children:Wc[t]})]})}const ji="adhdev:langchange";function eC(){const e=Ct.language;return Tn(e)?e:Hu()}function tC(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(ji,{detail:{language:e}}))}function sC(){const[e,t]=l.useState(eC);l.useEffect(()=>{const r=i=>{Tn(i)&&t(i)},a=i=>{const c=i.detail||{};Tn(c.language)&&t(c.language)},o=i=>{if(i.key!==di)return;const c=i.newValue;Tn(c)&&c!==Ct.language&&(Ct.changeLanguage(c),ui(c))};return Ct.on("languageChanged",r),window.addEventListener(ji,a),window.addEventListener("storage",o),()=>{Ct.off("languageChanged",r),window.removeEventListener(ji,a),window.removeEventListener("storage",o)}},[]);const n=l.useCallback(r=>{if(Tn(r)){t(r);try{localStorage.setItem(di,r)}catch{}Ct.changeLanguage(r),ui(r),tC(r)}},[]);return{language:e,setLanguage:n}}function nC({trigger:e,viewport:t,menu:n,variant:r,gap:a=6,margin:o=8}){const i=e.top-o,c=t.height-e.bottom-o,u=r==="sidebar";let p=u;u&&i<n.height&&c>i&&(p=!1),!u&&c<n.height&&i>c&&(p=!0);const d=p?i:c,m=Math.max(80,Math.min(n.height,d));let f;p?f=e.top-a-m:f=e.bottom+a,f=Oc(f,o,Math.max(o,t.height-m-o));const g=Oc(e.left,o,Math.max(o,t.width-n.width-o));return{top:f,left:g,maxHeight:m}}function Oc(e,t,n){return Math.min(Math.max(e,t),n)}function rC({open:e}){return s.jsx("svg",{width:12,height:12,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:`lang-switch-caret${e?" open":""}`,children:s.jsx("polyline",{points:"6 9 12 15 18 9"})})}function aC({collapsed:e,variant:t="sidebar"}){const{language:n,setLanguage:r}=sC(),{t:a}=Ne("common"),[o,i]=l.useState(!1),[c,u]=l.useState(0),p=l.useRef(null),d=l.useRef(null),m=l.useRef(null),f=l.useId(),[g,S]=l.useState(null),h=l.useCallback(()=>{const P=d.current;if(!P)return;const D=P.getBoundingClientRect(),_=m.current,W=Math.max((_==null?void 0:_.offsetWidth)??0,168),$=(_==null?void 0:_.scrollHeight)??Qs.length*36+12;S(nC({trigger:{top:D.top,left:D.left,right:D.right,bottom:D.bottom,width:D.width,height:D.height},viewport:{width:window.innerWidth,height:window.innerHeight},menu:{width:W,height:$},variant:t}))},[t]),x=Math.max(0,Qs.findIndex(P=>P.code===n)),y=Qs[x]??Qs[0],b=a("language.label",{defaultValue:"Language"}),C=a("language.select",{defaultValue:"Select language"}),j=P=>`${f}-opt-${P}`,k=l.useCallback(()=>{u(x),i(!0)},[x]),v=l.useCallback((P=!0)=>{var D;i(!1),P&&((D=d.current)==null||D.focus())},[]),N=l.useCallback(P=>{const D=Qs[P];D&&r(D.code),v()},[r,v]);l.useEffect(()=>{if(!o)return;const P=W=>{var $,E;return!!(($=p.current)!=null&&$.contains(W)||(E=m.current)!=null&&E.contains(W))},D=W=>{P(W.target)||i(!1)},_=W=>{P(W.target)||i(!1)};return document.addEventListener("pointerdown",D,!0),document.addEventListener("focusin",_,!0),()=>{document.removeEventListener("pointerdown",D,!0),document.removeEventListener("focusin",_,!0)}},[o]),l.useLayoutEffect(()=>{if(!o){S(null);return}h();const P=()=>h();return window.addEventListener("resize",P),window.addEventListener("scroll",P,!0),()=>{window.removeEventListener("resize",P),window.removeEventListener("scroll",P,!0)}},[o,h]),l.useEffect(()=>{var P;o&&g&&((P=m.current)==null||P.focus())},[o,g]);const w=P=>{const D=Qs.length-1;switch(P.key){case"ArrowDown":P.preventDefault(),u(_=>_>=D?0:_+1);break;case"ArrowUp":P.preventDefault(),u(_=>_<=0?D:_-1);break;case"Home":P.preventDefault(),u(0);break;case"End":P.preventDefault(),u(D);break;case"Enter":case" ":P.preventDefault(),N(c);break;case"Escape":P.preventDefault(),v();break;case"Tab":i(!1);break}},A=P=>{o||(P.key==="ArrowDown"||P.key==="ArrowUp"||P.key==="Enter"||P.key===" ")&&(P.preventDefault(),k())},T=t==="landing"?"lang-switch-trigger lang-switch-trigger--landing":`lang-switch-trigger lang-switch-trigger--sidebar nav-item cursor-pointer${e?" justify-center py-2.5 px-0":""}`,I=t==="landing"||!e;return s.jsxs("div",{ref:p,className:"lang-switch",children:[s.jsxs("button",{ref:d,type:"button",className:T,"aria-haspopup":"listbox","aria-expanded":o,"aria-label":`${b}: ${y.label}`,title:`${b}: ${y.label}`,onClick:()=>o?v(!1):k(),onKeyDown:A,children:[s.jsx("span",{className:"nav-icon lang-switch-icon",children:s.jsx(gb,{size:16})}),I&&s.jsx("span",{className:"lang-switch-label text-xs",children:y.label}),I&&s.jsx(rC,{open:o})]}),o&&typeof document<"u"&&un.createPortal(s.jsx("ul",{ref:m,role:"listbox",tabIndex:-1,"aria-label":C,"aria-activedescendant":j(c),className:`lang-switch-menu lang-switch-menu--${t}`,style:{position:"fixed",top:(g==null?void 0:g.top)??0,left:(g==null?void 0:g.left)??0,maxHeight:g==null?void 0:g.maxHeight,overflowY:"auto",visibility:g?"visible":"hidden"},onKeyDown:w,children:Qs.map((P,D)=>{const _=P.code===y.code,W=D===c;return s.jsxs("li",{id:j(D),role:"option","aria-selected":_,className:`lang-switch-option${W?" is-active":""}${_?" is-selected":""}`,onMouseEnter:()=>u(D),onClick:()=>N(D),children:[s.jsx("span",{className:"lang-switch-check","aria-hidden":"true",children:_?s.jsx(xu,{size:14}):null}),s.jsx("span",{className:"lang-switch-option-label",children:P.label})]},P.code)})}),document.body)]})}const oC=[],iC=[];function So(e,t){return e?typeof e=="function"?e(t):e:null}const lC=l.memo(function({renderState:t,brand:n,navItems:r,sidebarSections:a,footerItems:o,footerInfo:i,footerActions:c,closeMobileMenu:u}){const{t:p}=Ne("common"),{collapsed:d,mobileMenuOpen:m}=t,f=S=>`nav-item${S.active?" active":""} cursor-pointer ${d?"justify-center py-2.5 px-0":""}${S.className?` ${S.className}`:""}`,g=S=>s.jsxs("div",{className:f(S),id:`nav-${S.id}`,onClick:()=>{S.onSelect(),u()},title:d?S.title??(typeof S.label=="string"?S.label:void 0):S.title,children:[s.jsx("span",{className:"nav-icon",children:S.icon}),!d&&S.label]},S.id);return s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${d?"justify-center gap-0":""}`,children:So(n,t)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":p("app.closeMenu"),onClick:u,children:s.jsx(Mt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(g)}),a.map(S=>s.jsxs("div",{className:S.className??"border-t border-border-subtle pt-2 mt-2",children:[!d&&S.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:S.title}):null,S.items.map(g)]},S.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[o.map(g),So(i,t),s.jsx(ZS,{collapsed:d}),s.jsx(aC,{collapsed:d}),So(c,t)]})]})});function cC({children:e,brand:t,navItems:n,sidebarSections:r=oC,footerItems:a=iC,footerInfo:o,footerActions:i,preMainContent:c,collapsedStorageKey:u="sidebar-collapsed"}){const{t:p}=Ne("common"),[d,m]=l.useState(!1),[f,g]=l.useState(()=>{try{return localStorage.getItem(u)==="1"}catch{return!1}}),S=l.useCallback(()=>m(!0),[]),h=l.useCallback(()=>m(!1),[]),x=l.useCallback(()=>{g(b=>{const C=!b;try{localStorage.setItem(u,C?"1":"0")}catch{}return C})},[u]),y=l.useMemo(()=>({collapsed:f,mobileMenuOpen:d,openMobileMenu:S,closeMobileMenu:h,toggleCollapsed:x}),[f,d,S,h,x]);return s.jsxs("div",{className:`app-layout${d?" mobile-menu-open":""}${f?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":p("app.openMenu"),onClick:S,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),d&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":p("app.closeMenu"),onClick:h,onKeyDown:b=>b.key==="Escape"&&h()}),s.jsx(lC,{renderState:y,brand:t,navItems:n,sidebarSections:r,footerItems:a,footerInfo:o,footerActions:i,closeMobileMenu:h}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function gt({title:e,icon:t,description:n,accentColor:r,className:a,collapsible:o,defaultOpen:i=!0,badge:c,children:u}){const[p,d]=l.useState(i),m=o?p:!0,f=(e||n)&&s.jsxs("div",{className:Wt("flex items-start justify-between gap-3",m&&"mb-4"),children:[s.jsxs("div",{className:"min-w-0",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary flex items-center gap-1.5",children:[t&&s.jsx("span",{children:t}),s.jsx("span",{children:e}),c]}),n&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:n})]}),o&&s.jsx("span",{className:Wt("mt-0.5 shrink-0 text-text-muted transition-transform select-none",m?"rotate-90":"rotate-0"),"aria-hidden":!0,children:"▸"})]});return s.jsxs("div",{className:Wt("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",r&&"border-l-[3px]",a),style:r?{borderLeftColor:r}:void 0,children:[o&&f?s.jsx("button",{type:"button",className:"w-full bg-transparent border-none p-0 text-left cursor-pointer",onClick:()=>d(g=>!g),"aria-expanded":m,children:f}):f,m&&u]})}function Ya({icon:e,title:t,description:n,action:r,className:a}){return s.jsxs("div",{className:Wt("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[s.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),s.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:n}),r]})}const dC={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"},uC={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Lt({variant:e,children:t,onDismiss:n,className:r}){return s.jsxs("div",{className:Wt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",dC[e],r),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:uC[e]}),s.jsx("span",{children:t})]}),n&&s.jsx("button",{onClick:n,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function At({label:e,hint:t,children:n,className:r}){return s.jsxs("div",{className:Wt("mb-5",r),children:[s.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),n,t&&s.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function hs(e){const{className:t,...n}=e;return s.jsx("input",{...n,className:Wt("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none","focus:border-accent transition-colors",t)})}const pC={primary:"btn-primary",secondary:"btn-secondary",warning:"btn-warning",danger:"btn-danger",ghost:"btn-ghost"},Is=l.forwardRef(function({variant:t="secondary",size:n="md",type:r,className:a,...o},i){return s.jsx("button",{ref:i,type:r??"button",className:Wt("btn",pC[t],n==="sm"&&"btn-sm",a),...o})}),mC=l.forwardRef(function({options:t,children:n,className:r,...a},o){return s.jsx("select",{ref:o,className:Wt("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none cursor-pointer","focus:border-accent transition-colors",r),...a,children:n??(t==null?void 0:t.map(i=>s.jsx("option",{value:i.value,disabled:i.disabled,children:i.label},i.value)))})}),hC={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"},fC={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function bC({status:e,label:t,className:n}){const r=t||e;return s.jsxs("span",{className:Wt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",hC[e],n),children:[s.jsx("span",{className:Wt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",fC[e])}),r]})}function tn({label:e,description:t,checked:n,disabled:r,onChange:a,extra:o}){return s.jsxs("div",{className:`flex justify-between items-center ${r?"opacity-60":""}`,children:[s.jsxs("div",{className:"pr-4",children:[s.jsx("div",{className:"font-medium text-sm",children:e}),s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[o,s.jsxs("button",{type:"button",role:"switch","aria-checked":n,"aria-disabled":r,disabled:r,onClick:()=>a(!n),className:`relative inline-flex items-center ${r?"cursor-not-allowed":"cursor-pointer"}`,children:[s.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:n?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),s.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${n?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function gC({onPrefChange:e}){const{t}=Ne("common"),[n,r]=vw(),[a,o]=l.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);l.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){o("unsupported");return}o(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,u)=>{r({[c]:u}),e==null||e(c,u)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(tn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Un,{size:15})," ",t("notifications.masterToggleLabel")]}),description:t("notifications.masterToggleDesc"),checked:n.globalEnabled,onChange:c=>i("globalEnabled",c)}),n.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),n.globalEnabled&&s.jsx(tn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(xs,{size:15})," ",t("notifications.browserNotificationsLabel")]}),description:t("notifications.browserNotificationsDesc"),checked:n.browserNotifications,onChange:c=>i("browserNotifications",c)}),n.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:t("notifications.standaloneBackgroundInfo")}),a==="default"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-status-warning",children:[s.jsx("span",{children:t("notifications.standalonePermissionDefault")}),s.jsx("button",{onClick:()=>{Ku().then(o)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:t("notifications.allowNotifications")})]}),a==="denied"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:t("notifications.permissionDenied")}),a==="unsupported"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:t("notifications.standalonePermissionUnsupported")})]}),n.globalEnabled&&n.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(tn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Su,{size:15})," ",t("notifications.completionAlertsLabel")]}),description:t("notifications.completionAlertsDesc"),checked:n.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(tn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(cb,{size:15})," ",t("notifications.approvalAlertsLabel")]}),description:t("notifications.approvalAlertsDesc"),checked:n.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(tn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(wr,{size:15})," ",t("notifications.connectionAlertsLabel")]}),description:t("notifications.connectionAlertsDesc"),checked:n.disconnectAlert,onChange:c=>i("disconnectAlert",c)})]}),!n.globalEnabled&&s.jsx("p",{className:"text-[11px] text-text-muted italic",children:t("notifications.allDisabled")})]})}function Da(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/);if(!t)return null;const n=t[4]??null;let r=null;if(n){const a=n.match(/(?:^|\.)(\d+)$/);r=a?Number(a[1]):null}return{base:[Number(t[1]),Number(t[2]),Number(t[3])],prereleaseNumber:r,isPrerelease:n!==null}}function Uc(e){var t;return((t=Da(e))==null?void 0:t.base)??null}function Zp(e,t){const n=Da(e),r=Da(t);if(!n||!r)return e!==t;for(let a=0;a<3;a+=1){if(n.base[a]<r.base[a])return!0;if(n.base[a]>r.base[a])return!1}return n.isPrerelease&&r.isPrerelease?n.prereleaseNumber===null||r.prereleaseNumber===null?!1:n.prereleaseNumber<r.prereleaseNumber:!1}function Ja(e,t){const n=e.version||null;return!n||!t||e.versionMismatch===!0&&!Da(t)?!1:Zp(n,t)}function br(e,t){if(e.versionUpdateRequired===!0)return!0;const n=e.version||null;if(!n||!t||!Zp(n,t))return!1;const r=Uc(n),a=Uc(t);return!r||!a?!1:r[0]!==a[0]||r[1]!==a[1]}function Pn(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="stable"||t==="latest"?"stable":t==="preview"||t==="next"?"preview":null}function xC(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="latest"||t==="stable"?"latest":t==="next"||t==="preview"?"next":null}function cr(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function dl(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},n=Pn(t.channel)||Pn(e.updateChannel)||Pn(e.releaseChannel)||void 0,r=xC(t.npmTag)||(n==="preview"?"next":n==="stable"?"latest":void 0),a=cr(t.targetVersion)||cr(e.serverVersion)||void 0,o=cr(t.minVersion)||void 0,i=cr(t.updateCommand)||(n?`adhdev update --channel ${n}`:void 0);return{...n?{channel:n}:{},...r?{npmTag:r}:{},...a?{targetVersion:a}:{},...o?{minVersion:o}:{},...i?{updateCommand:i}:{}}}function $s(e,t=null){return dl(e).targetVersion||t}function vC(e){return dl(e).channel||null}function Qa(e){if(!e)return null;const t=dl(e);return t.channel?{channel:t.channel,...t.npmTag?{npmTag:t.npmTag}:{},...t.targetVersion?{targetVersion:t.targetVersion}:{},updatePolicy:t}:null}function yC(e){return Pn(e.updateChannel)||Pn(e.releaseChannel)}function em(e,t={}){const n=e.updatePolicy&&typeof e.updatePolicy=="object"?Pn(e.updatePolicy.channel):null,r=yC(e);if(n&&r&&n!==r)return`Switch to ${n}`;const a=cr(t.targetVersion);return a?`Update to v${a}`:t.fallback||(t.required?"Update now":"Upgrade")}const tm="Cannot update: node update policy unavailable; refresh and try again";async function wC(e,t,n){var a,o,i,c,u,p;const r=Qa(n);if(!r)return{state:"error",message:tm};try{const d=await e(t,"daemon_upgrade",r);return(a=d==null?void 0:d.result)!=null&&a.alreadyLatest?{state:"done",message:`Already on v${((o=d==null?void 0:d.result)==null?void 0:o.version)||"latest"}.`}:(i=d==null?void 0:d.result)!=null&&i.upgraded||(c=d==null?void 0:d.result)!=null&&c.success?{state:"done",message:`Upgrade to v${((u=d==null?void 0:d.result)==null?void 0:u.version)||"latest"} started. Daemon is restarting…`}:{state:"error",message:((p=d==null?void 0:d.result)==null?void 0:p.error)||"Upgrade failed"}}catch(d){return{state:"error",message:d instanceof Error?d.message:"Upgrade failed"}}}function kC(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Co(e,t){return e instanceof Error?e.message:t}function SC({ides:e,emptyMessage:t,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:a}){const{t:o}=Ne("common"),i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?s.jsx(Ya,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:o("machine.connectedMachines.noMachines"),description:t||o("machine.connectedMachines.defaultDescription")}):s.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>s.jsx(jC,{ide:c,allIdes:e,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:a},c.id))})}function Gc({title:e,message:t,confirmLabel:n,confirmColor:r,onConfirm:a,onCancel:o}){const{t:i}=Ne("common"),c=r==="red"?"bg-status-error/20 text-status-error border-status-error/40 hover:bg-status-error/30":"";return un.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:"var(--z-modal)"},onClick:o,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:u=>u.stopPropagation(),children:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx("button",{onClick:o,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:i("common.cancel")}),s.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:r==="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:n})]})]})}),document.body)}function CC(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),r=[...KS,...VS,...YS].find(a=>a.id===t||t.includes(a.id)||a.id.includes(t));return r?{icon:r.icon,name:r.name}:{icon:"📝",name:e}}function jC({ide:e,allIdes:t,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:a}){var $,E;const{t:o}=Ne("common"),[i,c]=l.useState("idle"),[u,p]=l.useState(""),[d,m]=l.useState(null),[f,g]=l.useState("idle"),[S,h]=l.useState(""),x=e.version||null,y=(($=e.machine)==null?void 0:$.platform)||((E=e.system)==null?void 0:E.platform)||"",b=is(e,{fallbackId:e.id}),C=y==="win32"?"🪟":y==="darwin"?"🍎":"🐧",j=t.filter(B=>B.daemonId===e.id&&B.transport==="cdp-page"),k=t.filter(B=>B.daemonId===e.id&&B.transport==="pty"),v=t.filter(B=>B.daemonId===e.id&&B.transport==="acp"),N=e.p2p,w=async()=>{if(!n)return;const B=Qa(e);if(!B){c("error"),p(tm);return}c("upgrading"),p(o("machine.connectedMachines.startingUpgrade"));try{const L=kC(await n(e.id,"daemon_upgrade",B));L.alreadyLatest?(c("done"),p(`Already on v${L.version||"latest"}.`)):L.upgraded||L.success?(c("done"),p(`Upgrade to v${L.version||"latest"} started. Daemon is restarting...`)):(c("error"),p(L.error||"Upgrade failed"))}catch(L){c("error"),p(Co(L,"Connection lost during upgrade"))}},A=async()=>{if(m(null),!!r){g("loading");try{await r(e.id),g("done"),h(o("machine.connectedMachines.machineDisconnected"))}catch(B){g("error"),h(Co(B,o("machine.connectedMachines.failedToDisconnect")))}}},T=async()=>{if(m(null),!!a){g("loading");try{await a(e.id),g("done"),h(o("machine.connectedMachines.tokenRevoked"))}catch(B){g("error"),h(Co(B,o("machine.connectedMachines.failedToRevokeToken")))}}},I="1.0.29",P=$s(e,I),D=Ja(e,P),_=br(e,P),W=j.length+k.length+v.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:C}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:b}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),x&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${D?"":"bg-bg-secondary"}`,style:D?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",x,!D&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[n&&D&&s.jsx("button",{onClick:w,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${I}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," ",o("machine.connectedMachines.upgrading")]}):i==="done"?o("machine.connectedMachines.updated"):_?o("machine.connectedMachines.updateNow"):o("machine.connectedMachines.updateTo",{version:I})}),r&&s.jsx("button",{onClick:()=>m("disconnect"),disabled:f==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:o("machine.connectedMachines.disconnect")}),a&&s.jsx("button",{onClick:()=>m("revoke"),disabled:f==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:o("machine.connectedMachines.remove")}),s.jsx(bC,{status:e.status==="online"?"online":"error"})]})]}),s.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[N&&s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${N.state==="connected"?"bg-status-online":"bg-text-muted/30"} ${N.state==="connecting"||N.state==="new"?"animate-pulse":""}`,style:N.state==="connecting"||N.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",N.state==="connected"?"connected":N.state==="connecting"||N.state==="new"?o("machine.connectedMachines.connecting"):N.state||"off"]}),N.peers!==void 0&&N.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",N.peers," peer",N.peers!==1?"s":"",")"]})]}),N&&W>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),W>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[j.map(B=>{const L=CC(B.type),R=B.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:L.icon}),s.jsx("span",{children:L.name}),R!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${R?"bg-status-online":"animate-pulse"}`,style:R?void 0:{background:"var(--status-warning)"},title:o(R?"machine.connectedMachines.cdpConnected":"machine.connectedMachines.cdpConnecting")})]},B.id)}),k.map(B=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"⌨️"}),s.jsx("span",{children:B.cliName||"CLI"})]},B.id)),v.map(B=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"🔗"}),s.jsx("span",{children:B.cliName||"ACP"})]},B.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:o("machine.connectedMachines.noIdesConnected")})]}),(u||S)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||f==="error"?"text-status-error":i==="done"||f==="done"?"text-status-online":"text-text-muted"}`,children:S||u})]}),d==="disconnect"&&s.jsx(Gc,{title:o("machine.connectedMachines.disconnectTitle"),message:`Disconnect "${b}" from ADHDev?
58
+ `).includes(a)))}function jS(e,t="recent"){const n=e.slice();return n.sort((r,a)=>{if(t==="oldest")return(Number(r.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(t==="messages"){const o=(Number(a.messageCount)||0)-(Number(r.messageCount)||0);if(o!==0)return o}return(Number(a.lastMessageAt)||0)-(Number(r.lastMessageAt)||0)}),n}function $p(e,t={}){return jS(CS(e,t),t.sortMode||"recent")}function Si(e,t){return typeof e=="function"?e(t??!1?"launch.resumeSavedHistory":"launch.startFresh"):e?"Resume saved history":"Start fresh"}function Hp(e,t){return typeof e=="function"?e(t??!1?"launch.resumingSavedHistory":"launch.startingFresh"):e?"Resuming saved history…":"Starting fresh…"}function NS(e){return e?e("launch.startFresh"):"Start fresh"}function AS(e){return e?e("launch.hostedRuntimeRecoveryDescription"):"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function TS(e){return e?e("launch.openSavedHistory"):"Open saved history"}function MS(e){return e?e("launch.savedHistoryTitle"):"Saved History"}function ll(e){return e?e("launch.savedHistoryHelper"):"Use saved history when you want continuity in the same provider conversation."}function DS(e){return e?e("launch.savedHistoryEmpty"):"No saved history found yet."}function IS(e){return e?e("launch.refreshSavedHistory"):"Refresh saved history"}function PS(e){return e?e("launch.refreshingSavedHistory"):"Refreshing saved history…"}function ja(e,t,n){if(typeof e=="function"){const o=t,i=n;return o==="start-fresh"?e("launch.startFreshWith",{label:i}):e("launch.restart",{label:i})}const r=e,a=t;return r==="start-fresh"?`Start fresh with ${a}?`:`Restart ${a}?`}function Na(e,t){if(typeof e=="function"){const r=t;return e(r==="start-fresh"?"launch.startFreshReview":r==="restart-ide"?"launch.restartIdeReview":"launch.restartStoppedReview")}const n=e;return n==="start-fresh"?"Review the provider and target folder before starting fresh.":n==="restart-ide"?"Review or change the target workspace before restarting this IDE.":"Review or change the target workspace before restarting this stopped session."}function Aa(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartFresh":"launch.confirmRestart"):e==="start-fresh"?"Start fresh":"Restart"}function Ta(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartingFresh":"launch.confirmRestarting"):e==="start-fresh"?"Starting fresh…":"Restarting…"}function Fp(e,t){return typeof e=="function"?e("launch.resumeWith",{label:t}):`Resume saved history with ${e}?`}function Bp(e){return e?e("launch.resumeReview"):"Review or change the target workspace before resuming saved history."}function LS(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 Wp({activeConv:e,ides:t,isCreatingChat:n,isRefreshingHistory:r,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:u,onSavedHistoryFiltersChange:p,onClose:d,onNewChat:m,onSwitchSession:f,onRefreshHistory:g,onResumeSavedSession:S}){var P;const{t:h}=Ne("common"),x=t.find(D=>D.id===e.routeId),y=(x==null?void 0:x.chats)||[],b=(P=x==null?void 0:x.activeChat)==null?void 0:P.id,C=ht(e)&&!pt(e),[j,k]=l.useState(()=>qt()),v=c||j,N=String(u||"").trim(),w=D=>{if(p){p(D);return}k(D)},A=l.useMemo(()=>a.map(D=>{const _=String(D.workspace||"").trim();return D.canResume||_||!N?D:{...D,workspace:N,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[N,a]),T=l.useMemo(()=>$p(A,{textQuery:v.textQuery,workspaceQuery:v.workspaceQuery,modelQuery:v.modelQuery,resumableOnly:v.resumableOnly,sortMode:v.sortMode}),[A,v.modelQuery,v.resumableOnly,v.sortMode,v.textQuery,v.workspaceQuery]),I=s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:d,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:C?MS(h):h("historyModal.chatHistory")}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Xk(e)}),C&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:ll(h)})]}),s.jsx("button",{onClick:d,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(Mt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!C&&s.jsx("button",{onClick:m,disabled:n,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:h(n?"historyModal.creating":"historyModal.startNewChat")}),C?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:v.textQuery,onChange:D=>w({...v,textQuery:D.target.value}),placeholder:h("historyModal.searchPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:v.workspaceQuery,onChange:D=>w({...v,workspaceQuery:D.target.value}),placeholder:h("historyModal.filterWorkspace"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:v.modelQuery,onChange:D=>w({...v,modelQuery:D.target.value}),placeholder:h("historyModal.filterModel"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:v.sortMode,onChange:D=>w({...v,sortMode:D.target.value}),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary",children:[s.jsx("option",{value:"recent",children:h("historyModal.sortRecent")}),s.jsx("option",{value:"oldest",children:h("historyModal.sortOldest")}),s.jsx("option",{value:"messages",children:h("historyModal.sortMessages")})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:v.resumableOnly,onChange:D=>w({...v,resumableOnly:D.target.checked})}),h("historyModal.resumeReadyOnly")]})]}),T.map(D=>{const _=e.providerSessionId===D.providerSessionId,W=_||!D.canResume||!!i,$=D.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{W||!S||S(D)},disabled:W,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${_?"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:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${_?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:D.title||h("historyModal.untitledSession")}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:D.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:LS(D.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:D.preview||h("historyModal.noSavedPreview")}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[D.workspace||h("historyModal.workspaceUnknown"),$?h("historyModal.selectedWorkspaceSuffix"):"",mn(D.summaryMetadata)?` · ${mn(D.summaryMetadata)}`:"",D.messageCount>0?` · ${h("historyModal.msgCount",{count:D.messageCount})}`:""]}),s.jsx("div",{className:"shrink-0",children:_?h("historyModal.statusActive"):D.canResume?$?h("historyModal.statusResumeSelectedWorkspace"):i===D.providerSessionId?h("historyModal.statusResuming"):h("historyModal.statusResume"):h("historyModal.statusMissingWorkspace")})]})]},D.id)})]}):y.map(D=>s.jsxs("div",{onClick:()=>{f(e.routeId,D.id),d()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${b===D.id?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"}`,children:[s.jsx("div",{className:`font-bold text-sm mb-1 ${b===D.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:D.title||h("historyModal.untitledSession")}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[D.id.substring(0,12),"..."]}),b===D.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:h("historyModal.statusActive")})]})]},D.id)),(C&&!o&&T.length===0||!C&&y.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(ab,{size:32})}),s.jsx("div",{className:"text-[13px]",children:C?a.length>0?h("historyModal.noMatchingHistory"):DS(h):h("historyModal.noRecentChats")})]}),C&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:PS(h)})})]}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:s.jsx("button",{onClick:g,disabled:r||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:r||o?h("historyModal.refreshing"):s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Fa,{size:13})," ",C?IS(h):h("historyModal.refreshHistory")]})})})]})]});return typeof document>"u"?I:un.createPortal(I,document.body)}const Hc={success:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",labelKey:"toast.label.success"},warning:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",labelKey:"toast.label.warning"},info:{accent:"var(--accent-primary)",chipBg:"color-mix(in srgb, var(--accent-primary) 14%, transparent)",chipText:"var(--accent-primary-light)",labelKey:"toast.label.info"}};function Op({toasts:e,onDismiss:t,onClickToast:n}){const{t:r}=Ne();return s.jsx("div",{className:"fixed right-4 top-[calc(env(safe-area-inset-top,0px)+64px)] z-[var(--z-toast)] flex flex-col gap-2 pointer-events-none sm:top-[calc(env(safe-area-inset-top,0px)+16px)]",children:e.map(a=>{const o=Hc[a.type]||Hc.info;return s.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var i;(i=a.actions)!=null&&i.length||n&&n(a)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${o.accent}, color-mix(in srgb, ${o.accent} 55%, transparent))`}}),s.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),t(a.id)},"aria-label":r("toast.dismiss"),children:s.jsx(Mt,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:o.chipBg,color:o.chipText,border:`1px solid color-mix(in srgb, ${o.accent} 22%, transparent)`},children:r(o.labelKey)})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:a.message}),a.actions&&a.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:a.actions.map((i,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:u=>{u.stopPropagation(),i.onClick(),t(a.id)},children:i.label},c))})]})]},a.id)})})}const RS=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function ES(e){const t=e.workspace||"";if(!t)return"";const n=t.split(/[/\\]/).filter(Boolean);return n.length>0?n[n.length-1]:t}function _S(e,t){return Up(e)||t}function Up(e){var a,o,i;const t=(o=(a=e.summaryMetadata)==null?void 0:a.items)==null?void 0:o.find(c=>(c==null?void 0:c.id)==="model"),n=((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim();if(n)return n;const r=(i=e.controlValues)==null?void 0:i.model;return typeof r=="string"&&r.trim()?r.trim():""}function $S(e){return Up(e)||void 0}function HS(e){return e.sessionId||e.instanceId||e.agentType}function Gp(e=[]){const t={};for(const n of e)n.type==="adhdev-daemon"&&(t[n.id]=is(n,{fallbackId:n.id}));return t}function qp(e,t={}){var r;const n=e.daemonId||((r=e.id)==null?void 0:r.split(":")[0])||e.id;return{machineName:tw(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[n]||t.defaultConnectionState||"new":t.defaultConnectionState}}function cl(e,t={}){return FS(e,qp(e,t))}function FS(e,t={}){var f,g,S,h,x,y,b,C,j;const n=[],r=t.machineName,a=t.connectionState,o=ES(e),i=e.workspace||"",c=iw(e.type,{agentName:e.cliName}),u=ht(e)||pt(e)?c:Bt(e.type),p=_S(e,u),d=Array.isArray(e.childSessions)?e.childSessions.map(k=>{var v,N,w;return{sessionId:k.id,instanceId:k.id,providerSessionId:k.providerSessionId,activeChatId:(v=k.activeChat)==null?void 0:v.id,transport:k.transport,sessionCapabilities:k.capabilities,agentType:k.providerType,agentName:k.providerName||Bt(k.providerType),model:$S(k),status:k.status,title:k.title,lastMessagePreview:k.lastMessagePreview,lastMessageRole:k.lastMessageRole,lastMessageAt:k.lastMessageAt,lastMessageHash:k.lastMessageHash,messages:((N=k.activeChat)==null?void 0:N.messages)||[],activeModal:((w=k.activeChat)==null?void 0:w.activeModal)||void 0,unread:k.unread,lastSeenAt:k.lastSeenAt,lastUpdated:k.lastUpdated,inboxBucket:k.inboxBucket,completionMarker:k.completionMarker,surfaceHidden:k.surfaceHidden,muted:k.muted,git:k.git,settings:k.settings,coordinator:k.coordinator,messageInput:k.messageInput}}):[],m=RS(e);if(m){const k=e.sessionId||e.instanceId,v=(f=e.settings)==null?void 0:f.meshCoordinatorFor,N=((g=e.settings)==null?void 0:g.meshNodeFor)||!((S=e.settings)!=null&&S.meshCoordinatorFor)&&((h=e.settings)==null?void 0:h.launchedByCoordinator),w=v?" (Coordinator)":N?" (Mesh Node)":"",A=c+w,T=(x=e.activeChat)==null?void 0:x.activeModal,I=T&&Array.isArray(T.buttons)&&T.buttons.length>0,P=lw(e.activeChat,[{status:e.status,activeModal:(y=e.activeChat)==null?void 0:y.activeModal}],e.agents||[]),D=e.activeChat||{title:"",messages:[]};let _=D.title&&String(D.title).trim()?String(D.title).trim():"";const W=(b=e.activeChat)==null?void 0:b.id,$=e.chats;if(W&&Array.isArray($)&&$.length>0){const J=$.find(V=>V.id===W||V.id&&String(V.id)===String(W));J!=null&&J.title&&String(J.title).trim()&&(_=String(J.title).trim())}const E=(ht(e)||pt(e),e.type),B=(ht(e)||pt(e))&&ic(_,A,E)?"":_,L=D.messages||[],R=typeof W=="string"?W.trim():"",M=(ht(e)||pt(e))&&R===String(e.type||"").trim(),F=R&&!M?R:e.providerSessionId,K=e.coordinator||(typeof((C=e.settings)==null?void 0:C.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:k,providerSessionId:e.providerSessionId,historySessionId:F,nativeSessionId:k,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:ht(e)&&e.mode||"chat",agentName:A,agentType:E,status:P,title:B,messages:L,resume:e.resume,hostIdeType:!ht(e)&&!pt(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||B||(ht(e)?e.mode==="chat"?A:`Terminal${w}`:A),displaySecondary:p,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:I?T.buttons:void 0,modalMessage:I?T.message:void 0,streamSource:"native",tabKey:ho(k,e.id),machineName:r,connectionState:a,settings:e.settings,coordinator:K,messageInput:e.messageInput})}if(m&&(ht(e)||pt(e)))return n;for(const k of d){const v=k.activeModal&&Array.isArray(k.activeModal.buttons)&&k.activeModal.buttons.length>0,N=cw(k),w=HS(k),A=`${e.id}:${w}`,T=k.title&&String(k.title).trim()||"",I=ic(T,k.agentName,k.agentType)?"":T,P=k.messages||[];if(!(k.transport==="cdp-webview"||!!k.sessionId||!!k.providerSessionId||P.length>0||v||!!I||!["idle","panel_hidden","disconnected","not_monitored"].includes(N)))continue;const _=k.coordinator||(typeof((j=k.settings)==null?void 0:j.meshCoordinatorFor)=="string"&&k.settings.meshCoordinatorFor?{meshId:k.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:k.sessionId||k.instanceId,providerSessionId:k.providerSessionId,historySessionId:k.activeChatId||k.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:k.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:k.sessionCapabilities,mode:"chat",agentName:k.agentName,agentType:k.agentType,status:N,title:I,messages:P,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:k.git||e.git,displayPrimary:o||I||k.agentName||u,displaySecondary:k.model&&k.model.trim()?k.model.trim():`${u} · ${k.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:k.lastMessagePreview,lastMessageRole:k.lastMessageRole,lastMessageAt:k.lastMessageAt,lastMessageHash:k.lastMessageHash,lastUpdated:k.lastUpdated||e.lastUpdated,inboxBucket:k.inboxBucket,completionMarker:k.completionMarker,modalButtons:v?k.activeModal.buttons:void 0,modalMessage:v?k.activeModal.message:void 0,streamSource:"agent-stream",tabKey:ho(k.sessionId||k.instanceId,A),machineName:r,connectionState:a,settings:k.settings,coordinator:_,messageInput:k.messageInput})}return n.length===0&&n.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:i,git:e.git,displayPrimary:o||u,displaySecondary:p,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:ho(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),n}function zp(e){return String(e.type||e.id||"").trim()}function Ma(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function BS(e,t){const n=(t||"").trim();if(!n)return[];const r=(e||[]).find(a=>a.type===n);return Ma(r==null?void 0:r.modelOptions)}function WS(e,t){const n=(t||"").trim();if(!n)return[];const r=(e||[]).find(a=>a.type===n);return Ma(r==null?void 0:r.thinkingLevelOptions)}function Kp(e){const t=new Map;for(const n of e||[])n!=null&&n.type&&t.set(n.type,{models:Ma(n.modelOptions),thinking:Ma(n.thinkingLevelOptions)});return t}function OS(e){var t;return e.category!=="cli"||!zp(e)||e.enabled===!1?!1:e.machineStatus?e.machineStatus==="detected":((t=e.lastDetection)==null?void 0:t.ok)===!0||e.installed===!0||!!e.detectedPath}function Hn(e){var r;const t=new Set,n=[];for(const a of e||[]){if(!OS(a))continue;const o=zp(a);if(!o||t.has(o))continue;t.add(o);const i=String(a.displayName||a.name||o),c=a.detectedPath||((r=a.lastDetection)==null?void 0:r.path)||null;n.push({type:o,label:i,icon:a.icon,statusLabel:c?`Detected at ${c}`:"Detected on this machine",detectedPath:c,...Array.isArray(a.modelOptions)&&a.modelOptions.length?{modelOptions:a.modelOptions}:{},...Array.isArray(a.thinkingLevelOptions)&&a.thinkingLevelOptions.length?{thinkingLevelOptions:a.thinkingLevelOptions}:{}})}return n}function Fn(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],n=new Set,r=[];for(const a of t){const o=typeof a=="string"?a.trim():"";!o||n.has(o)||(n.add(o),r.push(o))}return r}function jr(e){return e.map(t=>t.type)}function US(e,t){const n=Fn(e),r=t.trim();return!r||n.includes(r)?n:[...n,r]}function GS(e,t){return Fn(e).filter(n=>n!==t)}function Fc(e,t,n){const r=Fn(e),a=r.indexOf(t);if(a<0)return r;const o=r.filter(c=>c!==t);if(n==="top")return[t,...o];if(n==="bottom")return[...o,t];const i=n==="up"?Math.max(0,a-1):Math.min(o.length,a+1);return o.splice(i,0,t),o}function Bc({direction:e}){return s.jsx("svg",{"aria-hidden":"true",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e==="up"?s.jsx("polyline",{points:"18 15 12 9 6 15"}):s.jsx("polyline",{points:"6 9 12 15 18 9"})})}function qS({value:e,availableProviders:t,onChange:n,disabled:r=!1,saveButton:a}){const{t:o}=Ne("common"),[i,c]=l.useState(""),u=l.useMemo(()=>new Map(t.map(g=>[g.type,g])),[t]),p=l.useMemo(()=>Fn(e),[e]),d=p.filter(g=>!u.has(g)).length,m=t.filter(g=>!p.includes(g.type)),f=()=>{i&&(n(US(p,i)),c(""))};return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[s.jsx("div",{className:"flex flex-col gap-2",children:p.length===0?s.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:"No provider priority configured. Launches without an explicit CLI provider will fail closed."}):p.map((g,S)=>{const h=u.get(g),x=!!h;return s.jsxs("div",{className:`flex flex-col gap-2 rounded-md border border-border-subtle px-3 py-2 sm:flex-row sm:items-center sm:justify-between ${x?"bg-bg-primary":"bg-bg-primary/40"}`,children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",S+1]}),(h==null?void 0:h.icon)&&s.jsx("span",{"aria-hidden":"true",children:h.icon}),s.jsx("span",{className:`font-mono text-[12px] ${x?"text-text-primary":"text-text-muted"}`,children:g}),x?s.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:o("settings.providerPriority.available")}):s.jsx("span",{className:"rounded border border-amber-500/25 bg-amber-500/10 px-1.5 py-px text-[9px] font-semibold text-amber-400",children:o("settings.providerPriority.notOnMachine")})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:h?`${h.label} · ${h.statusLabel}`:"Kept in order; skipped at launch until detected here."})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move up",disabled:r||S===0,title:"Move up",onClick:()=>n(Fc(p,g,"up")),children:s.jsx(Bc,{direction:"up"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move down",disabled:r||S===p.length-1,title:"Move down",onClick:()=>n(Fc(p,g,"down")),children:s.jsx(Bc,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:r,onClick:()=>n(GS(p,g)),children:o("settings.providerPriority.remove")})]})]},g)})}),s.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[s.jsxs("label",{className:"flex-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:o("settings.providerPriority.addCliLabel")}),s.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:i,onChange:g=>c(g.target.value),disabled:r||m.length===0,children:[s.jsx("option",{value:"",children:m.length?"Select provider…":"No additional detected CLI providers"}),m.map(g=>s.jsxs("option",{value:g.type,children:[g.label," (",g.type,")"]},g.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:r||!i,onClick:f,children:o("settings.providerPriority.addProvider")}),a]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Launches use this order, top to bottom.",d>0?` ${d} provider${d===1?"":"s"} not detected here — kept in order, skipped until available.`:""]})]})}function zS(e){const t=e.split(":");return t.length>=3&&(t[1]==="ide"||t[1]==="cli"||t[1]==="acp")?{daemonId:t[0],targetSessionId:t.slice(2).join(":")||void 0}:{daemonId:e}}function Vp(e,t){const n=zS(e);return{daemonId:n.daemonId,payload:{...t,...n.targetSessionId&&!t.targetSessionId?{targetSessionId:n.targetSessionId}:{}}}}const Yp=[{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:"🏄"}],Jp=[{id:"antigravity-cli",name:"Antigravity CLI",icon:"🪐"},{id:"claude-cli",name:"Claude Code",icon:"🟠"},{id:"codex-cli",name:"Codex CLI",icon:"📦"},{id:"cursor-cli",name:"Cursor CLI",icon:"⚡"},{id:"hermes-cli",name:"Hermes",icon:"⚕️"},{id:"kimi",name:"Kimi",icon:"🌙"},{id:"opencode",name:"OpenCode CLI",icon:"◆"}],Qp=[{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:"🟠"}],KS=Yp,VS=Jp,YS=Qp;function JS({icon:e,title:t,subtitle:n,badge:r,actions:a,className:o}){return s.jsxs("div",{className:Wt("dashboard-header",o),children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"header-title flex items-center gap-2",children:[s.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,r&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[r.count!==void 0?r.count:""," ",r.text]})]}),n&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:n})]}),a&&s.jsx("div",{className:"flex gap-2",children:a})]})}function Lr({icon:e,title:t,subtitle:n,badge:r,actions:a,widthClassName:o="max-w-6xl",contentClassName:i,children:c}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(JS,{icon:e,title:t,subtitle:n,badge:r,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Wt("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const Ci="adhdev:themechange";function QS(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function jn(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function Nn(e){return e==="system"?QS():e}function Xp(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function ia(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(Ci,{detail:{preference:e,theme:t}}))}function XS(){const e=jn(),t=Nn(e);Xp(t),ia(e,t)}function qs(){const[e,t]=l.useState(jn),[n,r]=l.useState(()=>Nn(jn()));l.useEffect(()=>{Xp(n)},[n]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=u=>{if(e==="system"){const p=u.matches?"light":"dark";r(p),ia("system",p)}};return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[e]),l.useEffect(()=>{const i=u=>{const p=u.detail||{},d=p.preference,m=p.theme;t(d==="dark"||d==="light"||d==="system"?d:jn()),r(m==="dark"||m==="light"?m:Nn(jn()))},c=u=>{if(u.key!=="theme")return;const p=jn(),d=Nn(p);t(p),r(d)};return window.addEventListener(Ci,i),window.addEventListener("storage",c),()=>{window.removeEventListener(Ci,i),window.removeEventListener("storage",c)}},[]);const a=l.useCallback(i=>{const c=Nn(i);t(i),r(c);try{localStorage.setItem("theme",i)}catch{}ia(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",u=Nn(c);r(u);try{localStorage.setItem("theme",c)}catch{}return ia(c,u),c})},[]);return{theme:n,preference:e,setPreference:a,cycleTheme:o,isDark:n==="dark"}}const Wc={dark:"Dark",light:"Light",system:"System"};function ZS({collapsed:e}){const{preference:t,cycleTheme:n}=qs(),r=t==="dark"?s.jsx(ib,{size:16}):t==="light"?s.jsx(ob,{size:16}):s.jsx(lb,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:n,title:`Theme: ${Wc[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:r}),!e&&s.jsx("span",{className:"text-xs",children:Wc[t]})]})}const ji="adhdev:langchange";function eC(){const e=Ct.language;return Tn(e)?e:Hu()}function tC(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(ji,{detail:{language:e}}))}function sC(){const[e,t]=l.useState(eC);l.useEffect(()=>{const r=i=>{Tn(i)&&t(i)},a=i=>{const c=i.detail||{};Tn(c.language)&&t(c.language)},o=i=>{if(i.key!==di)return;const c=i.newValue;Tn(c)&&c!==Ct.language&&(Ct.changeLanguage(c),ui(c))};return Ct.on("languageChanged",r),window.addEventListener(ji,a),window.addEventListener("storage",o),()=>{Ct.off("languageChanged",r),window.removeEventListener(ji,a),window.removeEventListener("storage",o)}},[]);const n=l.useCallback(r=>{if(Tn(r)){t(r);try{localStorage.setItem(di,r)}catch{}Ct.changeLanguage(r),ui(r),tC(r)}},[]);return{language:e,setLanguage:n}}function nC({trigger:e,viewport:t,menu:n,variant:r,gap:a=6,margin:o=8}){const i=e.top-o,c=t.height-e.bottom-o,u=r==="sidebar";let p=u;u&&i<n.height&&c>i&&(p=!1),!u&&c<n.height&&i>c&&(p=!0);const d=p?i:c,m=Math.max(80,Math.min(n.height,d));let f;p?f=e.top-a-m:f=e.bottom+a,f=Oc(f,o,Math.max(o,t.height-m-o));const g=Oc(e.left,o,Math.max(o,t.width-n.width-o));return{top:f,left:g,maxHeight:m}}function Oc(e,t,n){return Math.min(Math.max(e,t),n)}function rC({open:e}){return s.jsx("svg",{width:12,height:12,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",className:`lang-switch-caret${e?" open":""}`,children:s.jsx("polyline",{points:"6 9 12 15 18 9"})})}function aC({collapsed:e,variant:t="sidebar"}){const{language:n,setLanguage:r}=sC(),{t:a}=Ne("common"),[o,i]=l.useState(!1),[c,u]=l.useState(0),p=l.useRef(null),d=l.useRef(null),m=l.useRef(null),f=l.useId(),[g,S]=l.useState(null),h=l.useCallback(()=>{const P=d.current;if(!P)return;const D=P.getBoundingClientRect(),_=m.current,W=Math.max((_==null?void 0:_.offsetWidth)??0,168),$=(_==null?void 0:_.scrollHeight)??Qs.length*36+12;S(nC({trigger:{top:D.top,left:D.left,right:D.right,bottom:D.bottom,width:D.width,height:D.height},viewport:{width:window.innerWidth,height:window.innerHeight},menu:{width:W,height:$},variant:t}))},[t]),x=Math.max(0,Qs.findIndex(P=>P.code===n)),y=Qs[x]??Qs[0],b=a("language.label",{defaultValue:"Language"}),C=a("language.select",{defaultValue:"Select language"}),j=P=>`${f}-opt-${P}`,k=l.useCallback(()=>{u(x),i(!0)},[x]),v=l.useCallback((P=!0)=>{var D;i(!1),P&&((D=d.current)==null||D.focus())},[]),N=l.useCallback(P=>{const D=Qs[P];D&&r(D.code),v()},[r,v]);l.useEffect(()=>{if(!o)return;const P=W=>{var $,E;return!!(($=p.current)!=null&&$.contains(W)||(E=m.current)!=null&&E.contains(W))},D=W=>{P(W.target)||i(!1)},_=W=>{P(W.target)||i(!1)};return document.addEventListener("pointerdown",D,!0),document.addEventListener("focusin",_,!0),()=>{document.removeEventListener("pointerdown",D,!0),document.removeEventListener("focusin",_,!0)}},[o]),l.useLayoutEffect(()=>{if(!o){S(null);return}h();const P=()=>h();return window.addEventListener("resize",P),window.addEventListener("scroll",P,!0),()=>{window.removeEventListener("resize",P),window.removeEventListener("scroll",P,!0)}},[o,h]),l.useEffect(()=>{var P;o&&g&&((P=m.current)==null||P.focus())},[o,g]);const w=P=>{const D=Qs.length-1;switch(P.key){case"ArrowDown":P.preventDefault(),u(_=>_>=D?0:_+1);break;case"ArrowUp":P.preventDefault(),u(_=>_<=0?D:_-1);break;case"Home":P.preventDefault(),u(0);break;case"End":P.preventDefault(),u(D);break;case"Enter":case" ":P.preventDefault(),N(c);break;case"Escape":P.preventDefault(),v();break;case"Tab":i(!1);break}},A=P=>{o||(P.key==="ArrowDown"||P.key==="ArrowUp"||P.key==="Enter"||P.key===" ")&&(P.preventDefault(),k())},T=t==="landing"?"lang-switch-trigger lang-switch-trigger--landing":`lang-switch-trigger lang-switch-trigger--sidebar nav-item cursor-pointer${e?" justify-center py-2.5 px-0":""}`,I=t==="landing"||!e;return s.jsxs("div",{ref:p,className:"lang-switch",children:[s.jsxs("button",{ref:d,type:"button",className:T,"aria-haspopup":"listbox","aria-expanded":o,"aria-label":`${b}: ${y.label}`,title:`${b}: ${y.label}`,onClick:()=>o?v(!1):k(),onKeyDown:A,children:[s.jsx("span",{className:"nav-icon lang-switch-icon",children:s.jsx(gb,{size:16})}),I&&s.jsx("span",{className:"lang-switch-label text-xs",children:y.label}),I&&s.jsx(rC,{open:o})]}),o&&typeof document<"u"&&un.createPortal(s.jsx("ul",{ref:m,role:"listbox",tabIndex:-1,"aria-label":C,"aria-activedescendant":j(c),className:`lang-switch-menu lang-switch-menu--${t}`,style:{position:"fixed",top:(g==null?void 0:g.top)??0,left:(g==null?void 0:g.left)??0,maxHeight:g==null?void 0:g.maxHeight,overflowY:"auto",visibility:g?"visible":"hidden"},onKeyDown:w,children:Qs.map((P,D)=>{const _=P.code===y.code,W=D===c;return s.jsxs("li",{id:j(D),role:"option","aria-selected":_,className:`lang-switch-option${W?" is-active":""}${_?" is-selected":""}`,onMouseEnter:()=>u(D),onClick:()=>N(D),children:[s.jsx("span",{className:"lang-switch-check","aria-hidden":"true",children:_?s.jsx(xu,{size:14}):null}),s.jsx("span",{className:"lang-switch-option-label",children:P.label})]},P.code)})}),document.body)]})}const oC=[],iC=[];function So(e,t){return e?typeof e=="function"?e(t):e:null}const lC=l.memo(function({renderState:t,brand:n,navItems:r,sidebarSections:a,footerItems:o,footerInfo:i,footerActions:c,closeMobileMenu:u}){const{t:p}=Ne("common"),{collapsed:d,mobileMenuOpen:m}=t,f=S=>`nav-item${S.active?" active":""} cursor-pointer ${d?"justify-center py-2.5 px-0":""}${S.className?` ${S.className}`:""}`,g=S=>s.jsxs("div",{className:f(S),id:`nav-${S.id}`,onClick:()=>{S.onSelect(),u()},title:d?S.title??(typeof S.label=="string"?S.label:void 0):S.title,children:[s.jsx("span",{className:"nav-icon",children:S.icon}),!d&&S.label]},S.id);return s.jsxs("aside",{className:`sidebar ${m?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${d?"justify-center gap-0":""}`,children:So(n,t)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":p("app.closeMenu"),onClick:u,children:s.jsx(Mt,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(g)}),a.map(S=>s.jsxs("div",{className:S.className??"border-t border-border-subtle pt-2 mt-2",children:[!d&&S.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:S.title}):null,S.items.map(g)]},S.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[o.map(g),So(i,t),s.jsx(ZS,{collapsed:d}),s.jsx(aC,{collapsed:d}),So(c,t)]})]})});function cC({children:e,brand:t,navItems:n,sidebarSections:r=oC,footerItems:a=iC,footerInfo:o,footerActions:i,preMainContent:c,collapsedStorageKey:u="sidebar-collapsed"}){const{t:p}=Ne("common"),[d,m]=l.useState(!1),[f,g]=l.useState(()=>{try{return localStorage.getItem(u)==="1"}catch{return!1}}),S=l.useCallback(()=>m(!0),[]),h=l.useCallback(()=>m(!1),[]),x=l.useCallback(()=>{g(b=>{const C=!b;try{localStorage.setItem(u,C?"1":"0")}catch{}return C})},[u]),y=l.useMemo(()=>({collapsed:f,mobileMenuOpen:d,openMobileMenu:S,closeMobileMenu:h,toggleCollapsed:x}),[f,d,S,h,x]);return s.jsxs("div",{className:`app-layout${d?" mobile-menu-open":""}${f?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":p("app.openMenu"),onClick:S,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),d&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":p("app.closeMenu"),onClick:h,onKeyDown:b=>b.key==="Escape"&&h()}),s.jsx(lC,{renderState:y,brand:t,navItems:n,sidebarSections:r,footerItems:a,footerInfo:o,footerActions:i,closeMobileMenu:h}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function gt({title:e,icon:t,description:n,accentColor:r,className:a,collapsible:o,defaultOpen:i=!0,badge:c,children:u}){const[p,d]=l.useState(i),m=o?p:!0,f=(e||n)&&s.jsxs("div",{className:Wt("flex items-start justify-between gap-3",m&&"mb-4"),children:[s.jsxs("div",{className:"min-w-0",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary flex items-center gap-1.5",children:[t&&s.jsx("span",{children:t}),s.jsx("span",{children:e}),c]}),n&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:n})]}),o&&s.jsx("span",{className:Wt("mt-0.5 shrink-0 text-text-muted transition-transform select-none",m?"rotate-90":"rotate-0"),"aria-hidden":!0,children:"▸"})]});return s.jsxs("div",{className:Wt("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",r&&"border-l-[3px]",a),style:r?{borderLeftColor:r}:void 0,children:[o&&f?s.jsx("button",{type:"button",className:"w-full bg-transparent border-none p-0 text-left cursor-pointer",onClick:()=>d(g=>!g),"aria-expanded":m,children:f}):f,m&&u]})}function Ya({icon:e,title:t,description:n,action:r,className:a}){return s.jsxs("div",{className:Wt("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[s.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),s.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:n}),r]})}const dC={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"},uC={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Lt({variant:e,children:t,onDismiss:n,className:r}){return s.jsxs("div",{className:Wt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",dC[e],r),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:uC[e]}),s.jsx("span",{children:t})]}),n&&s.jsx("button",{onClick:n,className:"cursor-pointer border-none bg-transparent text-current text-base opacity-70 hover:opacity-100 transition-opacity",children:"✕"})]})}function At({label:e,hint:t,children:n,className:r}){return s.jsxs("div",{className:Wt("mb-5",r),children:[s.jsx("label",{className:"block text-xs font-semibold text-text-muted uppercase tracking-wider mb-2",children:e}),n,t&&s.jsx("p",{className:"text-xs text-text-muted mt-1.5",children:t})]})}function hs(e){const{className:t,...n}=e;return s.jsx("input",{...n,className:Wt("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none","focus:border-accent transition-colors",t)})}const pC={primary:"btn-primary",secondary:"btn-secondary",warning:"btn-warning",danger:"btn-danger",ghost:"btn-ghost"},Is=l.forwardRef(function({variant:t="secondary",size:n="md",type:r,className:a,...o},i){return s.jsx("button",{ref:i,type:r??"button",className:Wt("btn",pC[t],n==="sm"&&"btn-sm",a),...o})}),mC=l.forwardRef(function({options:t,children:n,className:r,...a},o){return s.jsx("select",{ref:o,className:Wt("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none cursor-pointer","focus:border-accent transition-colors",r),...a,children:n??(t==null?void 0:t.map(i=>s.jsx("option",{value:i.value,disabled:i.disabled,children:i.label},i.value)))})}),hC={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"},fC={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function bC({status:e,label:t,className:n}){const r=t||e;return s.jsxs("span",{className:Wt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",hC[e],n),children:[s.jsx("span",{className:Wt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",fC[e])}),r]})}function tn({label:e,description:t,checked:n,disabled:r,onChange:a,extra:o}){return s.jsxs("div",{className:`flex justify-between items-center ${r?"opacity-60":""}`,children:[s.jsxs("div",{className:"pr-4",children:[s.jsx("div",{className:"font-medium text-sm",children:e}),s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[o,s.jsxs("button",{type:"button",role:"switch","aria-checked":n,"aria-disabled":r,disabled:r,onClick:()=>a(!n),className:`relative inline-flex items-center ${r?"cursor-not-allowed":"cursor-pointer"}`,children:[s.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:n?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),s.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${n?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function gC({onPrefChange:e}){const{t}=Ne("common"),[n,r]=vw(),[a,o]=l.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);l.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){o("unsupported");return}o(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,u)=>{r({[c]:u}),e==null||e(c,u)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(tn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Un,{size:15})," ",t("notifications.masterToggleLabel")]}),description:t("notifications.masterToggleDesc"),checked:n.globalEnabled,onChange:c=>i("globalEnabled",c)}),n.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),n.globalEnabled&&s.jsx(tn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(xs,{size:15})," ",t("notifications.browserNotificationsLabel")]}),description:t("notifications.browserNotificationsDesc"),checked:n.browserNotifications,onChange:c=>i("browserNotifications",c)}),n.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:t("notifications.standaloneBackgroundInfo")}),a==="default"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-status-warning",children:[s.jsx("span",{children:t("notifications.standalonePermissionDefault")}),s.jsx("button",{onClick:()=>{Ku().then(o)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:t("notifications.allowNotifications")})]}),a==="denied"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:t("notifications.permissionDenied")}),a==="unsupported"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:t("notifications.standalonePermissionUnsupported")})]}),n.globalEnabled&&n.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(tn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Su,{size:15})," ",t("notifications.completionAlertsLabel")]}),description:t("notifications.completionAlertsDesc"),checked:n.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(tn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(cb,{size:15})," ",t("notifications.approvalAlertsLabel")]}),description:t("notifications.approvalAlertsDesc"),checked:n.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(tn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(wr,{size:15})," ",t("notifications.connectionAlertsLabel")]}),description:t("notifications.connectionAlertsDesc"),checked:n.disconnectAlert,onChange:c=>i("disconnectAlert",c)})]}),!n.globalEnabled&&s.jsx("p",{className:"text-[11px] text-text-muted italic",children:t("notifications.allDisabled")})]})}function Da(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/);if(!t)return null;const n=t[4]??null;let r=null;if(n){const a=n.match(/(?:^|\.)(\d+)$/);r=a?Number(a[1]):null}return{base:[Number(t[1]),Number(t[2]),Number(t[3])],prereleaseNumber:r,isPrerelease:n!==null}}function Uc(e){var t;return((t=Da(e))==null?void 0:t.base)??null}function Zp(e,t){const n=Da(e),r=Da(t);if(!n||!r)return e!==t;for(let a=0;a<3;a+=1){if(n.base[a]<r.base[a])return!0;if(n.base[a]>r.base[a])return!1}return n.isPrerelease&&r.isPrerelease?n.prereleaseNumber===null||r.prereleaseNumber===null?!1:n.prereleaseNumber<r.prereleaseNumber:!1}function Ja(e,t){const n=e.version||null;return!n||!t||e.versionMismatch===!0&&!Da(t)?!1:Zp(n,t)}function br(e,t){if(e.versionUpdateRequired===!0)return!0;const n=e.version||null;if(!n||!t||!Zp(n,t))return!1;const r=Uc(n),a=Uc(t);return!r||!a?!1:r[0]!==a[0]||r[1]!==a[1]}function Pn(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="stable"||t==="latest"?"stable":t==="preview"||t==="next"?"preview":null}function xC(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="latest"||t==="stable"?"latest":t==="next"||t==="preview"?"next":null}function cr(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function dl(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},n=Pn(t.channel)||Pn(e.updateChannel)||Pn(e.releaseChannel)||void 0,r=xC(t.npmTag)||(n==="preview"?"next":n==="stable"?"latest":void 0),a=cr(t.targetVersion)||cr(e.serverVersion)||void 0,o=cr(t.minVersion)||void 0,i=cr(t.updateCommand)||(n?`adhdev update --channel ${n}`:void 0);return{...n?{channel:n}:{},...r?{npmTag:r}:{},...a?{targetVersion:a}:{},...o?{minVersion:o}:{},...i?{updateCommand:i}:{}}}function $s(e,t=null){return dl(e).targetVersion||t}function vC(e){return dl(e).channel||null}function Qa(e){if(!e)return null;const t=dl(e);return t.channel?{channel:t.channel,...t.npmTag?{npmTag:t.npmTag}:{},...t.targetVersion?{targetVersion:t.targetVersion}:{},updatePolicy:t}:null}function yC(e){return Pn(e.updateChannel)||Pn(e.releaseChannel)}function em(e,t={}){const n=e.updatePolicy&&typeof e.updatePolicy=="object"?Pn(e.updatePolicy.channel):null,r=yC(e);if(n&&r&&n!==r)return`Switch to ${n}`;const a=cr(t.targetVersion);return a?`Update to v${a}`:t.fallback||(t.required?"Update now":"Upgrade")}const tm="Cannot update: node update policy unavailable; refresh and try again";async function wC(e,t,n){var a,o,i,c,u,p;const r=Qa(n);if(!r)return{state:"error",message:tm};try{const d=await e(t,"daemon_upgrade",r);return(a=d==null?void 0:d.result)!=null&&a.alreadyLatest?{state:"done",message:`Already on v${((o=d==null?void 0:d.result)==null?void 0:o.version)||"latest"}.`}:(i=d==null?void 0:d.result)!=null&&i.upgraded||(c=d==null?void 0:d.result)!=null&&c.success?{state:"done",message:`Upgrade to v${((u=d==null?void 0:d.result)==null?void 0:u.version)||"latest"} started. Daemon is restarting…`}:{state:"error",message:((p=d==null?void 0:d.result)==null?void 0:p.error)||"Upgrade failed"}}catch(d){return{state:"error",message:d instanceof Error?d.message:"Upgrade failed"}}}function kC(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Co(e,t){return e instanceof Error?e.message:t}function SC({ides:e,emptyMessage:t,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:a}){const{t:o}=Ne("common"),i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?s.jsx(Ya,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:o("machine.connectedMachines.noMachines"),description:t||o("machine.connectedMachines.defaultDescription")}):s.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>s.jsx(jC,{ide:c,allIdes:e,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:a},c.id))})}function Gc({title:e,message:t,confirmLabel:n,confirmColor:r,onConfirm:a,onCancel:o}){const{t:i}=Ne("common"),c=r==="red"?"bg-status-error/20 text-status-error border-status-error/40 hover:bg-status-error/30":"";return un.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:"var(--z-modal)"},onClick:o,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:u=>u.stopPropagation(),children:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx("button",{onClick:o,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:i("common.cancel")}),s.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:r==="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:n})]})]})}),document.body)}function CC(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),r=[...KS,...VS,...YS].find(a=>a.id===t||t.includes(a.id)||a.id.includes(t));return r?{icon:r.icon,name:r.name}:{icon:"📝",name:e}}function jC({ide:e,allIdes:t,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:a}){var $,E;const{t:o}=Ne("common"),[i,c]=l.useState("idle"),[u,p]=l.useState(""),[d,m]=l.useState(null),[f,g]=l.useState("idle"),[S,h]=l.useState(""),x=e.version||null,y=(($=e.machine)==null?void 0:$.platform)||((E=e.system)==null?void 0:E.platform)||"",b=is(e,{fallbackId:e.id}),C=y==="win32"?"🪟":y==="darwin"?"🍎":"🐧",j=t.filter(B=>B.daemonId===e.id&&B.transport==="cdp-page"),k=t.filter(B=>B.daemonId===e.id&&B.transport==="pty"),v=t.filter(B=>B.daemonId===e.id&&B.transport==="acp"),N=e.p2p,w=async()=>{if(!n)return;const B=Qa(e);if(!B){c("error"),p(tm);return}c("upgrading"),p(o("machine.connectedMachines.startingUpgrade"));try{const L=kC(await n(e.id,"daemon_upgrade",B));L.alreadyLatest?(c("done"),p(`Already on v${L.version||"latest"}.`)):L.upgraded||L.success?(c("done"),p(`Upgrade to v${L.version||"latest"} started. Daemon is restarting...`)):(c("error"),p(L.error||"Upgrade failed"))}catch(L){c("error"),p(Co(L,"Connection lost during upgrade"))}},A=async()=>{if(m(null),!!r){g("loading");try{await r(e.id),g("done"),h(o("machine.connectedMachines.machineDisconnected"))}catch(B){g("error"),h(Co(B,o("machine.connectedMachines.failedToDisconnect")))}}},T=async()=>{if(m(null),!!a){g("loading");try{await a(e.id),g("done"),h(o("machine.connectedMachines.tokenRevoked"))}catch(B){g("error"),h(Co(B,o("machine.connectedMachines.failedToRevokeToken")))}}},I="1.0.30",P=$s(e,I),D=Ja(e,P),_=br(e,P),W=j.length+k.length+v.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:C}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:b}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),x&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${D?"":"bg-bg-secondary"}`,style:D?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",x,!D&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[n&&D&&s.jsx("button",{onClick:w,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${I}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," ",o("machine.connectedMachines.upgrading")]}):i==="done"?o("machine.connectedMachines.updated"):_?o("machine.connectedMachines.updateNow"):o("machine.connectedMachines.updateTo",{version:I})}),r&&s.jsx("button",{onClick:()=>m("disconnect"),disabled:f==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:o("machine.connectedMachines.disconnect")}),a&&s.jsx("button",{onClick:()=>m("revoke"),disabled:f==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:o("machine.connectedMachines.remove")}),s.jsx(bC,{status:e.status==="online"?"online":"error"})]})]}),s.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[N&&s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${N.state==="connected"?"bg-status-online":"bg-text-muted/30"} ${N.state==="connecting"||N.state==="new"?"animate-pulse":""}`,style:N.state==="connecting"||N.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",N.state==="connected"?"connected":N.state==="connecting"||N.state==="new"?o("machine.connectedMachines.connecting"):N.state||"off"]}),N.peers!==void 0&&N.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",N.peers," peer",N.peers!==1?"s":"",")"]})]}),N&&W>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),W>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[j.map(B=>{const L=CC(B.type),R=B.cdpConnected;return s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:L.icon}),s.jsx("span",{children:L.name}),R!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${R?"bg-status-online":"animate-pulse"}`,style:R?void 0:{background:"var(--status-warning)"},title:o(R?"machine.connectedMachines.cdpConnected":"machine.connectedMachines.cdpConnecting")})]},B.id)}),k.map(B=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"⌨️"}),s.jsx("span",{children:B.cliName||"CLI"})]},B.id)),v.map(B=>s.jsxs("span",{className:"flex items-center gap-1 bg-bg-secondary px-1.5 py-0.5 rounded",children:[s.jsx("span",{children:"🔗"}),s.jsx("span",{children:B.cliName||"ACP"})]},B.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:o("machine.connectedMachines.noIdesConnected")})]}),(u||S)&&s.jsx("div",{className:`text-xs mt-2 px-1 ${i==="error"||f==="error"?"text-status-error":i==="done"||f==="done"?"text-status-online":"text-text-muted"}`,children:S||u})]}),d==="disconnect"&&s.jsx(Gc,{title:o("machine.connectedMachines.disconnectTitle"),message:`Disconnect "${b}" from ADHDev?
59
59
 
60
60
  This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
61
61
 
@@ -66,8 +66,8 @@ This will:
66
66
  • Delete the machine registration
67
67
  • Require restarting ADHDev on that machine
68
68
 
69
- Use this if you want to permanently remove a machine.`,confirmLabel:o("machine.connectedMachines.remove"),confirmColor:"red",onConfirm:T,onCancel:()=>m(null)})]})}const NC=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli","gemini-cli"];function AC({daemonId:e,knownCliTypes:t=NC}){const{t:n}=Ne("common"),{sendCommand:r}=St(),[a,o]=l.useState({}),[i,c]=l.useState({}),[u,p]=l.useState(!0),[d,m]=l.useState(null),[f,g]=l.useState(null),[S,h]=l.useState(""),x=l.useCallback(async()=>{if(e){p(!0),g(null);try{const C=await r(e,"list_coordinator_prompts",{}),j=C!=null&&C.result&&typeof C.result=="object"?C.result:C;if(!(j!=null&&j.success)){g((j==null?void 0:j.error)||"Failed to load");return}const k=j.entries||{};h(j.dir||"");const v={};for(const N of t)v[N]=k[N]||{override:"",append:""};for(const N of Object.keys(k))v[N]||(v[N]=k[N]);o(v),c(JSON.parse(JSON.stringify(v)))}catch(C){g((C==null?void 0:C.message)||String(C))}finally{p(!1)}}},[r,e,t]);l.useEffect(()=>{x()},[x]);const y=l.useCallback(async(C,j)=>{var k;if(e){m(`${C}:${j}`),g(null);try{const v=((k=a[C])==null?void 0:k[j])||"",N=await r(e,"write_coordinator_prompt",{key:C,kind:j,content:v}),w=N!=null&&N.result&&typeof N.result=="object"?N.result:N;if(!(w!=null&&w.success)){g((w==null?void 0:w.error)||"Save failed");return}c(A=>({...A,[C]:{...A[C]||{override:"",append:""},[j]:v}}))}catch(v){g((v==null?void 0:v.message)||String(v))}finally{m(null)}}},[r,e,a]),b=l.useMemo(()=>(C,j)=>{var k,v;return(((k=a[C])==null?void 0:k[j])||"")!==(((v=i[C])==null?void 0:v[j])||"")},[a,i]);return e?s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{className:"text-[12px] text-text-muted",children:[s.jsxs("p",{children:["Customize the coordinator prompt this daemon's mesh coordinator sessions get. ",s.jsx("span",{className:"font-mono text-[11px]",children:S||"~/.adhdev/coordinator-prompts/"})]}),s.jsxs("p",{className:"mt-1",children:[s.jsx(si,{i18nKey:"settings.coordinatorPrompts.overrideDesc",ns:"common",components:{strong:s.jsx("strong",{})}})," ",s.jsx(si,{i18nKey:"settings.coordinatorPrompts.appendDesc",ns:"common",components:{strong:s.jsx("strong",{})}}),"Leave a field empty + Save to remove it (reset to default). Supports placeholders: ","{{meshName}}",", ","{{repo}}",", ","{{nodes}}",", ","{{rules}}",", etc."]})]}),f&&s.jsx("div",{className:"text-[12px] text-status-error bg-status-error/10 border border-status-error/40 rounded px-3 py-2",children:f}),u&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"Loading…"}),s.jsx("div",{className:"flex flex-col gap-6",children:Object.entries(a).map(([C,j])=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-2",children:C}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:n("settings.coordinatorPrompts.overrideLabel")}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:4,value:j.override,onChange:k=>o(v=>({...v,[C]:{...v[C],override:k.target.value}})),placeholder:"(empty — use daemon default base prompt)",disabled:d===`${C}:override`}),s.jsx("div",{className:"mt-1 mb-3 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void y(C,"override"),disabled:d===`${C}:override`||!b(C,"override"),children:d===`${C}:override`?"Saving…":b(C,"override")?"Save override":"Saved"})}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:n("settings.coordinatorPrompts.appendLabel")}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:3,value:j.append,onChange:k=>o(v=>({...v,[C]:{...v[C],append:k.target.value}})),placeholder:"(empty — nothing appended at this layer)",disabled:d===`${C}:append`}),s.jsx("div",{className:"mt-1 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void y(C,"append"),disabled:d===`${C}:append`||!b(C,"append"),children:d===`${C}:append`?"Saving…":b(C,"append")?"Save append":"Saved"})})]},C))})]}):s.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const TC=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function MC(){const{preference:e,setPreference:t}=qs();return s.jsx("div",{className:"flex gap-2",children:TC.map(n=>s.jsxs("button",{onClick:()=>t(n.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${e===n.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===n.id?{color:"var(--accent-on-primary)"}:void 0,children:[s.jsx("span",{children:n.icon}),n.label]},n.id))})}function DC(e){const t=e.trim();return/^#[0-9a-fA-F]{6}$/.test(t)?t:/^#[0-9a-fA-F]{3}$/.test(t)?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:null}function IC(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function jo(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function qc(e){const{r:t,g:n,b:r}=IC(e);return .2126*jo(t)+.7152*jo(n)+.0722*jo(r)}function zc(e,t){const n=qc(e),r=qc(t),a=Math.max(n,r),o=Math.min(n,r);return(a+.05)/(o+.05)}function sm(e){const t=DC(e);if(!t)return"#111827";const n="#111827",r="#ffffff";return zc(t,n)>=zc(t,r)?n:r}const Ni={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},Ai={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},PC=[{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"}}}],nm="adhdev-chat-theme",rm="adhdev-chat-theme-custom";function la(){if(typeof window>"u")return"ember";try{return localStorage.getItem(nm)||"ember"}catch{return"ember"}}function ms(e){try{const t=localStorage.getItem(rm);if(t){const n=JSON.parse(t);return{...e==="dark"?Ni:Ai,...n[e]}}}catch{}return e==="dark"?Ni:Ai}function Gr(e,t){try{localStorage.setItem(rm,JSON.stringify({dark:e,light:t}))}catch{}}function ns(e,t){const n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${n}, ${r}, ${a}, ${t})`}function Ia(e,t){const n=Math.min(255,parseInt(e.slice(1,3),16)+t),r=Math.min(255,parseInt(e.slice(3,5),16)+t),a=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${n.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const LC={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function gr(e,t){var a;const n=(a=LC[e])==null?void 0:a[t];if(!n)return;const r=document.documentElement;r.style.setProperty("--accent-primary",n),r.style.setProperty("--accent-primary-light",Ia(n,24)),r.style.setProperty("--accent-on-primary",sm(n)),r.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${n}, ${Ia(n,18)})`),r.style.setProperty("--border-accent",ns(n,.35)),r.style.setProperty("--nav-active-bg",ns(n,.1)),r.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${n}, 0 0 12px ${ns(n,.06)}`)}function on(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",ns(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",ns(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",ns(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",ns(e.borderSubtle,.5)),t.style.setProperty("--border-default",ns(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Ia(e.accentColor,30)),t.style.setProperty("--accent-on-primary",sm(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Ia(e.accentColor,40)})`),t.style.setProperty("--border-accent",ns(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",ns(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${ns(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${ns(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.style.setProperty("--chat-input-border",e.inputBorder)}function ul(){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(n=>e.style.removeProperty(n))}function RC(e){try{localStorage.setItem(nm,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ln()?"dark":"light";on(ms(t))}else ul(),gr(e,ln()?"dark":"light")}function EC(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=la();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ln()?"dark":"light";on(ms(t))}else ul(),gr(e,ln()?"dark":"light")}function ln(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Gt({label:e,value:t,onChange:n}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange:r=>n(r.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),s.jsx("input",{type:"text",value:t,onChange:r=>{/^#[0-9a-fA-F]{0,6}$/.test(r.target.value)&&n(r.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function er({title:e,children:t}){return s.jsxs("div",{style:{marginBottom:14},children:[s.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:t})]})}function _C({dark:e,onColorsChange:t}){const{t:n}=Ne("common"),r=e?"dark":"light",[a,o]=l.useState(()=>ms(r));l.useEffect(()=>{o(ms(r))},[r]);const i=l.useCallback((c,u)=>{o(p=>{const d={...p,[c]:u},f=ms(r==="dark"?"light":"dark");return r==="dark"?Gr(d,f):Gr(f,d),on(d),t(d),d})},[r,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[n("settings.theme.customEditorTitle"),s.jsx("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:n(e?"settings.theme.darkMode":"settings.theme.lightMode")})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(er,{title:n("settings.theme.sectionAppBackground"),children:[s.jsx(Gt,{label:n("settings.theme.colorBackground"),value:a.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(Gt,{label:n("settings.theme.colorSurface"),value:a.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(Gt,{label:n("settings.theme.colorCard"),value:a.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(er,{title:n("settings.theme.sectionAppText"),children:[s.jsx(Gt,{label:n("settings.theme.colorPrimary"),value:a.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(Gt,{label:n("settings.theme.colorSecondary"),value:a.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(Gt,{label:n("settings.theme.colorMuted"),value:a.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(er,{title:n("settings.theme.sectionBordersAccent"),children:[s.jsx(Gt,{label:n("settings.theme.colorBorderSubtle"),value:a.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(Gt,{label:n("settings.theme.colorBorderDefault"),value:a.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(Gt,{label:n("settings.theme.colorAccent"),value:a.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(er,{title:n("settings.theme.sectionChatBubbles"),children:[s.jsx(Gt,{label:n("settings.theme.colorUserBubble"),value:a.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(Gt,{label:n("settings.theme.colorUserText"),value:a.userText,onChange:c=>i("userText",c)}),s.jsx(Gt,{label:n("settings.theme.colorAgentBubble"),value:a.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(Gt,{label:n("settings.theme.colorAgentText"),value:a.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(er,{title:n("settings.theme.sectionChatLayout"),children:[s.jsx(Gt,{label:n("settings.theme.colorChatBg"),value:a.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(Gt,{label:n("settings.theme.colorSendButton"),value:a.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(Gt,{label:n("settings.theme.colorInputBorder"),value:a.inputBorder,onChange:c=>i("inputBorder",c)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:n("settings.theme.labelBubbleRadius")}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.jsx("input",{type:"range",min:4,max:24,value:a.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[a.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const c=e?Ni:Ai,p=ms(e?"light":"dark");e?Gr(c,p):Gr(p,c),o(c),on(c),t(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:n("settings.theme.resetToDefaults")})]})}function $C(){const{t:e}=Ne("common"),[t,n]=l.useState(la),[r,a]=l.useState(!0),[o,i]=l.useState(()=>ms("dark"));l.useEffect(()=>{a(ln());const p=new MutationObserver(()=>{const f=ln();a(f);const g=la();g==="custom"?on(ms(f?"dark":"light")):gr(g,f?"dark":"light")});p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const d=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const f=ln();a(f);const g=la();g==="custom"?on(ms(f?"dark":"light")):gr(g,f?"dark":"light")};return d.addEventListener("change",m),()=>{p.disconnect(),d.removeEventListener("change",m)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?on(ms(r?"dark":"light")):(ul(),gr(t,r?"dark":"light"))},[t,r]),l.useEffect(()=>{i(ms(r?"dark":"light"))},[r]);const c=p=>{n(p),RC(p)},u=[...PC,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText},light:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:u.map(p=>{const d=t===p.id,m=r?p.preview.dark:p.preview.light,f=p.id==="honey"||p.id==="ember"?"#1a1a1a":p.id==="custom"?o.userText:"#fff";return s.jsxs("button",{onClick:()=>c(p.id),className:"text-left rounded-xl p-3 transition-all",style:{background:d?"var(--bg-glass-hover)":"var(--bg-glass)",border:d?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:d?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:e("settings.theme.helloHelp")}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.userBubble,color:f},children:e("settings.theme.fixBug")}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:e("settings.theme.onIt")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[d&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:p.id==="custom"?e("settings.theme.customLabel"):p.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:p.description})]})]})]},p.id)})}),t==="custom"&&s.jsx(_C,{dark:r,onColorsChange:p=>i(p)})]})}const pl="adhdev_mobileDashboardMode_v1",Ti="adhdev:mobile-dashboard-mode-change";function ml(){try{return localStorage.getItem(pl)==="workspace"?"workspace":"chat"}catch{return"chat"}}function HC(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??ml())},n=a=>{const o=a.detail;t(o)},r=a=>{a.key&&a.key!==pl||t()};return window.addEventListener(Ti,n),window.addEventListener("storage",r),()=>{window.removeEventListener(Ti,n),window.removeEventListener("storage",r)}}function FC(e){try{localStorage.setItem(pl,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ti,{detail:e}))}function BC(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(ml()==="chat")},[]),s.jsx(tn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(bn,{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:n=>{t(n),FC(n?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const WC="Choose a preset or create a fully custom theme. Custom themes control the entire app — backgrounds, text, borders, and chat bubbles.",OC="Choose whether the dashboard opens like a chat app on phones or keeps the full workspace layout.";function UC({themeDescription:e=WC,mobileDescription:t=OC,fontsSlot:n}){const{t:r}=Ne("common");return s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:r("settings.appearance.modeLabel")}),s.jsx(MC,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:r("settings.appearance.themeLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:e}),s.jsx($C,{})]}),n,s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:r("settings.appearance.mobileLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:t}),s.jsx(BC,{})]})]})}const No=new Map,Kc=new Map;function GC(e){if(!e||typeof e!="object")return null;const t=e,n=t.result&&typeof t.result=="object"?t.result:t,r=n.machine;return!r||typeof r!="object"?null:{machine:r,timestamp:typeof n.timestamp=="number"?n.timestamp:void 0}}function qC(e,t,n,r){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:r,platform:n.platform,machine:n}}function am(){const{sendCommand:e}=St(),{injectEntries:t,getIdes:n}=yr();return l.useCallback(async(r,a)=>{if(!r)return;const o=(a==null?void 0:a.minFreshMs)??J0,i=Kc.get(r)||0;if(!(a!=null&&a.force)&&i>0&&Date.now()-i<o)return;const c=No.get(r);if(c)return c;const u=(async()=>{const p=await e(r,"get_machine_runtime_stats"),d=GC(p);if(!d)return;const m=n().find(g=>g.id===r),f=qC(m,r,d.machine,d.timestamp||Date.now());t([f]),Kc.set(r,Date.now())})().finally(()=>{No.delete(r)});return No.set(r,u),u},[n,t,e])}function zC(e,t,n){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:n.timestamp,platform:n.machine.platform,machine:{...(e==null?void 0:e.machine)||{},...n.machine}}}function KC(e,t){const{sendData:n}=St(),{injectEntries:r,getIdes:a}=yr(),o=Array.from(new Set(e.filter(Boolean))).join("|");l.useEffect(()=>{if(!(t!=null&&t.enabled)||!n)return;const i=o?o.split("|"):[];if(i.length===0)return;const c=i.map(u=>fs.subscribe({sendData:n},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:t==null?void 0:t.intervalMs}},d=>{const m=a().find(g=>g.id===u),f=zC(m,u,d);r([f])}));return()=>{c.forEach(u=>u())}},[o,a,r,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,n])}function VC(e,t){const{sendData:n}=St(),[r,a]=l.useState(null),[o,i]=l.useState(!1);return l.useEffect(()=>{if(!e){a(null),i(!1);return}if(!(t!=null&&t.enabled)||!n){i(!1);return}a(null),i(!0);let c=null;const u=fs.subscribe({sendData:n},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},p=>{c&&(clearTimeout(c),c=null),a(p.diagnostics),i(!1)});return u.initialSendAccepted?c=setTimeout(()=>{i(!1)},Z0):i(!1),()=>{c&&clearTimeout(c),u()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,n]),{diagnostics:r,loading:o,applyDiagnostics:a}}function YC(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function om(e){const{sendData:t}=St(),[n,r]=l.useState({});return l.useEffect(()=>{const a=YC(e);if(!a||!e.sessionId||!t){r({});return}const o=fs.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},i=>{r({status:i.status,modalMessage:i.modalMessage,modalButtons:i.modalButtons}),Ln.record({interactionId:i.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:i.status,modalButtonCount:Array.isArray(i.modalButtons)?i.modalButtons.length:0}})});return o.initialSendAccepted||r({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),n}function JC(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function QC(e){const t=(e==null?void 0:e.result)??e;return typeof(t==null?void 0:t.error)=="string"?t.error:"Interactive prompt response failed"}async function XC(e,t,n){const r=await n(`/api/v1/sessions/${encodeURIComponent(e)}/interactive-prompt/resolve`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let a=`HTTP ${r.status}`;try{const o=await r.json();typeof(o==null?void 0:o.error)=="string"&&(a=o.error)}catch{}throw new Error(a)}}async function ZC({promptSession:e,response:t,useP2PCommand:n,sendCommand:r,fetchImpl:a=fetch}){if(n){const o=await r(e.routeId,"interactive_prompt_response",{targetSessionId:e.sessionId,sessionId:e.sessionId,response:t});if(!JC(o))throw new Error(QC(o));return}await XC(e.sessionId,t,a)}function im(e){const{ides:t,isP2PActive:n,p2pStates:r}=As(),{sendCommand:a}=St(),[o,i]=l.useState(null),[c,u]=l.useState(!1),[p,d]=l.useState(null),m=l.useRef(!1),f=l.useMemo(()=>Kb(t,e),[t,e]),g=!!f,S=l.useMemo(()=>f?f.prompt.promptId===o?null:f:null,[o,f]),h=l.useCallback(async b=>{if(!S||m.current)return;m.current=!0;const C=Pu(S.prompt,b);u(!0),d(null);try{const j=(r==null?void 0:r[S.daemonId])==="connected"||n===!0;await ZC({promptSession:S,response:C,useP2PCommand:j,sendCommand:a}),i(S.prompt.promptId)}catch(j){throw d(j instanceof Error?j.message:String(j)),j}finally{u(!1),m.current=!1}},[n,r,S,a]),x=l.useCallback(()=>{S&&i(S.prompt.promptId)},[S]),y=l.useCallback(()=>{i(null),d(null)},[]);return{promptSession:S,hasActivePrompt:g,responseError:p,isSubmitting:c,submit:h,cancel:x,reopen:y}}function lm(e){return e instanceof Error?e.message:String(e||"")}function ej(e){const t=lm(e);return t.includes("P2P command timeout")||t.includes("P2P not connected")||t.includes("P2P channel not open")||t.includes("P2P not available")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}function tj(e){const t=lm(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function cm({conversation:e,mode:t,ides:n,sendDaemonCommand:r,setCliViewModeOverrides:a}){if(!e||!ht(e)||pt(e))return;const o=Gn(e);if(o===t)return;const i=e.sessionId;i&&a(c=>({...c,[i]:t}));try{await r(Rs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Ns(e),mode:t})}catch(c){const u=tj(c);i&&!u&&a(p=>{const d={...p};return o===nj(n,i)?delete d[i]:d[i]=o,d}),ej(c)?console.warn(u?"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 Vc(e,t){const n=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!n||e.transport!=="pty")return e;const r=t[n];return!r||e.mode===r?e:{...e,mode:r}}function sj(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let n=!1;const r=e.map(a=>{const o=Vc(a,t),i=Array.isArray(a.childSessions)?a.childSessions.map(u=>Vc(u,t)):a.childSessions,c=i!==a.childSessions;return o!==a||c?(n=!0,{...o,...c?{childSessions:i}:{}}):a});return n?r:e}function nj(e,t){if(!t)return null;for(const n of e){if(n.sessionId===t&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal";for(const r of n.childSessions||[])if(r.id===t&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal"}return null}function rj({visibleConversations:e,clearedTabs:t,setClearedTabs:n,setActionLogs:r,isConversationMuted:a}){l.useEffect(()=>{Ku()},[]);const o=l.useMemo(()=>e.map(i=>({id:i.tabKey,name:Lp(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null,target:{providerSessionId:i.providerSessionId,sessionId:i.sessionId,tabKey:i.tabKey,routeId:i.routeId},muted:a?a(i):!1})),[e,a]);return Sw(o),l.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{n(u=>{const p=Date.now(),d={};for(const[m,f]of Object.entries(u))p-f<5e3&&(d[m]=f);return Object.keys(d).length===Object.keys(u).length?u:d})},5500);return()=>clearTimeout(c)},[t,n]),l.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;r(u=>{const p=u.filter(d=>d.timestamp>c).slice(-100);return p.length===u.length?u:p})},6e4);return()=>clearInterval(i)},[r]),null}function Yc(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function cn(e){const t=[...e.messages].reverse().find(a=>!(a!=null&&a._localId))||e.messages[e.messages.length-1],n=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,r=Yc(t==null?void 0:t.receivedAt)||Yc(t==null?void 0:t.timestamp)||0;return Math.max(n,r)}function Mi(e,t=0){return cn(e)||e.lastUpdated||t||0}function dm(e){return cn(e)||e.lastUpdated||0}function um(e,t,n=dm){const r=n(t)-n(e);if(r!==0)return r;const a=(e.machineName||"").localeCompare(t.machineName||"");if(a!==0)return a;const o=e.displayPrimary.localeCompare(t.displayPrimary);if(o!==0)return o;const i=e.displaySecondary.localeCompare(t.displaySecondary);return i!==0?i:e.tabKey.localeCompare(t.tabKey)}function Di(e){var n;const t=as(e.status,{activeModal:(n=e.modalButtons)!=null&&n.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function aj(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!Di(e)&&!e.title.trim()}function oj(e){return e.length===0?null:[...e].sort((t,n)=>{const r=Number(Di(n))-Number(Di(t));if(r!==0)return r;const a=n.messages.length-t.messages.length;return a!==0?a:um(t,n)})[0]||null}function bs(e,t){const n=e.filter(i=>i.routeId===t);if(n.length===0)return null;const r=n.find(i=>i.streamSource==="native")||null,a=n.filter(i=>i.streamSource==="agent-stream"),o=oj(a);return r?o&&aj(r)?o:r:o||n[0]||null}function ij(e){const t=e.filter(a=>a.type!=="adhdev-daemon"),n=new Set;for(const a of t){if(!fi(a))continue;const o=Wu(a);o&&n.add(o)}const r=new Map;for(const a of t){const o=ew(a,n),i=r.get(o);if(!i){r.set(o,a);continue}const c=m=>(m.workspace?1:0)+(m.activeChat?1:0)+(m.lastMessagePreview?1:0),u=c(i),p=c(a),d=p>u||p===u&&(a.timestamp||0)>(i.timestamp||0)?a:i;r.set(o,lj(d,d===a?i:a))}return Array.from(r.values())}function lj(e,t){const n=fi(t),r=fi(e);if(!n&&!r)return e;const a=r?n?void 0:t:e,o=r?e:n?t:void 0,i=a&&String(a.daemonId||"").trim()||String(e.ownerDaemonId||"").trim()||String(t.ownerDaemonId||"").trim()||void 0,c=String(e.ownerMachineName||"").trim()||String(t.ownerMachineName||"").trim()||void 0,u=o==null?void 0:o.settings;return{...e,...i&&{ownerDaemonId:i},...c&&!e.ownerMachineName&&{ownerMachineName:c},...u&&!r&&{settings:{...u,...e.settings??{}}}}}function Ao(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function cj(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function Jc(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],n=t[t.length-1],r=n?cj(Rn(n.content)):"";return[e.id||"",e.title||"",e.status||"",t.length,String((n==null?void 0:n.id)||""),String((n==null?void 0:n.index)??""),String((n==null?void 0:n.receivedAt)??(n==null?void 0:n.timestamp)??""),r].join(":")}function dj(e){const t=Array.isArray(e.childSessions)?e.childSessions:[];return[e.id,e.sessionId||"",e.providerSessionId||"",e.transport||"",e.mode||"",e.status||"",e.workspace||"",e.lastMessageHash||"",String(e.lastMessageAt||""),e.lastMessagePreview||"",e.lastMessageRole||"",String(e.lastUpdated||""),Jc(e.activeChat),...t.map(n=>[n.id||"",n.providerSessionId||"",n.transport||"",n.mode||"",n.status||"",n.title||"",n.lastMessageHash||"",String(n.lastMessageAt||""),n.lastMessagePreview||"",n.lastMessageRole||"",String(n.lastUpdated||""),Jc(n.activeChat)].join(":"))].join("|")}function uj(e,t){const n=Date.now();return e.map(r=>{const a=t[r.tabKey];return a&&n-a<5e3?{...r,messages:[],title:""}:r})}function pj(e,t){const n=new Map;for(const r of e){const a=t.get(r.routeId)||r;for(const o of mr({routeId:r.routeId}))n.set(o,a);for(const o of mr({providerSessionId:r.providerSessionId,sessionId:r.sessionId}))n.set(o,r.streamSource==="native"?a:r);for(const o of mr({tabKey:r.tabKey}))n.set(o,r)}return n}function mj(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function hj(e){const t=mj(e);if(!t)return`empty:${e.messages.length}`;if(t.id)return`id:${String(t.id)}`;if(t._localId)return`local:${String(t._localId)}`;const n=String(t.role||""),r=Rn(t.content).slice(0,240);return`${e.messages.length}:${n}:${r}`}function fj({ides:e,connectionStates:t,clearedTabs:n}){const r=l.useMemo(()=>ij(e),[e]),a=l.useMemo(()=>Eu(e),[e]),o=l.useMemo(()=>Gp(e),[e]),i=l.useRef([]),c=l.useRef([]),u=l.useRef([]),p=l.useRef(new Map),d=l.useRef(new Map),m=l.useMemo(()=>{const j=new Map,k=[];for(const A of r){const{connectionState:T="new",machineName:I}=qp(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),P=dj(A),D=p.current.get(A.id);if(D&&D.ide===A&&D.sourceSignature===P&&D.connectionState===T&&D.machineName===I){j.set(A.id,D),k.push(...D.conversations);continue}const _=cl(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),W={ide:A,sourceSignature:P,connectionState:T,machineName:I,conversations:_};j.set(A.id,W),k.push(..._)}p.current=j;const v=new Map,N=A=>{const T=hj(A),I=d.current.get(A.tabKey);if(I&&I.signature===T)return v.set(A.tabKey,I),I.timestamp;const P={signature:T,timestamp:dm(A)||(I==null?void 0:I.timestamp)||0};return v.set(A.tabKey,P),P.timestamp},w=[...k].sort((A,T)=>um(A,T,N));return d.current=v,w},[r,t,o]),f=l.useMemo(()=>{const j=uj(m,n);return Ao(i.current,j)?i.current:(i.current=j,j)},[m,n]),g=l.useMemo(()=>{const j=new Map,k=Array.from(new Set(f.map(v=>v.routeId)));for(const v of k){const N=bs(f,v);N&&j.set(v,N)}return j},[f]),S=l.useMemo(()=>{const j=new Map;for(const k of f){const v=g.get(k.routeId),N=k.streamSource==="native"&&v?v:k;for(const w of mr({providerSessionId:k.providerSessionId,sessionId:k.sessionId,tabKey:k.tabKey}))j.set(w,N)}return j},[f,g]),h=l.useMemo(()=>pj(f,g),[f,g]),x=l.useCallback(j=>{if(j)return S.get(j)},[S]),y=l.useCallback(j=>{if(j)return h.get(j)},[h]),b=l.useMemo(()=>{const j=f.filter(k=>!Gs(k,a).surfaceHidden);return Ao(c.current,j)?c.current:(c.current=j,j)},[f,a]),C=l.useMemo(()=>{const j=b.map(k=>k.tabKey);return Ao(u.current,j)?u.current:(u.current=j,j)},[b]);return{chatIdes:r,conversations:f,visibleConversations:b,visibleTabKeys:C,resolveConversationBySessionId:x,resolveConversationByTarget:y}}function bj({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:n,setSearchParams:r}){const a=l.useMemo(()=>{var c;return e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),o=l.useMemo(()=>{var c;return!e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),i=l.useCallback(()=>{t&&r(c=>{const u=new URLSearchParams(c);return u.delete("activeTab"),u},{replace:!0})},[r,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:o,consumeRequestedActiveTab:i}}function gj({ides:e,sendDaemonCommand:t,setToasts:n,resolveConversationByTarget:r}){l.useEffect(()=>{ft.setIdes(e)},[e]),l.useEffect(()=>{ft.setResolveAction((a,o,i)=>{t(a,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const a=ft.onToast(o=>{n(c=>c.some(p=>p.message===o.message&&o.timestamp-p.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 i=o.duration||5e3;setTimeout(()=>n(c=>c.filter(u=>u.id!==o.id)),i)});return()=>{a()}},[n]),l.useEffect(()=>{const a=Mp.on("status_event",o=>{ft.handleRawEvent(o,"ws")});return()=>{a()}},[]),l.useEffect(()=>{var o;const a=i=>{var h;const c=i.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 u=c.targetSessionId||c.targetKey||c.daemonId,p=r(u),d=(p==null?void 0:p.routeId)||c.daemonId;if(!d)return;const m=Number(c.buttonIndex),f=c.button||((h=p==null?void 0:p.modalButtons)==null?void 0:h[m])||"Approve",g=String(f).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),S=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(g);t(d,"resolve_action",{action:S?"approve":"reject",button:f,...Number.isFinite(m)&&{buttonIndex:m},...(p==null?void 0:p.sessionId)&&{targetSessionId:p.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(x=>console.error("[SW Action] approval failed:",x))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",a),()=>{var i;return(i=navigator.serviceWorker)==null?void 0:i.removeEventListener("message",a)}},[r,t])}const xj="adhdev_dashboardLayout_v1",vj="adhdev_dashboardDockview_v1",yj="adhdev_dashboardDockviewHiddenRestore_v1",tr={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function hl(e,t){try{const n=localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}}function wj(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function pm(e){return`${xj}:${e}`}function kj(e){const t=pm(e);return hl(t,null)}function Sj(e,t){try{const n=t.groupAssignments.length===0&&t.focusedGroup===0&&Object.keys(t.groupActiveTabIds).length===0&&Object.keys(t.groupTabOrders).length===0&&t.groupSizes.length===0,r=pm(e);if(n){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function mm(e){return`${vj}:${e}`}function Cj(e){const t=mm(e);return hl(t,null)}function jj(e,t){try{const n=mm(e);if(!t){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function hm(e){return`${yj}:${e}`}function Nj(e){const t=hm(e);return hl(t,{})}function Aj(e,t){try{const n=hm(e);if(Object.keys(t).length===0){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Tj(){return{groupAssignments:[...tr.groupAssignments],focusedGroup:tr.focusedGroup,groupActiveTabIds:{...tr.groupActiveTabIds},groupTabOrders:{...tr.groupTabOrders},groupSizes:[...tr.groupSizes]}}function Mj(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):t.length===0}function Dj(){const[e]=l.useState(()=>wj(typeof window<"u"?window.innerWidth:1280)),[t,n]=l.useState(()=>new Map),[r,a]=l.useState(0),[o,i]=l.useState({}),[c,u]=l.useState({}),[p,d]=l.useState([]),[m,f]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[g,S]=l.useState(!1),h=l.useCallback(()=>{if(g)return;const A=kj(e)??Tj();n(new Map(A.groupAssignments)),a(A.focusedGroup),i(A.groupActiveTabIds),u(A.groupTabOrders),d(A.groupSizes),S(!0)},[g,e]);l.useEffect(()=>{g&&Sj(e,{groupAssignments:[...t.entries()],focusedGroup:r,groupActiveTabIds:o,groupTabOrders:c,groupSizes:p})},[g,e,t,r,o,c,p]),l.useEffect(()=>{const A=window.matchMedia("(max-width: 767px)"),T=I=>f(I.matches);return A.addEventListener("change",T),()=>A.removeEventListener("change",T)},[]);const x=l.useCallback(A=>{n(A)},[]),y=l.useCallback(A=>{a(A)},[]),b=l.useCallback(A=>{i(A)},[]),C=l.useCallback(A=>{u(A)},[]),j=l.useCallback(A=>{d(A)},[]),k=l.useCallback(A=>{y(A)},[y]),v=l.useCallback((A,T)=>{i(I=>(I[A]??null)===(T??null)?I:{...I,[A]:T})},[]),N=l.useCallback((A,T)=>{u(I=>{const P=I[A];return Mj(P,T)?I:{...I,[A]:T}})},[]),w=l.useCallback((A,T)=>{const I=T.get(A)??0;return v(I,A),k(I),I},[k,v]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:x,focusedGroup:r,updateFocusedGroup:y,focusGroup:k,groupActiveTabIds:o,updateGroupActiveTabIds:b,setGroupActiveTab:v,groupTabOrders:c,updateGroupTabOrders:C,setGroupTabOrder:N,groupSizes:p,updateGroupSizes:j,isMobile:m,hasHydratedStoredLayout:g,hydrateStoredLayout:h,focusConversationTab:w}}function Ij(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0],r=Oa(t);return typeof(n==null?void 0:n.id)=="string"&&r.includes(n.id)}function Pj({urlActiveTab:e,conversations:t,resolveConversationBySessionId:n,normalizedGroupAssignments:r,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:i,setSearchParams:c,historyModalOpen:u,activeConv:p,isRefreshingHistory:d,ides:m,handleRefreshHistory:f}){const g=l.useRef(!1),S=l.useRef(!1),h=l.useRef(null),x=l.useRef(!1);l.useEffect(()=>{if(!e||g.current||t.length===0)return;if(!a){o();return}const y=n(e);y&&(i(y.tabKey,r),g.current=!0,S.current=!0,h.current!=null&&(window.clearTimeout(h.current),h.current=null),c(b=>{const C=new URLSearchParams(b);return C.delete("activeTab"),C},{replace:!0}))},[e,t,n,r,a,o,i,c]),l.useEffect(()=>{if(!(S.current||a)&&t.length!==0){if(!e){o(),S.current=!0;return}if(g.current){S.current=!0;return}if(h.current==null)return h.current=window.setTimeout(()=>{h.current=null,!(S.current||a)&&(o(),S.current=!0)},1500),()=>{h.current!=null&&(window.clearTimeout(h.current),h.current=null)}}},[e,t.length,a,o]),l.useEffect(()=>{if(!u){x.current=!1;return}if(!p||x.current||d)return;const y=m.find(b=>b.id===p.routeId);y&&(!y.chats||y.chats.length===0||Ij(y.chats,p))&&(x.current=!0,f())},[u,p,d,m,f])}function To(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0];if((n==null?void 0:n.active)===!0)return!0;const r=Oa(t);return typeof(n==null?void 0:n.id)=="string"&&r.includes(n.id)}function fm({sendDaemonCommand:e,activeConv:t,chats:n,updateRouteChats:r,setToasts:a,setClearedTabs:o}){const[i,c]=l.useState(!1),[u,p]=l.useState(!1),d=l.useCallback(async S=>{try{await e("standalone","launch_ide",{ideType:S,enableCdp:!0})}catch(h){console.error("Launch failed",h)}},[e]),m=l.useCallback(async(S,h)=>{try{const x=S||(t==null?void 0:t.daemonId)||"",y=await e(x,"switch_chat",{id:h,sessionId:h,...nn(t)}),b=y==null?void 0:y.result;if((y==null?void 0:y.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?Cn(a,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?Cn(a,`⚠️ Switch error: ${b}`):Cn(a,"⚠️ Session switch failed")}catch(x){console.error("Switch failed",x),Cn(a,`❌ Switch failed: ${x.message||"connection error"}`)}},[t,e,a]),f=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const S=rn(t);await e(S,"new_chat",{...nn(t)}),xk(S,t.sessionId,Oa(t)[0]),o(h=>({...h,[t.tabKey]:Date.now()}))}catch(S){console.error("New chat failed",S)}finally{c(!1)}}},[t,i,e,o]),g=l.useCallback(async()=>{var S,h;if(!(!t||u)){p(!0);try{const x=rn(t),y=async()=>e(x,"list_chats",{forceExpand:!0,...nn(t)});let b=await y(),C=(b==null?void 0:b.chats)||((S=b==null?void 0:b.result)==null?void 0:S.chats);To(C,t)&&(await new Promise(j=>setTimeout(j,450)),b=await y(),C=(b==null?void 0:b.chats)||((h=b==null?void 0:b.result)==null?void 0:h.chats)),b!=null&&b.success&&Array.isArray(C)&&(r(t.routeId,C),To(C,t)&&!To(n,t)&&Cn(a,"⚠️ History dialog did not fully open — try once more"))}catch(x){console.error("Refresh history failed",x)}finally{p(!1)}}},[t,n,u,e,r,a]);return{isCreatingChat:i,isRefreshingHistory:u,handleLaunchIde:d,handleSwitchSession:m,handleNewChat:f,handleRefreshHistory:g}}function Lj(e,t){if(e.size!==t.size)return!1;for(const[n,r]of e)if(t.get(n)!==r)return!1;return!0}function Rj(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function Qc(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(a=>t[Number(a)]===e[Number(a)])}function qr(e,t){const n=new Set(t),r=t.length>0?[0]:[];for(const[i,c]of e)!n.has(i)||c<=0||r.includes(c)||r.push(c);r.sort((i,c)=>i-c);const a={};r.forEach((i,c)=>{a[i]=c}),r.length===0&&(a[0]=0);const o=new Map;for(const[i,c]of e){if(!n.has(i)||c<=0)continue;const u=a[c];typeof u=="number"&&u>0&&o.set(i,u)}return{assignments:o,groupCount:Math.max(1,r.length),mapping:a,usedGroups:r}}function Xc(e,t){const n={};for(const[r,a]of Object.entries(e)){const o=t[Number(r)];typeof o=="number"&&(n[o]=a)}return n}function Ej(e,t,n){if(t.length===0)return 0;if(typeof n[e]=="number")return n[e];const r=[...t].reverse().find(a=>a<e)??t[0];return n[r]??0}function _j(e,t,n){if(t.length<=1)return[];const r=t.map(i=>e[i]).filter(i=>Number.isFinite(i)),a=r.length===t.length?r:Array(n).fill(100/n),o=a.reduce((i,c)=>i+c,0);return o>0?a.map(i=>i/o*100):Array(n).fill(100/n)}function Zc(e,t){const n={};for(const[r,a]of Object.entries(e)){const o=Number(r);n[o>=t?o+1:o]=a}return n}function ed(e){return Array(e).fill(100/e)}function $j({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:n,updateGroupActiveTabIds:r,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:i,isMobile:c,visibleConversations:u,visibleTabKeys:p}){const d=l.useRef(null),m=l.useMemo(()=>qr(e,p),[e,p]),f=m.assignments,g=l.useMemo(()=>c?1:m.groupCount,[m.groupCount,c]),S=g>1,h=l.useCallback((k,v)=>{t(N=>{const w=new Map(qr(N,p).assignments);return v===0?w.delete(k):w.set(k,v),w}),r(N=>({...N,[v]:k})),n(v)},[t,p,r,n]),x=l.useCallback(k=>{t(v=>{const N=qr(v,p).assignments,w=new Map;for(const[A,T]of N)T!==k&&(T>k?w.set(A,T-1):w.set(A,T));return w}),i(v=>{if(v.length<=1)return[];const N=[...v];N.splice(k,1);const w=N.reduce((A,T)=>A+T,0);return w>0?N.map(A=>A/w*100):[]}),n(0)},[t,p,i,n]),y=l.useCallback((k,v)=>{v.preventDefault();const N=d.current;if(!N)return;const w=v.clientX,A=N.offsetWidth,T=o.length===g?[...o]:ed(g),I=D=>{const W=(D.clientX-w)/A*100,$=[...T];$[k]=Math.max(15,T[k]+W),$[k+1]=Math.max(15,T[k+1]-W),i($)},P=()=>{document.removeEventListener("mousemove",I),document.removeEventListener("mouseup",P),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",I),document.addEventListener("mouseup",P)},[o,g,i]),b=l.useCallback((k,v,N)=>{if(g>=4)return;const w=N==="left"?v:v+1;t(A=>{const T=qr(A,p).assignments,I=new Map;for(const P of u){const D=T.get(P.tabKey)??0,_=D>=w?D+1:D;_>0&&I.set(P.tabKey,_)}return w>0&&I.set(k,w),I}),i(A=>{const T=A.length===g?[...A]:ed(g),I=T[v]??100/g,P=Math.max(15,I/2),D=Math.max(15,I/2),_=[...T];_[v]=P,_.splice(w,0,D);const W=_.reduce(($,E)=>$+E,0);return _.map($=>$/W*100)}),r(A=>{const T=Zc(A,w);return T[w]=k,T}),a(A=>{const T=Zc(A,w);return T[w]=[k],T}),n(w)},[g,t,p,u,i,r,a,n]);l.useEffect(()=>{Lj(e,f)||t(f)},[e,f,t]),l.useEffect(()=>{const{mapping:k,usedGroups:v}=m;r(N=>{const w=Xc(N,k);return Qc(N,w)?N:w}),a(N=>{const w=Xc(N,k);return Qc(N,w)?N:w}),n(N=>{const w=c?0:Ej(N,v,k);return N===w?N:w}),i(N=>{const w=c?[]:_j(N,v,m.groupCount);return Rj(N,w)?N:w})},[m,c,r,a,n,i]);const C=l.useMemo(()=>{const k=Array.from({length:g},()=>[]);for(const v of u){const N=f.get(v.tabKey)??0,w=Math.min(N,g-1);k[w].push(v)}return k},[u,f,g]),j=l.useCallback(()=>{t(new Map),n(0)},[t,n]);return{containerRef:d,normalizedGroupAssignments:f,numGroups:g,isSplitMode:S,groupedConvs:C,moveTabToGroup:h,closeGroup:x,handleResizeStart:y,splitTabRelative:b,clearAllSplits:j}}function Hj({ides:e,sendDaemonCommand:t}){const n="1.0.29",r=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:Ja(m,$s(m,n))).sort((m,f)=>Number(br(f,$s(f,n)))-Number(br(m,$s(m,n)))),[n,e]),a=l.useMemo(()=>r.some(m=>br(m,$s(m,n))),[n,r]),o=l.useMemo(()=>r.map(m=>$s(m,n)).find(m=>typeof m=="string"&&m.trim().length>0)||n,[n,r]),[i,c]=l.useState(!1),[u,p]=l.useState({}),d=l.useCallback(async m=>{var S,h;const f=e.find(x=>x.id===m);if(!f)return;p(x=>({...x,[m]:"upgrading"}));const g=Qa(f);if(!g){p(x=>({...x,[m]:"error"}));return}try{const x=await t(m,"daemon_upgrade",g);(S=x==null?void 0:x.result)!=null&&S.upgraded||(h=x==null?void 0:x.result)!=null&&h.success?p(y=>({...y,[m]:"done"})):p(y=>({...y,[m]:"error"}))}catch{p(x=>({...x,[m]:"error"}))}},[e,t]);return{versionMismatchDaemons:r,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:u,handleBannerUpgrade:d}}const bm=80;function ca(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function Fj(e){return{...e,createdAt:ca(e.createdAt),updatedAt:ca(e.updatedAt,e.createdAt),lastEventAt:ca(e.lastEventAt,e.updatedAt||e.createdAt)}}function Bj(e){const t=Bu(e);return t==="unknown:"?e.id:t}function Wj(e){return[e.type,Fu(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Oj(e,t=bm){const n=new Map;for(const r of e){if(r.deletedAt)continue;const a=Bj(r),o=n.get(a);if(!o){n.set(a,r);continue}(r.updatedAt>o.updatedAt||r.updatedAt===o.updatedAt&&r.createdAt>o.createdAt)&&n.set(a,r)}return Array.from(n.values()).sort((r,a)=>{const o=a.updatedAt-r.updatedAt;return o!==0?o:a.createdAt-r.createdAt}).slice(0,Math.max(0,t))}function Uj(e,t){const n=Date.now(),r=[];for(const a of e){const o=a.sessionId?t.get(a.sessionId):void 0;if(o!=null&&o.surfaceHidden||o!=null&&o.muted)continue;const i=Wa(a,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const u=ca(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,n),p=Wj({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});r.push(Fj({id:p,dedupKey:p,type:c,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:op(a),preview:D0(a),createdAt:u,updatedAt:u,lastEventAt:u}))}return Oj(r)}function Gj(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function qj(e){const{conversations:t,liveSessionInboxState:n,maxItems:r=bm}=e,a=l.useMemo(()=>Uj(t,n).slice(0,Math.max(0,r)),[t,n,r]),o=l.useMemo(()=>Gj(a),[a]);return{notifications:a,unreadCount:o}}function zj({notifications:e,sendDaemonCommand:t}){const n=l.useCallback(o=>{const i=e.find(u=>u.id===o),c=Math.max(Date.now(),(i==null?void 0:i.updatedAt)||0);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_session_seen",{sessionId:i.sessionId,seenAt:c}).catch(()=>{})},[e,t]),r=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_notification_unread",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]),a=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"delete_notification",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:n,handleMarkDashboardNotificationUnread:r,handleDeleteDashboardNotification:a}}function fl(...e){const t=new Set,n=[],r=a=>{const o=typeof a=="string"?a.trim():"";if(!o)return;const i=o.toLowerCase();t.has(i)||(t.add(i),n.push(o))};for(const a of e){if(Array.isArray(a)){for(const o of a)r(o);continue}r(a)}return n}function Kj(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const n=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(n){const r=n[1].toUpperCase(),a=(n[2]||"").replace(/[\\/]+/g,"\\");return a?`${r}:\\${a}`:`${r}:\\`}return null}function bl(e,t=[]){if(e==="win32"){for(const n of t){if(typeof n!="string")continue;const r=Kj(n);if(r)return r}return"C:\\"}for(const n of t){const r=typeof n=="string"?n.trim():"";if(r)return r}return"~"}function Vj(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const n=t.includes("\\")?"\\":"/",r=t.split(/[\\/]/);return/^[A-Za-z]:$/.test(r[0]||"")?r.length<=2?`${r[0]}\\`:r.slice(0,-1).join("\\"):r.length<=2?n:r.slice(0,-1).join(n)||n}function Yj(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function gl(e,t,n){const r=await e(t,"file_list_browse",{path:n}),a=Yj(r);if(!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||(r==null?void 0:r.error)||"Could not browse folder");const o=typeof(a==null?void 0:a.path)=="string"?a.path:n,i=o.includes("\\")?"\\":"/",c=(p,d)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${d}`:p==="/"||p==="\\"?`${i}${d}`:`${p.replace(/[\\/]+$/,"")}${i}${d}`,u=Array.isArray(a==null?void 0:a.files)?a.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:typeof(p==null?void 0:p.path)=="string"&&p.path.trim()?p.path:c(o,p.name)})).sort((p,d)=>p.name.localeCompare(d.name)):[];return{path:o,directories:u}}function td(e,t){const n=t.meshId||"",r={meshId:n,workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp",adhdevMcpArgs:t.adhdevMcpArgs||`mcp --mode ipc --repo-mesh ${n}`};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand|adhdevMcpArgs)\s*\}\}/g,(a,o)=>r[o]||"")}function gm(e,t={}){const n=e==null?void 0:e.mcpConfig;if((n==null?void 0:n.mode)!=="manual")return null;const a=td(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"}).trim();return!a.includes(`
70
- `)&&!a.startsWith("{")?null:{serverName:n.serverName||"adhdev-mesh",configFormat:n.format,configPathCommand:n.configPathCommand,requiresRestart:n.requiresRestart===!0,instructions:n.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:td(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"})}}function Jj(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.instructions=="string"?t.instructions:"",r=typeof t.template=="string"?t.template:"";return!n&&!r?null:{serverName:typeof t.serverName=="string"?t.serverName:void 0,configFormat:typeof t.configFormat=="string"?t.configFormat:void 0,configPathCommand:typeof t.configPathCommand=="string"?t.configPathCommand:void 0,requiresRestart:t.requiresRestart===!0,instructions:n||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:r}}function Nr(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function xm(e){return Ua(e)||e.tabKey||e.routeId||null}function vm(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",n=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",r=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",a=e.conversations.find(o=>{if(r&&o.routeId!==r)return!1;const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey].map(c=>typeof c=="string"?c.trim():"").filter(Boolean);return!!(t&&i.includes(t)||n&&i.includes(n)||r&&o.routeId===r)});if(a!=null&&a.tabKey)return a.tabKey;if(r){const o=bs(e.conversations,r)||e.conversations.find(i=>i.routeId===r);if(o!=null&&o.tabKey)return o.tabKey}return t||n||r||null}function Hs(e){return String(e||"").trim()}function ym(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Pa(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Qj(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function Xj(e,t){const n=Hs(e.providerSessionId),r=Hs(e.targetSessionId),a=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(Hs).filter(Boolean);return!!(n&&i.includes(n)||r&&i.includes(r))});return a?a.tabKey:r||n||null}function Zj(e,t,n){if(t.event!=="agent:generating_completed")return null;const r=ym(t.daemonId);if(r&&r!==e.machineId)return null;const a=Hs(t.providerType);if(e.providerType&&a!==e.providerType)return null;const o=Hs(e.resumeSessionId),i=Hs(e.launchedSessionId),c=Hs(t.providerSessionId),u=Hs(t.targetSessionId);if(o&&o!==c&&o!==u||i&&i!==c&&i!==u)return null;const p=Pa(e.workspacePath);if(p){const d=Pa(t.workspaceName);if(d&&!Qj(d,p))return null}return Xj(t,n)}function sd(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function e1({ides:e,conversations:t,onOpenSession:n}){const[r,a]=l.useState(null),o=l.useRef(null),i=l.useCallback(()=>{o.current=null,a(null)},[]),c=l.useCallback(u=>{o.current=u,a(u)},[]);return l.useEffect(()=>{if(!r)return;const u=Pa(r.workspacePath),p=e.find(m=>{var x,y,b,C;if(!m||m.type==="adhdev-daemon"||ym(m.daemonId||m.id)!==r.machineId||(Sr(m)?"cli":Dn(m)?"acp":"ide")!==r.kind)return!1;const S=String(m.agentType||m.type||"");if(r.providerType&&S!==r.providerType)return!1;if(r.resumeSessionId)return String(m.providerSessionId||"")===r.resumeSessionId;if(r.launchedSessionId){const j=String(r.launchedSessionId||"");return[m.providerSessionId,m.sessionId,m.instanceId,m.id].map(v=>String(v||"")).filter(Boolean).includes(j)}if(u){const j=Pa(m.workspace||m.runtimeWorkspaceLabel);return j?j===u:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((C=(b=(y=(x=m.activeChat)==null?void 0:x.messages)==null?void 0:y.at)==null?void 0:b.call(y,-1))==null?void 0:C.timestamp)||0)>=r.startedAt-5e3});if(!p)return;const d=vm({entrySessionId:p.sessionId,entryInstanceId:p.instanceId,entryRouteId:p.id,conversations:t});d&&(i(),n(d))},[i,t,e,n,r]),l.useEffect(()=>ft.onStatusEvent(u=>{const p=o.current;if(!p)return;const d=Zj(p,u,t);d&&(i(),n(d))}),[i,t,n]),l.useEffect(()=>{if(!r)return;const u=window.setTimeout(()=>{a(p=>!p||p.startedAt!==r.startedAt?p:(o.current=null,null))},45e3);return()=>window.clearTimeout(u)},[r]),{trackPendingLaunch:c}}function t1(e,t){var r,a,o,i;const n={cliType:e};return(r=t==null?void 0:t.workspacePath)!=null&&r.trim()?n.dir=t.workspacePath.trim():t!=null&&t.workspaceId?n.workspaceId=t.workspaceId:t!=null&&t.useHome&&(n.useHome=!0),(a=t==null?void 0:t.resumeSessionId)!=null&&a.trim()&&(n.resumeSessionId=t.resumeSessionId.trim()),Array.isArray(t==null?void 0:t.cliArgs)&&t.cliArgs.length>0&&(n.cliArgs=t.cliArgs),(o=t==null?void 0:t.initialModel)!=null&&o.trim()&&(n.initialModel=t.initialModel.trim()),(i=t==null?void 0:t.initialThinkingLevel)!=null&&i.trim()&&(n.initialThinkingLevel=t.initialThinkingLevel.trim()),t!=null&&t.settings&&(n.settings=t.settings),n}function s1({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:n,activeConv:r,ides:a,setCliViewModeOverrides:o}){const i=el(),{launchCli:c}=$a(),u=l.useCallback(async(x,y)=>gl(e,x,y),[e]),p=l.useCallback(async(x,y)=>{if(!y.trim())return{ok:!1,error:"Choose a workspace path first."};try{const b=await e(x,"workspace_add",{path:y.trim()});return b!=null&&b.success?{ok:!0}:{ok:!1,error:(b==null?void 0:b.error)||"Could not save workspace"}}catch(b){return{ok:!1,error:b instanceof Error?b.message:"Could not save workspace"}}},[e]),d=l.useCallback(async(x,y,b)=>{var C;try{const j={ideType:y,enableCdp:!0};(C=b==null?void 0:b.workspacePath)!=null&&C.trim()&&(j.workspace=b.workspacePath.trim());const k=await e(x,"launch_ide",j);return!(k!=null&&k.success)&&(k==null?void 0:k.success)!==void 0?{ok:!1,error:(k==null?void 0:k.error)||"Could not launch IDE"}:(t({machineId:x,kind:"ide",providerType:y,workspacePath:(b==null?void 0:b.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(j){return{ok:!1,error:j instanceof Error?j.message:"Could not launch IDE"}}},[e,t]),m=l.useCallback(async(x,y,b,C)=>{const j=Date.now();try{const k=t1(b,C),v=await c(x,k),N=(v==null?void 0:v.result)||v,w=(N==null?void 0:N.sessionId)||(N==null?void 0:N.id);return v!=null&&v.success&&w?(t({machineId:x,kind:y,providerType:b,workspacePath:(C==null?void 0:C.workspacePath)||null,resumeSessionId:(C==null?void 0:C.resumeSessionId)||null,launchedSessionId:w,startedAt:j}),{ok:!0}):v!=null&&v.success?(t({machineId:x,kind:y,providerType:b,workspacePath:(C==null?void 0:C.workspacePath)||null,resumeSessionId:(C==null?void 0:C.resumeSessionId)||null,startedAt:j}),{ok:!0}):{ok:!1,error:(v==null?void 0:v.error)||(N==null?void 0:N.error)||`Could not launch ${y.toUpperCase()} session`,code:(v==null?void 0:v.code)||(N==null?void 0:N.code)||void 0}}catch(k){return sd(k)?(t({machineId:x,kind:y,providerType:b,workspacePath:(C==null?void 0:C.workspacePath)||null,resumeSessionId:(C==null?void 0:C.resumeSessionId)||null,startedAt:j}),{ok:!0}):{ok:!1,error:k instanceof Error?k.message:`Could not launch ${y.toUpperCase()} session`}}},[c,e,t]),f=l.useCallback(async x=>{var y;if(i!=null&&i.listMeshes)return i.listMeshes(x);if(!x)return[];try{const b=await e(x,"list_meshes",{}),C=(b==null?void 0:b.result)??b;if((C==null?void 0:C.success)===!1)throw new Error((C==null?void 0:C.error)||"Could not load meshes");return(Array.isArray(C==null?void 0:C.meshes)?C.meshes:Array.isArray((y=C==null?void 0:C.result)==null?void 0:y.meshes)?C.result.meshes:[]).map(k=>{var v;return{id:String((k==null?void 0:k.id)||""),name:String((k==null?void 0:k.name)||(k==null?void 0:k.id)||"Untitled mesh"),repoIdentity:(k==null?void 0:k.repoIdentity)||(k==null?void 0:k.repo_identity)||null,workspace:Array.isArray(k==null?void 0:k.nodes)&&k.nodes.length>0?String(((v=k.nodes[0])==null?void 0:v.workspace)||""):null,nodesCount:Array.isArray(k==null?void 0:k.nodes)?k.nodes.length:void 0,status:(k==null?void 0:k.status)||null}}).filter(k=>k.id)}catch(b){throw console.error("List meshes failed",b),b}},[i,e]),g=l.useCallback(async(x,y,b,C)=>{var k,v;if(!y.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(x,y,b,C);const j=Date.now();try{const N={meshId:y.trim()};b.trim()&&(N.cliType=b.trim());const w=(k=C==null?void 0:C.initialModel)==null?void 0:k.trim(),A=(v=C==null?void 0:C.initialThinkingLevel)==null?void 0:v.trim();w&&(N.initialModel=w),A&&(N.initialThinkingLevel=A);const T=await e(x,"launch_mesh_coordinator",N),I=(T==null?void 0:T.result)??T;if((I==null?void 0:I.success)===!1||(T==null?void 0:T.success)===!1){const D=String((I==null?void 0:I.code)||(T==null?void 0:T.code)||""),_=Jj((I==null?void 0:I.meshCoordinatorSetup)||(I==null?void 0:I.manualSetup)||(T==null?void 0:T.meshCoordinatorSetup)||(T==null?void 0:T.manualSetup));return{ok:!1,error:(I==null?void 0:I.error)||(T==null?void 0:T.error)||"Could not launch mesh coordinator",code:D||void 0,manualSetup:_}}const P=(I==null?void 0:I.sessionId)||(I==null?void 0:I.id);return P?n(P):t({machineId:x,kind:"cli",providerType:(I==null?void 0:I.cliType)||b.trim()||void 0,workspacePath:(I==null?void 0:I.workspace)||null,startedAt:j}),{ok:!0}}catch(N){return sd(N)?(t({machineId:x,kind:"cli",providerType:b.trim()||void 0,startedAt:j}),{ok:!0}):{ok:!1,error:N instanceof Error?N.message:"Could not launch mesh coordinator"}}},[i,n,e,t]),S=l.useCallback(async(x,y)=>{if(!x||!y)return[];try{const b=await e(x,"list_saved_sessions",{providerType:y,kind:"cli",limit:30}),C=(b==null?void 0:b.result)??b;return Array.isArray(C==null?void 0:C.sessions)?C.sessions:[]}catch(b){return console.error("List saved sessions failed",b),[]}},[e]),h=l.useCallback(async x=>{await cm({conversation:r,mode:x,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[r,a,e,o]);return{handleBrowseMachineDirectory:u,handleSaveMachineWorkspace:p,handleLaunchMachineIde:d,handleLaunchMachineProvider:m,handleListMachineMeshes:f,handleLaunchMeshCoordinator:g,handleListMachineSavedSessions:S,setActiveCliViewMode:h}}function n1(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 r1(e,t,n=Date.now()){return!e||!n1(t)?null:{tabKey:e,nonce:n}}function a1({isMobile:e,conversations:t,visibleConversations:n,groupActiveTabIds:r,focusedGroup:a,groupedConvs:o,setSearchParams:i}){const[c,u]=l.useState(null),[p,d]=l.useState(null),m=l.useMemo(()=>{var x,y;if(!e){if(c){const b=t.find(C=>C.tabKey===c);if(b)return b}return n[0]}const h=r[a];if(h){const b=t.find(C=>C.tabKey===h);if(b)return b}return((x=o[a])==null?void 0:x[0])||((y=o[0])==null?void 0:y[0])},[t,c,a,r,o,e,n]),f=l.useCallback(h=>{u(h)},[]),g=l.useCallback(h=>{u(h.tabKey),i(x=>{const y=new URLSearchParams(x),b=P0(h);return b?y.set("activeTab",b):y.delete("activeTab"),y},{replace:!0})},[i]),S=l.useCallback((h,x)=>{const y=r1(h,x);y&&d(y)},[]);return{activeConv:m,openDesktopConversation:g,requestScrollToBottom:S,scrollToBottomRequest:p,setDesktopActiveTab:f}}function o1(e){const t=e.completedKey||null,n=e.pendingKey||null;return e.shouldMarkSeen?t===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:n!==null&&n!==e.autoReadKey,nextPendingKey:n===e.autoReadKey?n:null}:n===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:!1,nextPendingKey:n}:{shouldSchedule:!0,shouldCancelPending:n!==null&&n!==e.autoReadKey,nextPendingKey:e.autoReadKey}:{shouldSchedule:!1,shouldCancelPending:!!n,nextPendingKey:null}}function i1(e){const t=String(e.liveState.completionMarker||""),n=String(e.liveState.seenCompletionMarker||""),r=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,o=[e.tabKey,e.historySessionId||"",t,n,r,a?"1":"0"].join(":");return{shouldMarkSeen:!!(r==="task_complete"&&a&&(!t||t!==n)),autoReadKey:o,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function l1({activeConv:e,isMobile:t,liveSessionInboxState:n,sendDaemonCommand:r}){const a=l.useRef(null),o=l.useRef(null),i=l.useRef(null),c=l.useRef(null),u=l.useRef(null);l.useEffect(()=>{const p=()=>{i.current&&(clearTimeout(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null),o.current=null};if(t){p(),a.current=null;return}if(!(e!=null&&e.sessionId)){p(),a.current=null;return}const d=Gs(e,n),m=i1({tabKey:e.tabKey,historySessionId:Ua(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:cn(e),liveState:d}),f=m.autoReadKey,g=o1({autoReadKey:f,shouldMarkSeen:m.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!m.shouldMarkSeen){g.shouldCancelPending&&p(),a.current=f;return}if(!g.shouldSchedule)return;g.shouldCancelPending&&p();const S=()=>{if(document.visibilityState!=="visible"||a.current===f)return;a.current=f,o.current=null,i.current=null,c.current=null,u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null);const x=m.readAt;r(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:x,completionMarker:m.completionMarker}).catch(()=>{})};if(o.current=g.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(S,1500);const x=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};u.current=x,document.addEventListener("visibilitychange",x);return}const h=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(S,800),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null))};u.current=h,document.addEventListener("visibilitychange",h)},[e,t,n,r]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),u.current&&document.removeEventListener("visibilitychange",u.current)},[])}function Mo(e){if(!e)return"";const t=String(e.workspacePath||"").trim();if(t)return t;const n=String(e.workspaceName||"").trim();return/^(?:~\/|\/|[A-Za-z]:[\\/])/.test(n)?n:""}function c1({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:n,ides:r,sendDaemonCommand:a,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:u}){var B;const{launchCli:p}=$a(),[d,m]=l.useState(!1),[f,g]=l.useState([]),[S,h]=l.useState(()=>qt()),[x,y]=l.useState(!1),[b,C]=l.useState(null),j=l.useRef(null),k=l.useMemo(()=>n||t||e,[e,n,t]),v=!!k&&ht(k)&&!pt(k),N=l.useMemo(()=>{if(!k||!v)return null;const L=k.daemonId||k.routeId||"",R=Ns(k),M=Mo(k);return`${L}:${R}:${k.providerSessionId||""}:${M}`},[k,v]),w=l.useMemo(()=>!k||!v?"":Mo(k),[k,v]),{isCreatingChat:A,isRefreshingHistory:T,handleSwitchSession:I,handleNewChat:P,handleRefreshHistory:D}=fm({sendDaemonCommand:a,activeConv:k,chats:(B=r.find(L=>L.id===(k==null?void 0:k.routeId)))==null?void 0:B.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),_=l.useCallback(()=>{m(!0)},[]),W=l.useCallback(()=>{m(!1)},[]),$=l.useCallback(async()=>{if(!(!k||!v||x)){y(!0);try{const L=k.daemonId||k.routeId,R=Ns(k),M=Mo(k),F=await a(L,"list_saved_sessions",{agentType:R,providerType:R,kind:"cli",limit:50,...k.providerSessionId?{providerSessionId:k.providerSessionId}:{},...M?{workspace:M}:{}}),K=(F==null?void 0:F.result)??F;g(Array.isArray(K==null?void 0:K.sessions)?K.sessions:[])}catch(L){console.error("Refresh saved sessions failed",L),g([])}finally{y(!1)}}},[k,x,v,a]);l.useEffect(()=>{if(!d){j.current=null;return}if(!v){j.current=null,g([]),y(!1);return}!N||x||j.current!==N&&(j.current=N,$())},[$,d,x,v,N]);const E=l.useCallback(async L=>{if(!k||!v||!L.providerSessionId||!L.workspace)return;const R=k.daemonId||k.routeId,M=Ns(k);try{C(L.providerSessionId);const F=await p(R,{cliType:M,dir:L.workspace,resumeSessionId:L.providerSessionId,initialModel:qu(L.summaryMetadata,"model",{preferShortValue:!0})||void 0}),K=(F==null?void 0:F.result)??F,J=typeof(K==null?void 0:K.sessionId)=="string"?K.sessionId:typeof(K==null?void 0:K.id)=="string"?K.id:"";J&&u(V=>{const Y=new URLSearchParams(V);return Y.set("activeTab",J),Y},{replace:!0}),W()}catch(F){console.error("Resume saved session failed",F)}finally{C(null)}},[W,k,v,a,u]);return{historyModalOpen:d,openHistoryModal:_,closeHistoryModal:W,historyTargetConv:k,isSavedSessionHistoryTarget:v,isHistoryCreatingChat:A,isHistoryRefreshingHistory:T,handleHistorySwitchSession:I,handleHistoryNewChat:P,handleHistoryRefresh:D,savedHistorySessions:f,savedHistoryFilters:S,setSavedHistoryFilters:h,missingWorkspaceResumePath:w,isSavedHistoryLoading:x,resumingSavedHistorySessionId:b,handleRefreshSavedHistory:$,handleResumeSavedHistorySession:E}}function d1({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}){const[u,p]=l.useState(null),[d,m]=l.useState(null),f=l.useMemo(()=>{if(e||!r)return null;const y=c(r);return y&&!ht(y)&&!pt(y)?y:null},[e,r,c]),g=l.useMemo(()=>{const y=u==null?void 0:u.routeId;if(!y)return null;const b=u!=null&&u.tabKey?o.find(C=>C.tabKey===u.tabKey):a?o.find(C=>C.tabKey===a):null;return(b==null?void 0:b.routeId)===y?b:bs(o,y)},[o,u,a]),S=l.useMemo(()=>{if(g)return i.find(y=>y.id===g.routeId)},[i,g]);l.useEffect(()=>{f&&(p({routeId:f.routeId,tabKey:fc(f)}),m(f),n({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,n,f]);const h=l.useCallback(y=>{y&&(p({routeId:y.routeId,tabKey:fc(y)}),m(y))},[]),x=l.useCallback(()=>{p(null),m(null)},[]);return{remoteDialogConv:g,remoteDialogIdeEntry:S,remoteDialogActiveConv:d,setRemoteDialogActiveConv:m,openRemoteDialog:h,closeRemoteDialog:x}}function u1({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c,activeConv:u,sendDaemonCommand:p}){const{remoteDialogConv:d,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:g,openRemoteDialog:S,closeRemoteDialog:h}=d1({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}),[x,y]=l.useState(!1),[b,C]=l.useState(null),j=l.useCallback(async N=>{const w=N||u;!w||!ht(w)&&!pt(w)||(C(w),y(!0))},[u]),k=l.useCallback(()=>{y(!1),C(null)},[]),v=l.useCallback(async N=>{const w=b||u;if(!w||!ht(w)&&!pt(w)){k();return}y(!1);try{const A=Ns(w),T=w.routeId||w.daemonId||"";await p(T,"stop_cli",{cliType:A,targetSessionId:w.sessionId,mode:N,...za(w)})}catch(A){console.error("Stop CLI failed:",A)}finally{C(null)}},[u,k,b,p]);return{remoteDialogConv:d,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:g,openRemoteDialog:S,closeRemoteDialog:h,cliStopDialogOpen:x,cliStopTargetConv:b,requestCliStop:j,cancelCliStop:k,confirmCliStop:v}}function Do(e,t=!0){return(e??!0)&&t}const xl=l.memo(function({activeConv:t,clearToken:n,isCliTerminal:r,ideEntry:a,terminalRef:o,handleModalButton:i,handleRelaunch:c,handleSendChat:u,handleForceSendChat:p,isSendingChat:d,sendFeedbackMessage:m=null,handleFocusAgent:f,isFocusingAgent:g,actionLogs:S,userName:h,scrollToBottomRequestNonce:x,isInputActive:y=!0,isVisible:b=!0}){const C=r,j=!r,k=Do(b,C),v=Do(b,j),N=Do(b),w=om(t),A=w.status||w.modalMessage||w.modalButtons?{...t,...w.status?{status:w.status}:{},...w.modalMessage!==void 0?{modalMessage:w.modalMessage}:{},...w.modalButtons!==void 0?{modalButtons:w.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(_u,{activeConv:A,onModalButton:i}),A.transport!=="pty"&&A.transport!=="acp"&&A.cdpConnected===!1?s.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:s.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[s.jsx("span",{className:"text-sm",children:s.jsx(pn,{size:14})}),s.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),s.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:c,children:"Relaunch with CDP"})]})}):null,A.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!r,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:C?"visible":"hidden",pointerEvents:C?"auto":"none"},children:s.jsx(mS,{activeConv:A,clearToken:n,terminalRef:o,handleSendChat:u,isSendingChat:d,sendFeedbackMessage:m,isVisible:k,isInputActive:y&&k})}),s.jsx("div",{"aria-hidden":r,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:j?"visible":"hidden",pointerEvents:j?"auto":"none"},children:s.jsx(ki,{activeConv:A,ideEntry:a,handleSendChat:u,isSendingChat:d,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:S,userName:h,scrollToBottomRequestNonce:x,isInputActive:y&&v,isVisible:v})})]}):s.jsx(ki,{activeConv:A,ideEntry:a,handleSendChat:u,handleForceSendChat:p,isSendingChat:d,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:S,userName:h,scrollToBottomRequestNonce:x,isInputActive:y&&N,isVisible:N})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.handleForceSendChat===t.handleForceSendChat&&e.isSendingChat===t.isSendingChat&&e.sendFeedbackMessage===t.sendFeedbackMessage&&e.handleFocusAgent===t.handleFocusAgent&&e.isFocusingAgent===t.isFocusingAgent&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function p1({conversation:e,className:t="",onOpenNativeConversation:n,onOpenMachine:r,interactive:a=!0,meshOnly:o=!1}){var j,k,v;const{t:i}=Ne("common"),c=Mr(),u=Rs(e),p=o?null:ap(e),d=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),m=!o&&e.streamSource==="agent-stream"&&!!e.agentName,f=!o&&!m&&(e.transport==="pty"||e.transport==="acp"),g=_n(e),S=I0(e),h=(j=e.settings)==null?void 0:j.meshNodeFor,x=e.meshQueueStats,y=((k=e.coordinator)==null?void 0:k.meshId)||((v=e.settings)==null?void 0:v.meshCoordinatorFor),b=l.useCallback(()=>{if(r){r();return}u&&c("/dashboard",{state:{openMachineId:u}})},[u,c,r]),C=l.useCallback(()=>{if(n){n();return}const N=xm(e);N&&c(Nr(N))},[e,c,n]);return!d&&!m&&!f&&!p&&!h&&!x?null:s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[d&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:C,title:S,children:[s.jsx(xs,{size:12}),s.jsx("span",{children:S})]}):s.jsxs("span",{className:"conversation-meta-chip",title:S,children:[s.jsx(xs,{size:12}),s.jsx("span",{children:S})]})),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(wr,{size:12}),s.jsx("span",{children:g})]}),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(wr,{size:12}),s.jsx("span",{children:g})]}),p&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:b,title:p,children:[s.jsx(Os,{size:12}),s.jsx("span",{children:p})]}):s.jsxs("span",{className:"conversation-meta-chip",title:p,children:[s.jsx(Os,{size:12}),s.jsx("span",{children:p})]})),h&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(Os,{size:12}),s.jsx("span",{children:i("dashboard.metaChips.meshNode")})]}),y&&x&&s.jsxs("span",{className:`conversation-meta-chip ${x.pending>0?"is-active":""}`,style:x.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${x.pending} pending, ${x.assigned} assigned, ${x.completed} completed, ${x.failed} failed`,children:[s.jsx(Zf,{size:12}),s.jsxs("span",{children:[x.pending," Pending"]})]})]})}function m1({selectedConversation:e,isAcp:t,isStandalone:n,selectedIdeEntry:r,actionLogs:a,userName:o,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:u,onBack:p,onOpenNativeConversation:d,onOpenMachine:m,onOpenHistory:f,onOpenRemote:g,onOpenMeshGraph:S,onStopCli:h,cliViewMode:x,onSetCliViewMode:y,handleSendChat:b,handleForceSendChat:C,handleFocusAgent:j,handleModalButton:k,handleRelaunch:v}){var P,D;const N=l.useRef(null),w=ht(e)&&!t,A=w&&x==="terminal",T=!!e.daemonId&&!!((P=e.coordinator)!=null&&P.meshId||(D=e.settings)!=null&&D.meshCoordinatorFor),I=n?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${I} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:s.jsx(Wi,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:kt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(p1,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>m(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[w&&x&&s.jsx(_p,{mode:x,onChange:y,compact:!0}),w&&h&&s.jsx("button",{onClick:()=>{h(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(Mt,{size:14})}),T&&S&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(os,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:s.jsx(Ui,{size:14})}),!t&&!w&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:s.jsx(xs,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(xl,{activeConv:e,clearToken:0,isCliTerminal:A,ideEntry:r,terminalRef:N,handleModalButton:k,handleRelaunch:v,handleSendChat:b,handleForceSendChat:C,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:j,isFocusingAgent:u,actionLogs:a,userName:o})})]})}const Io={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 h1(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function wm(){const[e,t]=l.useState("unix"),[n,r]=l.useState("powershell"),[a,o]=l.useState(!1),i=e==="unix"?"unix":n;l.useEffect(()=>{t(h1())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(Io[i].cmd).catch(()=>{}),o(!0),setTimeout(()=>o(!1),2e3)},[i]);return s.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("unix"),children:"🍎🐧 macOS / Linux"}),s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("windows"),children:"🪟 Windows"})]}),e==="windows"&&s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${n==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>r("powershell"),children:"⚡ PowerShell"}),s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${n==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>r("cmd"),children:">_ CMD"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:c,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:Io[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Io[i].cmd}),s.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:a?"✓":"📋"})]}),s.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",s.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function km({section:e,onSectionChange:t}){const n=[{key:"machines",label:"Machines",icon:xs},{key:"chats",label:"Chats",icon:bn}];return s.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:s.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:n.map(({key:r,label:a,icon:o})=>{const i=e===r;return s.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${i?"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:i?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(r),type:"button","aria-pressed":i,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${i?"text-accent-primary":"bg-transparent text-current"}`,style:i?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(o,{size:15})}),s.jsx("span",{children:a})]},r)})})})}function zr({title:e,className:t=""}){return s.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${t}`,children:s.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function wn({children:e,className:t=""}){return s.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${t}`,children:e})}function sr({icon:e,title:t,subtitle:n,children:r}){return s.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[s.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:n}),r]})}function f1({conversation:e,onCancel:t,onConfirm:n}){const{t:r}=Ne(),a=kt(e);return s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:t,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-hide-confirm-title",className:"card fade-in mobile-compact-dialog relative w-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-bg-primary",children:[s.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base md:text-lg font-extrabold",children:r("mobileInbox.hideTitle",{title:a})}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:r("mobileInbox.hideDescription")})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s.jsx("button",{onClick:n,className:"btn btn-primary w-full justify-center min-h-[42px]",children:r("mobileInbox.hide")}),s.jsx("button",{onClick:t,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:r("common.cancel")})]})]})]})}function Kr({item:e,type:t,getAvatarText:n,onOpenConversation:r,onRequestHideConversation:a,onRequestStopCli:o,onOpenMeshGraph:i,onCollectChatDebugBundle:c,isMuted:u,onToggleMute:p}){const{t:d}=Ne(),m=t==="needs_attention"||t==="task_complete",f=t==="working",g=t==="earlier",S=t==="task_complete",{isReconnecting:h,isConnecting:x}=gn(e.conversation),y=kt(e.conversation),b=$n(e.conversation),C=Pp(e.conversation,{requiresAction:t==="needs_attention"}),j=m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":f?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":g?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",k=m?"bg-accent-primary shadow-glow":f?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":g?"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",v=g?"text-text-secondary":"text-text-primary",N=g?"text-text-muted":"text-text-secondary",w=g?"text-text-secondary opacity-80":"text-text-muted",A=g?"text-text-muted opacity-80":"text-text-muted",T=!f&&!S,I=Dp(e.conversation),P="text-[color:var(--status-warning)]",D=_=>{if(!c)return;_.preventDefault(),_.stopPropagation();const W=c==null?void 0:c(e.conversation);Promise.resolve(W).catch($=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",$)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${j}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[m||f?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${k}`,style:m?{color:"var(--accent-on-primary)"}:void 0,children:n(y)}),I&&i&&s.jsx("button",{type:"button",className:"mobile-inbox-mesh-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:_=>{_.preventDefault(),_.stopPropagation(),i(e.conversation)},"aria-label":d("mobileInbox.openMeshGraphFor",{title:y}),title:d("mobileInbox.openLiveMeshGraph"),children:s.jsx(os,{size:13})})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>r(e.conversation),onContextMenu:D,type:"button",children:[s.jsx("div",{className:"flex items-center gap-2 pr-[124px]",children:s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${v}`,children:y})}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${N}`,children:[s.jsx("span",{className:"truncate",children:b}),s.jsx(Ca,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),h?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${P} animate-pulse`,children:d("mobileInbox.reconnectingItem")})]}):x?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:d("mobileInbox.connectingItem")})]}):C==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:P,children:d("mobileInbox.actionNeeded")})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${w}`,children:e.preview})]}),s.jsxs("div",{className:"mobile-inbox-corner-actions absolute top-3 right-3 flex items-center gap-1.5",children:[T&&s.jsx("span",{className:`mr-0.5 text-[11px] font-medium shrink-0 ${A}`,children:Ru(e.timestamp)}),S&&s.jsx("span",{className:"rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:d("mobileInbox.done")}),p&&s.jsx("button",{type:"button",className:`mobile-inbox-mute-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border transition-colors ${u?"border-amber-500/60 bg-amber-500 text-white hover:bg-amber-600":"border-border-subtle bg-bg-primary/70 text-text-muted hover:border-border-default hover:text-text-primary"}`,onClick:_=>{_.preventDefault(),_.stopPropagation(),p()},"aria-label":u?d("mobileInbox.unmute",{title:y}):d("mobileInbox.mute",{title:y}),title:d(u?"mobileInbox.mutedTitle":"mobileInbox.muteNotifications"),children:u?s.jsx(ku,{size:13}):s.jsx(Un,{size:13})}),a&&s.jsx("button",{type:"button",className:"mobile-inbox-hide-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:_=>{_.preventDefault(),_.stopPropagation(),a()},"aria-label":d("mobileInbox.hideConversationAria",{title:y}),title:d("mobileInbox.hideConversationTitle"),children:s.jsx(Gi,{size:13})}),o&&s.jsx("button",{type:"button",className:"mobile-inbox-stop-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-status-error/30 bg-bg-primary/70 text-status-error transition-colors hover:border-status-error/60 hover:bg-status-error/10",onClick:_=>{_.preventDefault(),_.stopPropagation(),o()},"aria-label":d("mobileInbox.stopSessionAria",{title:y}),title:d("mobileInbox.stopSessionTitle"),children:s.jsx(Mt,{size:13})})]})]})},e.conversation.tabKey)}function nd({size:e=32}){return s.jsx("div",{className:"flex flex-col items-center gap-2.5",children:s.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:e,height:e}})})}function rd({count:e,label:t}){return e<=0?null:s.jsxs("span",{className:"inline-flex items-center gap-1.5 text-accent-primary","aria-live":"polite",children:[s.jsxs("span",{className:"relative flex h-2 w-2 shrink-0",children:[s.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-accent-primary/60"}),s.jsx("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-accent-primary"})]}),s.jsx("span",{className:"font-semibold",children:t})]})}function b1({section:e,attentionItems:t,unreadItems:n,workingItems:r,completedItems:a,hiddenConversations:o,machineCards:i,getAvatarText:c,actionLogs:u,sendDaemonCommand:p,onOpenConversation:d,onShowAllHidden:m,onHideConversation:f,onOpenMeshGraph:g,onStopCli:S,onOpenNewSession:h,onOpenMachine:x,onOpenSettings:y,onSectionChange:b,wsStatus:C="connected",isStandalone:j=!1,onCollectChatDebugBundle:k,isConversationMuted:v,onToggleMuteConversation:N}){const{t:w}=Ne(),[A,T]=l.useState(null),I=C==="disconnected"||C==="reconnecting"||C==="offline"||C==="auth_failed",P=i.length>0,D=t.length>0||n.length>0||r.length>0||a.length>0,_=w(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),W=j?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",$=j?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",E=l.useCallback(async R=>{const M=rn(R);if(!M)return;const F=Array.isArray(R.messages)?R.messages:[],K=pp({activeConv:R,visibleMessages:F,actionLogs:u,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:F.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),J=await p(M,"get_chat_debug_bundle",{...nn(R),delivery:"daemon_file",frontendSnapshot:K}),V=fr(J),Y=fp(V),se=await hp(Y);se==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),ft.showToast(mp(V,{locatorCopyStatus:se}),se==="failed"?"warning":"success")},[u,p]),B=k||E,L=l.useCallback(()=>{A&&(f==null||f(A),T(null))},[A,f]);return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${W}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:_}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||n.length>0)&&s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[s.jsx(Un,{size:13}),s.jsx("span",{children:t.length+n.length})]}),s.jsx("button",{onClick:y,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:s.jsx(Ha,{size:18})})]})]})}),s.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${$}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:I?s.jsx(sr,{icon:s.jsx(nd,{}),title:w(C==="offline"?"mobileInbox.networkOffline":C==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:w(C==="offline"?"mobileInbox.waitingForNetwork":C==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):i.length===0?s.jsx(sr,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:w(j?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:w(j?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!j&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(wm,{})})}):s.jsx(wn,{children:i.map((R,M)=>s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${M>0?"border-t border-border-subtle/70":""}`,onClick:()=>x(R.id),type:"button",children:[s.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:c(R.label)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:R.label}),s.jsxs("span",{className:"flex items-center gap-2 text-[11px] font-medium text-text-muted shrink-0",children:[s.jsx(rd,{count:R.generatingCount,label:w("mobileInbox.generatingCount",{count:R.generatingCount})}),R.unread>0?s.jsx("span",{className:"text-accent-primary",children:w("mobileInbox.newCount",{count:R.unread})}):R.total>0?w("mobileInbox.chatCount",{count:R.total}):w("mobileInbox.idle")]})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:R.subtitle}),R.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[w("mobileInbox.chatCount",{count:R.total}),R.unread>0?w("mobileInbox.unreadSuffix",{count:R.unread}):"",R.generatingCount>0?w("mobileInbox.collapsedGeneratingSuffix",{count:R.generatingCount}):""]}):R.generatingCount>0?s.jsx("div",{className:"text-[13px] text-accent-primary mt-0.5 font-medium",children:w("mobileInbox.generatingCount",{count:R.generatingCount})}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:w("mobileInbox.noActiveChats")})]})]},R.id))})}),e==="chats"&&t.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(zr,{title:w("mobileInbox.needsAttention"),className:"mb-0"}),s.jsx(wn,{children:t.map((R,M)=>s.jsx("div",{className:M>0?"border-t border-border-subtle/70":"",children:s.jsx(Kr,{item:R,type:"needs_attention",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>T(R.conversation):void 0,onRequestStopCli:S?()=>S(R.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:B,isMuted:v==null?void 0:v(R.conversation),onToggleMute:N?()=>N(R.conversation):void 0})},R.conversation.tabKey))})]}),e==="chats"&&n.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(zr,{title:w("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),s.jsx(wn,{children:n.map((R,M)=>s.jsx("div",{className:M>0?"border-t border-border-subtle/70":"",children:s.jsx(Kr,{item:R,type:"task_complete",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>T(R.conversation):void 0,onRequestStopCli:S?()=>S(R.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:B,isMuted:v==null?void 0:v(R.conversation),onToggleMute:N?()=>N(R.conversation):void 0})},R.conversation.tabKey))})]}),e==="chats"&&r.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(zr,{title:w("mobileInbox.workingNow"),className:"mb-0 mt-2"}),s.jsx(wn,{children:r.map((R,M)=>s.jsx("div",{className:M>0?"border-t border-border-subtle/70":"",children:s.jsx(Kr,{item:R,type:"working",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>T(R.conversation):void 0,onRequestStopCli:S?()=>S(R.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:B,isMuted:v==null?void 0:v(R.conversation),onToggleMute:N?()=>N(R.conversation):void 0})},R.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&s.jsx(zr,{title:w("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(wn,{children:a.map((R,M)=>s.jsx("div",{className:M>0?"border-t border-border-subtle/70":"",children:s.jsx(Kr,{item:R,type:"earlier",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>T(R.conversation):void 0,onRequestStopCli:S?()=>S(R.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:B,isMuted:v==null?void 0:v(R.conversation),onToggleMute:N?()=>N(R.conversation):void 0})},R.conversation.tabKey))}):D?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:w("mobileInbox.allCaughtUp")}):I?s.jsx(sr,{icon:s.jsx(nd,{size:28}),title:w("mobileInbox.connecting"),subtitle:w("mobileInbox.connectingSubtitle")}):P?s.jsx(sr,{icon:s.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:s.jsx(bn,{size:20})}),title:w("mobileInbox.noConversations"),subtitle:w("paneGroup.newSessionDescription"),children:h&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:h,"aria-label":w("paneGroup.newSession"),title:w("paneGroup.newSession"),children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s.jsx("span",{children:w("paneGroup.newSession")})]})}):s.jsx(sr,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:w("mobileInbox.noMachinesConnected"),subtitle:w("mobileInbox.noMachinesSubtitle")})]}),e==="chats"&&o.length>0&&(()=>{const R=Xb(o);return s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(wn,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:w("mobileInbox.hiddenTabs")}),s.jsx(rd,{count:R,label:w("mobileInbox.generatingCount",{count:R})})]}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[w("mobileInbox.collapsedCount",{count:o.length}),R>0?w("mobileInbox.collapsedGeneratingSuffix",{count:R}):""]})]}),s.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-[12px] font-semibold text-accent-primary hover:border-border-default",onClick:m,children:w("mobileInbox.restoreAll")})]})})})})()]}),e==="chats"&&h&&D&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:h,"aria-label":w("paneGroup.newSession"),title:w("paneGroup.newSession"),children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),A&&s.jsx(f1,{conversation:A,onCancel:()=>T(null),onConfirm:L}),s.jsx(km,{section:e,onSectionChange:b})]})}function g1(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 Sm(e){const t=[e.workspace||"Workspace unknown"],n=mn(e.summaryMetadata);n&&t.push(n),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const r=g1(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:r?`Updated ${r}`:"",preview:(e.preview||"").trim()}}function vl({title:e,description:t,currentPath:n,directories:r,busy:a=!1,error:o="",confirmLabel:i="Use this folder",onClose:c,onNavigate:u,onConfirm:p}){const[d,m]=l.useState(n),{t:f}=Ne("common");l.useEffect(()=>{m(n)},[n]);const g=Vj(n),S=d.trim();return s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:c,"aria-label":"Close folder browser",children:s.jsx(Mt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!g||a||u(g)},disabled:!g||a,children:[s.jsx(Wi,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:f("machine.workspaceBrowse.currentFolder")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:d,onChange:h=>m(h.target.value),onKeyDown:h=>{h.key!=="Enter"||!S||a||(h.preventDefault(),u(S))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!S||a||u(S)},disabled:!S||a,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):r.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:r.map(h=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>u(h.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(En,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:h.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:h.path})]})]},h.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:c,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(S||n),disabled:!S&&!n||a,children:i})]})]})})}function Xa({title:e,description:t,details:n,workspaceOptions:r,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:i,busyLabel:c,busy:u=!1,showArgsInput:p,argsValue:d,onArgsChange:m,showModelInput:f,modelValue:g,onModelChange:S,historyProviderNode:h,onConfirm:x,onCancel:y}){const{t:b}=Ne("common"),C=i??b("machine.launchConfirm.launch"),j=c??b("machine.launchConfirm.launching"),k=r==null?void 0:r.find(v=>v.key===a);return s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:y,"aria-label":b("machine.launchConfirm.closeAria"),children:s.jsx(Mt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[r&&r.length>0&&o&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.workspace")}),s.jsx("select",{value:a||"",onChange:v=>o(v.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:u,children:r.map(v=>s.jsx("option",{value:v.key,children:v.label},v.key))}),(k==null?void 0:k.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:k.description})]}),h,n.map(v=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:v.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:v.value})]},`${v.label}:${v.value}`)),f&&S&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.languageModel")}),s.jsx("input",{type:"text",value:g||"",onChange:v=>S(v.target.value),placeholder:b("machine.launchConfirm.autoDetect"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]}),p&&m&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.cliArgs")}),s.jsx("input",{type:"text",value:d||"",onChange:v=>m(v.target.value),placeholder:b("machine.launchConfirm.cliArgsPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:y,disabled:u,children:b("machine.launchConfirm.cancel")}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:x,disabled:u,children:[s.jsx(wu,{size:14}),u?j:C]})]})]})})}function ad(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function Cm(e){const{machine:t,currentWorkspacePath:n,currentWorkspaceId:r,includeHome:a=!0,homeLabel:o="Home directory",homeDescription:i="Launch without a workspace"}=e,c=[];a&&c.push({key:"__home__",label:o,description:i,workspaceId:null,workspacePath:null});for(const d of t.workspaces||[])c.push({key:`saved:${d.id}`,label:`${d.id===t.defaultWorkspaceId?"⭐ ":""}${ad(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const u=(n==null?void 0:n.trim())||"",p=u?(t.workspaces||[]).find(d=>d.path===u):null;if(u&&!p&&c.push({key:`custom:${u}`,label:ad(u),description:u,workspaceId:null,workspacePath:u}),r){const d=`saved:${r}`;if(c.some(m=>m.key===d))return{options:c,selectedKey:d}}return p?{options:c,selectedKey:`saved:${p.id}`}:u?{options:c,selectedKey:`custom:${u}`}:{options:c,selectedKey:"__home__"}}function x1(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function v1(e){return[x1(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function y1(e){return e.lastLaunchedAt?Ba(e.lastLaunchedAt):""}function jm(e){return{metaText:v1(e),updatedLabel:y1(e)}}function Po(e,t,n){return e?"ide":t>0?"cli":n>0?"acp":null}function w1({selectedMachineEntry:e,cliProviders:t,acpProviders:n,machineAction:r,onBrowseDirectory:a,onListSavedSessions:o}){var ae,we,Me,qe;const i=qn(),[c,u]=l.useState(!1),p=(((ae=e.detectedIdes)==null?void 0:ae.length)||0)>0,d=l.useMemo(()=>(e.workspaces||[]).map(ve=>({id:ve.id,path:ve.path,label:ve.label})),[e]),m=e.defaultWorkspaceId||null,[f,g]=l.useState(m||((we=d[0])==null?void 0:we.id)||""),[S,h]=l.useState(""),[x,y]=l.useState(""),[b,C]=l.useState([]),[j,k]=l.useState(!1),[v,N]=l.useState(""),[w,A]=l.useState(!1),[T,I]=l.useState(Po(p,t.length,n.length)),P=l.useRef(null),[D,_]=l.useState(null),W=l.useRef("__home__"),[$,E]=l.useState("__home__"),[B,L]=l.useState(""),[R,M]=l.useState(""),[F,K]=l.useState(""),[J,V]=l.useState([]),[Y,se]=l.useState(()=>qt().textQuery),[ie,Z]=l.useState(()=>qt().workspaceQuery),[O,ee]=l.useState(()=>qt().modelQuery),[G,le]=l.useState(()=>qt().resumableOnly),[je,ge]=l.useState(()=>qt().sortMode),[Ce,ue]=l.useState(!1),[z,U]=l.useState(!1),q=l.useRef(null),Q=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const me=f==="__custom__"?S.trim():((Me=d.find(ve=>ve.id===f))==null?void 0:Me.path)||"",Ae=f==="__custom__"&&!!me&&r.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(r.message),de=f!=="__custom__"&&((qe=d.find(ve=>ve.id===f))==null?void 0:qe.path)||"",H=l.useMemo(()=>(e.recentLaunches||[]).map(ve=>ve.workspace),[e]),he=l.useCallback(async ve=>{k(!0),N("");try{const $e=await a(ve);y($e.path),h($e.path),C($e.directories)}catch($e){N($e instanceof Error?$e.message:"Could not load folder")}finally{k(!1)}},[a]),fe=l.useCallback(()=>{var $e;g("__custom__"),A(!0);const ve=bl(e.platform,fl(S.trim(),de,H,e.defaultWorkspacePath,($e=d.find(lt=>lt.id===m))==null?void 0:$e.path,d.map(lt=>lt.path)));he(ve)},[S,m,he,H,de,e.platform,d]),ye=l.useCallback(ve=>{if(ve!=null&&ve.workspaceId){g(ve.workspaceId),h("");return}if(ve!=null&&ve.workspacePath){g("__custom__"),h(ve.workspacePath);return}g(""),h("")},[]),Pe=l.useCallback(ve=>{if(g(ve),ve==="__custom__"){fe();return}h("")},[fe]),He=l.useCallback(ve=>{g("__custom__"),h(ve)},[]),ke=l.useCallback((ve,$e)=>{P.current=$e,W.current=ve.selectedWorkspaceKey||"__home__",E(ve.selectedWorkspaceKey||"__home__"),L(ve.initialArgs||""),M(ve.initialModel||""),K(""),V([]);const lt=ve.providerType?`${e.id}:${ve.providerType}`:null;if(SS(Q.current,lt)){const at=qt();se(at.textQuery),Z(at.workspaceQuery),ee(at.modelQuery),le(at.resumableOnly),ge(at.sortMode)}Q.current=lt,_(ve),ve.providerType&&o&&(ue(!0),o(ve.providerType).then(at=>V(at||[])).catch(at=>console.warn("Failed to load saved sessions",at)).finally(()=>ue(!1)))},[o,e.id]),pe=l.useMemo(()=>$p(J,{textQuery:Y,workspaceQuery:ie,modelQuery:O,resumableOnly:G,sortMode:je}),[O,G,J,je,Y,ie]);l.useEffect(()=>{F&&(pe.some(ve=>ve.providerSessionId===F)||K(""))},[pe,F]);const st=l.useCallback(()=>{P.current&&(U(!0),P.current().finally(()=>{P.current=null,U(!1),_(null)}))},[]),De=l.useCallback(()=>{P.current=null,_(null)},[]),_e=l.useCallback(ve=>{W.current=ve,E(ve)},[]);return l.useEffect(()=>{var ve;q.current!==e.id&&(q.current=e.id,g(m||((ve=d[0])==null?void 0:ve.id)||"__custom__"),h(""),y(""),C([]),N(""),A(!1),se(qt().textQuery),Z(qt().workspaceQuery),ee(qt().modelQuery),le(qt().resumableOnly),ge(qt().sortMode),Q.current=null,I(Po(p,t.length,n.length)))},[n.length,t.length,m,p,e.id,d]),l.useEffect(()=>{var ve;f!=="__custom__"&&(f&&d.some($e=>$e.id===f)||g(m||((ve=d[0])==null?void 0:ve.id)||"__custom__"))},[m,f,d]),l.useEffect(()=>{T==="ide"&&p||T==="cli"&&t.length>0||T==="acp"&&n.length>0||I(Po(p,t.length,n.length))},[T,n.length,t.length,p]),{showAllRecent:c,setShowAllRecent:u,hasIdeOptions:p,workspaceRows:d,defaultWorkspaceId:m,workspaceChoice:f,customWorkspacePath:S,browseCurrentPath:x,browseDirectories:b,browseBusy:j,browseError:v,browseDialogOpen:w,activeLauncherKind:T,launchConfirm:D,launchConfirmWorkspaceKeyRef:W,launchConfirmWorkspaceKey:$,launchConfirmArgs:B,launchConfirmModel:R,launchConfirmResumeId:F,launchConfirmSavedSessions:J,launchConfirmTextFilter:Y,launchConfirmWorkspaceFilter:ie,launchConfirmModelFilter:O,launchConfirmResumableOnly:G,launchConfirmSortMode:je,filteredLaunchConfirmSavedSessions:pe,launchConfirmSessionsLoading:Ce,launchConfirmBusy:z,resolvedWorkspacePath:me,canCreateMissingWorkspace:Ae,openBrowseDialog:fe,loadBrowsePath:he,handleWorkspaceChoiceChange:Pe,chooseCustomWorkspacePath:He,setCustomWorkspacePath:h,setBrowseDialogOpen:A,setActiveLauncherKind:I,openLaunchConfirm:ke,handleConfirmLaunch:st,closeLaunchConfirm:De,setWorkspaceSelectionFromOption:ye,setLaunchConfirmWorkspaceKeyAndSync:_e,setLaunchConfirmArgs:L,setLaunchConfirmModel:M,setLaunchConfirmResumeId:K,setLaunchConfirmTextFilter:se,setLaunchConfirmWorkspaceFilter:Z,setLaunchConfirmModelFilter:ee,setLaunchConfirmResumableOnly:le,setLaunchConfirmSortMode:ge}}function k1({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:n,cliProviders:r,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:i,machineAction:c,isStandalone:u,section:p,showBottomNav:d,onBack:m,onSectionChange:f,onOpenConversation:g,onOpenRecent:S,onOpenMachineDetails:h,onMachineUpgrade:x,onLaunchDetectedIde:y,onAddWorkspace:b,onBrowseDirectory:C,onLaunchWorkspaceProvider:j,onListSavedSessions:k}){const{t:v}=Ne("common"),N=E=>E==="ide"?"IDE":E==="cli"?"CLI":"ACP",w=n.slice(0,4),A=t.slice(0,3),T=w1({selectedMachineEntry:e,cliProviders:r,acpProviders:a,machineAction:c,onBrowseDirectory:C,onListSavedSessions:k}),I=l.useMemo(()=>w.map(E=>{const{metaText:B,updatedLabel:L}=jm(E);return{key:`recent-launch:${E.id}`,primary:E.label,secondary:B,updatedLabel:L,onClick:()=>{const{options:R,selectedKey:M}=Cm({machine:{workspaces:T.workspaceRows,defaultWorkspaceId:T.defaultWorkspaceId},currentWorkspacePath:E.workspace,homeLabel:v("newSession.homeDirectory"),homeDescription:v("newSession.launchWithoutWorkspace")});T.openLaunchConfirm({title:E.kind==="ide"?ja(v,"restart-ide",E.label):E.providerSessionId?Fp(v,E.label):ja(v,"start-fresh",E.label),description:E.kind==="ide"?Na(v,"restart-ide"):E.providerSessionId?Bp(v):Na(v,"start-fresh"),confirmLabel:E.kind==="ide"?Aa(v,"restart-ide"):E.providerSessionId?Si(v,!0):Aa(v,"start-fresh"),busyLabel:E.kind==="ide"?Ta(v,"restart-ide"):E.providerSessionId?Hp(v,!0):Ta(v,"start-fresh"),workspaceOptions:R,selectedWorkspaceKey:M,details:[{label:"Mode",value:N(E.kind)},...E.providerType?[{label:"Provider",value:E.providerType}]:[]]},async()=>{const F=R.find(K=>K.key===T.launchConfirmWorkspaceKeyRef.current);T.setWorkspaceSelectionFromOption(F),await S({...E,workspace:(F==null?void 0:F.workspacePath)??null})})}}}),[T,S,w,v]),P=l.useMemo(()=>A.map(E=>({key:`recent-chat:${E.conversation.tabKey}`,primary:kt(E.conversation),secondary:Jk(E.conversation,{timestampLabel:E.timestamp?Ru(E.timestamp):null}),unread:E.unread,onClick:()=>g(E.conversation)})),[g,A]),D=T.showAllRecent?I:I.slice(0,4),_=I.length>0,W=P.length>0,$=u?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${$} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:m,type:"button","aria-label":"Back",children:s.jsx(Wi,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:is(e,{fallbackId:e.id})}),s.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[W&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:P.map(E=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${E.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:E.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:E.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:E.secondary})]},E.key))})]}),_&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:D.map(E=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:E.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:E.primary}),E.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:E.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:E.secondary})]},E.key))}),I.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>T.setShowAllRecent(E=>!E),children:T.showAllRecent?"Show fewer":`Show ${I.length-4} more`})})]}),!1,s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:x,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",i]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:h,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),T.browseDialogOpen&&s.jsx(vl,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:T.browseCurrentPath,directories:T.browseDirectories,busy:T.browseBusy,error:T.browseError,confirmLabel:"Use this folder",onClose:()=>T.setBrowseDialogOpen(!1),onNavigate:E=>{T.loadBrowsePath(E)},onConfirm:E=>{T.chooseCustomWorkspacePath(E),T.setBrowseDialogOpen(!1)}}),T.launchConfirm&&s.jsx(Xa,{title:T.launchConfirm.title,description:T.launchConfirm.description,details:T.launchConfirm.details,workspaceOptions:T.launchConfirm.workspaceOptions,selectedWorkspaceKey:T.launchConfirmWorkspaceKey,onWorkspaceChange:T.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:T.launchConfirm.providerType?Si(v,!!T.launchConfirmResumeId):T.launchConfirm.confirmLabel,busyLabel:T.launchConfirm.providerType?void 0:T.launchConfirm.busyLabel,busy:T.launchConfirmBusy,showArgsInput:T.launchConfirm.showArgsInput,argsValue:T.launchConfirmArgs,onArgsChange:T.setLaunchConfirmArgs,showModelInput:T.launchConfirm.showModelInput,modelValue:T.launchConfirmModel,onModelChange:T.setLaunchConfirmModel,historyProviderNode:T.launchConfirm.providerType&&(T.launchConfirmSessionsLoading||T.launchConfirmSavedSessions.length>0)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),T.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:ll(v)}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:T.launchConfirmTextFilter,onChange:E=>T.setLaunchConfirmTextFilter(E.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:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:T.launchConfirmWorkspaceFilter,onChange:E=>T.setLaunchConfirmWorkspaceFilter(E.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:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:T.launchConfirmModelFilter,onChange:E=>T.setLaunchConfirmModelFilter(E.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:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsxs("select",{value:T.launchConfirmSortMode,onChange:E=>T.setLaunchConfirmSortMode(E.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:T.launchConfirmResumableOnly,onChange:E=>T.setLaunchConfirmResumableOnly(E.target.checked),disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:T.launchConfirmResumeId,onChange:E=>T.setLaunchConfirmResumeId(E.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:NS(v)}),T.filteredLaunchConfirmSavedSessions.map(E=>s.jsxs("option",{value:E.providerSessionId,disabled:!E.canResume,children:[E.title||E.providerSessionId," ",E.canResume?"":"(workspace missing)"]},E.providerSessionId))]}),!T.launchConfirmSessionsLoading&&T.launchConfirmSavedSessions.length>0&&T.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),T.launchConfirmResumeId&&(()=>{const E=T.filteredLaunchConfirmSavedSessions.find(L=>L.providerSessionId===T.launchConfirmResumeId);if(!E)return null;const B=Sm(E);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:B.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:B.providerSessionId}),s.jsx("div",{className:"mt-1",children:B.metaLine}),B.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:B.updatedLabel}),B.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:B.preview})]})})()]}),onConfirm:T.handleConfirmLaunch,onCancel:T.closeLaunchConfirm}),d&&s.jsx(km,{section:p,onSectionChange:f})]})}const od=8e3;function S1(e){const t=e&&typeof e=="object"&&"result"in e?e.result:e,n=t&&typeof t=="object",r=n&&t.success===!1,a=n&&t.mirrorStale===!0;return!r&&!a?{confirmed:!0}:{confirmed:!1,reason:r&&typeof t.error=="string"?t.error:a?"the coordinator did not confirm the change":"command was rejected"}}function Nm(e,t,n){const r=l.useRef(new Map),[,a]=l.useState(0),o=l.useCallback(()=>a(g=>g+1),[]);l.useEffect(()=>{const g=r.current;if(g.size===0)return;const S=Date.now();let h=!1;for(const[x,y]of g){const b=e.get(x),C=y.muted===void 0||(b?b.muted===y.muted:!1),j=y.hidden===void 0||(b?b.surfaceHidden===y.hidden:!1),k=S-y.at>od;(C&&j||k)&&(g.delete(x),h=!0)}h&&o()},[e,o]),l.useEffect(()=>{if(r.current.size===0)return;const g=setInterval(()=>{const S=r.current,h=Date.now();let x=!1;for(const[y,b]of S)h-b.at>od&&(S.delete(y),x=!0);x&&o(),S.size===0&&clearInterval(g)},1e3);return()=>clearInterval(g)});const i=l.useCallback((g,S)=>{const h=r.current.get(g);r.current.set(g,{...h,...S,at:Date.now()}),o()},[o]),c=l.useCallback(g=>{const S=g.sessionId,h=S?r.current.get(S):void 0;return(h==null?void 0:h.muted)!==void 0?h.muted:Gs(g,e).muted??!1},[e]),u=l.useCallback(g=>{const S=g.sessionId,h=S?r.current.get(S):void 0;return(h==null?void 0:h.hidden)!==void 0?h.hidden:Gs(g,e).surfaceHidden??!1},[e]),p=l.useCallback((g,S)=>{const h=Rs(g),x=g.sessionId;!h||!x||(i(x,S),t(h,"set_conversation_prefs",{sessionId:x,...S,...za(g)}).then(y=>{const b=S1(y);b.confirmed||(console.warn("[conversation-prefs] set_conversation_prefs not confirmed",b.reason),r.current.delete(x),o(),n==null||n(`Couldn't update conversation — ${b.reason}`))}).catch(y=>{console.warn("[conversation-prefs] set_conversation_prefs failed",y),r.current.delete(x),o();const b=y instanceof Error?y.message:String(y??"the daemon is unreachable");n==null||n(`Couldn't update conversation — ${b}`)}))},[t,i,o,n]),d=l.useCallback(g=>{p(g,{muted:!c(g)})},[p,c]),m=l.useCallback((g,S)=>{p(g,{hidden:S})},[p]),f=l.useCallback(g=>{p(g,{hidden:!u(g)})},[p,u]);return{isMuted:c,isHidden:u,toggleMute:d,setHidden:m,toggleHidden:f}}function da(e){return[...e].sort((t,n)=>{const r=n.timestamp-t.timestamp;return r!==0?r:t.conversation.tabKey.localeCompare(n.conversation.tabKey)})}function C1(e,t=[]){const n=new Map(e.map(a=>[a.conversation.tabKey,a])),r=t.map(a=>n.get(a)).filter(a=>!!a);return r.length===e.length?r:da(e)}function j1(e,t=[]){const n=e.filter(i=>i.requiresAction),r=e.filter(i=>i.unread&&!i.requiresAction),a=e.filter(i=>!i.unread&&!i.requiresAction&&i.isWorking),o=e.filter(i=>!i.unread&&!i.requiresAction&&!i.isWorking);return{attentionItems:da(n),unreadItems:da(r),workingItems:C1(a,t),completedItems:da(o)}}function N1(e){var r,a,o;const t=((r=e.p2p)==null?void 0:r.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":!(!!((a=e.p2p)!=null&&a.available)||!!((o=e.p2p)!=null&&o.state))&&e.status&&e.status!=="offline"?"Connected":"Offline"}function A1(e,t){if(!e)return[];const n=e.recentLaunches||[];return n.length>0?n.map(r=>({id:r.id,label:r.title||r.providerName||r.providerType,kind:r.kind,providerType:r.providerType,providerSessionId:r.providerSessionId,subtitle:mn(r.summaryMetadata)||r.workspace||void 0,workspace:r.workspace,summaryMetadata:r.summaryMetadata})):t.filter(r=>r.type!=="adhdev-daemon"&&r.daemonId===e.id).map(r=>{var i;const a=Sr(r)?"cli":Dn(r)?"acp":"ide",o=mn(r.summaryMetadata);return{id:`${a}:${r.type}:${r.workspace||""}`,label:((i=r.activeChat)==null?void 0:i.title)||(Sr(r)?r.cliName||r.type:Dn(r)&&r.cliName||r.type),kind:a,providerType:r.type,providerSessionId:r.providerSessionId,subtitle:Dn(r)?o||r.workspace||void 0:r.workspace||void 0,workspace:r.workspace||void 0,timestamp:r.lastMessageAt||0}}).sort((r,a)=>a.timestamp-r.timestamp).map(({timestamp:r,...a})=>a)}function T1(e,t,n=[]){const r=new Map;for(const o of t){const i=Rs(o.conversation),c=r.get(i);c?c.push(o):r.set(i,[o])}const a=new Map;for(const o of n){const i=Rs(o),c=a.get(i);c?c.push(o):a.set(i,[o])}return e.map(o=>{const i=r.get(o.id)||[],c=a.get(o.id)||[],u=[...i].sort((h,x)=>x.timestamp-h.timestamp)[0]||null,p=(u==null?void 0:u.conversation)||null,d=bi(o),m=i.filter(h=>h.unread||h.requiresAction).length,f=i.filter(h=>kr(h.conversation)).length+c.filter(kr).length,g=N1(o),S=[o.platform||"machine",g].filter(Boolean);return{id:o.id,label:is(o,{fallbackId:o.id}),subtitle:S.join(" · "),unread:m,total:i.length,generatingCount:f,latestConversation:p,latestTimestamp:(u==null?void 0:u.timestamp)||0,fallbackActivityAt:d,preview:p?Qk(p,Cp(p)):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((o,i)=>{const c=o.latestTimestamp||o.fallbackActivityAt||0,u=i.latestTimestamp||i.fallbackActivityAt||0;return u!==c?u-c:o.label.localeCompare(i.label)})}function M1(e){return e==="chat"}function Vr(e,t){var n;if(!(typeof window>"u"))try{if(!(!!((n=import.meta.env)!=null&&n.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${e}`,t)}catch{}}function D1({conversations:e,machineEntries:t,items:n,selectedConversation:r,selectedTabKey:a,screen:o,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:S,setScreen:h,setSelectedMachineId:x,setSection:y,setMachineBackTarget:b,resetMachineAction:C}){const j=l.useRef(null),k=l.useCallback(v=>{if(!(v!=null&&v.sessionId))return;const N=Gs(v,i),w=Math.max(Date.now(),cn(v),N.lastUpdated||0);Vr("mark_read:start",{tabKey:v.tabKey,sessionId:v.sessionId,displayPrimary:kt(v),inboxBucket:N.inboxBucket,unread:N.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:cn(v),readAt:w}),c(Rs(v)||v.routeId,"mark_session_seen",{sessionId:v.sessionId,providerSessionId:v.providerSessionId,seenAt:w,completionMarker:N.completionMarker}).then(A=>{Vr("mark_read:result",{tabKey:v.tabKey,sessionId:v.sessionId,result:A})}).catch(A=>{Vr("mark_read:error",{tabKey:v.tabKey,sessionId:v.sessionId,error:A instanceof Error?A.message:String(A)})})},[i,c]);return l.useEffect(()=>{var N;if(!r){M1(o)&&h("inbox"),S(((N=e[0])==null?void 0:N.tabKey)||null),j.current=null;return}if(o!=="chat"){j.current=null;return}const v=`${r.tabKey}:${r.sessionId||""}`;j.current!==v&&(j.current=v,k(r))},[e,k,o,r,h,S]),l.useEffect(()=>{if(!u)return;const v=e.find(N=>N.tabKey===u);v&&(S(v.tabKey),h("chat"),p==null||p())},[e,p,u,h,S]),l.useEffect(()=>{if(!d)return;const v=t.find(N=>N.id===d);v&&(x(v.id),C(),y("machines"),b("inbox"),h("machine"),m==null||m())},[t,m,d,C,b,h,y,x]),l.useEffect(()=>{f&&(y(f),h("inbox"),g==null||g())},[g,f,h,y]),l.useEffect(()=>{const v=n.filter(N=>N.inboxBucket==="task_complete"||N.unread);v.length!==0&&Vr("inbox_state",{screen:o,selectedTabKey:a,items:v.map(N=>{const w=Gs(N.conversation,i);return{liveState:w,tabKey:N.conversation.tabKey,sessionId:N.conversation.sessionId,displayPrimary:kt(N.conversation),serverBucket:w.inboxBucket,computedBucket:N.inboxBucket,serverUnread:w.unread,computedUnread:N.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,activityAt:cn(N.conversation)}})})},[n,i,o,a]),{markConversationRead:k}}function I1(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function id(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function P1(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function L1({sendDaemonCommand:e,navigate:t,ides:n,conversations:r}){const{launchCli:a}=$a(),[o,i]=l.useState("idle"),[c,u]=l.useState(""),[p,d]=l.useState(null),m=l.useCallback(()=>{i("idle"),u(""),d(null)},[]),f=l.useCallback(async(C,j,k)=>{var v;try{i("loading"),u(`Launching ${j}…`);const N={ideType:j,enableCdp:!0};(v=k==null?void 0:k.workspacePath)!=null&&v.trim()&&(N.workspace=k.workspacePath.trim()),await e(C,"launch_ide",N),i("done"),u(`${j} launch requested`)}catch(N){i("error"),u(N instanceof Error?N.message:"Launch IDE failed"),console.error("Launch IDE failed",N)}},[e]),g=l.useCallback(async(C,j,k)=>{if(j.trim())try{i("loading"),u(k!=null&&k.createIfMissing?"Creating folder…":"Saving workspace…");const v=await e(C,"workspace_add",{path:j.trim(),createIfMissing:(k==null?void 0:k.createIfMissing)===!0});if(v!=null&&v.success){i("done"),u(k!=null&&k.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),u((v==null?void 0:v.error)||"Could not save workspace")}catch(v){i("error"),u(v instanceof Error?v.message:"Could not save workspace")}},[e]),S=l.useCallback(async C=>{i("loading"),u("Starting daemon upgrade…");const j=n.find(v=>v.id===C||v.daemonId===C),k=await wC(e,C,j);i(k.state),u(k.message)},[n,e]),h=l.useCallback(async(C,j,k,v)=>{var A,T,I;const N=Date.now(),w={machineId:C,kind:j,providerType:k,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:N};try{i("loading"),u(`Launching ${k}…`),d(w);const P={cliType:k};(A=v==null?void 0:v.workspacePath)!=null&&A.trim()?P.dir=v.workspacePath.trim():v!=null&&v.workspaceId?P.workspaceId=v.workspaceId:v!=null&&v.useHome&&(P.useHome=!0),v!=null&&v.resumeSessionId&&(P.resumeSessionId=v.resumeSessionId),(T=v==null?void 0:v.args)!=null&&T.trim()&&(P.cliArgs=v.args.trim().split(/\s+/).filter(Boolean)),(I=v==null?void 0:v.model)!=null&&I.trim()&&(P.initialModel=v.model.trim());const D=await a(C,P),_=(D==null?void 0:D.result)||D,W=(_==null?void 0:_.sessionId)||(_==null?void 0:_.id);if(D!=null&&D.success&&W){d(null),i("done"),u(`${k} launched`),t(Nr(W));return}if(D!=null&&D.success){i("loading"),u(`${k} launch requested — waiting for session…`);return}d(null),i("error"),u((D==null?void 0:D.error)||(_==null?void 0:_.error)||`Could not launch ${j.toUpperCase()} workspace`)}catch(P){if(P1(P)){i("loading"),u(`${k} launch requested — waiting for session…`);return}d(null),i("error"),u(P instanceof Error?P.message:`Could not launch ${j.toUpperCase()} workspace`)}},[t,e]),x=l.useCallback(async(C,j)=>{try{const k=await e(C,"list_saved_sessions",{providerType:j,kind:"cli",limit:30}),v=(k==null?void 0:k.result)??k;return Array.isArray(v==null?void 0:v.sessions)?v.sessions:[]}catch(k){return console.error("Failed to list saved sessions on mobile:",k),[]}},[e]),y=l.useCallback(async(C,j)=>gl(e,C,j),[e]);l.useEffect(()=>{if(!p)return;const C=id(p.workspacePath),j=n.find(v=>{var P,D,_,W;if(!v||v.type==="adhdev-daemon"||I1(v.daemonId||v.id)!==p.machineId||(v.transport==="acp"?"acp":v.transport==="pty"?"cli":null)!==p.kind||String(v.agentType||v.type||"")!==p.providerType)return!1;const T=String(v.providerSessionId||"");if(p.resumeSessionId&&T)return T===p.resumeSessionId;if(C){const $=id(v.workspace||v.runtimeWorkspaceLabel);return $?$===C:!1}return Number(v.lastUpdated||v._lastUpdate||v.timestamp||((W=(_=(D=(P=v.activeChat)==null?void 0:P.messages)==null?void 0:D.at)==null?void 0:_.call(D,-1))==null?void 0:W.timestamp)||0)>=p.startedAt-5e3});if(!j)return;const k=vm({entrySessionId:j.sessionId,entryInstanceId:j.instanceId,entryRouteId:j.id,conversations:r});k&&(d(null),i("done"),u(`${p.providerType} launched`),t(Nr(k)))},[r,n,t,p]),l.useEffect(()=>{if(!p)return;const C=window.setTimeout(()=>{d(j=>!j||j.startedAt!==p.startedAt?j:(i("error"),u("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(C)},[p]);const b=l.useCallback(async(C,j)=>{var k;if(j.kind==="ide"&&j.providerType){await f(C,j.providerType,{workspacePath:j.workspace||null});return}if((j.kind==="cli"||j.kind==="acp")&&j.providerType){const v=((k=j.workspace)==null?void 0:k.trim())||"";await h(C,j.kind,j.providerType,{workspacePath:v||null,useHome:!v,resumeSessionId:j.providerSessionId||null})}},[f,h]);return{machineAction:{state:o,message:c},resetMachineAction:m,handleLaunchDetectedIde:f,handleAddWorkspace:g,handleMachineUpgrade:S,handleLaunchWorkspaceProvider:h,handleListSavedSessions:x,handleBrowseDirectory:y,handleOpenRecent:b}}function R1({conversations:e,selectedConversation:t,machineBackTarget:n,markConversationRead:r,resetMachineAction:a,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:u,setMachineBackTarget:p}){const d=l.useCallback(y=>{o(y.tabKey),i("chat"),r(y)},[r,i,o]),m=l.useCallback(y=>{const b=e.find(C=>C.routeId===y.routeId&&C.streamSource==="native");b&&(o(b.tabKey),i("chat"),r(b))},[e,r,i,o]),f=l.useCallback(()=>{r(t),i("inbox")},[r,t,i]),g=l.useCallback((y,b="inbox")=>{c(y),a(),u("machines"),p(b),i("machine")},[a,p,i,u,c]),S=l.useCallback(y=>{const b=Rs(y);b&&g(b,"chat")},[g]),h=l.useCallback(()=>{a(),i(n)},[n,a,i]),x=l.useCallback(y=>{u(y),i("inbox")},[i,u]);return{openConversation:d,openNativeConversation:m,backFromConversation:f,openMachine:g,openConversationMachine:S,backFromMachine:h,changeMachineSection:x}}function Bn(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function E1(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function _1({conversations:e,hiddenConversations:t,ides:n,actionLogs:r,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,userName:c,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,onOpenHistory:S,onOpenRemote:h,onStopCli:x,wsStatus:y,isConnected:b,onShowAllHiddenConversations:C,onHideConversation:j,onOpenMeshGraph:k,onOpenNewSession:v,liveSessionInboxState:N,setCliViewModeOverrides:w}){const[A,T]=l.useState(()=>{var fe;return((fe=e[0])==null?void 0:fe.tabKey)||null}),[I,P]=l.useState(()=>e[0]?"chat":"inbox"),[D,_]=l.useState("chats"),[W,$]=l.useState(null),[E,B]=l.useState("inbox"),L=l.useRef([]),R=Mr(),M="1.0.29",F=l.useMemo(()=>e.find(fe=>fe.tabKey===A)||e[0]||null,[e,A]),K=l.useMemo(()=>F?n.find(fe=>fe.id===F.routeId):void 0,[n,F]),J=l.useMemo(()=>!F||pt(F)||!ht(F)?null:Gn(F),[F]),V=l.useMemo(()=>n.filter(fe=>fe.type==="adhdev-daemon").sort(Qi),[n]),Y=l.useMemo(()=>V.find(fe=>fe.id===W)||null,[V,W]),se=Ka({sendDaemonCommand:a,activeConv:F||void 0,setActionLogs:o,isStandalone:i}),ie=L1({sendDaemonCommand:a,navigate:R,ides:n,conversations:e}),Z=Nk(e),O=l.useMemo(()=>e.map(fe=>{const ye=I==="chat"&&(F==null?void 0:F.tabKey)===fe.tabKey,Pe=Wa(fe,N,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ye}),He=cn(fe),ke=Cp(fe),pe=Ip(fe,ke);return{conversation:fe,timestamp:He,preview:pe,unread:Pe.unread,requiresAction:Pe.requiresAction,isWorking:Pe.isWorking,inboxBucket:Pe.inboxBucket}}),[e,N,I,F,Z]),{markConversationRead:ee}=D1({conversations:e,machineEntries:V,items:O,selectedConversation:F,selectedTabKey:A,screen:I,liveSessionInboxState:N,sendDaemonCommand:a,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:T,setScreen:P,setSelectedMachineId:$,setSection:_,setMachineBackTarget:B,resetMachineAction:ie.resetMachineAction}),G=R1({conversations:e,selectedConversation:F,machineBackTarget:E,markConversationRead:ee,resetMachineAction:ie.resetMachineAction,setSelectedTabKey:T,setScreen:P,setSelectedMachineId:$,setSection:_,setMachineBackTarget:B}),{isMuted:le,toggleMute:je}=Nm(N,a),{attentionItems:ge,unreadItems:Ce,workingItems:ue,completedItems:z}=l.useMemo(()=>j1(O,L.current),[O]);l.useEffect(()=>{L.current=ue.map(fe=>fe.conversation.tabKey)},[ue]);const U=l.useMemo(()=>Y?O.filter(fe=>Rs(fe.conversation)===Y.id):[],[O,Y]),q=l.useMemo(()=>A1(Y,n),[n,Y]),Q=!!Y&&Ja(Y,$s(Y,M)),me=l.useMemo(()=>(Y==null?void 0:Y.availableProviders)||[],[Y]),Ae=l.useMemo(()=>me.filter(fe=>Bn(fe,"cli")).map(fe=>({type:fe.type,displayName:fe.displayName||fe.type,icon:fe.icon})),[me]),de=l.useMemo(()=>me.filter(fe=>Bn(fe,"acp")).map(fe=>({type:fe.type,displayName:fe.displayName||fe.type,icon:fe.icon})),[me]),H=l.useMemo(()=>T1(V,O,t),[O,V,t]),he=l.useCallback(async fe=>{Y&&await ie.handleOpenRecent(Y.id,fe)},[ie,Y]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:I==="chat"&&F?s.jsx(m1,{selectedConversation:F,isAcp:pt(F),isStandalone:i,selectedIdeEntry:K,actionLogs:r,userName:c,isSendingChat:se.isSendingChat,sendFeedbackMessage:se.sendFeedbackMessage,isFocusingAgent:se.isFocusingAgent,handleModalButton:se.handleModalButton,handleRelaunch:se.handleRelaunch,onBack:G.backFromConversation,onOpenNativeConversation:G.openNativeConversation,onOpenMachine:G.openConversationMachine,onOpenHistory:S,onOpenRemote:h,onOpenMeshGraph:k,onStopCli:x,cliViewMode:J,onSetCliViewMode:async fe=>{await cm({conversation:F,mode:fe,ides:n,sendDaemonCommand:a,setCliViewModeOverrides:w})},handleSendChat:se.handleSendChat,handleForceSendChat:se.handleForceSendChat,handleFocusAgent:se.handleFocusAgent}):I==="machine"&&Y?s.jsx(k1,{selectedMachineEntry:Y,selectedMachineConversations:U,selectedMachineRecentLaunches:q,cliProviders:Ae,acpProviders:de,selectedMachineNeedsUpgrade:Q,appVersion:M,machineAction:ie.machineAction,isStandalone:i,section:D,showBottomNav:E==="inbox",onBack:G.backFromMachine,onSectionChange:G.changeMachineSection,onOpenConversation:G.openConversation,onOpenRecent:he,onOpenMachineDetails:()=>R(`/machines/${Y.id}`),onMachineUpgrade:()=>ie.handleMachineUpgrade(Y.id),onLaunchDetectedIde:(fe,ye)=>ie.handleLaunchDetectedIde(Y.id,fe,ye),onAddWorkspace:(fe,ye)=>ie.handleAddWorkspace(Y.id,fe,ye),onBrowseDirectory:fe=>ie.handleBrowseDirectory(Y.id,fe),onLaunchWorkspaceProvider:(fe,ye,Pe)=>ie.handleLaunchWorkspaceProvider(Y.id,fe,ye,Pe),onListSavedSessions:fe=>ie.handleListSavedSessions(Y.id,fe)}):s.jsx(b1,{section:D,attentionItems:ge,unreadItems:Ce,workingItems:ue,completedItems:z,hiddenConversations:t,machineCards:H,getAvatarText:E1,actionLogs:r,sendDaemonCommand:a,onOpenConversation:G.openConversation,onShowAllHidden:C,onHideConversation:j,onOpenMeshGraph:k,onStopCli:x,onOpenNewSession:v,onOpenMachine:G.openMachine,onOpenSettings:()=>R("/settings"),onSectionChange:_,wsStatus:y,isConnected:b,isStandalone:i,isConversationMuted:le,onToggleMuteConversation:je})})}function Lo(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function $1({conversations:e,numGroups:t,onMoveTab:n,onReceiveTab:r,onOwnTabDrop:a,onClearPreviewOrder:o}){const i=l.useRef(0),[c,u]=l.useState(!1),[p,d]=l.useState(null),m=l.useCallback(()=>{i.current=0,u(!1),d(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",m),window.addEventListener("drop",m),()=>{window.removeEventListener("dragend",m),window.removeEventListener("drop",m)}),[m]);const f=l.useCallback(x=>{x.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,u(!0))},[]),g=l.useCallback(x=>{if(!x.dataTransfer.types.includes("text/tab-key"))return;if(x.preventDefault(),!Lo(t,n)){d("merge");return}const y=x.currentTarget.getBoundingClientRect(),b=x.clientX-y.left,C=y.width/3;b<C?d("split-left"):b>C*2?d("split-right"):d("merge")},[t,n]),S=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,u(!1),d(null))},[]),h=l.useCallback(x=>{i.current=0,u(!1);const y=x.dataTransfer.getData("text/tab-key"),b=y?e.some(j=>j.tabKey===y):!1,C=p;if(d(null),o(),!!y){if(x.preventDefault(),C==="split-left"&&Lo(t,n)){n==null||n(y,"split-left");return}if(C==="split-right"&&Lo(t,n)){n==null||n(y,"split-right");return}if(b){a(y);return}r==null||r(y)}},[e,p,t,n,r,a,o]);return{dragOver:c,dropAction:p,resetDragState:m,handleDragEnter:f,handleDragOver:g,handleDragLeave:S,handleDrop:h}}function H1(e,t){const n=new Set(t.map(o=>o.tabKey)),r=e.filter(o=>n.has(o)),a=t.filter(o=>!e.includes(o.tabKey)).map(o=>o.tabKey);return[...r,...a]}function F1({conversations:e,initialActiveTabId:t,initialTabOrder:n,onActiveTabChange:r,onTabOrderChange:a}){const[o,i]=l.useState(t??null),[c,u]=l.useState(n??[]),[p,d]=l.useState(null),m=l.useRef(null),f=l.useRef(null),g=l.useRef(r),S=l.useRef(a);l.useEffect(()=>{g.current=r},[r]),l.useEffect(()=>{S.current=a},[a]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{u(N=>{const w=H1(N,e);return w.length===N.length&&w.every((A,T)=>A===N[T])?N:w})},[e]);const h=l.useMemo(()=>{const N=p??c;if(N.length===0)return e;const w=new Map(N.map((A,T)=>[A,T]));return[...e].sort((A,T)=>{const I=w.get(A.tabKey)??999,P=w.get(T.tabKey)??999;return I-P})},[e,p,c]);l.useEffect(()=>{var w,A;if(h.length===0){o!==null&&(i(null),(w=g.current)==null||w.call(g,null));return}if(o&&h.some(T=>T.tabKey===o))return;const N=h[0].tabKey;N!==o&&(i(N),(A=g.current)==null||A.call(g,N))},[h,o]);const x=l.useMemo(()=>h.find(N=>N.tabKey===o),[h,o]),y=l.useCallback(N=>{var w;i(N),(w=g.current)==null||w.call(g,N)},[]),b=l.useCallback((N,w,A)=>{u(T=>{var _;const I=T.filter(W=>W!==N),P=I.indexOf(w);if(P<0)return T;const D=A==="left"?P:P+1;return I.splice(D,0,N),(_=S.current)==null||_.call(S,I),I}),d(null)},[]),C=l.useCallback((N,w,A)=>{const I=(c.length>0?c:e.map(_=>_.tabKey)).filter(_=>_!==N),P=I.indexOf(w);if(P<0)return;const D=A==="left"?P:P+1;I.splice(D,0,N),m.current=I,d(I)},[c,e]),j=l.useCallback(()=>{var w;const N=m.current;N&&(u(N),(w=S.current)==null||w.call(S,N))},[]),k=l.useCallback(()=>{m.current=null,d(null)},[]),v=l.useCallback(N=>{u(w=>{var T;const A=w.filter(I=>I!==N);return A.push(N),(T=S.current)==null||T.call(S,A),A})},[]);return{activeTabId:o,activeConv:x,sortedConversations:h,previewOrderRef:m,draggingTabRef:f,selectTab:y,handleTabReorder:b,updatePreviewOrder:C,commitPreviewOrder:j,clearPreviewOrder:k,moveTabToEnd:v,setDraggingTabKey:N=>{f.current=N}}}function B1({dropAction:e,canSplit:t}){return s.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-left"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-left"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Left"})}),s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="merge"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="merge"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)"},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Move Here"})}),s.jsx("div",{className:"flex-1 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-right"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-right"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Right"})})]})}function yl({conversationsCount:e,isSplitMode:t,isStandalone:n,hasRegisteredMachines:r=!1,suppressGuide:a=!1,onOpenNewSession:o}){const{t:i}=Ne("common");if(a)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const c=!n&&!r,u=r&&!!o,p=i(r?"paneGroup.noConversations":n?"paneGroup.waitingForDaemon":"paneGroup.connectYourMachines"),d=i(r?"paneGroup.newSessionDescription":n?"paneGroup.daemonDescription":"paneGroup.installDescription");return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:p}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:d}),u&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:o,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:i("paneGroup.newSession"),"aria-label":i("paneGroup.newSession"),children:[s.jsx(zi,{size:14}),s.jsx("span",{children:i("paneGroup.newSession")})]})}),c&&s.jsx(wm,{}),c&&s.jsx("div",{className:"mt-8",children:s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"📚 Read the documentation →"})})]})]}):s.jsx("div",{className:"text-sm text-text-muted opacity-50",children:t?"Move a tab here to view":"No active agent"})}const Am="adhdev-tab-shortcuts";function Tm(){try{return JSON.parse(localStorage.getItem(Am)||"{}")}catch{return{}}}function Mm({enabled:e=!0,sortedTabKeys:t,onFocus:n,onSelectTab:r}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>Tm()),[c,u]=l.useState(null),p=l.useCallback(m=>{const f=[];return m.metaKey&&f.push(a?"⌘":"Meta"),m.ctrlKey&&f.push("Ctrl"),m.altKey&&f.push(a?"⌥":"Alt"),m.shiftKey&&f.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(f.push(m.key.length===1?m.key.toUpperCase():m.key),f.join("+"))},[a]),d=l.useCallback(m=>{i(m);try{localStorage.setItem(Am,JSON.stringify(m))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const m=f=>{if(f.preventDefault(),f.stopPropagation(),f.key==="Escape"){u(null);return}const g=p(f);if(!g)return;const S={...o};for(const[h,x]of Object.entries(S))x===g&&delete S[h];S[c]=g,d(S),u(null)};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[e,c,o,d,p]),l.useEffect(()=>{if(!e)return;const m=f=>{if(!(!f.ctrlKey&&!f.metaKey&&!f.altKey)){for(const[g,S]of Object.entries(o))if(t.includes(g)&&p(f)===S){f.preventDefault(),n(),r(g);return}}};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[e,o,t,n,r,p]),{isMac:a,tabShortcuts:o,shortcutListening:c,setShortcutListening:u,saveShortcuts:d}}const Ro=e=>{e.preventDefault()},W1=l.memo(function({conv:t,isActive:n,isDraggedTab:r,isTaskCompleteUnread:a,shortcut:o,conversationKeys:i,draggingTabRef:c,onFocus:u,onSelectTab:p,onConversationActivated:d,onPreviewReorder:m,onReorderTab:f,onCommitPreviewOrder:g,onClearPreviewOrder:S,onDragStateReset:h,onDragTabKeyChange:x,onReceiveTab:y,onOpenContextMenu:b,longPressTimer:C,isGroupActive:j}){const k=gn(t),v=k.isGenerating?"agent-tab-generating":k.isWaiting?"agent-tab-waiting":"",N=k.isReconnecting,w=Vk(t),A=Yk(t),T=Dp(t),I=l.useCallback(R=>{c.current=t.tabKey,x(t.tabKey),R.dataTransfer.setData("text/tab-key",t.tabKey),R.dataTransfer.effectAllowed="move"},[t.tabKey,c,x]),P=l.useCallback(()=>{c.current=null,x(null),g(),S(),h()},[c,x,g,S,h]),D=l.useCallback(R=>{const M=c.current;if(!(!M||M===t.tabKey)&&R.dataTransfer.types.includes("text/tab-key")){R.preventDefault(),R.stopPropagation();const F=R.currentTarget.getBoundingClientRect(),K=R.clientX<F.left+F.width/2?"left":"right";m(M,t.tabKey,K)}},[t.tabKey,c,m]),_=l.useCallback(R=>{R.preventDefault(),R.stopPropagation();const M=R.dataTransfer.getData("text/tab-key");if(M&&M!==t.tabKey){const F=R.currentTarget.getBoundingClientRect(),K=R.clientX<F.left+F.width/2?"left":"right";i.includes(M)?f(M,t.tabKey,K):y&&y(M)}S()},[t.tabKey,i,f,y,S]),W=l.useCallback(R=>{R.stopPropagation(),u(),p(t.tabKey),d(t)},[t,d,u,p]),$=l.useCallback(R=>{R.preventDefault(),b(R.clientX,R.clientY,t.tabKey)},[t.tabKey,b]),E=l.useCallback(R=>{const M=R.touches[0];C.current=setTimeout(()=>{b(M.clientX,M.clientY,t.tabKey)},600)},[t.tabKey,C,b]),B=l.useCallback(()=>{C.current&&clearTimeout(C.current)},[C]),L=["adhdev-dockview-tab",v,n&&"is-active",j&&"is-group-active",N&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:L,draggable:!0,onDragStart:I,onDragEnd:P,onDragOver:D,onDrop:_,onClick:W,onContextMenu:$,onTouchStart:E,onTouchEnd:B,onTouchMove:B,style:{position:"relative",cursor:"pointer",opacity:r?.4:void 0},children:[T&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-badge pointer-events-none absolute top-0.5 right-0.5 text-text-muted",title:"Mesh chat","aria-label":"Mesh chat",children:s.jsx(os,{size:11})}),a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:k.isGenerating?s.jsx("div",{className:"tab-spinner"}):k.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):N?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):k.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),w.length>0&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:A,"aria-label":A||w.join(" · "),children:w.join(" · ")}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:kt(t),children:kt(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[N?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:an(t)}):k.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[an(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:an(t)}),s.jsx(Ca,{git:t.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),o&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${o}`,children:o})]})},(e,t)=>e.conv===t.conv&&e.isActive===t.isActive&&e.isDraggedTab===t.isDraggedTab&&e.isTaskCompleteUnread===t.isTaskCompleteUnread&&e.shortcut===t.shortcut&&e.conversationKeys===t.conversationKeys&&e.isGroupActive===t.isGroupActive);function O1({conversations:e,activeTabId:t,groupIndex:n,unreadTabKeys:r,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:d,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:g,onReceiveTab:S,onHideTab:h,isGroupActive:x,allowTabShortcuts:y=!0}){const{t:b}=Ne("common"),[C,j]=l.useState(null),k=l.useRef(null),v=l.useRef(null),N=l.useMemo(()=>e.map(_=>_.tabKey),[e]);Dr("PaneGroupTabBar",{groupIndex:n,activeTabId:t,tabCount:e.length,ctxMenuTab:(C==null?void 0:C.tabKey)||null});const{isMac:w,tabShortcuts:A,shortcutListening:T,setShortcutListening:I,saveShortcuts:P}=Mm({enabled:y,sortedTabKeys:e.map(_=>_.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!C)return;const _=W=>{const $=document.querySelector("[data-pane-context-menu]");$&&$.contains(W.target)||j(null)};return window.addEventListener("mousedown",_,!0),()=>window.removeEventListener("mousedown",_,!0)},[C]),l.useEffect(()=>{const _=v.current;if(!_)return;const W=$=>{Math.abs($.deltaY)<=Math.abs($.deltaX)||($.preventDefault(),_.scrollLeft+=$.deltaY)};return _.addEventListener("wheel",W,{passive:!1}),()=>_.removeEventListener("wheel",W)},[]);const D=l.useCallback((_,W,$)=>{j({x:_,y:W,tabKey:$})},[]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:s.jsxs("div",{ref:v,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(_=>s.jsx(W1,{conv:_,isActive:t===_.tabKey,isDraggedTab:a.current===_.tabKey,isTaskCompleteUnread:r.has(_.tabKey),shortcut:y?A[_.tabKey]:void 0,conversationKeys:N,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:d,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:g,onReceiveTab:S,onOpenContextMenu:D,longPressTimer:k,isGroupActive:x},_.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:b("paneGroup.noTabsInGroup")})]})}),C&&s.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:C.x,top:C.y},children:[y&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:Ro,onClick:_=>{_.stopPropagation(),I(C.tabKey),j(null)},children:["⌨ ",A[C.tabKey]?`Change shortcut (${A[C.tabKey]})`:"Set shortcut"]}),A[C.tabKey]&&s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onMouseDown:Ro,onClick:()=>{const _={...A};delete _[C.tabKey],P(_),j(null)},children:"✕ Remove shortcut"})]}),h&&s.jsxs(s.Fragment,{children:[y&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:Ro,onClick:()=>{h(C.tabKey),j(null)},children:"🚫 Hide from Dashboard"})]})]}),y&&T&&s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>I(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:_=>_.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",w?"⌘+1":"Ctrl+1",", ",w?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:b("paneGroup.pressEscToCancel")})]})})]})}function U1({conversations:e,ides:t,clearedTabs:n,actionLogs:r,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,userName:u,groupIndex:p,onFocus:d,isSplitMode:m,numGroups:f,onMoveTab:g,onReceiveTab:S,style:h,onActiveTabChange:x,initialActiveTabId:y,initialTabOrder:b,onTabOrderChange:C,onHideTab:j,isFocused:k,allowTabShortcuts:v=!0,onOpenNewSession:N,liveSessionInboxState:w}){const{sendCommand:A}=St(),T=l.useRef(null),{activeTabId:I,activeConv:P,sortedConversations:D,draggingTabRef:_,selectTab:W,handleTabReorder:$,updatePreviewOrder:E,commitPreviewOrder:B,clearPreviewOrder:L,moveTabToEnd:R,setDraggingTabKey:M}=F1({conversations:e,initialActiveTabId:y,initialTabOrder:b,onActiveTabChange:x,onTabOrderChange:C}),F=Ka({sendDaemonCommand:a,activeConv:P,setActionLogs:o,isStandalone:i}),{dragOver:K,dropAction:J,resetDragState:V,handleDragEnter:Y,handleDragOver:se,handleDragLeave:ie,handleDrop:Z}=$1({conversations:e,numGroups:f,onMoveTab:g,onReceiveTab:S,onOwnTabDrop:R,onClearPreviewOrder:L}),O=P&&!pt(P)&&Gn(P)==="terminal",ee=l.useMemo(()=>P?t.find(ge=>ge.id===P.routeId):void 0,[t,P]),G=l.useMemo(()=>P?r.filter(ge=>ge.routeId===P.tabKey):[],[r,P]),le=l.useMemo(()=>new Set(D.filter(ge=>eg(ge,w,{isOpenConversation:ge.tabKey===I})).map(ge=>ge.tabKey)),[I,w,D]);Dr("PaneGroup",{groupIndex:p,conversationCount:e.length,activeTabId:I,dragOver:K});const je=l.useCallback(ge=>{ge.streamSource==="agent-stream"&&ge.agentType&&A(ge.routeId,up(),{agentType:ge.agentType,...ge.sessionId&&{targetSessionId:ge.sessionId}}).catch(()=>{})},[A]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:d,style:{...h,outline:K?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(O1,{conversations:D,activeTabId:I,groupIndex:p,numGroups:f,unreadTabKeys:le,draggingTabRef:_,onFocus:d,onSelectTab:W,onConversationActivated:je,onPreviewReorder:E,onReorderTab:$,onCommitPreviewOrder:B,onClearPreviewOrder:L,onDragStateReset:V,onDragTabKeyChange:M,onMoveTab:g,onReceiveTab:S,onHideTab:j,isGroupActive:k??!1,allowTabShortcuts:v}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:Y,onDragOver:se,onDragLeave:ie,onDrop:Z,children:[K&&s.jsx(B1,{dropAction:J,canSplit:!!(f<4&&g)}),P?s.jsx(xl,{activeConv:P,clearToken:n[P.tabKey]||0,isCliTerminal:!!O,ideEntry:ee,terminalRef:T,handleModalButton:F.handleModalButton,handleRelaunch:F.handleRelaunch,handleSendChat:F.handleSendChat,handleForceSendChat:F.handleForceSendChat,isSendingChat:F.isSendingChat,sendFeedbackMessage:F.sendFeedbackMessage,handleFocusAgent:F.handleFocusAgent,isFocusingAgent:F.isFocusingAgent,actionLogs:G,userName:u,isInputActive:!m||!!k}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(yl,{conversationsCount:e.length,isSplitMode:m,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:N})})]})]})}function G1({containerRef:e,isSplitMode:t,numGroups:n,groupSizes:r,groupedConvs:a,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:u,setActionLogs:p,isStandalone:d,hasRegisteredMachines:m,userName:f,focusedGroup:g,focusGroup:S,moveTabToGroup:h,splitTabRelative:x,closeGroup:y,handleResizeStart:b,groupActiveTabIds:C,setGroupActiveTab:j,groupTabOrders:k,setGroupTabOrder:v,toggleHiddenTab:N,onOpenNewSession:w,allowTabShortcuts:A=!0,liveSessionInboxState:T}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((I,P)=>{const D=t&&r.length===n?`${r[P]}%`:void 0;return s.jsxs(Pt.Fragment,{children:[t&&P>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:_=>b(P-1,_),onDoubleClick:()=>y(P),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(U1,{style:t?{flexBasis:D??`${100/n}%`,flexGrow:D?0:1,flexShrink:D?0:1}:void 0,conversations:I,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:u,setActionLogs:p,isStandalone:d,hasRegisteredMachines:m,userName:f,groupIndex:P,isFocused:t&&g===P,onFocus:()=>S(P),isSplitMode:t,numGroups:n,onMoveTab:(_,W)=>{W==="left"&&P>0?h(_,P-1):W==="right"&&P<n-1?h(_,P+1):W==="split-left"&&n<4?x(_,P,"left"):W==="split-right"&&n<4&&x(_,P,"right")},onReceiveTab:_=>h(_,P),onActiveTabChange:_=>j(P,_),initialActiveTabId:C[P],initialTabOrder:k[P],onTabOrderChange:_=>v(P,_),onHideTab:N,onOpenNewSession:w,allowTabShortcuts:A,liveSessionInboxState:T})]},P)})})}const Dm="adhdev-dashboard-action-shortcuts",q1=1200,z1=[["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 K1(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function mt(e,t){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return t?"⌘+⇧+Enter":"Ctrl+Shift+Enter";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+Ctrl+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return t?"⌘+Ctrl+⇧+↓":"Ctrl+Alt+Shift+↓";case"focusLeftPane":return"";case"focusRightPane":return"";case"focusUpPane":return"";case"focusDownPane":return"";case"moveActiveTabToLeftPane":return"";case"moveActiveTabToRightPane":return"";case"moveActiveTabToUpPane":return"";case"moveActiveTabToDownPane":return"";case"triggerPrimaryApprovalAction":return t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌘+⇧+←":"Ctrl+Shift+←";case"selectNextGroupTab":return t?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function Im(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:mt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:mt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:mt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:mt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:mt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:mt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:mt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:mt("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:mt("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:mt("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:mt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:mt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:mt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:mt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:mt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:mt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:mt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:mt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:mt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:mt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:mt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:mt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:mt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:mt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:mt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:mt("toggleCliView",e)}]}function Ii(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function La(e){const t=Object.fromEntries(Im(e).map(n=>[n.id,n.defaultShortcut]));try{const n=JSON.parse(localStorage.getItem(Dm)||"{}"),r={...t,...n};for(const[a,o]of z1)r[a]===o&&(r[a]=t[a]);return r}catch{return t}}function Pm(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function V1({enabled:e=!0,onTrigger:t}){const n=K1(),[r,a]=l.useState(()=>La(n)),[o,i]=l.useState(null),[c,u]=l.useState([]),p=l.useRef({parts:[],timer:null}),d=l.useCallback(h=>{const x=[];return h.metaKey&&x.push(n?"⌘":"Meta"),h.ctrlKey&&x.push("Ctrl"),h.altKey&&x.push(n?"⌥":"Alt"),h.shiftKey&&h.key.length!==1&&x.push(n?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(x.push(Pm(h.key)),x.join("+"))},[n]),m=l.useCallback(h=>{a(h);try{localStorage.setItem(Dm,JSON.stringify(h))}catch{}},[]);l.useEffect(()=>{const h=La(n),x=Object.entries(r),y=Object.entries(h);x.length===y.length&&x.every(([b,C])=>h[b]===C)||m(h)},[r,n,m]);const f=l.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),g=l.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},q1))},[]);l.useEffect(()=>{if(!o)return;const h=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){i(null),u([]);return}const y=d(x);if(!y)return;const C=!(x.metaKey||x.ctrlKey||x.altKey)&&/^[A-Z0-9]$/.test(y);if(c.length===0&&C){u([y]);return}const k=[...c,y].slice(0,2).join(" "),v={...r};for(const[N,w]of Object.entries(v))w===k&&delete v[N];v[o]=k,m(v),i(null),u([])};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[r,d,m,o,c]),l.useEffect(()=>{if(!e||o)return;const h=x=>{if(x.defaultPrevented)return;const y=d(x);if(!y)return;const b=x.metaKey||x.ctrlKey||x.altKey;if(Ii(x.target))return;const C=p.current.parts,j=b?[y]:[...C.slice(-1),y].slice(-2),k=j.join(" "),v=j[j.length-1],N=Object.entries(r).filter(([,P])=>!!P),w=N.find(([,P])=>P===k);if(w){x.preventDefault(),f(),t(w[0]);return}if(N.some(([,P])=>P.startsWith(`${k} `))){x.preventDefault(),p.current.parts=j,g();return}const T=N.find(([,P])=>P===v);if(T){x.preventDefault(),f(),t(T[0]);return}if(N.some(([,P])=>P.startsWith(`${v} `))){x.preventDefault(),p.current.parts=[v],g();return}f()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[r,g,e,d,t,f,o]),l.useEffect(()=>()=>f(),[f]);const S=l.useMemo(()=>Im(n),[n]);return{isMac:n,actionDefinitions:S,actionShortcuts:r,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:u,saveShortcuts:m}}function Y1({isTabInPopout:e,isTabFloating:t,tabShortcut:n,actionShortcuts:r}){const a=[];return e?(t&&a.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:r.dockActiveTab}),a.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:r.dockActiveTab})):t?a.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:r.dockActiveTab}):a.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:r.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:r.popoutActiveTab}),a.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:n?`Change shortcut (${n})`:"Set shortcut",shortcut:r.setActiveTabShortcut}),n&&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:r.hideCurrentTab,tone:"muted"}),a}function Lm(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function ld({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:n,ides:r}){return!e||n>0?!1:t?!Lm(r):!0}function J1({previousVisibleConversationCount:e,visibleConversationCount:t,ides:n}){return t>0||e<=0?!1:Lm(n)}const Rm=1e3,Q1=4;function cd(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function dd(e,t,n){return Math.abs(t.clientX-e.clientX)>n||Math.abs(t.clientY-e.clientY)>n}function X1({detachDelayMs:e=Rm,stillnessThresholdPx:t=Q1,onDetach:n,setTimeoutFn:r=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,i=null,c=null,u=null,p=null,d=!1;const m=()=>{p!=null&&(a(p),p=null)},f=()=>{m(),c=null},g=()=>{m(),o=null,i=null,c=null,u=null,d=!1},S=()=>{!o||!c||!u||d||p!=null||(p=r(()=>{p=null,!(!o||!c||!u||d)&&cd(u,i)&&(dd(c,u,t)||(d=!0,n({panelId:o,clientX:u.clientX,clientY:u.clientY})))},e))},h=y=>{if(!(!o||d)){if(!cd(y,i)){u={clientX:y.clientX,clientY:y.clientY},f();return}(!c||dd(c,y,t))&&(m(),c={clientX:y.clientX,clientY:y.clientY}),u={clientX:y.clientX,clientY:y.clientY},S()}},x=y=>{!o||d||(y&&(u={clientX:y.clientX,clientY:y.clientY}),f())};return{startDrag:y=>{m(),o=y.panelId,i=y.selfPanelBounds??null,c=null,u={clientX:y.clientX,clientY:y.clientY},d=!1},markSelfPanel:h,markNonSelfPanel:x,markNoDropTarget:x,markDockTarget:x,endDrag:g,isDragging:()=>o!=null,hasDetached:()=>d,dispose:g}}function Z1(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function ua(e){return kt(e)||e.tabKey}function eN(e){return`remote:${e}`}function ds(e){return e.startsWith("remote:")}function ud(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Eo(e){var r;const t=e==null?void 0:e.defaultView;if(!t)return;const n=a=>{if(a)try{a.focus({preventScroll:!0})}catch{try{a.focus()}catch{}}};try{t.focus(),n(e==null?void 0:e.body),n(e==null?void 0:e.documentElement),(r=t.requestAnimationFrame)==null||r.call(t,()=>{try{t.focus(),n(e==null?void 0:e.body)}catch{}})}catch{}}function _o(e,t){e.classList.remove(ni.className,ri.className),e.classList.add(t==="light"?ni.className:ri.className)}function pd(e){return e?Array.from(new Set(e.groups.map(t=>{var n,r;return(r=(n=t.element)==null?void 0:n.ownerDocument)==null?void 0:r.defaultView}).filter(t=>!!t&&t!==window))):[]}function tN(e,t,n){var i;const r=[t];let a;for(const c of r){let u;for(const p of c){const d=e.addPanel({id:p.tabKey,component:"conversation",title:ua(p),params:{kind:"conversation",tabKey:p.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});u||(u=d.id)}a=u??a}return n??((i=t[0])==null?void 0:i.tabKey)??null}function md(e,t){const n=new Set(t.map(a=>a.tabKey)),r=new Map;for(const a of t)r.set(a.tabKey,(r.get(a.tabKey)||0)+1);for(const a of[...e.panels])ds(a.id)||n.has(a.id)||e.removePanel(a);for(const a of t){const o=e.getPanel(a.tabKey);if(o){(r.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!==ua(a)&&o.api.setTitle(ua(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:ua(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 hd(e,t,n){var u,p;const r=n?eN(n):null;for(const d of[...e.panels])ds(d.id)&&(!r||d.id!==r)&&e.removePanel(d);if(!n||!r)return;const a=bs(t,n);if(!a&&e.totalPanels===0)return;const o=e.getPanel(r),i=Rp(a);if(o){o.title!==i&&o.api.setTitle(i);return}const c=(a==null?void 0:a.tabKey)??((u=e.activePanel)==null?void 0:u.id)??((p=e.panels.find(d=>!ds(d.id)))==null?void 0:p.id);e.addPanel({id:r,component:"remote",title:i,params:{kind:"remote",routeId:n},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function Em({doId:e,targetSessionId:t,connState:n,viewMode:r}){const[a,o]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?jt.onScreenshot("ide-page",(d,m)=>{if(d!==e)return;const f=new FileReader;f.onload=()=>o(f.result),f.readAsDataURL(m)}):void 0,[e]),l.useEffect(()=>{n!=="connected"&&o(null)},[n]),l.useEffect(()=>{var d;return e?((d=jt.onStatus)==null?void 0:d.call(jt,(m,f)=>{m===e&&f!=null&&f.screenshotUsage&&c(f.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{o(null)},[e,t]),l.useEffect(()=>{const p=e?jt.get(e):null;if(!(!p||n!=="connected"))return r!=="chat"&&t?p.startScreenshots(t):p.stopScreenshots(t),()=>{p.stopScreenshots(t)}},[r,n,t,e]);const u=l.useCallback(async(p,d)=>{const m=e?jt.get(e):null;return!m||n!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):m.sendInput(p,d,t)},[e,n,t]);return{connScreenshot:a,screenshotUsage:i,handleRemoteAction:u}}const _m=l.createContext(null);function Za(){const e=l.useContext(_m);if(!e)throw new Error("DashboardDockviewContext missing");return e}function sN(e){const[,t]=l.useState(0);l.useEffect(()=>{const n=()=>t(a=>a+1),r=[e.api.onDidActiveGroupChange(n),e.api.onDidTitleChange(n),e.api.onDidGroupChange(n),e.containerApi.onDidActivePanelChange(n)];return()=>{for(const a of r)a.dispose()}},[e.api,e.containerApi])}function nN({params:e}){var u;const t=Za(),n=l.useMemo(()=>bs([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),r=l.useMemo(()=>t.ides.find(p=>p.id===e.routeId),[t.ides,e.routeId]),a=(n==null?void 0:n.daemonId)||((u=n==null?void 0:n.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:i,handleRemoteAction:c}=Em({doId:a,targetSessionId:n?cp(n):(r==null?void 0:r.sessionId)||(r==null?void 0:r.instanceId),connState:(n==null?void 0:n.connectionState)||"new",viewMode:"remote"});return n?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(Iu,{addLog:()=>{},connState:n.connectionState||"new",connScreenshot:o,screenshotUsage:i,transportType:n.transport,onAction:c})}):s.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:"Remote view unavailable"})}function rN(){const e=Za();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(yl,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function aN(e){var b,C;sN(e);const t=Za(),n=l.useCallback(j=>{"button"in j&&j.button!==0||e.api.setActive()},[e.api]),r=e.params.kind==="remote"?void 0:t.conversationsByTabKey.get(e.params.tabKey),a=r==null?void 0:r.sessionId,o=l.useCallback(j=>Dk(j),[]),i=l.useCallback(()=>Mk(a),[a]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const j=bs([...t.conversationsByTabKey.values()],e.params.routeId),k=((b=e.api.group.activePanel)==null?void 0:b.id)===e.api.id,v=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${k?" is-active":""}${v?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(j==null?void 0:j.tabKey)||"",onMouseDown:n,onTouchStart:n,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:j!=null&&j.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:j.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const u=t.conversationsByTabKey.get(e.params.tabKey);if(!u)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const p=((C=e.api.group.activePanel)==null?void 0:C.id)===e.api.id,d=e.api.isGroupActive,m=Wa(u,t.liveSessionInboxState,{isOpenConversation:p}),f=m.isReconnecting,g=m.isConnecting,S=m.isGenerating||c,h=m.isWaiting,x=m.unread,y=t.tabShortcuts[u.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${p?" is-active":""}${d?" is-group-active":""}${f?" is-reconnecting":""}`,title:kt(u),"data-tab-key":e.params.tabKey,onMouseDown:n,onTouchStart:n,onContextMenu:j=>{var k;j.preventDefault(),n(j),t.openTabContextMenu({x:j.clientX,y:j.clientY,tabKey:u.tabKey,sourceDocument:((k=j.target)==null?void 0:k.ownerDocument)??document})},children:[x&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:S?s.jsx("div",{className:"tab-spinner"}):h?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):f?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):g?s.jsx("div",{className:"tab-connecting-spinner"}):u.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:kt(u)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:f?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:an(u)}):g?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:an(u)}):s.jsx("span",{children:an(u)})})]}),y&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:y,children:y})]})}function Yr(e){return e.isActive}function fd(e){return e.isVisible}function oN(e){e.preventDefault()}function iN({params:e,api:t}){var g;const n=Za(),r=l.useRef(null),[a,o]=l.useState(()=>Yr(t)),[i,c]=l.useState(()=>fd(t)),u=n.conversationsByTabKey.get(e.tabKey),p=Ka({sendDaemonCommand:n.sendDaemonCommand,activeConv:u,setActionLogs:n.setActionLogs,isStandalone:n.isStandalone});l.useEffect(()=>{o(Yr(t)),c(fd(t));const S=[t.onDidActiveChange(h=>o(h.isActive)),t.onDidActiveGroupChange(h=>{if(!Yr(t)&&!h.isActive){o(!1);return}o(Yr(t))}),t.onDidVisibilityChange(h=>c(h.isVisible))];return()=>{for(const h of S)h.dispose()}},[t]);const d=l.useMemo(()=>u?n.ides.find(S=>S.id===u.routeId):void 0,[n.ides,u]),m=l.useMemo(()=>u?n.actionLogs.filter(S=>S.routeId===u.tabKey):[],[n.actionLogs,u]);if(!u)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(yl,{conversationsCount:0,isSplitMode:!1,isStandalone:n.isStandalone,hasRegisteredMachines:n.hasRegisteredMachines,onOpenNewSession:n.onOpenNewSession,suppressGuide:n.hasDetachedConversationPanels})});const f=!pt(u)&&Gn(u)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(xl,{activeConv:u,clearToken:n.clearedTabs[u.tabKey]||0,isCliTerminal:f,ideEntry:d,terminalRef:r,handleModalButton:p.handleModalButton,handleRelaunch:p.handleRelaunch,handleSendChat:p.handleSendChat,handleForceSendChat:p.handleForceSendChat,isSendingChat:p.isSendingChat,handleFocusAgent:p.handleFocusAgent,isFocusingAgent:p.isFocusingAgent,actionLogs:m,userName:n.userName,scrollToBottomRequestNonce:((g=n.scrollToBottomRequest)==null?void 0:g.tabKey)===u.tabKey?n.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:i})})}function lN({visibleConversations:e,clearedTabs:t,ides:n,actionLogs:r,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:u,userName:p,toggleHiddenTab:d,actionShortcuts:m,registerActionHandlers:f,onActiveTabChange:g,onOpenNewSession:S,onRequestScrollToBottom:h,requestedActiveTabKey:x,requestedRemoteIdeId:y,onRequestedActiveTabConsumed:b,scrollToBottomRequest:C,liveSessionInboxState:j,layoutProfile:k}){var lt,at,bt;const{theme:v}=qs(),{sendCommand:N}=St(),w=l.useRef(null),A=l.useRef(null),T=l.useRef(null),I=l.useRef(!1),P=l.useRef(!1),D=l.useRef(!1),_=l.useRef(null),W=l.useRef([]),[$,E]=l.useState(null),[B,L]=l.useState(0),R=l.useRef(typeof window>"u"?{}:Nj(k)),M=l.useMemo(()=>new Map(e.map(X=>[X.tabKey,X])),[e]),F=l.useMemo(()=>{const X=w.current;return X?X.groups.some(te=>{try{const oe=te.model.location.type;return oe!=="floating"&&oe!=="popout"?!1:te.panels.some(be=>M.has(be.id))}catch{return!1}}):!1},[M,B,e]),K=l.useCallback(()=>{var X;(X=w.current)==null||X.focus()},[]),J=l.useCallback((X,te)=>{h==null||h(X,te)},[h]),V=l.useCallback(X=>{const te=document,oe=X.document;for(const Ie of te.querySelectorAll('link[rel="stylesheet"]')){const ze=oe.createElement("link");ze.rel="stylesheet",ze.href=Ie.href,Ie.crossOrigin&&(ze.crossOrigin=Ie.crossOrigin),oe.head.appendChild(ze)}for(const Ie of te.querySelectorAll("style")){const ze=oe.createElement("style");ze.textContent=Ie.textContent,oe.head.appendChild(ze)}const be=[];for(const Ie of te.styleSheets)try{for(const ze of Ie.cssRules)ze instanceof CSSStyleRule&&(ze.selectorText===":root"||ze.selectorText==="html")&&be.push(ze.cssText)}catch{}if(be.length>0){const Ie=oe.createElement("style");Ie.textContent=be.join(`
69
+ Use this if you want to permanently remove a machine.`,confirmLabel:o("machine.connectedMachines.remove"),confirmColor:"red",onConfirm:T,onCancel:()=>m(null)})]})}const NC=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli","gemini-cli"];function AC({daemonId:e,knownCliTypes:t=NC}){const{t:n}=Ne("common"),{sendCommand:r}=St(),[a,o]=l.useState({}),[i,c]=l.useState({}),[u,p]=l.useState(!0),[d,m]=l.useState(null),[f,g]=l.useState(null),[S,h]=l.useState(""),x=l.useCallback(async()=>{if(e){p(!0),g(null);try{const C=await r(e,"list_coordinator_prompts",{}),j=C!=null&&C.result&&typeof C.result=="object"?C.result:C;if(!(j!=null&&j.success)){g((j==null?void 0:j.error)||"Failed to load");return}const k=j.entries||{};h(j.dir||"");const v={};for(const N of t)v[N]=k[N]||{override:"",append:""};for(const N of Object.keys(k))v[N]||(v[N]=k[N]);o(v),c(JSON.parse(JSON.stringify(v)))}catch(C){g((C==null?void 0:C.message)||String(C))}finally{p(!1)}}},[r,e,t]);l.useEffect(()=>{x()},[x]);const y=l.useCallback(async(C,j)=>{var k;if(e){m(`${C}:${j}`),g(null);try{const v=((k=a[C])==null?void 0:k[j])||"",N=await r(e,"write_coordinator_prompt",{key:C,kind:j,content:v}),w=N!=null&&N.result&&typeof N.result=="object"?N.result:N;if(!(w!=null&&w.success)){g((w==null?void 0:w.error)||"Save failed");return}c(A=>({...A,[C]:{...A[C]||{override:"",append:""},[j]:v}}))}catch(v){g((v==null?void 0:v.message)||String(v))}finally{m(null)}}},[r,e,a]),b=l.useMemo(()=>(C,j)=>{var k,v;return(((k=a[C])==null?void 0:k[j])||"")!==(((v=i[C])==null?void 0:v[j])||"")},[a,i]);return e?s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{className:"text-[12px] text-text-muted",children:[s.jsxs("p",{children:["Customize the coordinator prompt this daemon's mesh coordinator sessions get. ",s.jsx("span",{className:"font-mono text-[11px]",children:S||"~/.adhdev/coordinator-prompts/"})]}),s.jsxs("p",{className:"mt-1",children:[s.jsx(si,{i18nKey:"settings.coordinatorPrompts.overrideDesc",ns:"common",components:{strong:s.jsx("strong",{})}})," ",s.jsx(si,{i18nKey:"settings.coordinatorPrompts.appendDesc",ns:"common",components:{strong:s.jsx("strong",{})}}),"Leave a field empty + Save to remove it (reset to default). Supports placeholders: ","{{meshName}}",", ","{{repo}}",", ","{{nodes}}",", ","{{rules}}",", etc."]})]}),f&&s.jsx("div",{className:"text-[12px] text-status-error bg-status-error/10 border border-status-error/40 rounded px-3 py-2",children:f}),u&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"Loading…"}),s.jsx("div",{className:"flex flex-col gap-6",children:Object.entries(a).map(([C,j])=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-2",children:C}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:n("settings.coordinatorPrompts.overrideLabel")}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:4,value:j.override,onChange:k=>o(v=>({...v,[C]:{...v[C],override:k.target.value}})),placeholder:"(empty — use daemon default base prompt)",disabled:d===`${C}:override`}),s.jsx("div",{className:"mt-1 mb-3 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void y(C,"override"),disabled:d===`${C}:override`||!b(C,"override"),children:d===`${C}:override`?"Saving…":b(C,"override")?"Save override":"Saved"})}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:n("settings.coordinatorPrompts.appendLabel")}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:3,value:j.append,onChange:k=>o(v=>({...v,[C]:{...v[C],append:k.target.value}})),placeholder:"(empty — nothing appended at this layer)",disabled:d===`${C}:append`}),s.jsx("div",{className:"mt-1 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void y(C,"append"),disabled:d===`${C}:append`||!b(C,"append"),children:d===`${C}:append`?"Saving…":b(C,"append")?"Save append":"Saved"})})]},C))})]}):s.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const TC=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function MC(){const{preference:e,setPreference:t}=qs();return s.jsx("div",{className:"flex gap-2",children:TC.map(n=>s.jsxs("button",{onClick:()=>t(n.id),className:`px-3 py-1.5 rounded-lg border text-sm font-medium transition-colors flex items-center gap-1.5 ${e===n.id?"bg-accent border-accent":"bg-bg-glass border-border-subtle hover:bg-bg-secondary text-text-muted hover:text-text-primary"}`,style:e===n.id?{color:"var(--accent-on-primary)"}:void 0,children:[s.jsx("span",{children:n.icon}),n.label]},n.id))})}function DC(e){const t=e.trim();return/^#[0-9a-fA-F]{6}$/.test(t)?t:/^#[0-9a-fA-F]{3}$/.test(t)?`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`:null}function IC(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function jo(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function qc(e){const{r:t,g:n,b:r}=IC(e);return .2126*jo(t)+.7152*jo(n)+.0722*jo(r)}function zc(e,t){const n=qc(e),r=qc(t),a=Math.max(n,r),o=Math.min(n,r);return(a+.05)/(o+.05)}function sm(e){const t=DC(e);if(!t)return"#111827";const n="#111827",r="#ffffff";return zc(t,n)>=zc(t,r)?n:r}const Ni={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},Ai={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},PC=[{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"}}}],nm="adhdev-chat-theme",rm="adhdev-chat-theme-custom";function la(){if(typeof window>"u")return"ember";try{return localStorage.getItem(nm)||"ember"}catch{return"ember"}}function ms(e){try{const t=localStorage.getItem(rm);if(t){const n=JSON.parse(t);return{...e==="dark"?Ni:Ai,...n[e]}}}catch{}return e==="dark"?Ni:Ai}function Gr(e,t){try{localStorage.setItem(rm,JSON.stringify({dark:e,light:t}))}catch{}}function ns(e,t){const n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${n}, ${r}, ${a}, ${t})`}function Ia(e,t){const n=Math.min(255,parseInt(e.slice(1,3),16)+t),r=Math.min(255,parseInt(e.slice(3,5),16)+t),a=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${n.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const LC={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function gr(e,t){var a;const n=(a=LC[e])==null?void 0:a[t];if(!n)return;const r=document.documentElement;r.style.setProperty("--accent-primary",n),r.style.setProperty("--accent-primary-light",Ia(n,24)),r.style.setProperty("--accent-on-primary",sm(n)),r.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${n}, ${Ia(n,18)})`),r.style.setProperty("--border-accent",ns(n,.35)),r.style.setProperty("--nav-active-bg",ns(n,.1)),r.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${n}, 0 0 12px ${ns(n,.06)}`)}function on(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",ns(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",ns(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",ns(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",ns(e.borderSubtle,.5)),t.style.setProperty("--border-default",ns(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",Ia(e.accentColor,30)),t.style.setProperty("--accent-on-primary",sm(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${Ia(e.accentColor,40)})`),t.style.setProperty("--border-accent",ns(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",ns(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${ns(e.accentColor,.06)}`),t.style.setProperty("--chat-user-bg",e.userBubble),t.style.setProperty("--chat-user-color",e.userText),t.style.setProperty("--chat-user-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px 4px ${e.bubbleRadius}px`),t.style.setProperty("--chat-assistant-bg",e.assistantBubble),t.style.setProperty("--chat-assistant-color",e.assistantText),t.style.setProperty("--chat-assistant-radius",`${e.bubbleRadius}px ${e.bubbleRadius}px ${e.bubbleRadius}px 4px`),t.style.setProperty("--chat-assistant-border",`1px solid ${ns(e.accentColor,.12)}`),t.style.setProperty("--chat-container-bg",e.containerBg),t.style.setProperty("--dashboard-pane-bg",e.containerBg),t.style.setProperty("--chat-thought-accent",e.accentColor),t.style.setProperty("--chat-tool-accent",e.accentColor),t.style.setProperty("--chat-action-color",e.accentColor),t.style.setProperty("--chat-send-bg",e.sendButton),t.style.setProperty("--chat-input-border",e.inputBorder)}function ul(){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(n=>e.style.removeProperty(n))}function RC(e){try{localStorage.setItem(nm,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ln()?"dark":"light";on(ms(t))}else ul(),gr(e,ln()?"dark":"light")}function EC(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=la();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=ln()?"dark":"light";on(ms(t))}else ul(),gr(e,ln()?"dark":"light")}function ln(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Gt({label:e,value:t,onChange:n}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange:r=>n(r.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),s.jsx("input",{type:"text",value:t,onChange:r=>{/^#[0-9a-fA-F]{0,6}$/.test(r.target.value)&&n(r.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function er({title:e,children:t}){return s.jsxs("div",{style:{marginBottom:14},children:[s.jsx("div",{style:{fontSize:"0.65rem",fontWeight:700,textTransform:"uppercase",color:"var(--text-muted)",letterSpacing:"0.08em",marginBottom:8,borderBottom:"1px solid var(--border-subtle)",paddingBottom:4},children:e}),s.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:t})]})}function _C({dark:e,onColorsChange:t}){const{t:n}=Ne("common"),r=e?"dark":"light",[a,o]=l.useState(()=>ms(r));l.useEffect(()=>{o(ms(r))},[r]);const i=l.useCallback((c,u)=>{o(p=>{const d={...p,[c]:u},f=ms(r==="dark"?"light":"dark");return r==="dark"?Gr(d,f):Gr(f,d),on(d),t(d),d})},[r,t]);return s.jsxs("div",{style:{marginTop:12,padding:"16px 14px",background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:12,overflow:"hidden"},children:[s.jsxs("div",{style:{fontSize:"0.75rem",fontWeight:700,color:"var(--text-primary)",marginBottom:14,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[n("settings.theme.customEditorTitle"),s.jsx("span",{style:{fontSize:"0.65rem",fontWeight:500,color:"var(--text-muted)",background:"var(--bg-glass)",padding:"2px 8px",borderRadius:4},children:n(e?"settings.theme.darkMode":"settings.theme.lightMode")})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[s.jsxs("div",{children:[s.jsxs(er,{title:n("settings.theme.sectionAppBackground"),children:[s.jsx(Gt,{label:n("settings.theme.colorBackground"),value:a.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(Gt,{label:n("settings.theme.colorSurface"),value:a.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(Gt,{label:n("settings.theme.colorCard"),value:a.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(er,{title:n("settings.theme.sectionAppText"),children:[s.jsx(Gt,{label:n("settings.theme.colorPrimary"),value:a.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(Gt,{label:n("settings.theme.colorSecondary"),value:a.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(Gt,{label:n("settings.theme.colorMuted"),value:a.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(er,{title:n("settings.theme.sectionBordersAccent"),children:[s.jsx(Gt,{label:n("settings.theme.colorBorderSubtle"),value:a.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(Gt,{label:n("settings.theme.colorBorderDefault"),value:a.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(Gt,{label:n("settings.theme.colorAccent"),value:a.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(er,{title:n("settings.theme.sectionChatBubbles"),children:[s.jsx(Gt,{label:n("settings.theme.colorUserBubble"),value:a.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(Gt,{label:n("settings.theme.colorUserText"),value:a.userText,onChange:c=>i("userText",c)}),s.jsx(Gt,{label:n("settings.theme.colorAgentBubble"),value:a.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(Gt,{label:n("settings.theme.colorAgentText"),value:a.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(er,{title:n("settings.theme.sectionChatLayout"),children:[s.jsx(Gt,{label:n("settings.theme.colorChatBg"),value:a.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(Gt,{label:n("settings.theme.colorSendButton"),value:a.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(Gt,{label:n("settings.theme.colorInputBorder"),value:a.inputBorder,onChange:c=>i("inputBorder",c)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:n("settings.theme.labelBubbleRadius")}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.jsx("input",{type:"range",min:4,max:24,value:a.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[a.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const c=e?Ni:Ai,p=ms(e?"light":"dark");e?Gr(c,p):Gr(p,c),o(c),on(c),t(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:n("settings.theme.resetToDefaults")})]})}function $C(){const{t:e}=Ne("common"),[t,n]=l.useState(la),[r,a]=l.useState(!0),[o,i]=l.useState(()=>ms("dark"));l.useEffect(()=>{a(ln());const p=new MutationObserver(()=>{const f=ln();a(f);const g=la();g==="custom"?on(ms(f?"dark":"light")):gr(g,f?"dark":"light")});p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const d=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const f=ln();a(f);const g=la();g==="custom"?on(ms(f?"dark":"light")):gr(g,f?"dark":"light")};return d.addEventListener("change",m),()=>{p.disconnect(),d.removeEventListener("change",m)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?on(ms(r?"dark":"light")):(ul(),gr(t,r?"dark":"light"))},[t,r]),l.useEffect(()=>{i(ms(r?"dark":"light"))},[r]);const c=p=>{n(p),RC(p)},u=[...PC,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText},light:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:u.map(p=>{const d=t===p.id,m=r?p.preview.dark:p.preview.light,f=p.id==="honey"||p.id==="ember"?"#1a1a1a":p.id==="custom"?o.userText:"#fff";return s.jsxs("button",{onClick:()=>c(p.id),className:"text-left rounded-xl p-3 transition-all",style:{background:d?"var(--bg-glass-hover)":"var(--bg-glass)",border:d?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:d?1:.75},children:[s.jsxs("div",{className:"rounded-lg p-3 mb-2.5 flex flex-col gap-1.5",style:{background:m.containerBg},children:[s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:e("settings.theme.helloHelp")}),s.jsx("div",{className:"self-end rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.userBubble,color:f},children:e("settings.theme.fixBug")}),s.jsx("div",{className:"self-start rounded-xl px-3 py-1.5 text-[10px] max-w-[75%]",style:{background:m.assistantBubble,border:m.assistantBorder,color:m.textColor},children:e("settings.theme.onIt")})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[d&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:p.id==="custom"?e("settings.theme.customLabel"):p.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:p.description})]})]})]},p.id)})}),t==="custom"&&s.jsx(_C,{dark:r,onColorsChange:p=>i(p)})]})}const pl="adhdev_mobileDashboardMode_v1",Ti="adhdev:mobile-dashboard-mode-change";function ml(){try{return localStorage.getItem(pl)==="workspace"?"workspace":"chat"}catch{return"chat"}}function HC(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??ml())},n=a=>{const o=a.detail;t(o)},r=a=>{a.key&&a.key!==pl||t()};return window.addEventListener(Ti,n),window.addEventListener("storage",r),()=>{window.removeEventListener(Ti,n),window.removeEventListener("storage",r)}}function FC(e){try{localStorage.setItem(pl,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ti,{detail:e}))}function BC(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(ml()==="chat")},[]),s.jsx(tn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(bn,{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:n=>{t(n),FC(n?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const WC="Choose a preset or create a fully custom theme. Custom themes control the entire app — backgrounds, text, borders, and chat bubbles.",OC="Choose whether the dashboard opens like a chat app on phones or keeps the full workspace layout.";function UC({themeDescription:e=WC,mobileDescription:t=OC,fontsSlot:n}){const{t:r}=Ne("common");return s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:r("settings.appearance.modeLabel")}),s.jsx(MC,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:r("settings.appearance.themeLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:e}),s.jsx($C,{})]}),n,s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:r("settings.appearance.mobileLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:t}),s.jsx(BC,{})]})]})}const No=new Map,Kc=new Map;function GC(e){if(!e||typeof e!="object")return null;const t=e,n=t.result&&typeof t.result=="object"?t.result:t,r=n.machine;return!r||typeof r!="object"?null:{machine:r,timestamp:typeof n.timestamp=="number"?n.timestamp:void 0}}function qC(e,t,n,r){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:r,platform:n.platform,machine:n}}function am(){const{sendCommand:e}=St(),{injectEntries:t,getIdes:n}=yr();return l.useCallback(async(r,a)=>{if(!r)return;const o=(a==null?void 0:a.minFreshMs)??J0,i=Kc.get(r)||0;if(!(a!=null&&a.force)&&i>0&&Date.now()-i<o)return;const c=No.get(r);if(c)return c;const u=(async()=>{const p=await e(r,"get_machine_runtime_stats"),d=GC(p);if(!d)return;const m=n().find(g=>g.id===r),f=qC(m,r,d.machine,d.timestamp||Date.now());t([f]),Kc.set(r,Date.now())})().finally(()=>{No.delete(r)});return No.set(r,u),u},[n,t,e])}function zC(e,t,n){return{...e||{},id:t,type:(e==null?void 0:e.type)||"adhdev-daemon",status:(e==null?void 0:e.status)||"online",timestamp:n.timestamp,platform:n.machine.platform,machine:{...(e==null?void 0:e.machine)||{},...n.machine}}}function KC(e,t){const{sendData:n}=St(),{injectEntries:r,getIdes:a}=yr(),o=Array.from(new Set(e.filter(Boolean))).join("|");l.useEffect(()=>{if(!(t!=null&&t.enabled)||!n)return;const i=o?o.split("|"):[];if(i.length===0)return;const c=i.map(u=>fs.subscribe({sendData:n},u,{type:"subscribe",topic:"machine.runtime",key:`machine:${u}`,params:{intervalMs:t==null?void 0:t.intervalMs}},d=>{const m=a().find(g=>g.id===u),f=zC(m,u,d);r([f])}));return()=>{c.forEach(u=>u())}},[o,a,r,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,n])}function VC(e,t){const{sendData:n}=St(),[r,a]=l.useState(null),[o,i]=l.useState(!1);return l.useEffect(()=>{if(!e){a(null),i(!1);return}if(!(t!=null&&t.enabled)||!n){i(!1);return}a(null),i(!0);let c=null;const u=fs.subscribe({sendData:n},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},p=>{c&&(clearTimeout(c),c=null),a(p.diagnostics),i(!1)});return u.initialSendAccepted?c=setTimeout(()=>{i(!1)},Z0):i(!1),()=>{c&&clearTimeout(c),u()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,n]),{diagnostics:r,loading:o,applyDiagnostics:a}}function YC(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function om(e){const{sendData:t}=St(),[n,r]=l.useState({});return l.useEffect(()=>{const a=YC(e);if(!a||!e.sessionId||!t){r({});return}const o=fs.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},i=>{r({status:i.status,modalMessage:i.modalMessage,modalButtons:i.modalButtons}),Ln.record({interactionId:i.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:i.status,modalButtonCount:Array.isArray(i.modalButtons)?i.modalButtons.length:0}})});return o.initialSendAccepted||r({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),n}function JC(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function QC(e){const t=(e==null?void 0:e.result)??e;return typeof(t==null?void 0:t.error)=="string"?t.error:"Interactive prompt response failed"}async function XC(e,t,n){const r=await n(`/api/v1/sessions/${encodeURIComponent(e)}/interactive-prompt/resolve`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let a=`HTTP ${r.status}`;try{const o=await r.json();typeof(o==null?void 0:o.error)=="string"&&(a=o.error)}catch{}throw new Error(a)}}async function ZC({promptSession:e,response:t,useP2PCommand:n,sendCommand:r,fetchImpl:a=fetch}){if(n){const o=await r(e.routeId,"interactive_prompt_response",{targetSessionId:e.sessionId,sessionId:e.sessionId,response:t});if(!JC(o))throw new Error(QC(o));return}await XC(e.sessionId,t,a)}function im(e){const{ides:t,isP2PActive:n,p2pStates:r}=As(),{sendCommand:a}=St(),[o,i]=l.useState(null),[c,u]=l.useState(!1),[p,d]=l.useState(null),m=l.useRef(!1),f=l.useMemo(()=>Kb(t,e),[t,e]),g=!!f,S=l.useMemo(()=>f?f.prompt.promptId===o?null:f:null,[o,f]),h=l.useCallback(async b=>{if(!S||m.current)return;m.current=!0;const C=Pu(S.prompt,b);u(!0),d(null);try{const j=(r==null?void 0:r[S.daemonId])==="connected"||n===!0;await ZC({promptSession:S,response:C,useP2PCommand:j,sendCommand:a}),i(S.prompt.promptId)}catch(j){throw d(j instanceof Error?j.message:String(j)),j}finally{u(!1),m.current=!1}},[n,r,S,a]),x=l.useCallback(()=>{S&&i(S.prompt.promptId)},[S]),y=l.useCallback(()=>{i(null),d(null)},[]);return{promptSession:S,hasActivePrompt:g,responseError:p,isSubmitting:c,submit:h,cancel:x,reopen:y}}function lm(e){return e instanceof Error?e.message:String(e||"")}function ej(e){const t=lm(e);return t.includes("P2P command timeout")||t.includes("P2P not connected")||t.includes("P2P channel not open")||t.includes("P2P not available")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}function tj(e){const t=lm(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function cm({conversation:e,mode:t,ides:n,sendDaemonCommand:r,setCliViewModeOverrides:a}){if(!e||!ht(e)||pt(e))return;const o=Gn(e);if(o===t)return;const i=e.sessionId;i&&a(c=>({...c,[i]:t}));try{await r(Rs(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:Ns(e),mode:t})}catch(c){const u=tj(c);i&&!u&&a(p=>{const d={...p};return o===nj(n,i)?delete d[i]:d[i]=o,d}),ej(c)?console.warn(u?"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 Vc(e,t){const n=typeof e.sessionId=="string"&&e.sessionId?e.sessionId:typeof e.id=="string"?e.id:"";if(!n||e.transport!=="pty")return e;const r=t[n];return!r||e.mode===r?e:{...e,mode:r}}function sj(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let n=!1;const r=e.map(a=>{const o=Vc(a,t),i=Array.isArray(a.childSessions)?a.childSessions.map(u=>Vc(u,t)):a.childSessions,c=i!==a.childSessions;return o!==a||c?(n=!0,{...o,...c?{childSessions:i}:{}}):a});return n?r:e}function nj(e,t){if(!t)return null;for(const n of e){if(n.sessionId===t&&n.transport==="pty")return n.mode==="chat"?"chat":"terminal";for(const r of n.childSessions||[])if(r.id===t&&r.transport==="pty")return r.mode==="chat"?"chat":"terminal"}return null}function rj({visibleConversations:e,clearedTabs:t,setClearedTabs:n,setActionLogs:r,isConversationMuted:a}){l.useEffect(()=>{Ku()},[]);const o=l.useMemo(()=>e.map(i=>({id:i.tabKey,name:Lp(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null,target:{providerSessionId:i.providerSessionId,sessionId:i.sessionId,tabKey:i.tabKey,routeId:i.routeId},muted:a?a(i):!1})),[e,a]);return Sw(o),l.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{n(u=>{const p=Date.now(),d={};for(const[m,f]of Object.entries(u))p-f<5e3&&(d[m]=f);return Object.keys(d).length===Object.keys(u).length?u:d})},5500);return()=>clearTimeout(c)},[t,n]),l.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;r(u=>{const p=u.filter(d=>d.timestamp>c).slice(-100);return p.length===u.length?u:p})},6e4);return()=>clearInterval(i)},[r]),null}function Yc(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function cn(e){const t=[...e.messages].reverse().find(a=>!(a!=null&&a._localId))||e.messages[e.messages.length-1],n=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,r=Yc(t==null?void 0:t.receivedAt)||Yc(t==null?void 0:t.timestamp)||0;return Math.max(n,r)}function Mi(e,t=0){return cn(e)||e.lastUpdated||t||0}function dm(e){return cn(e)||e.lastUpdated||0}function um(e,t,n=dm){const r=n(t)-n(e);if(r!==0)return r;const a=(e.machineName||"").localeCompare(t.machineName||"");if(a!==0)return a;const o=e.displayPrimary.localeCompare(t.displayPrimary);if(o!==0)return o;const i=e.displaySecondary.localeCompare(t.displaySecondary);return i!==0?i:e.tabKey.localeCompare(t.tabKey)}function Di(e){var n;const t=as(e.status,{activeModal:(n=e.modalButtons)!=null&&n.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function aj(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!Di(e)&&!e.title.trim()}function oj(e){return e.length===0?null:[...e].sort((t,n)=>{const r=Number(Di(n))-Number(Di(t));if(r!==0)return r;const a=n.messages.length-t.messages.length;return a!==0?a:um(t,n)})[0]||null}function bs(e,t){const n=e.filter(i=>i.routeId===t);if(n.length===0)return null;const r=n.find(i=>i.streamSource==="native")||null,a=n.filter(i=>i.streamSource==="agent-stream"),o=oj(a);return r?o&&aj(r)?o:r:o||n[0]||null}function ij(e){const t=e.filter(a=>a.type!=="adhdev-daemon"),n=new Set;for(const a of t){if(!fi(a))continue;const o=Wu(a);o&&n.add(o)}const r=new Map;for(const a of t){const o=ew(a,n),i=r.get(o);if(!i){r.set(o,a);continue}const c=m=>(m.workspace?1:0)+(m.activeChat?1:0)+(m.lastMessagePreview?1:0),u=c(i),p=c(a),d=p>u||p===u&&(a.timestamp||0)>(i.timestamp||0)?a:i;r.set(o,lj(d,d===a?i:a))}return Array.from(r.values())}function lj(e,t){const n=fi(t),r=fi(e);if(!n&&!r)return e;const a=r?n?void 0:t:e,o=r?e:n?t:void 0,i=a&&String(a.daemonId||"").trim()||String(e.ownerDaemonId||"").trim()||String(t.ownerDaemonId||"").trim()||void 0,c=String(e.ownerMachineName||"").trim()||String(t.ownerMachineName||"").trim()||void 0,u=o==null?void 0:o.settings;return{...e,...i&&{ownerDaemonId:i},...c&&!e.ownerMachineName&&{ownerMachineName:c},...u&&!r&&{settings:{...u,...e.settings??{}}}}}function Ao(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function cj(e){let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619)>>>0;return t.toString(16).padStart(8,"0")}function Jc(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],n=t[t.length-1],r=n?cj(Rn(n.content)):"";return[e.id||"",e.title||"",e.status||"",t.length,String((n==null?void 0:n.id)||""),String((n==null?void 0:n.index)??""),String((n==null?void 0:n.receivedAt)??(n==null?void 0:n.timestamp)??""),r].join(":")}function dj(e){const t=Array.isArray(e.childSessions)?e.childSessions:[];return[e.id,e.sessionId||"",e.providerSessionId||"",e.transport||"",e.mode||"",e.status||"",e.workspace||"",e.lastMessageHash||"",String(e.lastMessageAt||""),e.lastMessagePreview||"",e.lastMessageRole||"",String(e.lastUpdated||""),Jc(e.activeChat),...t.map(n=>[n.id||"",n.providerSessionId||"",n.transport||"",n.mode||"",n.status||"",n.title||"",n.lastMessageHash||"",String(n.lastMessageAt||""),n.lastMessagePreview||"",n.lastMessageRole||"",String(n.lastUpdated||""),Jc(n.activeChat)].join(":"))].join("|")}function uj(e,t){const n=Date.now();return e.map(r=>{const a=t[r.tabKey];return a&&n-a<5e3?{...r,messages:[],title:""}:r})}function pj(e,t){const n=new Map;for(const r of e){const a=t.get(r.routeId)||r;for(const o of mr({routeId:r.routeId}))n.set(o,a);for(const o of mr({providerSessionId:r.providerSessionId,sessionId:r.sessionId}))n.set(o,r.streamSource==="native"?a:r);for(const o of mr({tabKey:r.tabKey}))n.set(o,r)}return n}function mj(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function hj(e){const t=mj(e);if(!t)return`empty:${e.messages.length}`;if(t.id)return`id:${String(t.id)}`;if(t._localId)return`local:${String(t._localId)}`;const n=String(t.role||""),r=Rn(t.content).slice(0,240);return`${e.messages.length}:${n}:${r}`}function fj({ides:e,connectionStates:t,clearedTabs:n}){const r=l.useMemo(()=>ij(e),[e]),a=l.useMemo(()=>Eu(e),[e]),o=l.useMemo(()=>Gp(e),[e]),i=l.useRef([]),c=l.useRef([]),u=l.useRef([]),p=l.useRef(new Map),d=l.useRef(new Map),m=l.useMemo(()=>{const j=new Map,k=[];for(const A of r){const{connectionState:T="new",machineName:I}=qp(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),P=dj(A),D=p.current.get(A.id);if(D&&D.ide===A&&D.sourceSignature===P&&D.connectionState===T&&D.machineName===I){j.set(A.id,D),k.push(...D.conversations);continue}const _=cl(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),W={ide:A,sourceSignature:P,connectionState:T,machineName:I,conversations:_};j.set(A.id,W),k.push(..._)}p.current=j;const v=new Map,N=A=>{const T=hj(A),I=d.current.get(A.tabKey);if(I&&I.signature===T)return v.set(A.tabKey,I),I.timestamp;const P={signature:T,timestamp:dm(A)||(I==null?void 0:I.timestamp)||0};return v.set(A.tabKey,P),P.timestamp},w=[...k].sort((A,T)=>um(A,T,N));return d.current=v,w},[r,t,o]),f=l.useMemo(()=>{const j=uj(m,n);return Ao(i.current,j)?i.current:(i.current=j,j)},[m,n]),g=l.useMemo(()=>{const j=new Map,k=Array.from(new Set(f.map(v=>v.routeId)));for(const v of k){const N=bs(f,v);N&&j.set(v,N)}return j},[f]),S=l.useMemo(()=>{const j=new Map;for(const k of f){const v=g.get(k.routeId),N=k.streamSource==="native"&&v?v:k;for(const w of mr({providerSessionId:k.providerSessionId,sessionId:k.sessionId,tabKey:k.tabKey}))j.set(w,N)}return j},[f,g]),h=l.useMemo(()=>pj(f,g),[f,g]),x=l.useCallback(j=>{if(j)return S.get(j)},[S]),y=l.useCallback(j=>{if(j)return h.get(j)},[h]),b=l.useMemo(()=>{const j=f.filter(k=>!Gs(k,a).surfaceHidden);return Ao(c.current,j)?c.current:(c.current=j,j)},[f,a]),C=l.useMemo(()=>{const j=b.map(k=>k.tabKey);return Ao(u.current,j)?u.current:(u.current=j,j)},[b]);return{chatIdes:r,conversations:f,visibleConversations:b,visibleTabKeys:C,resolveConversationBySessionId:x,resolveConversationByTarget:y}}function bj({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:n,setSearchParams:r}){const a=l.useMemo(()=>{var c;return e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),o=l.useMemo(()=>{var c;return!e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),i=l.useCallback(()=>{t&&r(c=>{const u=new URLSearchParams(c);return u.delete("activeTab"),u},{replace:!0})},[r,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:o,consumeRequestedActiveTab:i}}function gj({ides:e,sendDaemonCommand:t,setToasts:n,resolveConversationByTarget:r}){l.useEffect(()=>{ft.setIdes(e)},[e]),l.useEffect(()=>{ft.setResolveAction((a,o,i)=>{t(a,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const a=ft.onToast(o=>{n(c=>c.some(p=>p.message===o.message&&o.timestamp-p.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 i=o.duration||5e3;setTimeout(()=>n(c=>c.filter(u=>u.id!==o.id)),i)});return()=>{a()}},[n]),l.useEffect(()=>{const a=Mp.on("status_event",o=>{ft.handleRawEvent(o,"ws")});return()=>{a()}},[]),l.useEffect(()=>{var o;const a=i=>{var h;const c=i.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 u=c.targetSessionId||c.targetKey||c.daemonId,p=r(u),d=(p==null?void 0:p.routeId)||c.daemonId;if(!d)return;const m=Number(c.buttonIndex),f=c.button||((h=p==null?void 0:p.modalButtons)==null?void 0:h[m])||"Approve",g=String(f).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),S=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(g);t(d,"resolve_action",{action:S?"approve":"reject",button:f,...Number.isFinite(m)&&{buttonIndex:m},...(p==null?void 0:p.sessionId)&&{targetSessionId:p.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(x=>console.error("[SW Action] approval failed:",x))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",a),()=>{var i;return(i=navigator.serviceWorker)==null?void 0:i.removeEventListener("message",a)}},[r,t])}const xj="adhdev_dashboardLayout_v1",vj="adhdev_dashboardDockview_v1",yj="adhdev_dashboardDockviewHiddenRestore_v1",tr={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function hl(e,t){try{const n=localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}}function wj(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function pm(e){return`${xj}:${e}`}function kj(e){const t=pm(e);return hl(t,null)}function Sj(e,t){try{const n=t.groupAssignments.length===0&&t.focusedGroup===0&&Object.keys(t.groupActiveTabIds).length===0&&Object.keys(t.groupTabOrders).length===0&&t.groupSizes.length===0,r=pm(e);if(n){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function mm(e){return`${vj}:${e}`}function Cj(e){const t=mm(e);return hl(t,null)}function jj(e,t){try{const n=mm(e);if(!t){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function hm(e){return`${yj}:${e}`}function Nj(e){const t=hm(e);return hl(t,{})}function Aj(e,t){try{const n=hm(e);if(Object.keys(t).length===0){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Tj(){return{groupAssignments:[...tr.groupAssignments],focusedGroup:tr.focusedGroup,groupActiveTabIds:{...tr.groupActiveTabIds},groupTabOrders:{...tr.groupTabOrders},groupSizes:[...tr.groupSizes]}}function Mj(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):t.length===0}function Dj(){const[e]=l.useState(()=>wj(typeof window<"u"?window.innerWidth:1280)),[t,n]=l.useState(()=>new Map),[r,a]=l.useState(0),[o,i]=l.useState({}),[c,u]=l.useState({}),[p,d]=l.useState([]),[m,f]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[g,S]=l.useState(!1),h=l.useCallback(()=>{if(g)return;const A=kj(e)??Tj();n(new Map(A.groupAssignments)),a(A.focusedGroup),i(A.groupActiveTabIds),u(A.groupTabOrders),d(A.groupSizes),S(!0)},[g,e]);l.useEffect(()=>{g&&Sj(e,{groupAssignments:[...t.entries()],focusedGroup:r,groupActiveTabIds:o,groupTabOrders:c,groupSizes:p})},[g,e,t,r,o,c,p]),l.useEffect(()=>{const A=window.matchMedia("(max-width: 767px)"),T=I=>f(I.matches);return A.addEventListener("change",T),()=>A.removeEventListener("change",T)},[]);const x=l.useCallback(A=>{n(A)},[]),y=l.useCallback(A=>{a(A)},[]),b=l.useCallback(A=>{i(A)},[]),C=l.useCallback(A=>{u(A)},[]),j=l.useCallback(A=>{d(A)},[]),k=l.useCallback(A=>{y(A)},[y]),v=l.useCallback((A,T)=>{i(I=>(I[A]??null)===(T??null)?I:{...I,[A]:T})},[]),N=l.useCallback((A,T)=>{u(I=>{const P=I[A];return Mj(P,T)?I:{...I,[A]:T}})},[]),w=l.useCallback((A,T)=>{const I=T.get(A)??0;return v(I,A),k(I),I},[k,v]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:x,focusedGroup:r,updateFocusedGroup:y,focusGroup:k,groupActiveTabIds:o,updateGroupActiveTabIds:b,setGroupActiveTab:v,groupTabOrders:c,updateGroupTabOrders:C,setGroupTabOrder:N,groupSizes:p,updateGroupSizes:j,isMobile:m,hasHydratedStoredLayout:g,hydrateStoredLayout:h,focusConversationTab:w}}function Ij(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0],r=Oa(t);return typeof(n==null?void 0:n.id)=="string"&&r.includes(n.id)}function Pj({urlActiveTab:e,conversations:t,resolveConversationBySessionId:n,normalizedGroupAssignments:r,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:i,setSearchParams:c,historyModalOpen:u,activeConv:p,isRefreshingHistory:d,ides:m,handleRefreshHistory:f}){const g=l.useRef(!1),S=l.useRef(!1),h=l.useRef(null),x=l.useRef(!1);l.useEffect(()=>{if(!e||g.current||t.length===0)return;if(!a){o();return}const y=n(e);y&&(i(y.tabKey,r),g.current=!0,S.current=!0,h.current!=null&&(window.clearTimeout(h.current),h.current=null),c(b=>{const C=new URLSearchParams(b);return C.delete("activeTab"),C},{replace:!0}))},[e,t,n,r,a,o,i,c]),l.useEffect(()=>{if(!(S.current||a)&&t.length!==0){if(!e){o(),S.current=!0;return}if(g.current){S.current=!0;return}if(h.current==null)return h.current=window.setTimeout(()=>{h.current=null,!(S.current||a)&&(o(),S.current=!0)},1500),()=>{h.current!=null&&(window.clearTimeout(h.current),h.current=null)}}},[e,t.length,a,o]),l.useEffect(()=>{if(!u){x.current=!1;return}if(!p||x.current||d)return;const y=m.find(b=>b.id===p.routeId);y&&(!y.chats||y.chats.length===0||Ij(y.chats,p))&&(x.current=!0,f())},[u,p,d,m,f])}function To(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0];if((n==null?void 0:n.active)===!0)return!0;const r=Oa(t);return typeof(n==null?void 0:n.id)=="string"&&r.includes(n.id)}function fm({sendDaemonCommand:e,activeConv:t,chats:n,updateRouteChats:r,setToasts:a,setClearedTabs:o}){const[i,c]=l.useState(!1),[u,p]=l.useState(!1),d=l.useCallback(async S=>{try{await e("standalone","launch_ide",{ideType:S,enableCdp:!0})}catch(h){console.error("Launch failed",h)}},[e]),m=l.useCallback(async(S,h)=>{try{const x=S||(t==null?void 0:t.daemonId)||"",y=await e(x,"switch_chat",{id:h,sessionId:h,...nn(t)}),b=y==null?void 0:y.result;if((y==null?void 0:y.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?Cn(a,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?Cn(a,`⚠️ Switch error: ${b}`):Cn(a,"⚠️ Session switch failed")}catch(x){console.error("Switch failed",x),Cn(a,`❌ Switch failed: ${x.message||"connection error"}`)}},[t,e,a]),f=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const S=rn(t);await e(S,"new_chat",{...nn(t)}),xk(S,t.sessionId,Oa(t)[0]),o(h=>({...h,[t.tabKey]:Date.now()}))}catch(S){console.error("New chat failed",S)}finally{c(!1)}}},[t,i,e,o]),g=l.useCallback(async()=>{var S,h;if(!(!t||u)){p(!0);try{const x=rn(t),y=async()=>e(x,"list_chats",{forceExpand:!0,...nn(t)});let b=await y(),C=(b==null?void 0:b.chats)||((S=b==null?void 0:b.result)==null?void 0:S.chats);To(C,t)&&(await new Promise(j=>setTimeout(j,450)),b=await y(),C=(b==null?void 0:b.chats)||((h=b==null?void 0:b.result)==null?void 0:h.chats)),b!=null&&b.success&&Array.isArray(C)&&(r(t.routeId,C),To(C,t)&&!To(n,t)&&Cn(a,"⚠️ History dialog did not fully open — try once more"))}catch(x){console.error("Refresh history failed",x)}finally{p(!1)}}},[t,n,u,e,r,a]);return{isCreatingChat:i,isRefreshingHistory:u,handleLaunchIde:d,handleSwitchSession:m,handleNewChat:f,handleRefreshHistory:g}}function Lj(e,t){if(e.size!==t.size)return!1;for(const[n,r]of e)if(t.get(n)!==r)return!1;return!0}function Rj(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function Qc(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(a=>t[Number(a)]===e[Number(a)])}function qr(e,t){const n=new Set(t),r=t.length>0?[0]:[];for(const[i,c]of e)!n.has(i)||c<=0||r.includes(c)||r.push(c);r.sort((i,c)=>i-c);const a={};r.forEach((i,c)=>{a[i]=c}),r.length===0&&(a[0]=0);const o=new Map;for(const[i,c]of e){if(!n.has(i)||c<=0)continue;const u=a[c];typeof u=="number"&&u>0&&o.set(i,u)}return{assignments:o,groupCount:Math.max(1,r.length),mapping:a,usedGroups:r}}function Xc(e,t){const n={};for(const[r,a]of Object.entries(e)){const o=t[Number(r)];typeof o=="number"&&(n[o]=a)}return n}function Ej(e,t,n){if(t.length===0)return 0;if(typeof n[e]=="number")return n[e];const r=[...t].reverse().find(a=>a<e)??t[0];return n[r]??0}function _j(e,t,n){if(t.length<=1)return[];const r=t.map(i=>e[i]).filter(i=>Number.isFinite(i)),a=r.length===t.length?r:Array(n).fill(100/n),o=a.reduce((i,c)=>i+c,0);return o>0?a.map(i=>i/o*100):Array(n).fill(100/n)}function Zc(e,t){const n={};for(const[r,a]of Object.entries(e)){const o=Number(r);n[o>=t?o+1:o]=a}return n}function ed(e){return Array(e).fill(100/e)}function $j({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:n,updateGroupActiveTabIds:r,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:i,isMobile:c,visibleConversations:u,visibleTabKeys:p}){const d=l.useRef(null),m=l.useMemo(()=>qr(e,p),[e,p]),f=m.assignments,g=l.useMemo(()=>c?1:m.groupCount,[m.groupCount,c]),S=g>1,h=l.useCallback((k,v)=>{t(N=>{const w=new Map(qr(N,p).assignments);return v===0?w.delete(k):w.set(k,v),w}),r(N=>({...N,[v]:k})),n(v)},[t,p,r,n]),x=l.useCallback(k=>{t(v=>{const N=qr(v,p).assignments,w=new Map;for(const[A,T]of N)T!==k&&(T>k?w.set(A,T-1):w.set(A,T));return w}),i(v=>{if(v.length<=1)return[];const N=[...v];N.splice(k,1);const w=N.reduce((A,T)=>A+T,0);return w>0?N.map(A=>A/w*100):[]}),n(0)},[t,p,i,n]),y=l.useCallback((k,v)=>{v.preventDefault();const N=d.current;if(!N)return;const w=v.clientX,A=N.offsetWidth,T=o.length===g?[...o]:ed(g),I=D=>{const W=(D.clientX-w)/A*100,$=[...T];$[k]=Math.max(15,T[k]+W),$[k+1]=Math.max(15,T[k+1]-W),i($)},P=()=>{document.removeEventListener("mousemove",I),document.removeEventListener("mouseup",P),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",I),document.addEventListener("mouseup",P)},[o,g,i]),b=l.useCallback((k,v,N)=>{if(g>=4)return;const w=N==="left"?v:v+1;t(A=>{const T=qr(A,p).assignments,I=new Map;for(const P of u){const D=T.get(P.tabKey)??0,_=D>=w?D+1:D;_>0&&I.set(P.tabKey,_)}return w>0&&I.set(k,w),I}),i(A=>{const T=A.length===g?[...A]:ed(g),I=T[v]??100/g,P=Math.max(15,I/2),D=Math.max(15,I/2),_=[...T];_[v]=P,_.splice(w,0,D);const W=_.reduce(($,E)=>$+E,0);return _.map($=>$/W*100)}),r(A=>{const T=Zc(A,w);return T[w]=k,T}),a(A=>{const T=Zc(A,w);return T[w]=[k],T}),n(w)},[g,t,p,u,i,r,a,n]);l.useEffect(()=>{Lj(e,f)||t(f)},[e,f,t]),l.useEffect(()=>{const{mapping:k,usedGroups:v}=m;r(N=>{const w=Xc(N,k);return Qc(N,w)?N:w}),a(N=>{const w=Xc(N,k);return Qc(N,w)?N:w}),n(N=>{const w=c?0:Ej(N,v,k);return N===w?N:w}),i(N=>{const w=c?[]:_j(N,v,m.groupCount);return Rj(N,w)?N:w})},[m,c,r,a,n,i]);const C=l.useMemo(()=>{const k=Array.from({length:g},()=>[]);for(const v of u){const N=f.get(v.tabKey)??0,w=Math.min(N,g-1);k[w].push(v)}return k},[u,f,g]),j=l.useCallback(()=>{t(new Map),n(0)},[t,n]);return{containerRef:d,normalizedGroupAssignments:f,numGroups:g,isSplitMode:S,groupedConvs:C,moveTabToGroup:h,closeGroup:x,handleResizeStart:y,splitTabRelative:b,clearAllSplits:j}}function Hj({ides:e,sendDaemonCommand:t}){const n="1.0.30",r=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:Ja(m,$s(m,n))).sort((m,f)=>Number(br(f,$s(f,n)))-Number(br(m,$s(m,n)))),[n,e]),a=l.useMemo(()=>r.some(m=>br(m,$s(m,n))),[n,r]),o=l.useMemo(()=>r.map(m=>$s(m,n)).find(m=>typeof m=="string"&&m.trim().length>0)||n,[n,r]),[i,c]=l.useState(!1),[u,p]=l.useState({}),d=l.useCallback(async m=>{var S,h;const f=e.find(x=>x.id===m);if(!f)return;p(x=>({...x,[m]:"upgrading"}));const g=Qa(f);if(!g){p(x=>({...x,[m]:"error"}));return}try{const x=await t(m,"daemon_upgrade",g);(S=x==null?void 0:x.result)!=null&&S.upgraded||(h=x==null?void 0:x.result)!=null&&h.success?p(y=>({...y,[m]:"done"})):p(y=>({...y,[m]:"error"}))}catch{p(x=>({...x,[m]:"error"}))}},[e,t]);return{versionMismatchDaemons:r,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:u,handleBannerUpgrade:d}}const bm=80;function ca(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function Fj(e){return{...e,createdAt:ca(e.createdAt),updatedAt:ca(e.updatedAt,e.createdAt),lastEventAt:ca(e.lastEventAt,e.updatedAt||e.createdAt)}}function Bj(e){const t=Bu(e);return t==="unknown:"?e.id:t}function Wj(e){return[e.type,Fu(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function Oj(e,t=bm){const n=new Map;for(const r of e){if(r.deletedAt)continue;const a=Bj(r),o=n.get(a);if(!o){n.set(a,r);continue}(r.updatedAt>o.updatedAt||r.updatedAt===o.updatedAt&&r.createdAt>o.createdAt)&&n.set(a,r)}return Array.from(n.values()).sort((r,a)=>{const o=a.updatedAt-r.updatedAt;return o!==0?o:a.createdAt-r.createdAt}).slice(0,Math.max(0,t))}function Uj(e,t){const n=Date.now(),r=[];for(const a of e){const o=a.sessionId?t.get(a.sessionId):void 0;if(o!=null&&o.surfaceHidden||o!=null&&o.muted)continue;const i=Wa(a,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const u=ca(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,n),p=Wj({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});r.push(Fj({id:p,dedupKey:p,type:c,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:op(a),preview:D0(a),createdAt:u,updatedAt:u,lastEventAt:u}))}return Oj(r)}function Gj(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function qj(e){const{conversations:t,liveSessionInboxState:n,maxItems:r=bm}=e,a=l.useMemo(()=>Uj(t,n).slice(0,Math.max(0,r)),[t,n,r]),o=l.useMemo(()=>Gj(a),[a]);return{notifications:a,unreadCount:o}}function zj({notifications:e,sendDaemonCommand:t}){const n=l.useCallback(o=>{const i=e.find(u=>u.id===o),c=Math.max(Date.now(),(i==null?void 0:i.updatedAt)||0);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_session_seen",{sessionId:i.sessionId,seenAt:c}).catch(()=>{})},[e,t]),r=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_notification_unread",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]),a=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"delete_notification",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:n,handleMarkDashboardNotificationUnread:r,handleDeleteDashboardNotification:a}}function fl(...e){const t=new Set,n=[],r=a=>{const o=typeof a=="string"?a.trim():"";if(!o)return;const i=o.toLowerCase();t.has(i)||(t.add(i),n.push(o))};for(const a of e){if(Array.isArray(a)){for(const o of a)r(o);continue}r(a)}return n}function Kj(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const n=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(n){const r=n[1].toUpperCase(),a=(n[2]||"").replace(/[\\/]+/g,"\\");return a?`${r}:\\${a}`:`${r}:\\`}return null}function bl(e,t=[]){if(e==="win32"){for(const n of t){if(typeof n!="string")continue;const r=Kj(n);if(r)return r}return"C:\\"}for(const n of t){const r=typeof n=="string"?n.trim():"";if(r)return r}return"~"}function Vj(e){const t=e.replace(/[\\/]+$/,"");if(!t||t==="/"||/^[A-Za-z]:$/.test(t))return null;const n=t.includes("\\")?"\\":"/",r=t.split(/[\\/]/);return/^[A-Za-z]:$/.test(r[0]||"")?r.length<=2?`${r[0]}\\`:r.slice(0,-1).join("\\"):r.length<=2?n:r.slice(0,-1).join(n)||n}function Yj(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function gl(e,t,n){const r=await e(t,"file_list_browse",{path:n}),a=Yj(r);if(!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||(r==null?void 0:r.error)||"Could not browse folder");const o=typeof(a==null?void 0:a.path)=="string"?a.path:n,i=o.includes("\\")?"\\":"/",c=(p,d)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${d}`:p==="/"||p==="\\"?`${i}${d}`:`${p.replace(/[\\/]+$/,"")}${i}${d}`,u=Array.isArray(a==null?void 0:a.files)?a.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:typeof(p==null?void 0:p.path)=="string"&&p.path.trim()?p.path:c(o,p.name)})).sort((p,d)=>p.name.localeCompare(d.name)):[];return{path:o,directories:u}}function td(e,t){const n=t.meshId||"",r={meshId:n,workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp",adhdevMcpArgs:t.adhdevMcpArgs||`mcp --mode ipc --repo-mesh ${n}`};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand|adhdevMcpArgs)\s*\}\}/g,(a,o)=>r[o]||"")}function gm(e,t={}){const n=e==null?void 0:e.mcpConfig;if((n==null?void 0:n.mode)!=="manual")return null;const a=td(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"}).trim();return!a.includes(`
70
+ `)&&!a.startsWith("{")?null:{serverName:n.serverName||"adhdev-mesh",configFormat:n.format,configPathCommand:n.configPathCommand,requiresRestart:n.requiresRestart===!0,instructions:n.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:td(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"})}}function Jj(e){if(!e||typeof e!="object")return null;const t=e,n=typeof t.instructions=="string"?t.instructions:"",r=typeof t.template=="string"?t.template:"";return!n&&!r?null:{serverName:typeof t.serverName=="string"?t.serverName:void 0,configFormat:typeof t.configFormat=="string"?t.configFormat:void 0,configPathCommand:typeof t.configPathCommand=="string"?t.configPathCommand:void 0,requiresRestart:t.requiresRestart===!0,instructions:n||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:r}}function Nr(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function xm(e){return Ua(e)||e.tabKey||e.routeId||null}function vm(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",n=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",r=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",a=e.conversations.find(o=>{if(r&&o.routeId!==r)return!1;const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey].map(c=>typeof c=="string"?c.trim():"").filter(Boolean);return!!(t&&i.includes(t)||n&&i.includes(n)||r&&o.routeId===r)});if(a!=null&&a.tabKey)return a.tabKey;if(r){const o=bs(e.conversations,r)||e.conversations.find(i=>i.routeId===r);if(o!=null&&o.tabKey)return o.tabKey}return t||n||r||null}function Hs(e){return String(e||"").trim()}function ym(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Pa(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Qj(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function Xj(e,t){const n=Hs(e.providerSessionId),r=Hs(e.targetSessionId),a=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(Hs).filter(Boolean);return!!(n&&i.includes(n)||r&&i.includes(r))});return a?a.tabKey:r||n||null}function Zj(e,t,n){if(t.event!=="agent:generating_completed")return null;const r=ym(t.daemonId);if(r&&r!==e.machineId)return null;const a=Hs(t.providerType);if(e.providerType&&a!==e.providerType)return null;const o=Hs(e.resumeSessionId),i=Hs(e.launchedSessionId),c=Hs(t.providerSessionId),u=Hs(t.targetSessionId);if(o&&o!==c&&o!==u||i&&i!==c&&i!==u)return null;const p=Pa(e.workspacePath);if(p){const d=Pa(t.workspaceName);if(d&&!Qj(d,p))return null}return Xj(t,n)}function sd(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function e1({ides:e,conversations:t,onOpenSession:n}){const[r,a]=l.useState(null),o=l.useRef(null),i=l.useCallback(()=>{o.current=null,a(null)},[]),c=l.useCallback(u=>{o.current=u,a(u)},[]);return l.useEffect(()=>{if(!r)return;const u=Pa(r.workspacePath),p=e.find(m=>{var x,y,b,C;if(!m||m.type==="adhdev-daemon"||ym(m.daemonId||m.id)!==r.machineId||(Sr(m)?"cli":Dn(m)?"acp":"ide")!==r.kind)return!1;const S=String(m.agentType||m.type||"");if(r.providerType&&S!==r.providerType)return!1;if(r.resumeSessionId)return String(m.providerSessionId||"")===r.resumeSessionId;if(r.launchedSessionId){const j=String(r.launchedSessionId||"");return[m.providerSessionId,m.sessionId,m.instanceId,m.id].map(v=>String(v||"")).filter(Boolean).includes(j)}if(u){const j=Pa(m.workspace||m.runtimeWorkspaceLabel);return j?j===u:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((C=(b=(y=(x=m.activeChat)==null?void 0:x.messages)==null?void 0:y.at)==null?void 0:b.call(y,-1))==null?void 0:C.timestamp)||0)>=r.startedAt-5e3});if(!p)return;const d=vm({entrySessionId:p.sessionId,entryInstanceId:p.instanceId,entryRouteId:p.id,conversations:t});d&&(i(),n(d))},[i,t,e,n,r]),l.useEffect(()=>ft.onStatusEvent(u=>{const p=o.current;if(!p)return;const d=Zj(p,u,t);d&&(i(),n(d))}),[i,t,n]),l.useEffect(()=>{if(!r)return;const u=window.setTimeout(()=>{a(p=>!p||p.startedAt!==r.startedAt?p:(o.current=null,null))},45e3);return()=>window.clearTimeout(u)},[r]),{trackPendingLaunch:c}}function t1(e,t){var r,a,o,i;const n={cliType:e};return(r=t==null?void 0:t.workspacePath)!=null&&r.trim()?n.dir=t.workspacePath.trim():t!=null&&t.workspaceId?n.workspaceId=t.workspaceId:t!=null&&t.useHome&&(n.useHome=!0),(a=t==null?void 0:t.resumeSessionId)!=null&&a.trim()&&(n.resumeSessionId=t.resumeSessionId.trim()),Array.isArray(t==null?void 0:t.cliArgs)&&t.cliArgs.length>0&&(n.cliArgs=t.cliArgs),(o=t==null?void 0:t.initialModel)!=null&&o.trim()&&(n.initialModel=t.initialModel.trim()),(i=t==null?void 0:t.initialThinkingLevel)!=null&&i.trim()&&(n.initialThinkingLevel=t.initialThinkingLevel.trim()),t!=null&&t.settings&&(n.settings=t.settings),n}function s1({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:n,activeConv:r,ides:a,setCliViewModeOverrides:o}){const i=el(),{launchCli:c}=$a(),u=l.useCallback(async(x,y)=>gl(e,x,y),[e]),p=l.useCallback(async(x,y)=>{if(!y.trim())return{ok:!1,error:"Choose a workspace path first."};try{const b=await e(x,"workspace_add",{path:y.trim()});return b!=null&&b.success?{ok:!0}:{ok:!1,error:(b==null?void 0:b.error)||"Could not save workspace"}}catch(b){return{ok:!1,error:b instanceof Error?b.message:"Could not save workspace"}}},[e]),d=l.useCallback(async(x,y,b)=>{var C;try{const j={ideType:y,enableCdp:!0};(C=b==null?void 0:b.workspacePath)!=null&&C.trim()&&(j.workspace=b.workspacePath.trim());const k=await e(x,"launch_ide",j);return!(k!=null&&k.success)&&(k==null?void 0:k.success)!==void 0?{ok:!1,error:(k==null?void 0:k.error)||"Could not launch IDE"}:(t({machineId:x,kind:"ide",providerType:y,workspacePath:(b==null?void 0:b.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(j){return{ok:!1,error:j instanceof Error?j.message:"Could not launch IDE"}}},[e,t]),m=l.useCallback(async(x,y,b,C)=>{const j=Date.now();try{const k=t1(b,C),v=await c(x,k),N=(v==null?void 0:v.result)||v,w=(N==null?void 0:N.sessionId)||(N==null?void 0:N.id);return v!=null&&v.success&&w?(t({machineId:x,kind:y,providerType:b,workspacePath:(C==null?void 0:C.workspacePath)||null,resumeSessionId:(C==null?void 0:C.resumeSessionId)||null,launchedSessionId:w,startedAt:j}),{ok:!0}):v!=null&&v.success?(t({machineId:x,kind:y,providerType:b,workspacePath:(C==null?void 0:C.workspacePath)||null,resumeSessionId:(C==null?void 0:C.resumeSessionId)||null,startedAt:j}),{ok:!0}):{ok:!1,error:(v==null?void 0:v.error)||(N==null?void 0:N.error)||`Could not launch ${y.toUpperCase()} session`,code:(v==null?void 0:v.code)||(N==null?void 0:N.code)||void 0}}catch(k){return sd(k)?(t({machineId:x,kind:y,providerType:b,workspacePath:(C==null?void 0:C.workspacePath)||null,resumeSessionId:(C==null?void 0:C.resumeSessionId)||null,startedAt:j}),{ok:!0}):{ok:!1,error:k instanceof Error?k.message:`Could not launch ${y.toUpperCase()} session`}}},[c,e,t]),f=l.useCallback(async x=>{var y;if(i!=null&&i.listMeshes)return i.listMeshes(x);if(!x)return[];try{const b=await e(x,"list_meshes",{}),C=(b==null?void 0:b.result)??b;if((C==null?void 0:C.success)===!1)throw new Error((C==null?void 0:C.error)||"Could not load meshes");return(Array.isArray(C==null?void 0:C.meshes)?C.meshes:Array.isArray((y=C==null?void 0:C.result)==null?void 0:y.meshes)?C.result.meshes:[]).map(k=>{var v;return{id:String((k==null?void 0:k.id)||""),name:String((k==null?void 0:k.name)||(k==null?void 0:k.id)||"Untitled mesh"),repoIdentity:(k==null?void 0:k.repoIdentity)||(k==null?void 0:k.repo_identity)||null,workspace:Array.isArray(k==null?void 0:k.nodes)&&k.nodes.length>0?String(((v=k.nodes[0])==null?void 0:v.workspace)||""):null,nodesCount:Array.isArray(k==null?void 0:k.nodes)?k.nodes.length:void 0,status:(k==null?void 0:k.status)||null}}).filter(k=>k.id)}catch(b){throw console.error("List meshes failed",b),b}},[i,e]),g=l.useCallback(async(x,y,b,C)=>{var k,v;if(!y.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(x,y,b,C);const j=Date.now();try{const N={meshId:y.trim()};b.trim()&&(N.cliType=b.trim());const w=(k=C==null?void 0:C.initialModel)==null?void 0:k.trim(),A=(v=C==null?void 0:C.initialThinkingLevel)==null?void 0:v.trim();w&&(N.initialModel=w),A&&(N.initialThinkingLevel=A);const T=await e(x,"launch_mesh_coordinator",N),I=(T==null?void 0:T.result)??T;if((I==null?void 0:I.success)===!1||(T==null?void 0:T.success)===!1){const D=String((I==null?void 0:I.code)||(T==null?void 0:T.code)||""),_=Jj((I==null?void 0:I.meshCoordinatorSetup)||(I==null?void 0:I.manualSetup)||(T==null?void 0:T.meshCoordinatorSetup)||(T==null?void 0:T.manualSetup));return{ok:!1,error:(I==null?void 0:I.error)||(T==null?void 0:T.error)||"Could not launch mesh coordinator",code:D||void 0,manualSetup:_}}const P=(I==null?void 0:I.sessionId)||(I==null?void 0:I.id);return P?n(P):t({machineId:x,kind:"cli",providerType:(I==null?void 0:I.cliType)||b.trim()||void 0,workspacePath:(I==null?void 0:I.workspace)||null,startedAt:j}),{ok:!0}}catch(N){return sd(N)?(t({machineId:x,kind:"cli",providerType:b.trim()||void 0,startedAt:j}),{ok:!0}):{ok:!1,error:N instanceof Error?N.message:"Could not launch mesh coordinator"}}},[i,n,e,t]),S=l.useCallback(async(x,y)=>{if(!x||!y)return[];try{const b=await e(x,"list_saved_sessions",{providerType:y,kind:"cli",limit:30}),C=(b==null?void 0:b.result)??b;return Array.isArray(C==null?void 0:C.sessions)?C.sessions:[]}catch(b){return console.error("List saved sessions failed",b),[]}},[e]),h=l.useCallback(async x=>{await cm({conversation:r,mode:x,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[r,a,e,o]);return{handleBrowseMachineDirectory:u,handleSaveMachineWorkspace:p,handleLaunchMachineIde:d,handleLaunchMachineProvider:m,handleListMachineMeshes:f,handleLaunchMeshCoordinator:g,handleListMachineSavedSessions:S,setActiveCliViewMode:h}}function n1(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 r1(e,t,n=Date.now()){return!e||!n1(t)?null:{tabKey:e,nonce:n}}function a1({isMobile:e,conversations:t,visibleConversations:n,groupActiveTabIds:r,focusedGroup:a,groupedConvs:o,setSearchParams:i}){const[c,u]=l.useState(null),[p,d]=l.useState(null),m=l.useMemo(()=>{var x,y;if(!e){if(c){const b=t.find(C=>C.tabKey===c);if(b)return b}return n[0]}const h=r[a];if(h){const b=t.find(C=>C.tabKey===h);if(b)return b}return((x=o[a])==null?void 0:x[0])||((y=o[0])==null?void 0:y[0])},[t,c,a,r,o,e,n]),f=l.useCallback(h=>{u(h)},[]),g=l.useCallback(h=>{u(h.tabKey),i(x=>{const y=new URLSearchParams(x),b=P0(h);return b?y.set("activeTab",b):y.delete("activeTab"),y},{replace:!0})},[i]),S=l.useCallback((h,x)=>{const y=r1(h,x);y&&d(y)},[]);return{activeConv:m,openDesktopConversation:g,requestScrollToBottom:S,scrollToBottomRequest:p,setDesktopActiveTab:f}}function o1(e){const t=e.completedKey||null,n=e.pendingKey||null;return e.shouldMarkSeen?t===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:n!==null&&n!==e.autoReadKey,nextPendingKey:n===e.autoReadKey?n:null}:n===e.autoReadKey?{shouldSchedule:!1,shouldCancelPending:!1,nextPendingKey:n}:{shouldSchedule:!0,shouldCancelPending:n!==null&&n!==e.autoReadKey,nextPendingKey:e.autoReadKey}:{shouldSchedule:!1,shouldCancelPending:!!n,nextPendingKey:null}}function i1(e){const t=String(e.liveState.completionMarker||""),n=String(e.liveState.seenCompletionMarker||""),r=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,o=[e.tabKey,e.historySessionId||"",t,n,r,a?"1":"0"].join(":");return{shouldMarkSeen:!!(r==="task_complete"&&a&&(!t||t!==n)),autoReadKey:o,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function l1({activeConv:e,isMobile:t,liveSessionInboxState:n,sendDaemonCommand:r}){const a=l.useRef(null),o=l.useRef(null),i=l.useRef(null),c=l.useRef(null),u=l.useRef(null);l.useEffect(()=>{const p=()=>{i.current&&(clearTimeout(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null),o.current=null};if(t){p(),a.current=null;return}if(!(e!=null&&e.sessionId)){p(),a.current=null;return}const d=Gs(e,n),m=i1({tabKey:e.tabKey,historySessionId:Ua(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:cn(e),liveState:d}),f=m.autoReadKey,g=o1({autoReadKey:f,shouldMarkSeen:m.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!m.shouldMarkSeen){g.shouldCancelPending&&p(),a.current=f;return}if(!g.shouldSchedule)return;g.shouldCancelPending&&p();const S=()=>{if(document.visibilityState!=="visible"||a.current===f)return;a.current=f,o.current=null,i.current=null,c.current=null,u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null);const x=m.readAt;r(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:x,completionMarker:m.completionMarker}).catch(()=>{})};if(o.current=g.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(S,1500);const x=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};u.current=x,document.addEventListener("visibilitychange",x);return}const h=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(S,800),u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null))};u.current=h,document.addEventListener("visibilitychange",h)},[e,t,n,r]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),u.current&&document.removeEventListener("visibilitychange",u.current)},[])}function Mo(e){if(!e)return"";const t=String(e.workspacePath||"").trim();if(t)return t;const n=String(e.workspaceName||"").trim();return/^(?:~\/|\/|[A-Za-z]:[\\/])/.test(n)?n:""}function c1({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:n,ides:r,sendDaemonCommand:a,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:u}){var B;const{launchCli:p}=$a(),[d,m]=l.useState(!1),[f,g]=l.useState([]),[S,h]=l.useState(()=>qt()),[x,y]=l.useState(!1),[b,C]=l.useState(null),j=l.useRef(null),k=l.useMemo(()=>n||t||e,[e,n,t]),v=!!k&&ht(k)&&!pt(k),N=l.useMemo(()=>{if(!k||!v)return null;const L=k.daemonId||k.routeId||"",R=Ns(k),M=Mo(k);return`${L}:${R}:${k.providerSessionId||""}:${M}`},[k,v]),w=l.useMemo(()=>!k||!v?"":Mo(k),[k,v]),{isCreatingChat:A,isRefreshingHistory:T,handleSwitchSession:I,handleNewChat:P,handleRefreshHistory:D}=fm({sendDaemonCommand:a,activeConv:k,chats:(B=r.find(L=>L.id===(k==null?void 0:k.routeId)))==null?void 0:B.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),_=l.useCallback(()=>{m(!0)},[]),W=l.useCallback(()=>{m(!1)},[]),$=l.useCallback(async()=>{if(!(!k||!v||x)){y(!0);try{const L=k.daemonId||k.routeId,R=Ns(k),M=Mo(k),F=await a(L,"list_saved_sessions",{agentType:R,providerType:R,kind:"cli",limit:50,...k.providerSessionId?{providerSessionId:k.providerSessionId}:{},...M?{workspace:M}:{}}),K=(F==null?void 0:F.result)??F;g(Array.isArray(K==null?void 0:K.sessions)?K.sessions:[])}catch(L){console.error("Refresh saved sessions failed",L),g([])}finally{y(!1)}}},[k,x,v,a]);l.useEffect(()=>{if(!d){j.current=null;return}if(!v){j.current=null,g([]),y(!1);return}!N||x||j.current!==N&&(j.current=N,$())},[$,d,x,v,N]);const E=l.useCallback(async L=>{if(!k||!v||!L.providerSessionId||!L.workspace)return;const R=k.daemonId||k.routeId,M=Ns(k);try{C(L.providerSessionId);const F=await p(R,{cliType:M,dir:L.workspace,resumeSessionId:L.providerSessionId,initialModel:qu(L.summaryMetadata,"model",{preferShortValue:!0})||void 0}),K=(F==null?void 0:F.result)??F,J=typeof(K==null?void 0:K.sessionId)=="string"?K.sessionId:typeof(K==null?void 0:K.id)=="string"?K.id:"";J&&u(V=>{const Y=new URLSearchParams(V);return Y.set("activeTab",J),Y},{replace:!0}),W()}catch(F){console.error("Resume saved session failed",F)}finally{C(null)}},[W,k,v,a,u]);return{historyModalOpen:d,openHistoryModal:_,closeHistoryModal:W,historyTargetConv:k,isSavedSessionHistoryTarget:v,isHistoryCreatingChat:A,isHistoryRefreshingHistory:T,handleHistorySwitchSession:I,handleHistoryNewChat:P,handleHistoryRefresh:D,savedHistorySessions:f,savedHistoryFilters:S,setSavedHistoryFilters:h,missingWorkspaceResumePath:w,isSavedHistoryLoading:x,resumingSavedHistorySessionId:b,handleRefreshSavedHistory:$,handleResumeSavedHistorySession:E}}function d1({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}){const[u,p]=l.useState(null),[d,m]=l.useState(null),f=l.useMemo(()=>{if(e||!r)return null;const y=c(r);return y&&!ht(y)&&!pt(y)?y:null},[e,r,c]),g=l.useMemo(()=>{const y=u==null?void 0:u.routeId;if(!y)return null;const b=u!=null&&u.tabKey?o.find(C=>C.tabKey===u.tabKey):a?o.find(C=>C.tabKey===a):null;return(b==null?void 0:b.routeId)===y?b:bs(o,y)},[o,u,a]),S=l.useMemo(()=>{if(g)return i.find(y=>y.id===g.routeId)},[i,g]);l.useEffect(()=>{f&&(p({routeId:f.routeId,tabKey:fc(f)}),m(f),n({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,n,f]);const h=l.useCallback(y=>{y&&(p({routeId:y.routeId,tabKey:fc(y)}),m(y))},[]),x=l.useCallback(()=>{p(null),m(null)},[]);return{remoteDialogConv:g,remoteDialogIdeEntry:S,remoteDialogActiveConv:d,setRemoteDialogActiveConv:m,openRemoteDialog:h,closeRemoteDialog:x}}function u1({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c,activeConv:u,sendDaemonCommand:p}){const{remoteDialogConv:d,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:g,openRemoteDialog:S,closeRemoteDialog:h}=d1({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}),[x,y]=l.useState(!1),[b,C]=l.useState(null),j=l.useCallback(async N=>{const w=N||u;!w||!ht(w)&&!pt(w)||(C(w),y(!0))},[u]),k=l.useCallback(()=>{y(!1),C(null)},[]),v=l.useCallback(async N=>{const w=b||u;if(!w||!ht(w)&&!pt(w)){k();return}y(!1);try{const A=Ns(w),T=w.routeId||w.daemonId||"";await p(T,"stop_cli",{cliType:A,targetSessionId:w.sessionId,mode:N,...za(w)})}catch(A){console.error("Stop CLI failed:",A)}finally{C(null)}},[u,k,b,p]);return{remoteDialogConv:d,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:g,openRemoteDialog:S,closeRemoteDialog:h,cliStopDialogOpen:x,cliStopTargetConv:b,requestCliStop:j,cancelCliStop:k,confirmCliStop:v}}function Do(e,t=!0){return(e??!0)&&t}const xl=l.memo(function({activeConv:t,clearToken:n,isCliTerminal:r,ideEntry:a,terminalRef:o,handleModalButton:i,handleRelaunch:c,handleSendChat:u,handleForceSendChat:p,isSendingChat:d,sendFeedbackMessage:m=null,handleFocusAgent:f,isFocusingAgent:g,actionLogs:S,userName:h,scrollToBottomRequestNonce:x,isInputActive:y=!0,isVisible:b=!0}){const C=r,j=!r,k=Do(b,C),v=Do(b,j),N=Do(b),w=om(t),A=w.status||w.modalMessage||w.modalButtons?{...t,...w.status?{status:w.status}:{},...w.modalMessage!==void 0?{modalMessage:w.modalMessage}:{},...w.modalButtons!==void 0?{modalButtons:w.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(_u,{activeConv:A,onModalButton:i}),A.transport!=="pty"&&A.transport!=="acp"&&A.cdpConnected===!1?s.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:s.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[s.jsx("span",{className:"text-sm",children:s.jsx(pn,{size:14})}),s.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),s.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:c,children:"Relaunch with CDP"})]})}):null,A.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!r,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:C?"visible":"hidden",pointerEvents:C?"auto":"none"},children:s.jsx(mS,{activeConv:A,clearToken:n,terminalRef:o,handleSendChat:u,isSendingChat:d,sendFeedbackMessage:m,isVisible:k,isInputActive:y&&k})}),s.jsx("div",{"aria-hidden":r,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:j?"visible":"hidden",pointerEvents:j?"auto":"none"},children:s.jsx(ki,{activeConv:A,ideEntry:a,handleSendChat:u,isSendingChat:d,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:S,userName:h,scrollToBottomRequestNonce:x,isInputActive:y&&v,isVisible:v})})]}):s.jsx(ki,{activeConv:A,ideEntry:a,handleSendChat:u,handleForceSendChat:p,isSendingChat:d,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:S,userName:h,scrollToBottomRequestNonce:x,isInputActive:y&&N,isVisible:N})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.handleForceSendChat===t.handleForceSendChat&&e.isSendingChat===t.isSendingChat&&e.sendFeedbackMessage===t.sendFeedbackMessage&&e.handleFocusAgent===t.handleFocusAgent&&e.isFocusingAgent===t.isFocusingAgent&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function p1({conversation:e,className:t="",onOpenNativeConversation:n,onOpenMachine:r,interactive:a=!0,meshOnly:o=!1}){var j,k,v;const{t:i}=Ne("common"),c=Mr(),u=Rs(e),p=o?null:ap(e),d=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),m=!o&&e.streamSource==="agent-stream"&&!!e.agentName,f=!o&&!m&&(e.transport==="pty"||e.transport==="acp"),g=_n(e),S=I0(e),h=(j=e.settings)==null?void 0:j.meshNodeFor,x=e.meshQueueStats,y=((k=e.coordinator)==null?void 0:k.meshId)||((v=e.settings)==null?void 0:v.meshCoordinatorFor),b=l.useCallback(()=>{if(r){r();return}u&&c("/dashboard",{state:{openMachineId:u}})},[u,c,r]),C=l.useCallback(()=>{if(n){n();return}const N=xm(e);N&&c(Nr(N))},[e,c,n]);return!d&&!m&&!f&&!p&&!h&&!x?null:s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[d&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:C,title:S,children:[s.jsx(xs,{size:12}),s.jsx("span",{children:S})]}):s.jsxs("span",{className:"conversation-meta-chip",title:S,children:[s.jsx(xs,{size:12}),s.jsx("span",{children:S})]})),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(wr,{size:12}),s.jsx("span",{children:g})]}),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(wr,{size:12}),s.jsx("span",{children:g})]}),p&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:b,title:p,children:[s.jsx(Os,{size:12}),s.jsx("span",{children:p})]}):s.jsxs("span",{className:"conversation-meta-chip",title:p,children:[s.jsx(Os,{size:12}),s.jsx("span",{children:p})]})),h&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(Os,{size:12}),s.jsx("span",{children:i("dashboard.metaChips.meshNode")})]}),y&&x&&s.jsxs("span",{className:`conversation-meta-chip ${x.pending>0?"is-active":""}`,style:x.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${x.pending} pending, ${x.assigned} assigned, ${x.completed} completed, ${x.failed} failed`,children:[s.jsx(Zf,{size:12}),s.jsxs("span",{children:[x.pending," Pending"]})]})]})}function m1({selectedConversation:e,isAcp:t,isStandalone:n,selectedIdeEntry:r,actionLogs:a,userName:o,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:u,onBack:p,onOpenNativeConversation:d,onOpenMachine:m,onOpenHistory:f,onOpenRemote:g,onOpenMeshGraph:S,onStopCli:h,cliViewMode:x,onSetCliViewMode:y,handleSendChat:b,handleForceSendChat:C,handleFocusAgent:j,handleModalButton:k,handleRelaunch:v}){var P,D;const N=l.useRef(null),w=ht(e)&&!t,A=w&&x==="terminal",T=!!e.daemonId&&!!((P=e.coordinator)!=null&&P.meshId||(D=e.settings)!=null&&D.meshCoordinatorFor),I=n?"px-4 pt-3.5 pb-2.5":"px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-2.5";return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:`flex items-center justify-between gap-3 ${I} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:s.jsx(Wi,{size:18})}),s.jsxs("div",{className:"min-w-0 flex-1 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:kt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(p1,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>d(e),onOpenMachine:()=>m(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[w&&x&&s.jsx(_p,{mode:x,onChange:y,compact:!0}),w&&h&&s.jsx("button",{onClick:()=>{h(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(Mt,{size:14})}),T&&S&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>S(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(os,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:s.jsx(Ui,{size:14})}),!t&&!w&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:s.jsx(xs,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(xl,{activeConv:e,clearToken:0,isCliTerminal:A,ideEntry:r,terminalRef:N,handleModalButton:k,handleRelaunch:v,handleSendChat:b,handleForceSendChat:C,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:j,isFocusingAgent:u,actionLogs:a,userName:o})})]})}const Io={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 h1(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function wm(){const[e,t]=l.useState("unix"),[n,r]=l.useState("powershell"),[a,o]=l.useState(!1),i=e==="unix"?"unix":n;l.useEffect(()=>{t(h1())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(Io[i].cmd).catch(()=>{}),o(!0),setTimeout(()=>o(!1),2e3)},[i]);return s.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("unix"),children:"🍎🐧 macOS / Linux"}),s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("windows"),children:"🪟 Windows"})]}),e==="windows"&&s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${n==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>r("powershell"),children:"⚡ PowerShell"}),s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${n==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>r("cmd"),children:">_ CMD"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:c,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:Io[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:Io[i].cmd}),s.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:a?"✓":"📋"})]}),s.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",s.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function km({section:e,onSectionChange:t}){const n=[{key:"machines",label:"Machines",icon:xs},{key:"chats",label:"Chats",icon:bn}];return s.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:s.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:n.map(({key:r,label:a,icon:o})=>{const i=e===r;return s.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${i?"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:i?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(r),type:"button","aria-pressed":i,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${i?"text-accent-primary":"bg-transparent text-current"}`,style:i?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(o,{size:15})}),s.jsx("span",{children:a})]},r)})})})}function zr({title:e,className:t=""}){return s.jsx("div",{className:`mx-1 flex items-center justify-between gap-2 px-1 py-1 text-xs ${t}`,children:s.jsx("span",{className:"font-bold uppercase tracking-[0.18em] text-text-secondary",children:e})})}function wn({children:e,className:t=""}){return s.jsx("div",{className:`w-full min-w-0 self-stretch overflow-hidden rounded-[24px] border border-border-subtle/80 bg-bg-secondary/40 shadow-[0_10px_30px_rgba(0,0,0,0.05)] ${t}`,children:e})}function sr({icon:e,title:t,subtitle:n,children:r}){return s.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[s.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:n}),r]})}function f1({conversation:e,onCancel:t,onConfirm:n}){const{t:r}=Ne(),a=kt(e);return s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:t,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-hide-confirm-title",className:"card fade-in mobile-compact-dialog relative w-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-bg-primary",children:[s.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base md:text-lg font-extrabold",children:r("mobileInbox.hideTitle",{title:a})}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:r("mobileInbox.hideDescription")})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s.jsx("button",{onClick:n,className:"btn btn-primary w-full justify-center min-h-[42px]",children:r("mobileInbox.hide")}),s.jsx("button",{onClick:t,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:r("common.cancel")})]})]})]})}function Kr({item:e,type:t,getAvatarText:n,onOpenConversation:r,onRequestHideConversation:a,onRequestStopCli:o,onOpenMeshGraph:i,onCollectChatDebugBundle:c,isMuted:u,onToggleMute:p}){const{t:d}=Ne(),m=t==="needs_attention"||t==="task_complete",f=t==="working",g=t==="earlier",S=t==="task_complete",{isReconnecting:h,isConnecting:x}=gn(e.conversation),y=kt(e.conversation),b=$n(e.conversation),C=Pp(e.conversation,{requiresAction:t==="needs_attention"}),j=m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":f?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":g?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",k=m?"bg-accent-primary shadow-glow":f?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":g?"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",v=g?"text-text-secondary":"text-text-primary",N=g?"text-text-muted":"text-text-secondary",w=g?"text-text-secondary opacity-80":"text-text-muted",A=g?"text-text-muted opacity-80":"text-text-muted",T=!f&&!S,I=Dp(e.conversation),P="text-[color:var(--status-warning)]",D=_=>{if(!c)return;_.preventDefault(),_.stopPropagation();const W=c==null?void 0:c(e.conversation);Promise.resolve(W).catch($=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",$)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${j}`,children:s.jsxs("div",{className:"relative flex w-full items-start gap-3.5 px-4 py-3.5 text-left",children:[m||f?s.jsx("span",{className:"pointer-events-none absolute left-0 top-3 bottom-3 w-[3px] rounded-r-full bg-accent-primary/80"}):null,s.jsxs("div",{className:"mobile-inbox-leading-rail flex w-11 shrink-0 flex-col items-center gap-1.5",children:[s.jsx("span",{className:`w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 ${k}`,style:m?{color:"var(--accent-on-primary)"}:void 0,children:n(y)}),I&&i&&s.jsx("button",{type:"button",className:"mobile-inbox-mesh-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:_=>{_.preventDefault(),_.stopPropagation(),i(e.conversation)},"aria-label":d("mobileInbox.openMeshGraphFor",{title:y}),title:d("mobileInbox.openLiveMeshGraph"),children:s.jsx(os,{size:13})})]}),s.jsxs("button",{className:"relative flex min-w-0 flex-1 flex-col gap-0.5 text-left",onClick:()=>r(e.conversation),onContextMenu:D,type:"button",children:[s.jsx("div",{className:"flex items-center gap-2 pr-[124px]",children:s.jsx("span",{className:`text-[15px] font-bold truncate tracking-tight ${v}`,children:y})}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${N}`,children:[s.jsx("span",{className:"truncate",children:b}),s.jsx(Ca,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),h?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${P} animate-pulse`,children:d("mobileInbox.reconnectingItem")})]}):x?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:d("mobileInbox.connectingItem")})]}):C==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:P,children:d("mobileInbox.actionNeeded")})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${w}`,children:e.preview})]}),s.jsxs("div",{className:"mobile-inbox-corner-actions absolute top-3 right-3 flex items-center gap-1.5",children:[T&&s.jsx("span",{className:`mr-0.5 text-[11px] font-medium shrink-0 ${A}`,children:Ru(e.timestamp)}),S&&s.jsx("span",{className:"rounded-full border border-accent-primary/16 bg-accent-primary/10 px-2 py-0.5 text-[10px] font-bold text-accent-primary",children:d("mobileInbox.done")}),p&&s.jsx("button",{type:"button",className:`mobile-inbox-mute-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border transition-colors ${u?"border-amber-500/60 bg-amber-500 text-white hover:bg-amber-600":"border-border-subtle bg-bg-primary/70 text-text-muted hover:border-border-default hover:text-text-primary"}`,onClick:_=>{_.preventDefault(),_.stopPropagation(),p()},"aria-label":u?d("mobileInbox.unmute",{title:y}):d("mobileInbox.mute",{title:y}),title:d(u?"mobileInbox.mutedTitle":"mobileInbox.muteNotifications"),children:u?s.jsx(ku,{size:13}):s.jsx(Un,{size:13})}),a&&s.jsx("button",{type:"button",className:"mobile-inbox-hide-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:_=>{_.preventDefault(),_.stopPropagation(),a()},"aria-label":d("mobileInbox.hideConversationAria",{title:y}),title:d("mobileInbox.hideConversationTitle"),children:s.jsx(Gi,{size:13})}),o&&s.jsx("button",{type:"button",className:"mobile-inbox-stop-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-status-error/30 bg-bg-primary/70 text-status-error transition-colors hover:border-status-error/60 hover:bg-status-error/10",onClick:_=>{_.preventDefault(),_.stopPropagation(),o()},"aria-label":d("mobileInbox.stopSessionAria",{title:y}),title:d("mobileInbox.stopSessionTitle"),children:s.jsx(Mt,{size:13})})]})]})},e.conversation.tabKey)}function nd({size:e=32}){return s.jsx("div",{className:"flex flex-col items-center gap-2.5",children:s.jsx("div",{className:"rounded-full animate-spin border-[2.5px] border-accent-primary/20 border-t-accent-primary-light",style:{width:e,height:e}})})}function rd({count:e,label:t}){return e<=0?null:s.jsxs("span",{className:"inline-flex items-center gap-1.5 text-accent-primary","aria-live":"polite",children:[s.jsxs("span",{className:"relative flex h-2 w-2 shrink-0",children:[s.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-accent-primary/60"}),s.jsx("span",{className:"relative inline-flex h-2 w-2 rounded-full bg-accent-primary"})]}),s.jsx("span",{className:"font-semibold",children:t})]})}function b1({section:e,attentionItems:t,unreadItems:n,workingItems:r,completedItems:a,hiddenConversations:o,machineCards:i,getAvatarText:c,actionLogs:u,sendDaemonCommand:p,onOpenConversation:d,onShowAllHidden:m,onHideConversation:f,onOpenMeshGraph:g,onStopCli:S,onOpenNewSession:h,onOpenMachine:x,onOpenSettings:y,onSectionChange:b,wsStatus:C="connected",isStandalone:j=!1,onCollectChatDebugBundle:k,isConversationMuted:v,onToggleMuteConversation:N}){const{t:w}=Ne(),[A,T]=l.useState(null),I=C==="disconnected"||C==="reconnecting"||C==="offline"||C==="auth_failed",P=i.length>0,D=t.length>0||n.length>0||r.length>0||a.length>0,_=w(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),W=j?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",$=j?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",E=l.useCallback(async R=>{const M=rn(R);if(!M)return;const F=Array.isArray(R.messages)?R.messages:[],K=pp({activeConv:R,visibleMessages:F,actionLogs:u,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:F.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),J=await p(M,"get_chat_debug_bundle",{...nn(R),delivery:"daemon_file",frontendSnapshot:K}),V=fr(J),Y=fp(V),se=await hp(Y);se==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),ft.showToast(mp(V,{locatorCopyStatus:se}),se==="failed"?"warning":"success")},[u,p]),B=k||E,L=l.useCallback(()=>{A&&(f==null||f(A),T(null))},[A,f]);return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${W}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:_}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||n.length>0)&&s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[s.jsx(Un,{size:13}),s.jsx("span",{children:t.length+n.length})]}),s.jsx("button",{onClick:y,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:s.jsx(Ha,{size:18})})]})]})}),s.jsxs("div",{className:`flex min-h-0 w-full min-w-0 flex-1 flex-col gap-3 overflow-y-auto overflow-x-hidden [-webkit-overflow-scrolling:touch] ${$}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:I?s.jsx(sr,{icon:s.jsx(nd,{}),title:w(C==="offline"?"mobileInbox.networkOffline":C==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:w(C==="offline"?"mobileInbox.waitingForNetwork":C==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):i.length===0?s.jsx(sr,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:w(j?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:w(j?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!j&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(wm,{})})}):s.jsx(wn,{children:i.map((R,M)=>s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${M>0?"border-t border-border-subtle/70":""}`,onClick:()=>x(R.id),type:"button",children:[s.jsx("span",{className:"w-11 h-11 rounded-full flex items-center justify-center text-sm font-bold shrink-0 bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/16 text-text-primary shadow-[0_2px_8px_rgba(0,0,0,0.12)]",children:c(R.label)}),s.jsxs("div",{className:"flex-1 min-w-0 flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[15px] font-bold text-text-primary truncate tracking-tight",children:R.label}),s.jsxs("span",{className:"flex items-center gap-2 text-[11px] font-medium text-text-muted shrink-0",children:[s.jsx(rd,{count:R.generatingCount,label:w("mobileInbox.generatingCount",{count:R.generatingCount})}),R.unread>0?s.jsx("span",{className:"text-accent-primary",children:w("mobileInbox.newCount",{count:R.unread})}):R.total>0?w("mobileInbox.chatCount",{count:R.total}):w("mobileInbox.idle")]})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:R.subtitle}),R.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[w("mobileInbox.chatCount",{count:R.total}),R.unread>0?w("mobileInbox.unreadSuffix",{count:R.unread}):"",R.generatingCount>0?w("mobileInbox.collapsedGeneratingSuffix",{count:R.generatingCount}):""]}):R.generatingCount>0?s.jsx("div",{className:"text-[13px] text-accent-primary mt-0.5 font-medium",children:w("mobileInbox.generatingCount",{count:R.generatingCount})}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:w("mobileInbox.noActiveChats")})]})]},R.id))})}),e==="chats"&&t.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(zr,{title:w("mobileInbox.needsAttention"),className:"mb-0"}),s.jsx(wn,{children:t.map((R,M)=>s.jsx("div",{className:M>0?"border-t border-border-subtle/70":"",children:s.jsx(Kr,{item:R,type:"needs_attention",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>T(R.conversation):void 0,onRequestStopCli:S?()=>S(R.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:B,isMuted:v==null?void 0:v(R.conversation),onToggleMute:N?()=>N(R.conversation):void 0})},R.conversation.tabKey))})]}),e==="chats"&&n.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(zr,{title:w("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),s.jsx(wn,{children:n.map((R,M)=>s.jsx("div",{className:M>0?"border-t border-border-subtle/70":"",children:s.jsx(Kr,{item:R,type:"task_complete",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>T(R.conversation):void 0,onRequestStopCli:S?()=>S(R.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:B,isMuted:v==null?void 0:v(R.conversation),onToggleMute:N?()=>N(R.conversation):void 0})},R.conversation.tabKey))})]}),e==="chats"&&r.length>0&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[s.jsx(zr,{title:w("mobileInbox.workingNow"),className:"mb-0 mt-2"}),s.jsx(wn,{children:r.map((R,M)=>s.jsx("div",{className:M>0?"border-t border-border-subtle/70":"",children:s.jsx(Kr,{item:R,type:"working",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>T(R.conversation):void 0,onRequestStopCli:S?()=>S(R.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:B,isMuted:v==null?void 0:v(R.conversation),onToggleMute:N?()=>N(R.conversation):void 0})},R.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&s.jsx(zr,{title:w("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(wn,{children:a.map((R,M)=>s.jsx("div",{className:M>0?"border-t border-border-subtle/70":"",children:s.jsx(Kr,{item:R,type:"earlier",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>T(R.conversation):void 0,onRequestStopCli:S?()=>S(R.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:B,isMuted:v==null?void 0:v(R.conversation),onToggleMute:N?()=>N(R.conversation):void 0})},R.conversation.tabKey))}):D?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:w("mobileInbox.allCaughtUp")}):I?s.jsx(sr,{icon:s.jsx(nd,{size:28}),title:w("mobileInbox.connecting"),subtitle:w("mobileInbox.connectingSubtitle")}):P?s.jsx(sr,{icon:s.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:s.jsx(bn,{size:20})}),title:w("mobileInbox.noConversations"),subtitle:w("paneGroup.newSessionDescription"),children:h&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:h,"aria-label":w("paneGroup.newSession"),title:w("paneGroup.newSession"),children:[s.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),s.jsx("span",{children:w("paneGroup.newSession")})]})}):s.jsx(sr,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:w("mobileInbox.noMachinesConnected"),subtitle:w("mobileInbox.noMachinesSubtitle")})]}),e==="chats"&&o.length>0&&(()=>{const R=Xb(o);return s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(wn,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:w("mobileInbox.hiddenTabs")}),s.jsx(rd,{count:R,label:w("mobileInbox.generatingCount",{count:R})})]}),s.jsxs("div",{className:"mt-0.5 text-[13px] text-text-muted",children:[w("mobileInbox.collapsedCount",{count:o.length}),R>0?w("mobileInbox.collapsedGeneratingSuffix",{count:R}):""]})]}),s.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-[12px] font-semibold text-accent-primary hover:border-border-default",onClick:m,children:w("mobileInbox.restoreAll")})]})})})})()]}),e==="chats"&&h&&D&&s.jsx("button",{className:"fixed right-5 bottom-[calc(env(safe-area-inset-bottom,0px)+64px+20px)] z-50 flex items-center justify-center w-14 h-14 rounded-full hover:scale-105 active:scale-95 transition-transform",style:{background:"var(--accent-primary)",color:"var(--accent-on-primary)",boxShadow:"var(--shadow-md)"},onClick:h,"aria-label":w("paneGroup.newSession"),title:w("paneGroup.newSession"),children:s.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}),A&&s.jsx(f1,{conversation:A,onCancel:()=>T(null),onConfirm:L}),s.jsx(km,{section:e,onSectionChange:b})]})}function g1(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 Sm(e){const t=[e.workspace||"Workspace unknown"],n=mn(e.summaryMetadata);n&&t.push(n),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const r=g1(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:r?`Updated ${r}`:"",preview:(e.preview||"").trim()}}function vl({title:e,description:t,currentPath:n,directories:r,busy:a=!1,error:o="",confirmLabel:i="Use this folder",onClose:c,onNavigate:u,onConfirm:p}){const[d,m]=l.useState(n),{t:f}=Ne("common");l.useEffect(()=>{m(n)},[n]);const g=Vj(n),S=d.trim();return s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:c,"aria-label":"Close folder browser",children:s.jsx(Mt,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!g||a||u(g)},disabled:!g||a,children:[s.jsx(Wi,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:f("machine.workspaceBrowse.currentFolder")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:d,onChange:h=>m(h.target.value),onKeyDown:h=>{h.key!=="Enter"||!S||a||(h.preventDefault(),u(S))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!S||a||u(S)},disabled:!S||a,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):r.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:r.map(h=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>u(h.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(En,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:h.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:h.path})]})]},h.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:c,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(S||n),disabled:!S&&!n||a,children:i})]})]})})}function Xa({title:e,description:t,details:n,workspaceOptions:r,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:i,busyLabel:c,busy:u=!1,showArgsInput:p,argsValue:d,onArgsChange:m,showModelInput:f,modelValue:g,onModelChange:S,historyProviderNode:h,onConfirm:x,onCancel:y}){const{t:b}=Ne("common"),C=i??b("machine.launchConfirm.launch"),j=c??b("machine.launchConfirm.launching"),k=r==null?void 0:r.find(v=>v.key===a);return s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:y,"aria-label":b("machine.launchConfirm.closeAria"),children:s.jsx(Mt,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[r&&r.length>0&&o&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.workspace")}),s.jsx("select",{value:a||"",onChange:v=>o(v.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:u,children:r.map(v=>s.jsx("option",{value:v.key,children:v.label},v.key))}),(k==null?void 0:k.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:k.description})]}),h,n.map(v=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:v.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:v.value})]},`${v.label}:${v.value}`)),f&&S&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.languageModel")}),s.jsx("input",{type:"text",value:g||"",onChange:v=>S(v.target.value),placeholder:b("machine.launchConfirm.autoDetect"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]}),p&&m&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.cliArgs")}),s.jsx("input",{type:"text",value:d||"",onChange:v=>m(v.target.value),placeholder:b("machine.launchConfirm.cliArgsPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:u})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:y,disabled:u,children:b("machine.launchConfirm.cancel")}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:x,disabled:u,children:[s.jsx(wu,{size:14}),u?j:C]})]})]})})}function ad(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function Cm(e){const{machine:t,currentWorkspacePath:n,currentWorkspaceId:r,includeHome:a=!0,homeLabel:o="Home directory",homeDescription:i="Launch without a workspace"}=e,c=[];a&&c.push({key:"__home__",label:o,description:i,workspaceId:null,workspacePath:null});for(const d of t.workspaces||[])c.push({key:`saved:${d.id}`,label:`${d.id===t.defaultWorkspaceId?"⭐ ":""}${ad(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const u=(n==null?void 0:n.trim())||"",p=u?(t.workspaces||[]).find(d=>d.path===u):null;if(u&&!p&&c.push({key:`custom:${u}`,label:ad(u),description:u,workspaceId:null,workspacePath:u}),r){const d=`saved:${r}`;if(c.some(m=>m.key===d))return{options:c,selectedKey:d}}return p?{options:c,selectedKey:`saved:${p.id}`}:u?{options:c,selectedKey:`custom:${u}`}:{options:c,selectedKey:"__home__"}}function x1(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function v1(e){return[x1(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function y1(e){return e.lastLaunchedAt?Ba(e.lastLaunchedAt):""}function jm(e){return{metaText:v1(e),updatedLabel:y1(e)}}function Po(e,t,n){return e?"ide":t>0?"cli":n>0?"acp":null}function w1({selectedMachineEntry:e,cliProviders:t,acpProviders:n,machineAction:r,onBrowseDirectory:a,onListSavedSessions:o}){var ae,we,Me,qe;const i=qn(),[c,u]=l.useState(!1),p=(((ae=e.detectedIdes)==null?void 0:ae.length)||0)>0,d=l.useMemo(()=>(e.workspaces||[]).map(ve=>({id:ve.id,path:ve.path,label:ve.label})),[e]),m=e.defaultWorkspaceId||null,[f,g]=l.useState(m||((we=d[0])==null?void 0:we.id)||""),[S,h]=l.useState(""),[x,y]=l.useState(""),[b,C]=l.useState([]),[j,k]=l.useState(!1),[v,N]=l.useState(""),[w,A]=l.useState(!1),[T,I]=l.useState(Po(p,t.length,n.length)),P=l.useRef(null),[D,_]=l.useState(null),W=l.useRef("__home__"),[$,E]=l.useState("__home__"),[B,L]=l.useState(""),[R,M]=l.useState(""),[F,K]=l.useState(""),[J,V]=l.useState([]),[Y,se]=l.useState(()=>qt().textQuery),[ie,Z]=l.useState(()=>qt().workspaceQuery),[O,ee]=l.useState(()=>qt().modelQuery),[G,le]=l.useState(()=>qt().resumableOnly),[je,ge]=l.useState(()=>qt().sortMode),[Ce,ue]=l.useState(!1),[z,U]=l.useState(!1),q=l.useRef(null),Q=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const me=f==="__custom__"?S.trim():((Me=d.find(ve=>ve.id===f))==null?void 0:Me.path)||"",Ae=f==="__custom__"&&!!me&&r.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(r.message),de=f!=="__custom__"&&((qe=d.find(ve=>ve.id===f))==null?void 0:qe.path)||"",H=l.useMemo(()=>(e.recentLaunches||[]).map(ve=>ve.workspace),[e]),he=l.useCallback(async ve=>{k(!0),N("");try{const $e=await a(ve);y($e.path),h($e.path),C($e.directories)}catch($e){N($e instanceof Error?$e.message:"Could not load folder")}finally{k(!1)}},[a]),fe=l.useCallback(()=>{var $e;g("__custom__"),A(!0);const ve=bl(e.platform,fl(S.trim(),de,H,e.defaultWorkspacePath,($e=d.find(lt=>lt.id===m))==null?void 0:$e.path,d.map(lt=>lt.path)));he(ve)},[S,m,he,H,de,e.platform,d]),ye=l.useCallback(ve=>{if(ve!=null&&ve.workspaceId){g(ve.workspaceId),h("");return}if(ve!=null&&ve.workspacePath){g("__custom__"),h(ve.workspacePath);return}g(""),h("")},[]),Pe=l.useCallback(ve=>{if(g(ve),ve==="__custom__"){fe();return}h("")},[fe]),He=l.useCallback(ve=>{g("__custom__"),h(ve)},[]),ke=l.useCallback((ve,$e)=>{P.current=$e,W.current=ve.selectedWorkspaceKey||"__home__",E(ve.selectedWorkspaceKey||"__home__"),L(ve.initialArgs||""),M(ve.initialModel||""),K(""),V([]);const lt=ve.providerType?`${e.id}:${ve.providerType}`:null;if(SS(Q.current,lt)){const at=qt();se(at.textQuery),Z(at.workspaceQuery),ee(at.modelQuery),le(at.resumableOnly),ge(at.sortMode)}Q.current=lt,_(ve),ve.providerType&&o&&(ue(!0),o(ve.providerType).then(at=>V(at||[])).catch(at=>console.warn("Failed to load saved sessions",at)).finally(()=>ue(!1)))},[o,e.id]),pe=l.useMemo(()=>$p(J,{textQuery:Y,workspaceQuery:ie,modelQuery:O,resumableOnly:G,sortMode:je}),[O,G,J,je,Y,ie]);l.useEffect(()=>{F&&(pe.some(ve=>ve.providerSessionId===F)||K(""))},[pe,F]);const st=l.useCallback(()=>{P.current&&(U(!0),P.current().finally(()=>{P.current=null,U(!1),_(null)}))},[]),De=l.useCallback(()=>{P.current=null,_(null)},[]),_e=l.useCallback(ve=>{W.current=ve,E(ve)},[]);return l.useEffect(()=>{var ve;q.current!==e.id&&(q.current=e.id,g(m||((ve=d[0])==null?void 0:ve.id)||"__custom__"),h(""),y(""),C([]),N(""),A(!1),se(qt().textQuery),Z(qt().workspaceQuery),ee(qt().modelQuery),le(qt().resumableOnly),ge(qt().sortMode),Q.current=null,I(Po(p,t.length,n.length)))},[n.length,t.length,m,p,e.id,d]),l.useEffect(()=>{var ve;f!=="__custom__"&&(f&&d.some($e=>$e.id===f)||g(m||((ve=d[0])==null?void 0:ve.id)||"__custom__"))},[m,f,d]),l.useEffect(()=>{T==="ide"&&p||T==="cli"&&t.length>0||T==="acp"&&n.length>0||I(Po(p,t.length,n.length))},[T,n.length,t.length,p]),{showAllRecent:c,setShowAllRecent:u,hasIdeOptions:p,workspaceRows:d,defaultWorkspaceId:m,workspaceChoice:f,customWorkspacePath:S,browseCurrentPath:x,browseDirectories:b,browseBusy:j,browseError:v,browseDialogOpen:w,activeLauncherKind:T,launchConfirm:D,launchConfirmWorkspaceKeyRef:W,launchConfirmWorkspaceKey:$,launchConfirmArgs:B,launchConfirmModel:R,launchConfirmResumeId:F,launchConfirmSavedSessions:J,launchConfirmTextFilter:Y,launchConfirmWorkspaceFilter:ie,launchConfirmModelFilter:O,launchConfirmResumableOnly:G,launchConfirmSortMode:je,filteredLaunchConfirmSavedSessions:pe,launchConfirmSessionsLoading:Ce,launchConfirmBusy:z,resolvedWorkspacePath:me,canCreateMissingWorkspace:Ae,openBrowseDialog:fe,loadBrowsePath:he,handleWorkspaceChoiceChange:Pe,chooseCustomWorkspacePath:He,setCustomWorkspacePath:h,setBrowseDialogOpen:A,setActiveLauncherKind:I,openLaunchConfirm:ke,handleConfirmLaunch:st,closeLaunchConfirm:De,setWorkspaceSelectionFromOption:ye,setLaunchConfirmWorkspaceKeyAndSync:_e,setLaunchConfirmArgs:L,setLaunchConfirmModel:M,setLaunchConfirmResumeId:K,setLaunchConfirmTextFilter:se,setLaunchConfirmWorkspaceFilter:Z,setLaunchConfirmModelFilter:ee,setLaunchConfirmResumableOnly:le,setLaunchConfirmSortMode:ge}}function k1({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:n,cliProviders:r,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:i,machineAction:c,isStandalone:u,section:p,showBottomNav:d,onBack:m,onSectionChange:f,onOpenConversation:g,onOpenRecent:S,onOpenMachineDetails:h,onMachineUpgrade:x,onLaunchDetectedIde:y,onAddWorkspace:b,onBrowseDirectory:C,onLaunchWorkspaceProvider:j,onListSavedSessions:k}){const{t:v}=Ne("common"),N=E=>E==="ide"?"IDE":E==="cli"?"CLI":"ACP",w=n.slice(0,4),A=t.slice(0,3),T=w1({selectedMachineEntry:e,cliProviders:r,acpProviders:a,machineAction:c,onBrowseDirectory:C,onListSavedSessions:k}),I=l.useMemo(()=>w.map(E=>{const{metaText:B,updatedLabel:L}=jm(E);return{key:`recent-launch:${E.id}`,primary:E.label,secondary:B,updatedLabel:L,onClick:()=>{const{options:R,selectedKey:M}=Cm({machine:{workspaces:T.workspaceRows,defaultWorkspaceId:T.defaultWorkspaceId},currentWorkspacePath:E.workspace,homeLabel:v("newSession.homeDirectory"),homeDescription:v("newSession.launchWithoutWorkspace")});T.openLaunchConfirm({title:E.kind==="ide"?ja(v,"restart-ide",E.label):E.providerSessionId?Fp(v,E.label):ja(v,"start-fresh",E.label),description:E.kind==="ide"?Na(v,"restart-ide"):E.providerSessionId?Bp(v):Na(v,"start-fresh"),confirmLabel:E.kind==="ide"?Aa(v,"restart-ide"):E.providerSessionId?Si(v,!0):Aa(v,"start-fresh"),busyLabel:E.kind==="ide"?Ta(v,"restart-ide"):E.providerSessionId?Hp(v,!0):Ta(v,"start-fresh"),workspaceOptions:R,selectedWorkspaceKey:M,details:[{label:"Mode",value:N(E.kind)},...E.providerType?[{label:"Provider",value:E.providerType}]:[]]},async()=>{const F=R.find(K=>K.key===T.launchConfirmWorkspaceKeyRef.current);T.setWorkspaceSelectionFromOption(F),await S({...E,workspace:(F==null?void 0:F.workspacePath)??null})})}}}),[T,S,w,v]),P=l.useMemo(()=>A.map(E=>({key:`recent-chat:${E.conversation.tabKey}`,primary:kt(E.conversation),secondary:Jk(E.conversation,{timestampLabel:E.timestamp?Ru(E.timestamp):null}),unread:E.unread,onClick:()=>g(E.conversation)})),[g,A]),D=T.showAllRecent?I:I.slice(0,4),_=I.length>0,W=P.length>0,$=u?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${$} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:m,type:"button","aria-label":"Back",children:s.jsx(Wi,{size:18})}),s.jsxs("div",{className:"min-w-0 flex flex-col gap-0.5",children:[s.jsx("div",{className:"flex items-center gap-2 text-[17px] font-extrabold tracking-tight text-text-primary truncate",children:is(e,{fallbackId:e.id})}),s.jsxs("div",{className:"min-w-0 flex items-center flex-wrap gap-1.5 text-xs text-text-secondary truncate",children:[e.platform||"machine",e.version?` · v${e.version}`:""]})]})]})}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto py-2 flex flex-col gap-2 -webkit-overflow-scrolling-touch",children:[W&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:P.map(E=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${E.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:E.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:E.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:E.secondary})]},E.key))})]}),_&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:D.map(E=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:E.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:E.primary}),E.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:E.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:E.secondary})]},E.key))}),I.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>T.setShowAllRecent(E=>!E),children:T.showAllRecent?"Show fewer":`Show ${I.length-4} more`})})]}),!1,s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:x,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",i]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:h,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),T.browseDialogOpen&&s.jsx(vl,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:T.browseCurrentPath,directories:T.browseDirectories,busy:T.browseBusy,error:T.browseError,confirmLabel:"Use this folder",onClose:()=>T.setBrowseDialogOpen(!1),onNavigate:E=>{T.loadBrowsePath(E)},onConfirm:E=>{T.chooseCustomWorkspacePath(E),T.setBrowseDialogOpen(!1)}}),T.launchConfirm&&s.jsx(Xa,{title:T.launchConfirm.title,description:T.launchConfirm.description,details:T.launchConfirm.details,workspaceOptions:T.launchConfirm.workspaceOptions,selectedWorkspaceKey:T.launchConfirmWorkspaceKey,onWorkspaceChange:T.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:T.launchConfirm.providerType?Si(v,!!T.launchConfirmResumeId):T.launchConfirm.confirmLabel,busyLabel:T.launchConfirm.providerType?void 0:T.launchConfirm.busyLabel,busy:T.launchConfirmBusy,showArgsInput:T.launchConfirm.showArgsInput,argsValue:T.launchConfirmArgs,onArgsChange:T.setLaunchConfirmArgs,showModelInput:T.launchConfirm.showModelInput,modelValue:T.launchConfirmModel,onModelChange:T.setLaunchConfirmModel,historyProviderNode:T.launchConfirm.providerType&&(T.launchConfirmSessionsLoading||T.launchConfirmSavedSessions.length>0)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),T.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:ll(v)}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:T.launchConfirmTextFilter,onChange:E=>T.setLaunchConfirmTextFilter(E.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:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:T.launchConfirmWorkspaceFilter,onChange:E=>T.setLaunchConfirmWorkspaceFilter(E.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:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:T.launchConfirmModelFilter,onChange:E=>T.setLaunchConfirmModelFilter(E.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:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsxs("select",{value:T.launchConfirmSortMode,onChange:E=>T.setLaunchConfirmSortMode(E.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:T.launchConfirmResumableOnly,onChange:E=>T.setLaunchConfirmResumableOnly(E.target.checked),disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:T.launchConfirmResumeId,onChange:E=>T.setLaunchConfirmResumeId(E.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:NS(v)}),T.filteredLaunchConfirmSavedSessions.map(E=>s.jsxs("option",{value:E.providerSessionId,disabled:!E.canResume,children:[E.title||E.providerSessionId," ",E.canResume?"":"(workspace missing)"]},E.providerSessionId))]}),!T.launchConfirmSessionsLoading&&T.launchConfirmSavedSessions.length>0&&T.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),T.launchConfirmResumeId&&(()=>{const E=T.filteredLaunchConfirmSavedSessions.find(L=>L.providerSessionId===T.launchConfirmResumeId);if(!E)return null;const B=Sm(E);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:B.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:B.providerSessionId}),s.jsx("div",{className:"mt-1",children:B.metaLine}),B.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:B.updatedLabel}),B.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:B.preview})]})})()]}),onConfirm:T.handleConfirmLaunch,onCancel:T.closeLaunchConfirm}),d&&s.jsx(km,{section:p,onSectionChange:f})]})}const od=8e3;function S1(e){const t=e&&typeof e=="object"&&"result"in e?e.result:e,n=t&&typeof t=="object",r=n&&t.success===!1,a=n&&t.mirrorStale===!0;return!r&&!a?{confirmed:!0}:{confirmed:!1,reason:r&&typeof t.error=="string"?t.error:a?"the coordinator did not confirm the change":"command was rejected"}}function Nm(e,t,n){const r=l.useRef(new Map),[,a]=l.useState(0),o=l.useCallback(()=>a(g=>g+1),[]);l.useEffect(()=>{const g=r.current;if(g.size===0)return;const S=Date.now();let h=!1;for(const[x,y]of g){const b=e.get(x),C=y.muted===void 0||(b?b.muted===y.muted:!1),j=y.hidden===void 0||(b?b.surfaceHidden===y.hidden:!1),k=S-y.at>od;(C&&j||k)&&(g.delete(x),h=!0)}h&&o()},[e,o]),l.useEffect(()=>{if(r.current.size===0)return;const g=setInterval(()=>{const S=r.current,h=Date.now();let x=!1;for(const[y,b]of S)h-b.at>od&&(S.delete(y),x=!0);x&&o(),S.size===0&&clearInterval(g)},1e3);return()=>clearInterval(g)});const i=l.useCallback((g,S)=>{const h=r.current.get(g);r.current.set(g,{...h,...S,at:Date.now()}),o()},[o]),c=l.useCallback(g=>{const S=g.sessionId,h=S?r.current.get(S):void 0;return(h==null?void 0:h.muted)!==void 0?h.muted:Gs(g,e).muted??!1},[e]),u=l.useCallback(g=>{const S=g.sessionId,h=S?r.current.get(S):void 0;return(h==null?void 0:h.hidden)!==void 0?h.hidden:Gs(g,e).surfaceHidden??!1},[e]),p=l.useCallback((g,S)=>{const h=Rs(g),x=g.sessionId;!h||!x||(i(x,S),t(h,"set_conversation_prefs",{sessionId:x,...S,...za(g)}).then(y=>{const b=S1(y);b.confirmed||(console.warn("[conversation-prefs] set_conversation_prefs not confirmed",b.reason),r.current.delete(x),o(),n==null||n(`Couldn't update conversation — ${b.reason}`))}).catch(y=>{console.warn("[conversation-prefs] set_conversation_prefs failed",y),r.current.delete(x),o();const b=y instanceof Error?y.message:String(y??"the daemon is unreachable");n==null||n(`Couldn't update conversation — ${b}`)}))},[t,i,o,n]),d=l.useCallback(g=>{p(g,{muted:!c(g)})},[p,c]),m=l.useCallback((g,S)=>{p(g,{hidden:S})},[p]),f=l.useCallback(g=>{p(g,{hidden:!u(g)})},[p,u]);return{isMuted:c,isHidden:u,toggleMute:d,setHidden:m,toggleHidden:f}}function da(e){return[...e].sort((t,n)=>{const r=n.timestamp-t.timestamp;return r!==0?r:t.conversation.tabKey.localeCompare(n.conversation.tabKey)})}function C1(e,t=[]){const n=new Map(e.map(a=>[a.conversation.tabKey,a])),r=t.map(a=>n.get(a)).filter(a=>!!a);return r.length===e.length?r:da(e)}function j1(e,t=[]){const n=e.filter(i=>i.requiresAction),r=e.filter(i=>i.unread&&!i.requiresAction),a=e.filter(i=>!i.unread&&!i.requiresAction&&i.isWorking),o=e.filter(i=>!i.unread&&!i.requiresAction&&!i.isWorking);return{attentionItems:da(n),unreadItems:da(r),workingItems:C1(a,t),completedItems:da(o)}}function N1(e){var r,a,o;const t=((r=e.p2p)==null?void 0:r.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":!(!!((a=e.p2p)!=null&&a.available)||!!((o=e.p2p)!=null&&o.state))&&e.status&&e.status!=="offline"?"Connected":"Offline"}function A1(e,t){if(!e)return[];const n=e.recentLaunches||[];return n.length>0?n.map(r=>({id:r.id,label:r.title||r.providerName||r.providerType,kind:r.kind,providerType:r.providerType,providerSessionId:r.providerSessionId,subtitle:mn(r.summaryMetadata)||r.workspace||void 0,workspace:r.workspace,summaryMetadata:r.summaryMetadata})):t.filter(r=>r.type!=="adhdev-daemon"&&r.daemonId===e.id).map(r=>{var i;const a=Sr(r)?"cli":Dn(r)?"acp":"ide",o=mn(r.summaryMetadata);return{id:`${a}:${r.type}:${r.workspace||""}`,label:((i=r.activeChat)==null?void 0:i.title)||(Sr(r)?r.cliName||r.type:Dn(r)&&r.cliName||r.type),kind:a,providerType:r.type,providerSessionId:r.providerSessionId,subtitle:Dn(r)?o||r.workspace||void 0:r.workspace||void 0,workspace:r.workspace||void 0,timestamp:r.lastMessageAt||0}}).sort((r,a)=>a.timestamp-r.timestamp).map(({timestamp:r,...a})=>a)}function T1(e,t,n=[]){const r=new Map;for(const o of t){const i=Rs(o.conversation),c=r.get(i);c?c.push(o):r.set(i,[o])}const a=new Map;for(const o of n){const i=Rs(o),c=a.get(i);c?c.push(o):a.set(i,[o])}return e.map(o=>{const i=r.get(o.id)||[],c=a.get(o.id)||[],u=[...i].sort((h,x)=>x.timestamp-h.timestamp)[0]||null,p=(u==null?void 0:u.conversation)||null,d=bi(o),m=i.filter(h=>h.unread||h.requiresAction).length,f=i.filter(h=>kr(h.conversation)).length+c.filter(kr).length,g=N1(o),S=[o.platform||"machine",g].filter(Boolean);return{id:o.id,label:is(o,{fallbackId:o.id}),subtitle:S.join(" · "),unread:m,total:i.length,generatingCount:f,latestConversation:p,latestTimestamp:(u==null?void 0:u.timestamp)||0,fallbackActivityAt:d,preview:p?Qk(p,Cp(p)):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((o,i)=>{const c=o.latestTimestamp||o.fallbackActivityAt||0,u=i.latestTimestamp||i.fallbackActivityAt||0;return u!==c?u-c:o.label.localeCompare(i.label)})}function M1(e){return e==="chat"}function Vr(e,t){var n;if(!(typeof window>"u"))try{if(!(!!((n=import.meta.env)!=null&&n.DEV)||window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[mobile-read] ${e}`,t)}catch{}}function D1({conversations:e,machineEntries:t,items:n,selectedConversation:r,selectedTabKey:a,screen:o,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:S,setScreen:h,setSelectedMachineId:x,setSection:y,setMachineBackTarget:b,resetMachineAction:C}){const j=l.useRef(null),k=l.useCallback(v=>{if(!(v!=null&&v.sessionId))return;const N=Gs(v,i),w=Math.max(Date.now(),cn(v),N.lastUpdated||0);Vr("mark_read:start",{tabKey:v.tabKey,sessionId:v.sessionId,displayPrimary:kt(v),inboxBucket:N.inboxBucket,unread:N.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:cn(v),readAt:w}),c(Rs(v)||v.routeId,"mark_session_seen",{sessionId:v.sessionId,providerSessionId:v.providerSessionId,seenAt:w,completionMarker:N.completionMarker}).then(A=>{Vr("mark_read:result",{tabKey:v.tabKey,sessionId:v.sessionId,result:A})}).catch(A=>{Vr("mark_read:error",{tabKey:v.tabKey,sessionId:v.sessionId,error:A instanceof Error?A.message:String(A)})})},[i,c]);return l.useEffect(()=>{var N;if(!r){M1(o)&&h("inbox"),S(((N=e[0])==null?void 0:N.tabKey)||null),j.current=null;return}if(o!=="chat"){j.current=null;return}const v=`${r.tabKey}:${r.sessionId||""}`;j.current!==v&&(j.current=v,k(r))},[e,k,o,r,h,S]),l.useEffect(()=>{if(!u)return;const v=e.find(N=>N.tabKey===u);v&&(S(v.tabKey),h("chat"),p==null||p())},[e,p,u,h,S]),l.useEffect(()=>{if(!d)return;const v=t.find(N=>N.id===d);v&&(x(v.id),C(),y("machines"),b("inbox"),h("machine"),m==null||m())},[t,m,d,C,b,h,y,x]),l.useEffect(()=>{f&&(y(f),h("inbox"),g==null||g())},[g,f,h,y]),l.useEffect(()=>{const v=n.filter(N=>N.inboxBucket==="task_complete"||N.unread);v.length!==0&&Vr("inbox_state",{screen:o,selectedTabKey:a,items:v.map(N=>{const w=Gs(N.conversation,i);return{liveState:w,tabKey:N.conversation.tabKey,sessionId:N.conversation.sessionId,displayPrimary:kt(N.conversation),serverBucket:w.inboxBucket,computedBucket:N.inboxBucket,serverUnread:w.unread,computedUnread:N.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,activityAt:cn(N.conversation)}})})},[n,i,o,a]),{markConversationRead:k}}function I1(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function id(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function P1(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function L1({sendDaemonCommand:e,navigate:t,ides:n,conversations:r}){const{launchCli:a}=$a(),[o,i]=l.useState("idle"),[c,u]=l.useState(""),[p,d]=l.useState(null),m=l.useCallback(()=>{i("idle"),u(""),d(null)},[]),f=l.useCallback(async(C,j,k)=>{var v;try{i("loading"),u(`Launching ${j}…`);const N={ideType:j,enableCdp:!0};(v=k==null?void 0:k.workspacePath)!=null&&v.trim()&&(N.workspace=k.workspacePath.trim()),await e(C,"launch_ide",N),i("done"),u(`${j} launch requested`)}catch(N){i("error"),u(N instanceof Error?N.message:"Launch IDE failed"),console.error("Launch IDE failed",N)}},[e]),g=l.useCallback(async(C,j,k)=>{if(j.trim())try{i("loading"),u(k!=null&&k.createIfMissing?"Creating folder…":"Saving workspace…");const v=await e(C,"workspace_add",{path:j.trim(),createIfMissing:(k==null?void 0:k.createIfMissing)===!0});if(v!=null&&v.success){i("done"),u(k!=null&&k.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),u((v==null?void 0:v.error)||"Could not save workspace")}catch(v){i("error"),u(v instanceof Error?v.message:"Could not save workspace")}},[e]),S=l.useCallback(async C=>{i("loading"),u("Starting daemon upgrade…");const j=n.find(v=>v.id===C||v.daemonId===C),k=await wC(e,C,j);i(k.state),u(k.message)},[n,e]),h=l.useCallback(async(C,j,k,v)=>{var A,T,I;const N=Date.now(),w={machineId:C,kind:j,providerType:k,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:N};try{i("loading"),u(`Launching ${k}…`),d(w);const P={cliType:k};(A=v==null?void 0:v.workspacePath)!=null&&A.trim()?P.dir=v.workspacePath.trim():v!=null&&v.workspaceId?P.workspaceId=v.workspaceId:v!=null&&v.useHome&&(P.useHome=!0),v!=null&&v.resumeSessionId&&(P.resumeSessionId=v.resumeSessionId),(T=v==null?void 0:v.args)!=null&&T.trim()&&(P.cliArgs=v.args.trim().split(/\s+/).filter(Boolean)),(I=v==null?void 0:v.model)!=null&&I.trim()&&(P.initialModel=v.model.trim());const D=await a(C,P),_=(D==null?void 0:D.result)||D,W=(_==null?void 0:_.sessionId)||(_==null?void 0:_.id);if(D!=null&&D.success&&W){d(null),i("done"),u(`${k} launched`),t(Nr(W));return}if(D!=null&&D.success){i("loading"),u(`${k} launch requested — waiting for session…`);return}d(null),i("error"),u((D==null?void 0:D.error)||(_==null?void 0:_.error)||`Could not launch ${j.toUpperCase()} workspace`)}catch(P){if(P1(P)){i("loading"),u(`${k} launch requested — waiting for session…`);return}d(null),i("error"),u(P instanceof Error?P.message:`Could not launch ${j.toUpperCase()} workspace`)}},[t,e]),x=l.useCallback(async(C,j)=>{try{const k=await e(C,"list_saved_sessions",{providerType:j,kind:"cli",limit:30}),v=(k==null?void 0:k.result)??k;return Array.isArray(v==null?void 0:v.sessions)?v.sessions:[]}catch(k){return console.error("Failed to list saved sessions on mobile:",k),[]}},[e]),y=l.useCallback(async(C,j)=>gl(e,C,j),[e]);l.useEffect(()=>{if(!p)return;const C=id(p.workspacePath),j=n.find(v=>{var P,D,_,W;if(!v||v.type==="adhdev-daemon"||I1(v.daemonId||v.id)!==p.machineId||(v.transport==="acp"?"acp":v.transport==="pty"?"cli":null)!==p.kind||String(v.agentType||v.type||"")!==p.providerType)return!1;const T=String(v.providerSessionId||"");if(p.resumeSessionId&&T)return T===p.resumeSessionId;if(C){const $=id(v.workspace||v.runtimeWorkspaceLabel);return $?$===C:!1}return Number(v.lastUpdated||v._lastUpdate||v.timestamp||((W=(_=(D=(P=v.activeChat)==null?void 0:P.messages)==null?void 0:D.at)==null?void 0:_.call(D,-1))==null?void 0:W.timestamp)||0)>=p.startedAt-5e3});if(!j)return;const k=vm({entrySessionId:j.sessionId,entryInstanceId:j.instanceId,entryRouteId:j.id,conversations:r});k&&(d(null),i("done"),u(`${p.providerType} launched`),t(Nr(k)))},[r,n,t,p]),l.useEffect(()=>{if(!p)return;const C=window.setTimeout(()=>{d(j=>!j||j.startedAt!==p.startedAt?j:(i("error"),u("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(C)},[p]);const b=l.useCallback(async(C,j)=>{var k;if(j.kind==="ide"&&j.providerType){await f(C,j.providerType,{workspacePath:j.workspace||null});return}if((j.kind==="cli"||j.kind==="acp")&&j.providerType){const v=((k=j.workspace)==null?void 0:k.trim())||"";await h(C,j.kind,j.providerType,{workspacePath:v||null,useHome:!v,resumeSessionId:j.providerSessionId||null})}},[f,h]);return{machineAction:{state:o,message:c},resetMachineAction:m,handleLaunchDetectedIde:f,handleAddWorkspace:g,handleMachineUpgrade:S,handleLaunchWorkspaceProvider:h,handleListSavedSessions:x,handleBrowseDirectory:y,handleOpenRecent:b}}function R1({conversations:e,selectedConversation:t,machineBackTarget:n,markConversationRead:r,resetMachineAction:a,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:u,setMachineBackTarget:p}){const d=l.useCallback(y=>{o(y.tabKey),i("chat"),r(y)},[r,i,o]),m=l.useCallback(y=>{const b=e.find(C=>C.routeId===y.routeId&&C.streamSource==="native");b&&(o(b.tabKey),i("chat"),r(b))},[e,r,i,o]),f=l.useCallback(()=>{r(t),i("inbox")},[r,t,i]),g=l.useCallback((y,b="inbox")=>{c(y),a(),u("machines"),p(b),i("machine")},[a,p,i,u,c]),S=l.useCallback(y=>{const b=Rs(y);b&&g(b,"chat")},[g]),h=l.useCallback(()=>{a(),i(n)},[n,a,i]),x=l.useCallback(y=>{u(y),i("inbox")},[i,u]);return{openConversation:d,openNativeConversation:m,backFromConversation:f,openMachine:g,openConversationMachine:S,backFromMachine:h,changeMachineSection:x}}function Bn(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function E1(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function _1({conversations:e,hiddenConversations:t,ides:n,actionLogs:r,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,userName:c,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,onOpenHistory:S,onOpenRemote:h,onStopCli:x,wsStatus:y,isConnected:b,onShowAllHiddenConversations:C,onHideConversation:j,onOpenMeshGraph:k,onOpenNewSession:v,liveSessionInboxState:N,setCliViewModeOverrides:w}){const[A,T]=l.useState(()=>{var fe;return((fe=e[0])==null?void 0:fe.tabKey)||null}),[I,P]=l.useState(()=>e[0]?"chat":"inbox"),[D,_]=l.useState("chats"),[W,$]=l.useState(null),[E,B]=l.useState("inbox"),L=l.useRef([]),R=Mr(),M="1.0.30",F=l.useMemo(()=>e.find(fe=>fe.tabKey===A)||e[0]||null,[e,A]),K=l.useMemo(()=>F?n.find(fe=>fe.id===F.routeId):void 0,[n,F]),J=l.useMemo(()=>!F||pt(F)||!ht(F)?null:Gn(F),[F]),V=l.useMemo(()=>n.filter(fe=>fe.type==="adhdev-daemon").sort(Qi),[n]),Y=l.useMemo(()=>V.find(fe=>fe.id===W)||null,[V,W]),se=Ka({sendDaemonCommand:a,activeConv:F||void 0,setActionLogs:o,isStandalone:i}),ie=L1({sendDaemonCommand:a,navigate:R,ides:n,conversations:e}),Z=Nk(e),O=l.useMemo(()=>e.map(fe=>{const ye=I==="chat"&&(F==null?void 0:F.tabKey)===fe.tabKey,Pe=Wa(fe,N,{hideOpenTaskCompleteUnread:!0,isOpenConversation:ye}),He=cn(fe),ke=Cp(fe),pe=Ip(fe,ke);return{conversation:fe,timestamp:He,preview:pe,unread:Pe.unread,requiresAction:Pe.requiresAction,isWorking:Pe.isWorking,inboxBucket:Pe.inboxBucket}}),[e,N,I,F,Z]),{markConversationRead:ee}=D1({conversations:e,machineEntries:V,items:O,selectedConversation:F,selectedTabKey:A,screen:I,liveSessionInboxState:N,sendDaemonCommand:a,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:T,setScreen:P,setSelectedMachineId:$,setSection:_,setMachineBackTarget:B,resetMachineAction:ie.resetMachineAction}),G=R1({conversations:e,selectedConversation:F,machineBackTarget:E,markConversationRead:ee,resetMachineAction:ie.resetMachineAction,setSelectedTabKey:T,setScreen:P,setSelectedMachineId:$,setSection:_,setMachineBackTarget:B}),{isMuted:le,toggleMute:je}=Nm(N,a),{attentionItems:ge,unreadItems:Ce,workingItems:ue,completedItems:z}=l.useMemo(()=>j1(O,L.current),[O]);l.useEffect(()=>{L.current=ue.map(fe=>fe.conversation.tabKey)},[ue]);const U=l.useMemo(()=>Y?O.filter(fe=>Rs(fe.conversation)===Y.id):[],[O,Y]),q=l.useMemo(()=>A1(Y,n),[n,Y]),Q=!!Y&&Ja(Y,$s(Y,M)),me=l.useMemo(()=>(Y==null?void 0:Y.availableProviders)||[],[Y]),Ae=l.useMemo(()=>me.filter(fe=>Bn(fe,"cli")).map(fe=>({type:fe.type,displayName:fe.displayName||fe.type,icon:fe.icon})),[me]),de=l.useMemo(()=>me.filter(fe=>Bn(fe,"acp")).map(fe=>({type:fe.type,displayName:fe.displayName||fe.type,icon:fe.icon})),[me]),H=l.useMemo(()=>T1(V,O,t),[O,V,t]),he=l.useCallback(async fe=>{Y&&await ie.handleOpenRecent(Y.id,fe)},[ie,Y]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:I==="chat"&&F?s.jsx(m1,{selectedConversation:F,isAcp:pt(F),isStandalone:i,selectedIdeEntry:K,actionLogs:r,userName:c,isSendingChat:se.isSendingChat,sendFeedbackMessage:se.sendFeedbackMessage,isFocusingAgent:se.isFocusingAgent,handleModalButton:se.handleModalButton,handleRelaunch:se.handleRelaunch,onBack:G.backFromConversation,onOpenNativeConversation:G.openNativeConversation,onOpenMachine:G.openConversationMachine,onOpenHistory:S,onOpenRemote:h,onOpenMeshGraph:k,onStopCli:x,cliViewMode:J,onSetCliViewMode:async fe=>{await cm({conversation:F,mode:fe,ides:n,sendDaemonCommand:a,setCliViewModeOverrides:w})},handleSendChat:se.handleSendChat,handleForceSendChat:se.handleForceSendChat,handleFocusAgent:se.handleFocusAgent}):I==="machine"&&Y?s.jsx(k1,{selectedMachineEntry:Y,selectedMachineConversations:U,selectedMachineRecentLaunches:q,cliProviders:Ae,acpProviders:de,selectedMachineNeedsUpgrade:Q,appVersion:M,machineAction:ie.machineAction,isStandalone:i,section:D,showBottomNav:E==="inbox",onBack:G.backFromMachine,onSectionChange:G.changeMachineSection,onOpenConversation:G.openConversation,onOpenRecent:he,onOpenMachineDetails:()=>R(`/machines/${Y.id}`),onMachineUpgrade:()=>ie.handleMachineUpgrade(Y.id),onLaunchDetectedIde:(fe,ye)=>ie.handleLaunchDetectedIde(Y.id,fe,ye),onAddWorkspace:(fe,ye)=>ie.handleAddWorkspace(Y.id,fe,ye),onBrowseDirectory:fe=>ie.handleBrowseDirectory(Y.id,fe),onLaunchWorkspaceProvider:(fe,ye,Pe)=>ie.handleLaunchWorkspaceProvider(Y.id,fe,ye,Pe),onListSavedSessions:fe=>ie.handleListSavedSessions(Y.id,fe)}):s.jsx(b1,{section:D,attentionItems:ge,unreadItems:Ce,workingItems:ue,completedItems:z,hiddenConversations:t,machineCards:H,getAvatarText:E1,actionLogs:r,sendDaemonCommand:a,onOpenConversation:G.openConversation,onShowAllHidden:C,onHideConversation:j,onOpenMeshGraph:k,onStopCli:x,onOpenNewSession:v,onOpenMachine:G.openMachine,onOpenSettings:()=>R("/settings"),onSectionChange:_,wsStatus:y,isConnected:b,isStandalone:i,isConversationMuted:le,onToggleMuteConversation:je})})}function Lo(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function $1({conversations:e,numGroups:t,onMoveTab:n,onReceiveTab:r,onOwnTabDrop:a,onClearPreviewOrder:o}){const i=l.useRef(0),[c,u]=l.useState(!1),[p,d]=l.useState(null),m=l.useCallback(()=>{i.current=0,u(!1),d(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",m),window.addEventListener("drop",m),()=>{window.removeEventListener("dragend",m),window.removeEventListener("drop",m)}),[m]);const f=l.useCallback(x=>{x.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,u(!0))},[]),g=l.useCallback(x=>{if(!x.dataTransfer.types.includes("text/tab-key"))return;if(x.preventDefault(),!Lo(t,n)){d("merge");return}const y=x.currentTarget.getBoundingClientRect(),b=x.clientX-y.left,C=y.width/3;b<C?d("split-left"):b>C*2?d("split-right"):d("merge")},[t,n]),S=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,u(!1),d(null))},[]),h=l.useCallback(x=>{i.current=0,u(!1);const y=x.dataTransfer.getData("text/tab-key"),b=y?e.some(j=>j.tabKey===y):!1,C=p;if(d(null),o(),!!y){if(x.preventDefault(),C==="split-left"&&Lo(t,n)){n==null||n(y,"split-left");return}if(C==="split-right"&&Lo(t,n)){n==null||n(y,"split-right");return}if(b){a(y);return}r==null||r(y)}},[e,p,t,n,r,a,o]);return{dragOver:c,dropAction:p,resetDragState:m,handleDragEnter:f,handleDragOver:g,handleDragLeave:S,handleDrop:h}}function H1(e,t){const n=new Set(t.map(o=>o.tabKey)),r=e.filter(o=>n.has(o)),a=t.filter(o=>!e.includes(o.tabKey)).map(o=>o.tabKey);return[...r,...a]}function F1({conversations:e,initialActiveTabId:t,initialTabOrder:n,onActiveTabChange:r,onTabOrderChange:a}){const[o,i]=l.useState(t??null),[c,u]=l.useState(n??[]),[p,d]=l.useState(null),m=l.useRef(null),f=l.useRef(null),g=l.useRef(r),S=l.useRef(a);l.useEffect(()=>{g.current=r},[r]),l.useEffect(()=>{S.current=a},[a]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{u(N=>{const w=H1(N,e);return w.length===N.length&&w.every((A,T)=>A===N[T])?N:w})},[e]);const h=l.useMemo(()=>{const N=p??c;if(N.length===0)return e;const w=new Map(N.map((A,T)=>[A,T]));return[...e].sort((A,T)=>{const I=w.get(A.tabKey)??999,P=w.get(T.tabKey)??999;return I-P})},[e,p,c]);l.useEffect(()=>{var w,A;if(h.length===0){o!==null&&(i(null),(w=g.current)==null||w.call(g,null));return}if(o&&h.some(T=>T.tabKey===o))return;const N=h[0].tabKey;N!==o&&(i(N),(A=g.current)==null||A.call(g,N))},[h,o]);const x=l.useMemo(()=>h.find(N=>N.tabKey===o),[h,o]),y=l.useCallback(N=>{var w;i(N),(w=g.current)==null||w.call(g,N)},[]),b=l.useCallback((N,w,A)=>{u(T=>{var _;const I=T.filter(W=>W!==N),P=I.indexOf(w);if(P<0)return T;const D=A==="left"?P:P+1;return I.splice(D,0,N),(_=S.current)==null||_.call(S,I),I}),d(null)},[]),C=l.useCallback((N,w,A)=>{const I=(c.length>0?c:e.map(_=>_.tabKey)).filter(_=>_!==N),P=I.indexOf(w);if(P<0)return;const D=A==="left"?P:P+1;I.splice(D,0,N),m.current=I,d(I)},[c,e]),j=l.useCallback(()=>{var w;const N=m.current;N&&(u(N),(w=S.current)==null||w.call(S,N))},[]),k=l.useCallback(()=>{m.current=null,d(null)},[]),v=l.useCallback(N=>{u(w=>{var T;const A=w.filter(I=>I!==N);return A.push(N),(T=S.current)==null||T.call(S,A),A})},[]);return{activeTabId:o,activeConv:x,sortedConversations:h,previewOrderRef:m,draggingTabRef:f,selectTab:y,handleTabReorder:b,updatePreviewOrder:C,commitPreviewOrder:j,clearPreviewOrder:k,moveTabToEnd:v,setDraggingTabKey:N=>{f.current=N}}}function B1({dropAction:e,canSplit:t}){return s.jsxs("div",{className:"absolute inset-0 z-10 pointer-events-none hidden md:flex",children:[s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-left"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-left"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Left"})}),s.jsx("div",{className:"flex-1 border-r border-white/10 transition-all duration-150 flex items-center justify-center",style:{background:e==="merge"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="merge"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)"},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Move Here"})}),s.jsx("div",{className:"flex-1 transition-all duration-150 flex items-center justify-center",style:{background:e==="split-right"?"rgba(255,255,255,0.1)":"rgba(255,255,255,0.04)",boxShadow:e==="split-right"?"inset 0 0 0 2px var(--accent-primary)":"inset 0 0 0 1px rgba(255,255,255,0.05)",opacity:t?1:.45},children:s.jsx("div",{className:"px-3 py-1.5 rounded-full text-[11px] font-semibold text-white bg-black/45 backdrop-blur-sm",children:"Split Right"})})]})}function yl({conversationsCount:e,isSplitMode:t,isStandalone:n,hasRegisteredMachines:r=!1,suppressGuide:a=!1,onOpenNewSession:o}){const{t:i}=Ne("common");if(a)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const c=!n&&!r,u=r&&!!o,p=i(r?"paneGroup.noConversations":n?"paneGroup.waitingForDaemon":"paneGroup.connectYourMachines"),d=i(r?"paneGroup.newSessionDescription":n?"paneGroup.daemonDescription":"paneGroup.installDescription");return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:p}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:d}),u&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:o,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:i("paneGroup.newSession"),"aria-label":i("paneGroup.newSession"),children:[s.jsx(zi,{size:14}),s.jsx("span",{children:i("paneGroup.newSession")})]})}),c&&s.jsx(wm,{}),c&&s.jsx("div",{className:"mt-8",children:s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"text-sm font-medium text-accent hover:opacity-80 transition-colors flex items-center justify-center gap-1.5",children:"📚 Read the documentation →"})})]})]}):s.jsx("div",{className:"text-sm text-text-muted opacity-50",children:t?"Move a tab here to view":"No active agent"})}const Am="adhdev-tab-shortcuts";function Tm(){try{return JSON.parse(localStorage.getItem(Am)||"{}")}catch{return{}}}function Mm({enabled:e=!0,sortedTabKeys:t,onFocus:n,onSelectTab:r}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>Tm()),[c,u]=l.useState(null),p=l.useCallback(m=>{const f=[];return m.metaKey&&f.push(a?"⌘":"Meta"),m.ctrlKey&&f.push("Ctrl"),m.altKey&&f.push(a?"⌥":"Alt"),m.shiftKey&&f.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(f.push(m.key.length===1?m.key.toUpperCase():m.key),f.join("+"))},[a]),d=l.useCallback(m=>{i(m);try{localStorage.setItem(Am,JSON.stringify(m))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const m=f=>{if(f.preventDefault(),f.stopPropagation(),f.key==="Escape"){u(null);return}const g=p(f);if(!g)return;const S={...o};for(const[h,x]of Object.entries(S))x===g&&delete S[h];S[c]=g,d(S),u(null)};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[e,c,o,d,p]),l.useEffect(()=>{if(!e)return;const m=f=>{if(!(!f.ctrlKey&&!f.metaKey&&!f.altKey)){for(const[g,S]of Object.entries(o))if(t.includes(g)&&p(f)===S){f.preventDefault(),n(),r(g);return}}};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[e,o,t,n,r,p]),{isMac:a,tabShortcuts:o,shortcutListening:c,setShortcutListening:u,saveShortcuts:d}}const Ro=e=>{e.preventDefault()},W1=l.memo(function({conv:t,isActive:n,isDraggedTab:r,isTaskCompleteUnread:a,shortcut:o,conversationKeys:i,draggingTabRef:c,onFocus:u,onSelectTab:p,onConversationActivated:d,onPreviewReorder:m,onReorderTab:f,onCommitPreviewOrder:g,onClearPreviewOrder:S,onDragStateReset:h,onDragTabKeyChange:x,onReceiveTab:y,onOpenContextMenu:b,longPressTimer:C,isGroupActive:j}){const k=gn(t),v=k.isGenerating?"agent-tab-generating":k.isWaiting?"agent-tab-waiting":"",N=k.isReconnecting,w=Vk(t),A=Yk(t),T=Dp(t),I=l.useCallback(R=>{c.current=t.tabKey,x(t.tabKey),R.dataTransfer.setData("text/tab-key",t.tabKey),R.dataTransfer.effectAllowed="move"},[t.tabKey,c,x]),P=l.useCallback(()=>{c.current=null,x(null),g(),S(),h()},[c,x,g,S,h]),D=l.useCallback(R=>{const M=c.current;if(!(!M||M===t.tabKey)&&R.dataTransfer.types.includes("text/tab-key")){R.preventDefault(),R.stopPropagation();const F=R.currentTarget.getBoundingClientRect(),K=R.clientX<F.left+F.width/2?"left":"right";m(M,t.tabKey,K)}},[t.tabKey,c,m]),_=l.useCallback(R=>{R.preventDefault(),R.stopPropagation();const M=R.dataTransfer.getData("text/tab-key");if(M&&M!==t.tabKey){const F=R.currentTarget.getBoundingClientRect(),K=R.clientX<F.left+F.width/2?"left":"right";i.includes(M)?f(M,t.tabKey,K):y&&y(M)}S()},[t.tabKey,i,f,y,S]),W=l.useCallback(R=>{R.stopPropagation(),u(),p(t.tabKey),d(t)},[t,d,u,p]),$=l.useCallback(R=>{R.preventDefault(),b(R.clientX,R.clientY,t.tabKey)},[t.tabKey,b]),E=l.useCallback(R=>{const M=R.touches[0];C.current=setTimeout(()=>{b(M.clientX,M.clientY,t.tabKey)},600)},[t.tabKey,C,b]),B=l.useCallback(()=>{C.current&&clearTimeout(C.current)},[C]),L=["adhdev-dockview-tab",v,n&&"is-active",j&&"is-group-active",N&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:L,draggable:!0,onDragStart:I,onDragEnd:P,onDragOver:D,onDrop:_,onClick:W,onContextMenu:$,onTouchStart:E,onTouchEnd:B,onTouchMove:B,style:{position:"relative",cursor:"pointer",opacity:r?.4:void 0},children:[T&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-badge pointer-events-none absolute top-0.5 right-0.5 text-text-muted",title:"Mesh chat","aria-label":"Mesh chat",children:s.jsx(os,{size:11})}),a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:k.isGenerating?s.jsx("div",{className:"tab-spinner"}):k.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):N?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):k.isConnecting?s.jsx("div",{className:"tab-connecting-spinner"}):t.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),w.length>0&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:A,"aria-label":A||w.join(" · "),children:w.join(" · ")}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:kt(t),children:kt(t)}),s.jsxs("span",{className:"adhdev-dockview-tab-meta inline-flex min-w-0 items-center gap-1",children:[N?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting truncate",children:an(t)}):k.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[an(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:an(t)}),s.jsx(Ca,{git:t.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),o&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${o}`,children:o})]})},(e,t)=>e.conv===t.conv&&e.isActive===t.isActive&&e.isDraggedTab===t.isDraggedTab&&e.isTaskCompleteUnread===t.isTaskCompleteUnread&&e.shortcut===t.shortcut&&e.conversationKeys===t.conversationKeys&&e.isGroupActive===t.isGroupActive);function O1({conversations:e,activeTabId:t,groupIndex:n,unreadTabKeys:r,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:d,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:g,onReceiveTab:S,onHideTab:h,isGroupActive:x,allowTabShortcuts:y=!0}){const{t:b}=Ne("common"),[C,j]=l.useState(null),k=l.useRef(null),v=l.useRef(null),N=l.useMemo(()=>e.map(_=>_.tabKey),[e]);Dr("PaneGroupTabBar",{groupIndex:n,activeTabId:t,tabCount:e.length,ctxMenuTab:(C==null?void 0:C.tabKey)||null});const{isMac:w,tabShortcuts:A,shortcutListening:T,setShortcutListening:I,saveShortcuts:P}=Mm({enabled:y,sortedTabKeys:e.map(_=>_.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!C)return;const _=W=>{const $=document.querySelector("[data-pane-context-menu]");$&&$.contains(W.target)||j(null)};return window.addEventListener("mousedown",_,!0),()=>window.removeEventListener("mousedown",_,!0)},[C]),l.useEffect(()=>{const _=v.current;if(!_)return;const W=$=>{Math.abs($.deltaY)<=Math.abs($.deltaX)||($.preventDefault(),_.scrollLeft+=$.deltaY)};return _.addEventListener("wheel",W,{passive:!1}),()=>_.removeEventListener("wheel",W)},[]);const D=l.useCallback((_,W,$)=>{j({x:_,y:W,tabKey:$})},[]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:s.jsxs("div",{ref:v,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(_=>s.jsx(W1,{conv:_,isActive:t===_.tabKey,isDraggedTab:a.current===_.tabKey,isTaskCompleteUnread:r.has(_.tabKey),shortcut:y?A[_.tabKey]:void 0,conversationKeys:N,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:u,onReorderTab:p,onCommitPreviewOrder:d,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:g,onReceiveTab:S,onOpenContextMenu:D,longPressTimer:k,isGroupActive:x},_.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:b("paneGroup.noTabsInGroup")})]})}),C&&s.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:C.x,top:C.y},children:[y&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:Ro,onClick:_=>{_.stopPropagation(),I(C.tabKey),j(null)},children:["⌨ ",A[C.tabKey]?`Change shortcut (${A[C.tabKey]})`:"Set shortcut"]}),A[C.tabKey]&&s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onMouseDown:Ro,onClick:()=>{const _={...A};delete _[C.tabKey],P(_),j(null)},children:"✕ Remove shortcut"})]}),h&&s.jsxs(s.Fragment,{children:[y&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:Ro,onClick:()=>{h(C.tabKey),j(null)},children:"🚫 Hide from Dashboard"})]})]}),y&&T&&s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>I(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:_=>_.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",w?"⌘+1":"Ctrl+1",", ",w?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:b("paneGroup.pressEscToCancel")})]})})]})}function U1({conversations:e,ides:t,clearedTabs:n,actionLogs:r,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,userName:u,groupIndex:p,onFocus:d,isSplitMode:m,numGroups:f,onMoveTab:g,onReceiveTab:S,style:h,onActiveTabChange:x,initialActiveTabId:y,initialTabOrder:b,onTabOrderChange:C,onHideTab:j,isFocused:k,allowTabShortcuts:v=!0,onOpenNewSession:N,liveSessionInboxState:w}){const{sendCommand:A}=St(),T=l.useRef(null),{activeTabId:I,activeConv:P,sortedConversations:D,draggingTabRef:_,selectTab:W,handleTabReorder:$,updatePreviewOrder:E,commitPreviewOrder:B,clearPreviewOrder:L,moveTabToEnd:R,setDraggingTabKey:M}=F1({conversations:e,initialActiveTabId:y,initialTabOrder:b,onActiveTabChange:x,onTabOrderChange:C}),F=Ka({sendDaemonCommand:a,activeConv:P,setActionLogs:o,isStandalone:i}),{dragOver:K,dropAction:J,resetDragState:V,handleDragEnter:Y,handleDragOver:se,handleDragLeave:ie,handleDrop:Z}=$1({conversations:e,numGroups:f,onMoveTab:g,onReceiveTab:S,onOwnTabDrop:R,onClearPreviewOrder:L}),O=P&&!pt(P)&&Gn(P)==="terminal",ee=l.useMemo(()=>P?t.find(ge=>ge.id===P.routeId):void 0,[t,P]),G=l.useMemo(()=>P?r.filter(ge=>ge.routeId===P.tabKey):[],[r,P]),le=l.useMemo(()=>new Set(D.filter(ge=>eg(ge,w,{isOpenConversation:ge.tabKey===I})).map(ge=>ge.tabKey)),[I,w,D]);Dr("PaneGroup",{groupIndex:p,conversationCount:e.length,activeTabId:I,dragOver:K});const je=l.useCallback(ge=>{ge.streamSource==="agent-stream"&&ge.agentType&&A(ge.routeId,up(),{agentType:ge.agentType,...ge.sessionId&&{targetSessionId:ge.sessionId}}).catch(()=>{})},[A]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:d,style:{...h,outline:K?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(O1,{conversations:D,activeTabId:I,groupIndex:p,numGroups:f,unreadTabKeys:le,draggingTabRef:_,onFocus:d,onSelectTab:W,onConversationActivated:je,onPreviewReorder:E,onReorderTab:$,onCommitPreviewOrder:B,onClearPreviewOrder:L,onDragStateReset:V,onDragTabKeyChange:M,onMoveTab:g,onReceiveTab:S,onHideTab:j,isGroupActive:k??!1,allowTabShortcuts:v}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:Y,onDragOver:se,onDragLeave:ie,onDrop:Z,children:[K&&s.jsx(B1,{dropAction:J,canSplit:!!(f<4&&g)}),P?s.jsx(xl,{activeConv:P,clearToken:n[P.tabKey]||0,isCliTerminal:!!O,ideEntry:ee,terminalRef:T,handleModalButton:F.handleModalButton,handleRelaunch:F.handleRelaunch,handleSendChat:F.handleSendChat,handleForceSendChat:F.handleForceSendChat,isSendingChat:F.isSendingChat,sendFeedbackMessage:F.sendFeedbackMessage,handleFocusAgent:F.handleFocusAgent,isFocusingAgent:F.isFocusingAgent,actionLogs:G,userName:u,isInputActive:!m||!!k}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(yl,{conversationsCount:e.length,isSplitMode:m,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:N})})]})]})}function G1({containerRef:e,isSplitMode:t,numGroups:n,groupSizes:r,groupedConvs:a,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:u,setActionLogs:p,isStandalone:d,hasRegisteredMachines:m,userName:f,focusedGroup:g,focusGroup:S,moveTabToGroup:h,splitTabRelative:x,closeGroup:y,handleResizeStart:b,groupActiveTabIds:C,setGroupActiveTab:j,groupTabOrders:k,setGroupTabOrder:v,toggleHiddenTab:N,onOpenNewSession:w,allowTabShortcuts:A=!0,liveSessionInboxState:T}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((I,P)=>{const D=t&&r.length===n?`${r[P]}%`:void 0;return s.jsxs(Pt.Fragment,{children:[t&&P>0&&s.jsx("div",{className:"shrink-0 w-1 cursor-col-resize hover:bg-accent/30 transition-colors relative group",style:{background:"var(--border-subtle)"},onMouseDown:_=>b(P-1,_),onDoubleClick:()=>y(P),title:"Drag to resize · Double-click to merge",children:s.jsx("div",{className:"absolute inset-y-0 -left-1 -right-1 group-hover:bg-accent/10"})}),s.jsx(U1,{style:t?{flexBasis:D??`${100/n}%`,flexGrow:D?0:1,flexShrink:D?0:1}:void 0,conversations:I,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:u,setActionLogs:p,isStandalone:d,hasRegisteredMachines:m,userName:f,groupIndex:P,isFocused:t&&g===P,onFocus:()=>S(P),isSplitMode:t,numGroups:n,onMoveTab:(_,W)=>{W==="left"&&P>0?h(_,P-1):W==="right"&&P<n-1?h(_,P+1):W==="split-left"&&n<4?x(_,P,"left"):W==="split-right"&&n<4&&x(_,P,"right")},onReceiveTab:_=>h(_,P),onActiveTabChange:_=>j(P,_),initialActiveTabId:C[P],initialTabOrder:k[P],onTabOrderChange:_=>v(P,_),onHideTab:N,onOpenNewSession:w,allowTabShortcuts:A,liveSessionInboxState:T})]},P)})})}const Dm="adhdev-dashboard-action-shortcuts",q1=1200,z1=[["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 K1(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function mt(e,t){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return t?"⌘+⇧+Enter":"Ctrl+Shift+Enter";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+Ctrl+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return t?"⌘+Ctrl+⇧+↓":"Ctrl+Alt+Shift+↓";case"focusLeftPane":return"";case"focusRightPane":return"";case"focusUpPane":return"";case"focusDownPane":return"";case"moveActiveTabToLeftPane":return"";case"moveActiveTabToRightPane":return"";case"moveActiveTabToUpPane":return"";case"moveActiveTabToDownPane":return"";case"triggerPrimaryApprovalAction":return t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌘+⇧+←":"Ctrl+Shift+←";case"selectNextGroupTab":return t?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function Im(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:mt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:mt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:mt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:mt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:mt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:mt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:mt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:mt("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:mt("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:mt("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:mt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:mt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:mt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:mt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:mt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:mt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:mt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:mt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:mt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:mt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:mt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:mt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:mt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:mt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:mt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:mt("toggleCliView",e)}]}function Ii(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function La(e){const t=Object.fromEntries(Im(e).map(n=>[n.id,n.defaultShortcut]));try{const n=JSON.parse(localStorage.getItem(Dm)||"{}"),r={...t,...n};for(const[a,o]of z1)r[a]===o&&(r[a]=t[a]);return r}catch{return t}}function Pm(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function V1({enabled:e=!0,onTrigger:t}){const n=K1(),[r,a]=l.useState(()=>La(n)),[o,i]=l.useState(null),[c,u]=l.useState([]),p=l.useRef({parts:[],timer:null}),d=l.useCallback(h=>{const x=[];return h.metaKey&&x.push(n?"⌘":"Meta"),h.ctrlKey&&x.push("Ctrl"),h.altKey&&x.push(n?"⌥":"Alt"),h.shiftKey&&h.key.length!==1&&x.push(n?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(x.push(Pm(h.key)),x.join("+"))},[n]),m=l.useCallback(h=>{a(h);try{localStorage.setItem(Dm,JSON.stringify(h))}catch{}},[]);l.useEffect(()=>{const h=La(n),x=Object.entries(r),y=Object.entries(h);x.length===y.length&&x.every(([b,C])=>h[b]===C)||m(h)},[r,n,m]);const f=l.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),g=l.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},q1))},[]);l.useEffect(()=>{if(!o)return;const h=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){i(null),u([]);return}const y=d(x);if(!y)return;const C=!(x.metaKey||x.ctrlKey||x.altKey)&&/^[A-Z0-9]$/.test(y);if(c.length===0&&C){u([y]);return}const k=[...c,y].slice(0,2).join(" "),v={...r};for(const[N,w]of Object.entries(v))w===k&&delete v[N];v[o]=k,m(v),i(null),u([])};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[r,d,m,o,c]),l.useEffect(()=>{if(!e||o)return;const h=x=>{if(x.defaultPrevented)return;const y=d(x);if(!y)return;const b=x.metaKey||x.ctrlKey||x.altKey;if(Ii(x.target))return;const C=p.current.parts,j=b?[y]:[...C.slice(-1),y].slice(-2),k=j.join(" "),v=j[j.length-1],N=Object.entries(r).filter(([,P])=>!!P),w=N.find(([,P])=>P===k);if(w){x.preventDefault(),f(),t(w[0]);return}if(N.some(([,P])=>P.startsWith(`${k} `))){x.preventDefault(),p.current.parts=j,g();return}const T=N.find(([,P])=>P===v);if(T){x.preventDefault(),f(),t(T[0]);return}if(N.some(([,P])=>P.startsWith(`${v} `))){x.preventDefault(),p.current.parts=[v],g();return}f()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[r,g,e,d,t,f,o]),l.useEffect(()=>()=>f(),[f]);const S=l.useMemo(()=>Im(n),[n]);return{isMac:n,actionDefinitions:S,actionShortcuts:r,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:u,saveShortcuts:m}}function Y1({isTabInPopout:e,isTabFloating:t,tabShortcut:n,actionShortcuts:r}){const a=[];return e?(t&&a.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:r.dockActiveTab}),a.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:r.dockActiveTab})):t?a.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:r.dockActiveTab}):a.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:r.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:r.popoutActiveTab}),a.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:n?`Change shortcut (${n})`:"Set shortcut",shortcut:r.setActiveTabShortcut}),n&&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:r.hideCurrentTab,tone:"muted"}),a}function Lm(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function ld({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:n,ides:r}){return!e||n>0?!1:t?!Lm(r):!0}function J1({previousVisibleConversationCount:e,visibleConversationCount:t,ides:n}){return t>0||e<=0?!1:Lm(n)}const Rm=1e3,Q1=4;function cd(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function dd(e,t,n){return Math.abs(t.clientX-e.clientX)>n||Math.abs(t.clientY-e.clientY)>n}function X1({detachDelayMs:e=Rm,stillnessThresholdPx:t=Q1,onDetach:n,setTimeoutFn:r=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,i=null,c=null,u=null,p=null,d=!1;const m=()=>{p!=null&&(a(p),p=null)},f=()=>{m(),c=null},g=()=>{m(),o=null,i=null,c=null,u=null,d=!1},S=()=>{!o||!c||!u||d||p!=null||(p=r(()=>{p=null,!(!o||!c||!u||d)&&cd(u,i)&&(dd(c,u,t)||(d=!0,n({panelId:o,clientX:u.clientX,clientY:u.clientY})))},e))},h=y=>{if(!(!o||d)){if(!cd(y,i)){u={clientX:y.clientX,clientY:y.clientY},f();return}(!c||dd(c,y,t))&&(m(),c={clientX:y.clientX,clientY:y.clientY}),u={clientX:y.clientX,clientY:y.clientY},S()}},x=y=>{!o||d||(y&&(u={clientX:y.clientX,clientY:y.clientY}),f())};return{startDrag:y=>{m(),o=y.panelId,i=y.selfPanelBounds??null,c=null,u={clientX:y.clientX,clientY:y.clientY},d=!1},markSelfPanel:h,markNonSelfPanel:x,markNoDropTarget:x,markDockTarget:x,endDrag:g,isDragging:()=>o!=null,hasDetached:()=>d,dispose:g}}function Z1(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function ua(e){return kt(e)||e.tabKey}function eN(e){return`remote:${e}`}function ds(e){return e.startsWith("remote:")}function ud(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function Eo(e){var r;const t=e==null?void 0:e.defaultView;if(!t)return;const n=a=>{if(a)try{a.focus({preventScroll:!0})}catch{try{a.focus()}catch{}}};try{t.focus(),n(e==null?void 0:e.body),n(e==null?void 0:e.documentElement),(r=t.requestAnimationFrame)==null||r.call(t,()=>{try{t.focus(),n(e==null?void 0:e.body)}catch{}})}catch{}}function _o(e,t){e.classList.remove(ni.className,ri.className),e.classList.add(t==="light"?ni.className:ri.className)}function pd(e){return e?Array.from(new Set(e.groups.map(t=>{var n,r;return(r=(n=t.element)==null?void 0:n.ownerDocument)==null?void 0:r.defaultView}).filter(t=>!!t&&t!==window))):[]}function tN(e,t,n){var i;const r=[t];let a;for(const c of r){let u;for(const p of c){const d=e.addPanel({id:p.tabKey,component:"conversation",title:ua(p),params:{kind:"conversation",tabKey:p.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});u||(u=d.id)}a=u??a}return n??((i=t[0])==null?void 0:i.tabKey)??null}function md(e,t){const n=new Set(t.map(a=>a.tabKey)),r=new Map;for(const a of t)r.set(a.tabKey,(r.get(a.tabKey)||0)+1);for(const a of[...e.panels])ds(a.id)||n.has(a.id)||e.removePanel(a);for(const a of t){const o=e.getPanel(a.tabKey);if(o){(r.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!==ua(a)&&o.api.setTitle(ua(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:ua(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 hd(e,t,n){var u,p;const r=n?eN(n):null;for(const d of[...e.panels])ds(d.id)&&(!r||d.id!==r)&&e.removePanel(d);if(!n||!r)return;const a=bs(t,n);if(!a&&e.totalPanels===0)return;const o=e.getPanel(r),i=Rp(a);if(o){o.title!==i&&o.api.setTitle(i);return}const c=(a==null?void 0:a.tabKey)??((u=e.activePanel)==null?void 0:u.id)??((p=e.panels.find(d=>!ds(d.id)))==null?void 0:p.id);e.addPanel({id:r,component:"remote",title:i,params:{kind:"remote",routeId:n},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function Em({doId:e,targetSessionId:t,connState:n,viewMode:r}){const[a,o]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?jt.onScreenshot("ide-page",(d,m)=>{if(d!==e)return;const f=new FileReader;f.onload=()=>o(f.result),f.readAsDataURL(m)}):void 0,[e]),l.useEffect(()=>{n!=="connected"&&o(null)},[n]),l.useEffect(()=>{var d;return e?((d=jt.onStatus)==null?void 0:d.call(jt,(m,f)=>{m===e&&f!=null&&f.screenshotUsage&&c(f.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{o(null)},[e,t]),l.useEffect(()=>{const p=e?jt.get(e):null;if(!(!p||n!=="connected"))return r!=="chat"&&t?p.startScreenshots(t):p.stopScreenshots(t),()=>{p.stopScreenshots(t)}},[r,n,t,e]);const u=l.useCallback(async(p,d)=>{const m=e?jt.get(e):null;return!m||n!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):m.sendInput(p,d,t)},[e,n,t]);return{connScreenshot:a,screenshotUsage:i,handleRemoteAction:u}}const _m=l.createContext(null);function Za(){const e=l.useContext(_m);if(!e)throw new Error("DashboardDockviewContext missing");return e}function sN(e){const[,t]=l.useState(0);l.useEffect(()=>{const n=()=>t(a=>a+1),r=[e.api.onDidActiveGroupChange(n),e.api.onDidTitleChange(n),e.api.onDidGroupChange(n),e.containerApi.onDidActivePanelChange(n)];return()=>{for(const a of r)a.dispose()}},[e.api,e.containerApi])}function nN({params:e}){var u;const t=Za(),n=l.useMemo(()=>bs([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),r=l.useMemo(()=>t.ides.find(p=>p.id===e.routeId),[t.ides,e.routeId]),a=(n==null?void 0:n.daemonId)||((u=n==null?void 0:n.routeId)==null?void 0:u.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:i,handleRemoteAction:c}=Em({doId:a,targetSessionId:n?cp(n):(r==null?void 0:r.sessionId)||(r==null?void 0:r.instanceId),connState:(n==null?void 0:n.connectionState)||"new",viewMode:"remote"});return n?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(Iu,{addLog:()=>{},connState:n.connectionState||"new",connScreenshot:o,screenshotUsage:i,transportType:n.transport,onAction:c})}):s.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:"Remote view unavailable"})}function rN(){const e=Za();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(yl,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function aN(e){var b,C;sN(e);const t=Za(),n=l.useCallback(j=>{"button"in j&&j.button!==0||e.api.setActive()},[e.api]),r=e.params.kind==="remote"?void 0:t.conversationsByTabKey.get(e.params.tabKey),a=r==null?void 0:r.sessionId,o=l.useCallback(j=>Dk(j),[]),i=l.useCallback(()=>Mk(a),[a]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const j=bs([...t.conversationsByTabKey.values()],e.params.routeId),k=((b=e.api.group.activePanel)==null?void 0:b.id)===e.api.id,v=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${k?" is-active":""}${v?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(j==null?void 0:j.tabKey)||"",onMouseDown:n,onTouchStart:n,children:[s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"◫"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||"Remote"}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:j!=null&&j.machineName?s.jsxs(s.Fragment,{children:[s.jsx("span",{children:"Live remote view"}),s.jsx("span",{className:"adhdev-dockview-tab-dot",children:"·"}),s.jsx("span",{className:"adhdev-dockview-tab-machine",children:j.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const u=t.conversationsByTabKey.get(e.params.tabKey);if(!u)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const p=((C=e.api.group.activePanel)==null?void 0:C.id)===e.api.id,d=e.api.isGroupActive,m=Wa(u,t.liveSessionInboxState,{isOpenConversation:p}),f=m.isReconnecting,g=m.isConnecting,S=m.isGenerating||c,h=m.isWaiting,x=m.unread,y=t.tabShortcuts[u.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${p?" is-active":""}${d?" is-group-active":""}${f?" is-reconnecting":""}`,title:kt(u),"data-tab-key":e.params.tabKey,onMouseDown:n,onTouchStart:n,onContextMenu:j=>{var k;j.preventDefault(),n(j),t.openTabContextMenu({x:j.clientX,y:j.clientY,tabKey:u.tabKey,sourceDocument:((k=j.target)==null?void 0:k.ownerDocument)??document})},children:[x&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:S?s.jsx("div",{className:"tab-spinner"}):h?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):f?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):g?s.jsx("div",{className:"tab-connecting-spinner"}):u.connectionState==="connected"?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-connected",children:"●"}):s.jsx("span",{className:"adhdev-dockview-tab-status-text is-idle",children:"○"})}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("div",{className:"adhdev-dockview-tab-primary",children:kt(u)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:f?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:an(u)}):g?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:an(u)}):s.jsx("span",{children:an(u)})})]}),y&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:y,children:y})]})}function Yr(e){return e.isActive}function fd(e){return e.isVisible}function oN(e){e.preventDefault()}function iN({params:e,api:t}){var g;const n=Za(),r=l.useRef(null),[a,o]=l.useState(()=>Yr(t)),[i,c]=l.useState(()=>fd(t)),u=n.conversationsByTabKey.get(e.tabKey),p=Ka({sendDaemonCommand:n.sendDaemonCommand,activeConv:u,setActionLogs:n.setActionLogs,isStandalone:n.isStandalone});l.useEffect(()=>{o(Yr(t)),c(fd(t));const S=[t.onDidActiveChange(h=>o(h.isActive)),t.onDidActiveGroupChange(h=>{if(!Yr(t)&&!h.isActive){o(!1);return}o(Yr(t))}),t.onDidVisibilityChange(h=>c(h.isVisible))];return()=>{for(const h of S)h.dispose()}},[t]);const d=l.useMemo(()=>u?n.ides.find(S=>S.id===u.routeId):void 0,[n.ides,u]),m=l.useMemo(()=>u?n.actionLogs.filter(S=>S.routeId===u.tabKey):[],[n.actionLogs,u]);if(!u)return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col",children:s.jsx(yl,{conversationsCount:0,isSplitMode:!1,isStandalone:n.isStandalone,hasRegisteredMachines:n.hasRegisteredMachines,onOpenNewSession:n.onOpenNewSession,suppressGuide:n.hasDetachedConversationPanels})});const f=!pt(u)&&Gn(u)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(xl,{activeConv:u,clearToken:n.clearedTabs[u.tabKey]||0,isCliTerminal:f,ideEntry:d,terminalRef:r,handleModalButton:p.handleModalButton,handleRelaunch:p.handleRelaunch,handleSendChat:p.handleSendChat,handleForceSendChat:p.handleForceSendChat,isSendingChat:p.isSendingChat,handleFocusAgent:p.handleFocusAgent,isFocusingAgent:p.isFocusingAgent,actionLogs:m,userName:n.userName,scrollToBottomRequestNonce:((g=n.scrollToBottomRequest)==null?void 0:g.tabKey)===u.tabKey?n.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:i})})}function lN({visibleConversations:e,clearedTabs:t,ides:n,actionLogs:r,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:u,userName:p,toggleHiddenTab:d,actionShortcuts:m,registerActionHandlers:f,onActiveTabChange:g,onOpenNewSession:S,onRequestScrollToBottom:h,requestedActiveTabKey:x,requestedRemoteIdeId:y,onRequestedActiveTabConsumed:b,scrollToBottomRequest:C,liveSessionInboxState:j,layoutProfile:k}){var lt,at,bt;const{theme:v}=qs(),{sendCommand:N}=St(),w=l.useRef(null),A=l.useRef(null),T=l.useRef(null),I=l.useRef(!1),P=l.useRef(!1),D=l.useRef(!1),_=l.useRef(null),W=l.useRef([]),[$,E]=l.useState(null),[B,L]=l.useState(0),R=l.useRef(typeof window>"u"?{}:Nj(k)),M=l.useMemo(()=>new Map(e.map(X=>[X.tabKey,X])),[e]),F=l.useMemo(()=>{const X=w.current;return X?X.groups.some(te=>{try{const oe=te.model.location.type;return oe!=="floating"&&oe!=="popout"?!1:te.panels.some(be=>M.has(be.id))}catch{return!1}}):!1},[M,B,e]),K=l.useCallback(()=>{var X;(X=w.current)==null||X.focus()},[]),J=l.useCallback((X,te)=>{h==null||h(X,te)},[h]),V=l.useCallback(X=>{const te=document,oe=X.document;for(const Ie of te.querySelectorAll('link[rel="stylesheet"]')){const ze=oe.createElement("link");ze.rel="stylesheet",ze.href=Ie.href,Ie.crossOrigin&&(ze.crossOrigin=Ie.crossOrigin),oe.head.appendChild(ze)}for(const Ie of te.querySelectorAll("style")){const ze=oe.createElement("style");ze.textContent=Ie.textContent,oe.head.appendChild(ze)}const be=[];for(const Ie of te.styleSheets)try{for(const ze of Ie.cssRules)ze instanceof CSSStyleRule&&(ze.selectorText===":root"||ze.selectorText==="html")&&be.push(ze.cssText)}catch{}if(be.length>0){const Ie=oe.createElement("style");Ie.textContent=be.join(`
71
71
  `),oe.head.appendChild(Ie)}const re=te.documentElement.getAttribute("data-theme");re&&oe.documentElement.setAttribute("data-theme",re),oe.documentElement.style.colorScheme=re==="light"?"light":"dark",oe.body.className=te.body.className;const Te=te.documentElement.getAttribute("style");Te&&oe.documentElement.setAttribute("style",Te);const Ee=oe.getElementById("dv-popout-window");Ee instanceof HTMLElement&&(Ee.classList.add("adhdev-dockview"),_o(Ee,v))},[v]),Y=l.useCallback(()=>{var te;const X=w.current;if(X)for(const oe of X.groups)try{const be=(te=oe.element)==null?void 0:te.ownerDocument;if(!be||be===document)continue;const re=be.getElementById("dv-popout-window");re instanceof HTMLElement&&(re.classList.add("adhdev-dockview"),_o(re,v));const Te=document.documentElement.getAttribute("data-theme");Te&&be.documentElement.setAttribute("data-theme",Te),be.documentElement.style.colorScheme=Te==="light"?"light":"dark",be.body.className=document.body.className;const Ee=document.documentElement.getAttribute("style");Ee?be.documentElement.setAttribute("style",Ee):be.documentElement.removeAttribute("style")}catch{}},[v]),se=l.useCallback(X=>{const te=w.current;if(!te)return;const oe=te.getPanel(X);oe&&te.addPopoutGroup(oe,{popoutUrl:"/popout.html",onDidOpen:({window:be})=>{V(be),Ce();const re=M.get(X);be.document.title=re?`${kt(re)} — ADHDev`:"ADHDev — Popout"}})},[M,V]),ie=l.useCallback(X=>{const te=w.current,oe=te==null?void 0:te.getPanel(X);if(!te||!oe)return;const be=te.groups.filter(re=>{var Te;try{return((Te=re.element)==null?void 0:Te.ownerDocument)===document}catch{return!0}});be.length>0?oe.api.moveTo({group:be[0],position:"center"}):oe.api.moveTo({position:"center"}),oe.api.setActive()},[]),Z=l.useCallback(X=>{var be;const te=w.current;if(!te)return!1;const oe=te.getPanel(X);if(!oe)return!1;try{return((be=oe.group.element)==null?void 0:be.ownerDocument)!==document}catch{return!1}},[]),O=l.useCallback(X=>{Z(X)&&ie(X),d(X)},[Z,ie,d]),ee=l.useCallback(X=>{const te=w.current,oe=te==null?void 0:te.getPanel(X);!te||!oe||te.addFloatingGroup(oe,{width:600,height:500})},[]),G=l.useCallback(X=>{var oe;const te=(oe=w.current)==null?void 0:oe.getPanel(X);if(!te)return!1;try{return te.group.model.location.type==="floating"}catch{return!1}},[]),le=l.useCallback(()=>{var te,oe;const X=(oe=(te=w.current)==null?void 0:te.activePanel)==null?void 0:oe.id;return!X||ds(X)?null:M.has(X)?X:null},[M]),je=l.useCallback(X=>{const te=w.current,oe=te==null?void 0:te.getPanel(X);if(!te||!oe)return;const be=te.groups.filter(re=>{try{return re.model.location.type==="grid"}catch{return!0}});be.length>0?oe.api.moveTo({group:be[0],position:"center"}):oe.api.moveTo({position:"center"}),oe.api.setActive()},[]),ge=l.useCallback(()=>{var Te;const X=w.current;if(!X)return;const oe=X.groups.filter(Ee=>{var Ie;try{return((Ie=Ee.element)==null?void 0:Ie.ownerDocument)===document&&Ee.model.location.type==="grid"}catch{return!1}})[0]||null,be=[...X.panels];for(const Ee of be){const Ie=(Te=Ee.group.element)==null?void 0:Te.ownerDocument,ze=Ee.group.model.location.type;Ie===document&&ze==="grid"||(oe&&oe.id!==Ee.group.id?Ee.api.moveTo({group:oe,position:"center"}):Ee.api.moveTo({position:"center"}))}const re=X.activePanel;re&&(re.group.model.openPanel(re),re.api.setActive()),Eo(document)},[]),Ce=l.useCallback(()=>{var te,oe;const X=w.current;if(X)for(const be of X.groups){const re=(te=be.element)==null?void 0:te.ownerDocument;if(!re||re===document)continue;const Te=re.getElementById("dv-popout-window");if(!(Te instanceof HTMLElement))continue;let Ee=null,Ie=re.title||"ADHDev",ze="Popout workspace";const Ke=be.activePanel;if(Ke)if(Ee=Ke.id,ds(Ke.id)){const Be=((oe=Ke.params)==null?void 0:oe.routeId)||Ke.id.slice(7),ce=bs([...M.values()],Be);Ie=Rp(ce),ze=ce!=null&&ce.machineName?`Remote view · ${ce.machineName}`:"Remote view"}else{const Be=M.get(Ke.id);Ie=Be?kt(Be):Ke.title||Ke.id,ze=Be?an(Be):"Dockview panel"}re.title=`${Ie} — ADHDev`;const Qe=Array.from(re.querySelectorAll("#adhdev-popout-header"));for(const Be of Qe)Be.remove();const Ue=re.createElement("div");Ue.id="adhdev-popout-header",re.body.appendChild(Ue),Ue.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(";")),Ue.innerHTML=`
72
72
  <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
73
73
  <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
@@ -111,11 +111,11 @@ This will disconnect CDP and optionally kill the process.`))try{const M=await n(
111
111
 
112
112
  `)}function MD(e,t){return t==="issues"?e.filter(n=>n.level==="warn"||n.level==="error"):t==="info"?e.filter(n=>n.level!=="debug"):e}function DD(e,t){return t==="issues"?e.filter(n=>n.level==="warn"||n.level==="error"):t==="info"?e.filter(n=>n.level!=="debug"):e}function ID({daemonLogs:e,daemonRawText:t,daemonLogKind:n,debugTrace:r,webEvents:a,traceCategory:o,quickFilter:i,searchQuery:c,daemonLoading:u,traceLoading:p,daemonFetchError:d,traceFetchError:m}){const f=iD(r,o),g=dD(e,c),S=mD(t,c),h=hD(f,c),x=fD(a,c),y=MD(g,i),b=i==="all"?S:[],C=DD(h,i),j=i==="issues"?[]:x,k=bD({daemonLogs:g,daemonRawLines:S,trace:h,webEvents:x}),v=CD({daemonLogs:y,daemonRawLines:b,trace:C,webEvents:j}),N=ND(v),w=vD({daemonLoading:u,traceLoading:p,daemonFetchError:d,traceFetchError:m,daemonLogKind:n,daemonLogsCount:g.length,daemonRawLineCount:S.length,traceCount:h.length,webEventCount:x.length});return{filteredDaemonLogs:g,filteredDaemonRawLines:S,filteredTraceEntries:h,filteredWebEvents:x,visibleDaemonLogs:y,visibleDaemonRawLines:b,visibleTraceEntries:C,visibleWebEvents:j,quickFilterCounts:k,diagnosticEvents:v,diagnosticsSummary:N,sourceStates:w}}function PD(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Ch(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function Li(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 Ko(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 Dl(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function LD({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Li(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:Ch(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:Dl(e.source)}),e.category&&e.stage&&s.jsxs("span",{children:[e.category,".",e.stage]}),e.topic&&s.jsxs("span",{children:["topic=",e.topic]}),e.interactionId&&s.jsxs("span",{children:["ix=",e.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:e.message})]})}function RD({quickFilter:e,quickFilterCounts:t,searchQuery:n,autoRefresh:r,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:i,onCopyVisible:c,onToggleAutoRefresh:u,onRefresh:p,onClear:d}){return s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${t.info})`},{id:"issues",label:`Issues (${t.issues})`},{id:"all",label:`All (${t.all})`}].map(m=>s.jsx("button",{type:"button",onClick:()=>a(m.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===m.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:m.label},m.id))}),s.jsx("input",{value:n,onChange:m=>o(m.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:i,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:u,className:`machine-btn ${r?"text-green-500 border-green-500/30":""}`,children:r?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:p,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:d,className:"machine-btn",children:"Clear"})]})]})}function ED({logLevel:e,traceCategory:t,onLogLevelChange:n,onTraceCategoryChange:r}){return s.jsx(Ls,{padding:"sm",children:s.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wider text-text-muted font-semibold",children:"Advanced source scope"}),["debug","info","warn","error"].map(a=>s.jsxs("button",{onClick:()=>n(a),className:`machine-btn text-[10px] px-2 py-0.5 ${e===a?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:["Daemon ",a.toUpperCase(),"+"]},a))]}),s.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:aD.map(a=>s.jsx("button",{onClick:()=>r(a.value),className:`machine-btn text-[10px] px-2 py-0.5 ${t===a.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:a.label},a.value))})]})})}function _D({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:n,searchQuery:r,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:i,traceFetchError:c}){var d,m;const u=((d=e.latestIssue)==null?void 0:d.severity)==="error"?"danger":((m=e.latestIssue)==null?void 0:m.severity)==="warn"?"warning":"good",p=i||c?"danger":o?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${Ko(e.issueCount>0?"warning":"good")}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Diagnostics timeline"}),s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[t," visible event(s) · ",e.issueCount," issue signal(s)"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:r.trim()?`Filtered by “${r.trim()}”`:"Daemon, trace, and browser signals merged by time"})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Ko(u)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[Dl(e.latestIssue.source)," · ",e.latestIssue.severity.toUpperCase()]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:e.latestIssue.message}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2",children:Ch(e.latestIssue.ts)})]}):s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:"No visible warn/error signal"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:"Use Issues or All if you need a narrower or rawer view."})]})]}),s.jsxs("div",{className:`rounded-xl border p-3 ${Ko(p)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Source status"}),s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:i||c?"Needs attention":o?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",PD(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:n.map(f=>s.jsxs("div",{children:[f.label,": ",f.status]},f.id))})]})]})}function $D({patterns:e}){return e.length===0?null:s.jsxs("div",{className:"rounded-xl border border-amber-500/20 bg-amber-500/[0.04] p-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Repeated issue patterns"}),s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:e.map(t=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-primary px-3 py-2",children:[s.jsxs("div",{className:"text-[12px] text-text-primary font-medium",children:[t.count,"× ",t.severity.toUpperCase()," · ",Dl(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function HD({streams:e,sectionsOpen:t,setSectionsOpen:n,diagnosticEvents:r,visibleDaemonLogs:a,visibleDaemonRawLines:o,visibleTraceEntries:i,visibleWebEvents:c,quickFilter:u,searchQuery:p}){return s.jsxs("div",{className:"grid gap-3",children:[s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(d=>({...d,timeline:!d.timeline})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[r.length," visible diagnostic event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.timeline?"Hide":"Show"})]}),t.timeline&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[180px] max-h-[440px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[(e.daemonLoading||e.traceLoading)&&r.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading diagnostics…"}),(e.daemonFetchError||e.traceFetchError)&&r.length===0&&s.jsxs("div",{className:"p-6 text-center text-red-300 space-y-1",children:[e.daemonFetchError&&s.jsxs("div",{children:["Daemon logs: ",e.daemonFetchError]}),e.traceFetchError&&s.jsxs("div",{children:["Daemon trace: ",e.traceFetchError]})]}),!e.daemonLoading&&!e.traceLoading&&r.length===0&&!e.daemonFetchError&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No diagnostics match the current view."}),r.map(d=>s.jsx(LD,{event:d},d.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(d=>({...d,daemon:!d.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${o.length} visible raw line(s) from file fallback`:`${a.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.daemon?"Hide":"Show"})]}),t.daemon&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.daemonLoading&&a.length===0&&o.length===0&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&o.length===0&&e.daemonRawText&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:u==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),e.daemonLogKind==="structured"&&a.length===0&&e.daemonLogs.length>0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&o.map((d,m)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:d},`raw-${m}`)),e.daemonLogKind!=="text"&&a.map((d,m)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${Li(d.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(d.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:d.level==="error"?"ERR":d.level==="warn"?"WRN":d.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:d.message})]},`log-${m}`))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(d=>({...d,trace:!d.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[i.length," visible trace event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.trace?"Hide":"Show"})]}),t.trace&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.traceLoading&&i.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&i.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&i.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:p.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."}),i.map(d=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${Li(d.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(d.ts).toLocaleTimeString()}),s.jsx("span",{children:d.level.toUpperCase()}),s.jsxs("span",{children:[d.category,".",d.stage]}),d.interactionId&&s.jsxs("span",{children:["ix=",d.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:On(d.payload,360)||"No payload"})]},d.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(d=>({...d,web:!d.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[c.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.web?"Hide":"Show"})]}),t.web&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[c.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:p.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),c.map(d=>s.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(d.ts).toLocaleTimeString()}),s.jsx("span",{children:d.kind}),d.topic&&s.jsxs("span",{children:["topic=",d.topic]}),d.interactionId&&s.jsxs("span",{children:["ix=",d.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:On(d.payload,360)||"No payload"})]},d.id))]})]})]})}function FD({machineId:e,sendDaemonCommand:t}){const n=xD({machineId:e,sendDaemonCommand:t}),[r,a]=l.useState("info"),[o,i]=l.useState(""),[c,u]=l.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),p=l.useRef(null),d=l.useRef(!1),m=l.useMemo(()=>ID({daemonLogs:n.daemonLogs,daemonRawText:n.daemonRawText,daemonLogKind:n.daemonLogKind,debugTrace:n.debugTrace,webEvents:n.webEvents,traceCategory:n.traceCategory,quickFilter:r,searchQuery:o,daemonLoading:n.daemonLoading,traceLoading:n.traceLoading,daemonFetchError:n.daemonFetchError,traceFetchError:n.traceFetchError}),[r,o,n.daemonFetchError,n.daemonLoading,n.daemonLogKind,n.daemonLogs,n.daemonRawText,n.debugTrace,n.traceCategory,n.traceFetchError,n.traceLoading,n.webEvents]);l.useEffect(()=>{if(n.autoRefresh&&m.diagnosticEvents.length>0){const S=d.current?"smooth":"instant";setTimeout(()=>{var h;(h=p.current)==null||h.scrollIntoView({behavior:S}),d.current=!0},50)}},[m.diagnosticEvents.length,n.autoRefresh]);const f=l.useCallback(async()=>{var h;const S=gD({daemonLogs:m.visibleDaemonLogs,daemonRawLines:m.visibleDaemonRawLines,trace:m.visibleTraceEntries,webEvents:m.visibleWebEvents});if(!S.trim()){ft.showToast("No visible logs to copy.","info");return}try{await((h=navigator.clipboard)==null?void 0:h.writeText(S)),ft.showToast("Copied visible logs to clipboard.","success")}catch(x){ft.showToast(x instanceof Error?x.message:"Could not copy visible logs","warning")}},[m.visibleDaemonLogs,m.visibleDaemonRawLines,m.visibleTraceEntries,m.visibleWebEvents]),g=l.useCallback(async()=>{var h;const S=TD({events:m.diagnosticEvents,summary:m.diagnosticsSummary,sources:m.sourceStates});try{await((h=navigator.clipboard)==null?void 0:h.writeText(S)),ft.showToast("Copied diagnostic bundle to clipboard.","success")}catch(x){ft.showToast(x instanceof Error?x.message:"Could not copy diagnostic bundle","warning")}},[m.diagnosticEvents,m.diagnosticsSummary,m.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(RD,{quickFilter:r,quickFilterCounts:m.quickFilterCounts,searchQuery:o,autoRefresh:n.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:i,onCopyDiagnostics:()=>{g()},onCopyVisible:()=>{f()},onToggleAutoRefresh:()=>n.setAutoRefresh(S=>!S),onRefresh:n.refresh,onClear:n.clear}),s.jsx(ED,{logLevel:n.logLevel,traceCategory:n.traceCategory,onLogLevelChange:n.setLogLevel,onTraceCategoryChange:n.setTraceCategory}),s.jsx(_D,{diagnosticsSummary:m.diagnosticsSummary,diagnosticEventsCount:m.diagnosticEvents.length,sourceStates:m.sourceStates,searchQuery:o,lastUpdatedAt:n.lastUpdatedAt,autoRefresh:n.autoRefresh,daemonFetchError:n.daemonFetchError,traceFetchError:n.traceFetchError}),s.jsx($D,{patterns:m.diagnosticsSummary.repeatedPatterns}),s.jsx(HD,{streams:n,sectionsOpen:c,setSectionsOpen:u,diagnosticEvents:m.diagnosticEvents,visibleDaemonLogs:m.visibleDaemonLogs,visibleDaemonRawLines:m.visibleDaemonRawLines,visibleTraceEntries:m.visibleTraceEntries,visibleWebEvents:m.visibleWebEvents,quickFilter:r,searchQuery:o}),s.jsx("div",{ref:p})]})}function BD(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 jh(e){const t=typeof(e==null?void 0:e.runtimeRecoveryState)=="string"?String(e.runtimeRecoveryState).trim():"";return t?t==="auto_resumed"?"restored after restart":t==="resume_failed"?"restore failed":t==="host_restart_interrupted"?"host restart interrupted":t==="orphan_snapshot"?"snapshot recovered":t.replace(/_/g," "):null}function WD(e){var a;const t=[],n=[],r=[];for(const o of e||[]){const i=String((o==null?void 0:o.lifecycle)||"").trim(),c=jh((o==null?void 0:o.meta)||void 0),u=((a=o==null?void 0:o.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(i)?t.push(o):(i==="stopped"||i==="failed")&&(u||c)?n.push(o):r.push(o)}return{liveRuntimes:t,recoverySnapshots:n,inactiveRecords:r}}function OD(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Vo(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 Yo(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Jo(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Ud(e){if(!e)return"unknown";const t=Date.now()-e,n=Math.max(0,Math.round(t/1e3));if(n<60)return`${n}s ago`;const r=Math.round(n/60);if(r<60)return`${r}m ago`;const a=Math.round(r/60);return a<48?`${a}h ago`:`${Math.round(a/24)}d ago`}function UD(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function GD(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-bg-glass text-text-muted"}}function qD(e){var n;const t=new Map;for(const r of e){if(!["starting","running","stopping","interrupted"].includes(r.lifecycle))continue;const a=typeof((n=r.meta)==null?void 0:n.providerSessionId)=="string"?String(r.meta.providerSessionId).trim():"";if(!a)continue;const o=`${r.providerType}::${r.workspace}::${a}`;t.set(o,(t.get(o)||0)+1)}return Array.from(t.values()).filter(r=>r>1).length}function zD({machineId:e,cliSessions:t,sendDaemonCommand:n}){const[r,a]=l.useState(""),[o,i]=l.useState(null),[c,u]=l.useState(!1),p=VC(e,{enabled:!!e,includeSessions:!0,limit:wc,intervalMs:X0}),d=p.diagnostics,m=p.loading,f=p.applyDiagnostics,g=l.useMemo(()=>BD({diagnostics:d,loading:m,refreshing:c,error:r}),[d,m,c,r]),S=l.useMemo(()=>new Map(t.map(I=>[I.sessionId||I.id,I])),[t]),h=l.useCallback(async()=>{if(e){u(!0);try{const I=await n(e,"session_host_get_diagnostics",{includeSessions:!0,limit:wc}),P=Yo(I);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Could not load hosted runtime diagnostics");f(P.diagnostics||P.result||null),a("")}catch(I){const P=I instanceof Error?I.message:"Could not load hosted runtime diagnostics";a(P)}finally{u(!1)}}},[f,e,n]);l.useEffect(()=>{!e||d||m||c||h()},[d,m,e,h,c]);const x=l.useCallback(async(I,P)=>{const D=`${I}:${P.sessionId}`;if(!(I==="session_host_stop_session"&&!window.confirm(`Stop ${P.displayName}?
113
113
  This will terminate the hosted runtime.`))){i(D);try{const _=await n(e,I,{sessionId:P.sessionId}),W=Yo(_);if(!(W!=null&&W.success))throw new Error((W==null?void 0:W.error)||"Session host action failed");const $=I==="session_host_resume_session"?"resumed":I==="session_host_restart_session"?"restarted":"stopped";ft.showToast(`Session host ${$}: ${P.displayName}`,"success"),await h()}catch(_){const W=_ instanceof Error?_.message:"Session host action failed";ft.showToast(W,"warning"),a(W)}finally{i(_=>_===D?null:_)}}},[e,h,n]),y=l.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
114
- The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){i("session_host_prune_duplicate_sessions");try{const P=await n(e,"session_host_prune_duplicate_sessions",{}),D=Yo(P);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||"Duplicate prune failed");const _=D.result||{},W=Array.isArray(_.prunedSessionIds)?_.prunedSessionIds.length:0,$=typeof _.duplicateGroupCount=="number"?_.duplicateGroupCount:0;ft.showToast(`Pruned ${W} duplicate runtime(s) across ${$} group(s)`,"success"),await h()}catch(P){const D=P instanceof Error?P.message:"Duplicate prune failed";ft.showToast(D,"warning"),a(D)}finally{i(P=>P==="session_host_prune_duplicate_sessions"?null:P)}}},[e,h,n]),b=l.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((I,P)=>(P.lastActivityAt||0)-(I.lastActivityAt||0)),[d==null?void 0:d.sessions]),C=l.useMemo(()=>d!=null&&d.liveRuntimes||d!=null&&d.recoverySnapshots||d!=null&&d.inactiveRecords?{liveRuntimes:(d==null?void 0:d.liveRuntimes)||[],recoverySnapshots:(d==null?void 0:d.recoverySnapshots)||[],inactiveRecords:(d==null?void 0:d.inactiveRecords)||[]}:WD(b),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,b]),j=C.liveRuntimes,k=C.recoverySnapshots,v=C.inactiveRecords,N=l.useMemo(()=>qD(j),[j]),w=l.useMemo(()=>[...(d==null?void 0:d.recentTransitions)||[]].slice(-6).reverse(),[d==null?void 0:d.recentTransitions]),A=l.useMemo(()=>[...(d==null?void 0:d.recentLogs)||[]].reverse().find(I=>I.level==="warn"||I.level==="error")||null,[d==null?void 0:d.recentLogs]),T=(I,P)=>{var M;const D=o===`session_host_resume_session:${I.sessionId}`,_=o===`session_host_restart_session:${I.sessionId}`,W=o===`session_host_stop_session:${I.sessionId}`,$=jh(I.meta),E=S.get(I.sessionId),B=I.attachedClients.length===1?"1 client":`${I.attachedClients.length} clients`,L=P==="recovery"?"Recover":"Resume",R=OD(P);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:I.displayName||(E==null?void 0:E.cliName)||I.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${GD(I.lifecycle)}`,children:I.lifecycle}),$&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:$})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:I.workspaceLabel||(E==null?void 0:E.runtimeWorkspaceLabel)||I.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:I.runtimeKey}),I.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",I.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((M=I.writeOwner)==null?void 0:M.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:UD(I.writeOwner)}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[s.jsx(fu,{size:11})," ",B]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",Ud(I.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",R]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[P==="recovery"&&(I.lifecycle==="interrupted"||I.lifecycle==="failed"||I.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{x("session_host_resume_session",I)},children:D?`${L}ing…`:L}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{x("session_host_restart_session",I)},children:_?"Restarting…":"Restart"}),P==="live"&&(I.lifecycle==="running"||I.lifecycle==="starting"||I.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!o,onClick:()=>{x("session_host_stop_session",I)},children:W?"Stopping…":"Stop"})]})]})},I.sessionId)};return s.jsxs(Ls,{padding:"lg",className:"mb-5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(Os,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:AS()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[N>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{y()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${N})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${g.toneClass}`,children:g.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{h()},disabled:m||c,children:[s.jsx(Fa,{size:13}),m||c?"Refreshing…":"Refresh"]})]})]}),r&&!d&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(pn,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:r})]})]})}),d&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:k.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:Ud(d.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Jo(d.hostStartedAt)})]})]}),A&&s.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[s.jsx(pn,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:A.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Jo(A.timestamp),A.sessionId?` · ${A.sessionId}`:""]})]}),s.jsxs("div",{className:"mb-4 space-y-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(qi,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Vo("live")}),j.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):s.jsx("div",{className:"space-y-2",children:j.map(I=>T(I,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(Os,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Vo("recovery")}),k.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):s.jsx("div",{className:"space-y-2",children:k.map(I=>T(I,"recovery"))})]}),v.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Vo("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:v.map(I=>T(I,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),w.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:w.map(I=>{var D;const P=b.find(_=>_.sessionId===I.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(P==null?void 0:P.displayName)||((D=S.get(I.sessionId))==null?void 0:D.cliName)||I.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[I.action,I.lifecycle?` · ${I.lifecycle}`:"",I.detail?` · ${I.detail}`:"",I.error?` · ${I.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${I.success===!1?"text-red-300":"text-text-secondary"}`,children:Jo(I.timestamp)})]},`${I.sessionId}:${I.timestamp}:${I.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:d.endpoint||"unknown"}),r?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",r]}):null]})]})]})}function KD({machine:e,launchPick:t,actions:n}){const{t:r}=Ne("common"),{runLaunchCliCore:a,setLaunchPick:o}=n;return l.useEffect(()=>{const i=c=>{c.key==="Escape"&&o(null)};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[o]),s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] 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",onClick:()=>o(null),children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",onClick:i=>i.stopPropagation(),children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(i=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{o(null),a({cliType:t.cliType,workspaceId:i.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{o(null),a({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:r("newSession.defaultWorkspace")}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{o(null),a({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:r("newSession.homeDirectory")}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>o(null),children:"Cancel"})]})]})})}function VD(e,t){const n=vC(e),r=$s(e,t),a=Ja(e,r),o=br(e,r),i=em(e,{targetVersion:r,required:o,fallback:"Update daemon"});return a?{visible:!0,showButton:!0,title:o?"Daemon update required":"Version mismatch detected",description:o?"This machine is on an incompatible daemon version. Update it before starting more sessions.":n==="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.",buttonLabel:i,targetVersion:r,channel:n,required:o,tone:"warn"}:n==="preview"?{visible:!0,showButton:!1,title:r?"Preview daemon is up to date":"Preview update status unknown",description:r?"This machine is already on the current preview daemon target.":"The app is connected to preview, but the server did not report a preview target version yet.",buttonLabel:i,targetVersion:r,channel:n,required:!1,tone:r?"good":"info"}:{visible:!1,showButton:!1,title:"",description:"",buttonLabel:i,targetVersion:r,channel:n,required:!1,tone:"info"}}function Qo({icon:e,children:t}){return s.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,s.jsx("span",{children:t})]})}function Xo({children:e,className:t=""}){return s.jsx("div",{className:`rounded-2xl border border-border-subtle bg-bg-surface/70 backdrop-blur-sm p-3 ${t}`,children:e})}function YD({machineEntry:e,providers:t,recentLaunches:n,currentConversations:r,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:i}){const{t:c}=Ne("common"),u=r.slice(0,6),p=n.slice(0,4),m=VD(e,"1.0.29");return s.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[u.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Qo,{icon:s.jsx(bn,{size:13}),children:c("machine.commandCenter.currentChats")}),s.jsx(Xo,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(f=>{const g=Mi(f);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>i(f),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:kt(f)}),g>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Ba(g)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:$n(f)})]},f.tabKey)})})})]}),p.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Qo,{icon:s.jsx(yu,{size:13}),children:c("machine.commandCenter.recentLaunches")}),s.jsx(Xo,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:p.map(f=>{const{metaText:g,updatedLabel:S}=jm(f);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>o(f),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:f.label}),S&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:S})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:g})]},f.id)})})})]}),m.visible&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Qo,{icon:s.jsx(pn,{size:13}),children:c("machine.commandCenter.daemonUpdate")}),s.jsx(Xo,{className:m.tone==="good"?"border-emerald-500/20 bg-emerald-500/5":m.tone==="info"?"border-sky-500/20 bg-sky-500/5":"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:m.title}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[m.description,m.targetVersion&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",m.targetVersion,m.channel?` (${m.channel})`:""]})]}),m.showButton?s.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:a,children:[s.jsx(Fa,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:m.buttonLabel})]}):s.jsx("div",{className:m.tone==="good"?"text-xs font-medium text-emerald-300":"text-xs font-medium text-sky-300",children:"No preview update action is needed."})]})})]})]})}function JD({machineId:e,machine:t,ideSessions:n,cliSessions:r,acpSessions:a,actions:o,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:u,handleWorkspaceRemove:p,handleWorkspaceSetDefault:d}=o,{t:m}=Ne("common"),[f,g]=l.useState(!1),[S,h]=l.useState(""),[x,y]=l.useState([]),[b,C]=l.useState(!1),[j,k]=l.useState(""),v=l.useCallback(async w=>{C(!0),k("");try{const A=await gl(i,e,w);h(A.path),y(A.directories)}catch(A){k(A instanceof Error?A.message:"Could not load folder")}finally{C(!1)}},[e,i]),N=l.useCallback(()=>{g(!0);const w=[...n.map(T=>T.workspace),...r.map(T=>T.workspace),...a.map(T=>T.workspace)],A=bl(t.platform,fl(w,t.defaultWorkspacePath,(t.workspaces||[]).map(T=>T.path)));v(A)},[a,r,n,v,t.defaultWorkspacePath,t.platform,t.workspaces]);return s.jsxs(s.Fragment,{children:[s.jsxs(Ls,{padding:"lg",className:"mb-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(En,{size:14})," Workspaces"]}),s.jsx("button",{type:"button",className:"btn bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary px-3 py-1 rounded transition-colors text-xs",disabled:c,onClick:N,children:"+ Add workspace"})]}),(t.workspaces||[]).length===0?s.jsxs("div",{className:"text-[11px] text-text-muted py-4 text-center",children:["No saved workspaces yet. Click ",s.jsx("span",{className:"text-text-secondary",children:"+ Add workspace"})," to pick a folder."]}):s.jsx("ul",{className:"space-y-1.5 max-h-72 overflow-y-auto",children:(t.workspaces||[]).map(w=>{const A=w.id===t.defaultWorkspaceId;return s.jsxs("li",{className:`flex items-start gap-2 text-[11px] rounded-lg border px-2.5 py-2 transition-colors ${A?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[s.jsx("button",{type:"button",title:A?"Default workspace — click to unset":"Set as default workspace",disabled:c,onClick:()=>void d(A?null:w.id),className:`text-base leading-none shrink-0 transition-colors ${A?"text-yellow-400 hover:text-yellow-300":"text-text-muted/40 hover:text-yellow-400"}`,children:"★"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"font-medium text-text-primary truncate",children:Ou(w.path,w.label)}),s.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:w.path,children:w.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void p(w.id),children:m("machine.managedWorkspaces.remove")})]},w.id)})})]}),f&&s.jsx(vl,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:S,directories:x,busy:b,error:j,confirmLabel:"Add workspace",onClose:()=>g(!1),onNavigate:w=>{v(w)},onConfirm:w=>{(async()=>{if(!w)return;await u(w)&&g(!1)})()}})]})}function QD({machine:e,machineId:t,ideSessions:n,cliSessions:r,acpSessions:a,actions:o,sendDaemonCommand:i}){return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-border-subtle mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspaces"}),s.jsx("div",{className:"text-sm text-text-secondary",children:'Save folders as workspaces on this machine. Use the dashboard "+" button to launch a session.'})]}),i&&s.jsx(JD,{machineId:t,machine:e,ideSessions:n,cliSessions:r,acpSessions:a,actions:o,sendDaemonCommand:i})]})}function XD({onNicknameSynced:e}={}){var ge,Ce,ue,z,U,q,Q,me,Ae,de;const{t}=Ne("common"),{id:n}=lf(),r=Mr(),a=Hi(),{sendCommand:o}=St(),i=qn(),c=am(),u=Tp(),p=u.ides||[],d=u.initialLoaded??!0,m=p.find(H=>H.id===n&&H.type==="adhdev-daemon"),f=p.some(H=>H.type==="adhdev-daemon"),g=n?(ge=u.connectionRetryStatuses)==null?void 0:ge[n]:void 0,S=!!(g!=null&&g.blocked),[h,x]=l.useState("workspace"),[y,b]=l.useState(null);l.useCallback((H,he)=>{b({daemonId:H,workspace:he})},[]);const[,C]=l.useState("ide"),j=l.useRef(null),[k,v]=l.useState(null),N=l.useRef("__home__"),[w,A]=l.useState("__home__"),[T,I]=l.useState(!1),P=l.useRef(null);l.useEffect(()=>{!n||!m||!(!m.workspaces||!m.availableProviders||!m.detectedIdes||!m.recentLaunches)||i(n,{minFreshMs:3e4}).catch(()=>{})},[i,m,n]),l.useEffect(()=>{if(!n||!m||h!=="overview")return;const H=m.machine;(typeof(H==null?void 0:H.cpus)!="number"||typeof(H==null?void 0:H.totalMem)!="number"||typeof(H==null?void 0:H.arch)!="string"||typeof(H==null?void 0:H.release)!="string")&&c(n,{minFreshMs:3e4}).catch(()=>{})},[h,c,m,n]),KC(n&&h==="overview"?[n]:[],{enabled:h==="overview",intervalMs:Y0});const D=()=>{if(f){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},_=qM({machineId:n,registeredMachineId:(m==null?void 0:m.machineId)||null,sendDaemonCommand:o,onNicknameSynced:e,logsEndRef:P});l.useEffect(()=>ft.onToast(he=>{u.setToasts(ye=>{if(ye.some(ke=>ke.message===he.message&&he.timestamp-ke.timestamp<3e3))return ye;const He={id:he.id,message:he.message,type:he.type,timestamp:he.timestamp,targetKey:he.targetKey,actions:he.actions};return[...ye.slice(-4),He]});const fe=he.duration||5e3;setTimeout(()=>u.setToasts(ye=>ye.filter(Pe=>Pe.id!==he.id)),fe)}),[u]);const W=(m==null?void 0:m.availableProviders)||[],$={};for(const H of W)$[H.type]=H.icon;const E=m?{id:m.id,hostname:Uu(m,{fallbackId:m.id}),platform:((Ce=m.machine)==null?void 0:Ce.platform)||"unknown",arch:((ue=m.machine)==null?void 0:ue.arch)||"",cpus:((z=m.machine)==null?void 0:z.cpus)||0,totalMem:((U=m.machine)==null?void 0:U.totalMem)||0,freeMem:(q=m.machine)==null?void 0:q.freeMem,availableMem:(Q=m.machine)==null?void 0:Q.availableMem,loadavg:(me=m.machine)==null?void 0:me.loadavg,uptime:(Ae=m.machine)==null?void 0:Ae.uptime,release:((de=m.machine)==null?void 0:de.release)||"",cdpConnected:!!m.cdpConnected,machineNickname:m.machineNickname||null,p2p:m.p2p?{screenshotActive:!1,...m.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:m.detectedIdes||[],workspaces:m.workspaces||[],defaultWorkspaceId:m.defaultWorkspaceId??m.activeWorkspaceId??null,defaultWorkspacePath:m.defaultWorkspacePath??m.activeWorkspacePath??null}:null,B=p.filter(H=>H.daemonId===n&&H.type!=="adhdev-daemon").filter(H=>!Sr(H)&&!Dn(H)).map(H=>({id:H.id,sessionId:H.sessionId,type:H.type,version:H.version||"",instanceId:H.instanceId||"",status:H.status,workspace:H.workspace||null,terminals:H.terminals||0,aiAgents:dw(H.aiAgents||(H.agents||[]).map(he=>({id:he.name,name:he.name,status:he.status,version:he.version}))),activeChat:H.activeChat||null,chats:H.chats||[],childSessions:H.childSessions||[],cdpConnected:H.cdpConnected||!1,daemonId:n,lastMessageAt:H.lastMessageAt})),L=p.filter(H=>H.daemonId===n&&Sr(H)).map(H=>({id:H.id,sessionId:H.sessionId,type:H.type,cliName:H.cliName||H.type,status:H.status,workspace:H.workspace||"",activeChat:H.activeChat||null,providerSessionId:H.providerSessionId,mode:H.mode,runtimeKey:H.runtimeKey,runtimeDisplayName:H.runtimeDisplayName,runtimeWorkspaceLabel:H.runtimeWorkspaceLabel,runtimeWriteOwner:H.runtimeWriteOwner||null,runtimeAttachedClients:H.runtimeAttachedClients||[],daemonId:n,lastMessageAt:H.lastMessageAt})),R=p.filter(H=>H.daemonId===n&&Dn(H)).map(H=>({id:H.id,sessionId:H.sessionId,type:H.type,acpName:H.cliName||H.type,status:H.status,workspace:H.workspace||"",activeChat:H.activeChat||null,providerSessionId:H.providerSessionId,daemonId:n,lastMessageAt:H.lastMessageAt})),M=m?is(m,{fallbackId:n}):"",F="workspace",K=a.state,J=K==null?void 0:K.initialMachineTab,V=K==null?void 0:K.initialWorkspaceCategory;K==null||K.initialWorkspaceId,K==null||K.initialWorkspacePath;const Y=J==="ides"||J==="clis"||J==="acps"?"workspace":J||F,se=J==="ides"?"ide":J==="clis"?"cli":J==="acps"?"acp":V,ie=[...B.map(H=>{var he;return{id:`ide:${H.type}:${H.workspace||""}`,label:((he=H.activeChat)==null?void 0:he.title)||H.type,kind:"ide",providerType:H.type,subtitle:H.workspace||void 0,workspace:H.workspace||void 0,lastLaunchedAt:H.lastMessageAt||0}}),...L.map(H=>{var he;return{id:`cli:${H.type}:${H.workspace||""}`,label:((he=H.activeChat)==null?void 0:he.title)||H.cliName,kind:"cli",providerType:H.type,providerSessionId:H.providerSessionId,subtitle:H.workspace||void 0,workspace:H.workspace||void 0,lastLaunchedAt:H.lastMessageAt||0}}),...R.map(H=>{var he;return{id:`acp:${H.type}:${H.workspace||""}`,label:((he=H.activeChat)==null?void 0:he.title)||H.acpName,kind:"acp",providerType:H.type,providerSessionId:H.providerSessionId,subtitle:mn(H.summaryMetadata)||H.workspace||void 0,workspace:H.workspace||void 0,lastLaunchedAt:H.lastMessageAt||0}})].sort((H,he)=>(he.lastLaunchedAt||0)-(H.lastLaunchedAt||0)),Z=((m==null?void 0:m.recentLaunches)||[]).length>0?((m==null?void 0:m.recentLaunches)||[]).map(H=>({id:H.id,label:H.title||H.providerName||H.providerType,kind:H.kind,providerType:H.providerType,providerSessionId:H.providerSessionId,subtitle:mn(H.summaryMetadata)||H.workspace||void 0,workspace:H.workspace,summaryMetadata:H.summaryMetadata,lastLaunchedAt:H.lastLaunchedAt})):ie,O=l.useMemo(()=>{var he;const H=((he=u.connectionStates)==null?void 0:he[n||""])||void 0;return p.filter(fe=>fe.daemonId===n&&fe.type!=="adhdev-daemon").flatMap(fe=>cl(fe,{connectionStates:n&&H?{[n]:H}:void 0,defaultConnectionState:H})).filter(fe=>!(fe.transport==="pty"&&fe.mode==="terminal")).sort((fe,ye)=>Mi(ye)-Mi(fe))},[p,u.connectionStates,n]),ee=l.useCallback(H=>{const he=xm(H);he&&r(Nr(he))},[r]),G=l.useCallback(()=>{j.current&&(I(!0),j.current().finally(()=>{j.current=null,I(!1),v(null)}))},[]),le=l.useCallback(H=>{if(!E)return;const{options:he,selectedKey:fe}=Cm({machine:E,currentWorkspacePath:H.workspace,homeLabel:t("newSession.homeDirectory"),homeDescription:t("newSession.launchWithoutWorkspace")}),ye=async()=>{C(H.kind),x("workspace")};j.current=async()=>{const Pe=he.find(pe=>pe.key===N.current),He=(Pe==null?void 0:Pe.workspacePath)??null,ke=(Pe==null?void 0:Pe.workspaceId)??null;if(H.kind==="ide"&&H.providerType){await _.handleLaunchIde(H.providerType,He?{workspace:He}:void 0);return}if((H.kind==="cli"||H.kind==="acp")&&H.providerType){await _.runLaunchCliCore({cliType:H.providerType,dir:ke?void 0:He||"",workspaceId:ke||void 0,model:H.kind==="acp"&&qu(H.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:H.providerSessionId});return}await ye()},N.current=fe,A(fe),v({title:H.kind==="ide"?ja(t,"restart-ide",H.label):H.providerSessionId?Fp(t,H.label):ja(t,"start-fresh",H.label),description:H.kind==="ide"?Na(t,"restart-ide"):H.providerSessionId?Bp(t):Na(t,"start-fresh"),confirmLabel:H.kind==="ide"?Aa(t,"restart-ide"):H.providerSessionId?Si(t,!0):Aa(t,"start-fresh"),busyLabel:H.kind==="ide"?Ta(t,"restart-ide"):H.providerSessionId?Hp(t,!0):Ta(t,"start-fresh"),workspaceOptions:he,details:[{label:"Mode",value:H.kind.toUpperCase()},...H.providerType?[{label:"Provider",value:H.providerType}]:[]]})},[_,E]);if(l.useEffect(()=>{x(Y)},[F,Y,n]),l.useEffect(()=>{se&&C(se)},[se,n]),!E)return d?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:t("machine.detail.notFound")}),s.jsx("p",{className:"mt-3",children:t("machine.detail.offlineHint")}),s.jsx("button",{onClick:D,className:"machine-btn-back",children:t("machine.detail.back")})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:t("machine.detail.loading")})});const je=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(xs,{size:14})," ",t("machine.detail.tabWorkspace")]}),count:B.length+L.length+R.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Os,{size:14})," ",t("machine.detail.tabHostedRuntimes")]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ha,{size:14})," ",t("machine.detail.tabProviders")]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(eb,{size:14})," ",t("machine.detail.tabSystem")]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(gu,{size:14})," ",t("machine.detail.tabLogs")]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:D,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[_.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:_.nicknameInput,onChange:H=>_.setNicknameInput(H.target.value),onKeyDown:H=>{H.key==="Enter"&&_.handleSaveNickname(),H.key==="Escape"&&_.setEditingNickname(!1)},placeholder:t("machine.detail.nicknamePlaceholder"),className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:_.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:t("machine.detail.save")}),s.jsx("button",{onClick:()=>_.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:t("machine.detail.cancel")})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{_.setEditingNickname(!0),_.setNicknameInput(E.machineNickname||"")},title:t("machine.detail.clickToSetNickname"),children:M}),S?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),u.retryConnection&&n&&s.jsx("button",{onClick:()=>u.retryConnection(n),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:t("machine.detail.reconnect")})]}):s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[E.platform," · ",E.arch]}),s.jsx("span",{children:t("machine.detail.coresCount",{count:E.cpus})}),(m==null?void 0:m.version)&&s.jsxs("span",{children:["v",m.version]}),E.p2p.available&&s.jsx("span",{children:t("machine.detail.p2pState",{state:E.p2p.state==="connected"?t("machine.detail.p2pConnected"):E.p2p.state})}),E.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:E.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:je.map(H=>s.jsxs("button",{onClick:()=>x(H.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${h===H.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[H.label,H.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${h===H.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:H.count})]},H.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[h==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(YD,{machineEntry:m,providers:W,recentLaunches:Z,currentConversations:O,onUpgradeDaemon:async()=>{const H=Qa(m);if(H)try{await o(n,"daemon_upgrade",H)}catch{}},onOpenRecent:le,onOpenConversation:ee}),s.jsx(QD,{machine:E,machineId:n,ideSessions:B,cliSessions:L,acpSessions:R,actions:_,sendDaemonCommand:o})]}),h==="providers"&&s.jsx(rD,{machineId:n,providers:W,sendDaemonCommand:o}),h==="overview"&&s.jsx(zM,{machine:E,ideSessions:B,cliSessions:L,acpSessions:R}),h==="session-host"&&s.jsx(zD,{machineId:n,cliSessions:L,sendDaemonCommand:o}),h==="logs"&&s.jsx(FD,{machineId:n,sendDaemonCommand:o})]})})}),_.launchPick&&E&&s.jsx(KD,{machine:E,launchPick:_.launchPick,actions:_}),k&&s.jsx(Xa,{title:k.title,description:k.description,details:k.details,workspaceOptions:k.workspaceOptions,selectedWorkspaceKey:w,onWorkspaceChange:H=>{N.current=H,A(H)},confirmLabel:k.confirmLabel,busyLabel:k.busyLabel,busy:T,onConfirm:G,onCancel:()=>{j.current=null,v(null)}}),y&&s.jsx(Sh,{daemonId:y.daemonId,workspace:y.workspace,onClose:()=>b(null)}),s.jsx(Op,{toasts:u.toasts||[],onDismiss:H=>u.setToasts(he=>he.filter(fe=>fe.id!==H)),onClickToast:H=>{H.targetKey&&r(Nr(H.targetKey))}}),s.jsx("style",{children:`
114
+ The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){i("session_host_prune_duplicate_sessions");try{const P=await n(e,"session_host_prune_duplicate_sessions",{}),D=Yo(P);if(!(D!=null&&D.success))throw new Error((D==null?void 0:D.error)||"Duplicate prune failed");const _=D.result||{},W=Array.isArray(_.prunedSessionIds)?_.prunedSessionIds.length:0,$=typeof _.duplicateGroupCount=="number"?_.duplicateGroupCount:0;ft.showToast(`Pruned ${W} duplicate runtime(s) across ${$} group(s)`,"success"),await h()}catch(P){const D=P instanceof Error?P.message:"Duplicate prune failed";ft.showToast(D,"warning"),a(D)}finally{i(P=>P==="session_host_prune_duplicate_sessions"?null:P)}}},[e,h,n]),b=l.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((I,P)=>(P.lastActivityAt||0)-(I.lastActivityAt||0)),[d==null?void 0:d.sessions]),C=l.useMemo(()=>d!=null&&d.liveRuntimes||d!=null&&d.recoverySnapshots||d!=null&&d.inactiveRecords?{liveRuntimes:(d==null?void 0:d.liveRuntimes)||[],recoverySnapshots:(d==null?void 0:d.recoverySnapshots)||[],inactiveRecords:(d==null?void 0:d.inactiveRecords)||[]}:WD(b),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,b]),j=C.liveRuntimes,k=C.recoverySnapshots,v=C.inactiveRecords,N=l.useMemo(()=>qD(j),[j]),w=l.useMemo(()=>[...(d==null?void 0:d.recentTransitions)||[]].slice(-6).reverse(),[d==null?void 0:d.recentTransitions]),A=l.useMemo(()=>[...(d==null?void 0:d.recentLogs)||[]].reverse().find(I=>I.level==="warn"||I.level==="error")||null,[d==null?void 0:d.recentLogs]),T=(I,P)=>{var M;const D=o===`session_host_resume_session:${I.sessionId}`,_=o===`session_host_restart_session:${I.sessionId}`,W=o===`session_host_stop_session:${I.sessionId}`,$=jh(I.meta),E=S.get(I.sessionId),B=I.attachedClients.length===1?"1 client":`${I.attachedClients.length} clients`,L=P==="recovery"?"Recover":"Resume",R=OD(P);return s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("div",{className:"font-medium text-[13px] text-text-primary",children:I.displayName||(E==null?void 0:E.cliName)||I.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${GD(I.lifecycle)}`,children:I.lifecycle}),$&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:$})]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:"text-text-primary/90",children:I.workspaceLabel||(E==null?void 0:E.runtimeWorkspaceLabel)||I.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:I.runtimeKey}),I.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",I.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((M=I.writeOwner)==null?void 0:M.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:UD(I.writeOwner)}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"flex items-center gap-1 text-text-primary/85",children:[s.jsx(fu,{size:11})," ",B]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",Ud(I.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",R]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[P==="recovery"&&(I.lifecycle==="interrupted"||I.lifecycle==="failed"||I.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{x("session_host_resume_session",I)},children:D?`${L}ing…`:L}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{x("session_host_restart_session",I)},children:_?"Restarting…":"Restart"}),P==="live"&&(I.lifecycle==="running"||I.lifecycle==="starting"||I.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!o,onClick:()=>{x("session_host_stop_session",I)},children:W?"Stopping…":"Stop"})]})]})},I.sessionId)};return s.jsxs(Ls,{padding:"lg",className:"mb-5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(Os,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:AS()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[N>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{y()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${N})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${g.toneClass}`,children:g.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{h()},disabled:m||c,children:[s.jsx(Fa,{size:13}),m||c?"Refreshing…":"Refresh"]})]})]}),r&&!d&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(pn,{size:14,className:"mt-0.5 text-amber-300 shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-amber-100",children:"Hosted runtime diagnostics need attention"}),s.jsx("div",{className:"text-amber-200/90 mt-1",children:r})]})]})}),d&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:k.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:d.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:Ud(d.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Jo(d.hostStartedAt)})]})]}),A&&s.jsxs("div",{className:"rounded-xl border border-amber-500/[0.16] bg-amber-500/[0.07] px-3.5 py-3 text-[11px] text-text-secondary mb-4",children:[s.jsxs("div",{className:"flex items-center gap-1.5 text-amber-200 font-medium mb-1",children:[s.jsx(pn,{size:13})," Latest host warning"]}),s.jsx("div",{className:"text-text-primary leading-relaxed",children:A.message}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1",children:[Jo(A.timestamp),A.sessionId?` · ${A.sessionId}`:""]})]}),s.jsxs("div",{className:"mb-4 space-y-4",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(qi,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Vo("live")}),j.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):s.jsx("div",{className:"space-y-2",children:j.map(I=>T(I,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(Os,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Vo("recovery")}),k.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No recovery snapshots currently need attention."}):s.jsx("div",{className:"space-y-2",children:k.map(I=>T(I,"recovery"))})]}),v.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Vo("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:v.map(I=>T(I,"inactive"))})]})]}),s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Recent Host Activity"}),w.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3 text-[12px] text-text-secondary",children:"No recent runtime transitions yet."}):s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary divide-y divide-border-subtle",children:w.map(I=>{var D;const P=b.find(_=>_.sessionId===I.sessionId);return s.jsxs("div",{className:"px-3.5 py-2.5 text-[11px] flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-text-primary font-medium",children:(P==null?void 0:P.displayName)||((D=S.get(I.sessionId))==null?void 0:D.cliName)||I.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[I.action,I.lifecycle?` · ${I.lifecycle}`:"",I.detail?` · ${I.detail}`:"",I.error?` · ${I.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${I.success===!1?"text-red-300":"text-text-secondary"}`,children:Jo(I.timestamp)})]},`${I.sessionId}:${I.timestamp}:${I.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:d.endpoint||"unknown"}),r?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",r]}):null]})]})]})}function KD({machine:e,launchPick:t,actions:n}){const{t:r}=Ne("common"),{runLaunchCliCore:a,setLaunchPick:o}=n;return l.useEffect(()=>{const i=c=>{c.key==="Escape"&&o(null)};return window.addEventListener("keydown",i),()=>window.removeEventListener("keydown",i)},[o]),s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] 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",onClick:()=>o(null),children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",onClick:i=>i.stopPropagation(),children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(i=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{o(null),a({cliType:t.cliType,workspaceId:i.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:i.label||i.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:i.path})]},i.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{o(null),a({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:r("newSession.defaultWorkspace")}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{o(null),a({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:r("newSession.homeDirectory")}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>o(null),children:"Cancel"})]})]})})}function VD(e,t){const n=vC(e),r=$s(e,t),a=Ja(e,r),o=br(e,r),i=em(e,{targetVersion:r,required:o,fallback:"Update daemon"});return a?{visible:!0,showButton:!0,title:o?"Daemon update required":"Version mismatch detected",description:o?"This machine is on an incompatible daemon version. Update it before starting more sessions.":n==="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.",buttonLabel:i,targetVersion:r,channel:n,required:o,tone:"warn"}:n==="preview"?{visible:!0,showButton:!1,title:r?"Preview daemon is up to date":"Preview update status unknown",description:r?"This machine is already on the current preview daemon target.":"The app is connected to preview, but the server did not report a preview target version yet.",buttonLabel:i,targetVersion:r,channel:n,required:!1,tone:r?"good":"info"}:{visible:!1,showButton:!1,title:"",description:"",buttonLabel:i,targetVersion:r,channel:n,required:!1,tone:"info"}}function Qo({icon:e,children:t}){return s.jsxs("div",{className:"flex items-center gap-2 text-[11px] font-semibold text-text-muted tracking-[0.14em] uppercase",children:[e,s.jsx("span",{children:t})]})}function Xo({children:e,className:t=""}){return s.jsx("div",{className:`rounded-2xl border border-border-subtle bg-bg-surface/70 backdrop-blur-sm p-3 ${t}`,children:e})}function YD({machineEntry:e,providers:t,recentLaunches:n,currentConversations:r,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:i}){const{t:c}=Ne("common"),u=r.slice(0,6),p=n.slice(0,4),m=VD(e,"1.0.30");return s.jsxs("div",{className:"flex flex-col gap-4 md:min-w-[300px] md:max-w-[360px] shrink-0 md:h-full overflow-y-auto",children:[u.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Qo,{icon:s.jsx(bn,{size:13}),children:c("machine.commandCenter.currentChats")}),s.jsx(Xo,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(f=>{const g=Mi(f);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>i(f),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:kt(f)}),g>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Ba(g)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:$n(f)})]},f.tabKey)})})})]}),p.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Qo,{icon:s.jsx(yu,{size:13}),children:c("machine.commandCenter.recentLaunches")}),s.jsx(Xo,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:p.map(f=>{const{metaText:g,updatedLabel:S}=jm(f);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>o(f),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:f.label}),S&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:S})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:g})]},f.id)})})})]}),m.visible&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Qo,{icon:s.jsx(pn,{size:13}),children:c("machine.commandCenter.daemonUpdate")}),s.jsx(Xo,{className:m.tone==="good"?"border-emerald-500/20 bg-emerald-500/5":m.tone==="info"?"border-sky-500/20 bg-sky-500/5":"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:m.title}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[m.description,m.targetVersion&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",m.targetVersion,m.channel?` (${m.channel})`:""]})]}),m.showButton?s.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:a,children:[s.jsx(Fa,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:m.buttonLabel})]}):s.jsx("div",{className:m.tone==="good"?"text-xs font-medium text-emerald-300":"text-xs font-medium text-sky-300",children:"No preview update action is needed."})]})})]})]})}function JD({machineId:e,machine:t,ideSessions:n,cliSessions:r,acpSessions:a,actions:o,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:u,handleWorkspaceRemove:p,handleWorkspaceSetDefault:d}=o,{t:m}=Ne("common"),[f,g]=l.useState(!1),[S,h]=l.useState(""),[x,y]=l.useState([]),[b,C]=l.useState(!1),[j,k]=l.useState(""),v=l.useCallback(async w=>{C(!0),k("");try{const A=await gl(i,e,w);h(A.path),y(A.directories)}catch(A){k(A instanceof Error?A.message:"Could not load folder")}finally{C(!1)}},[e,i]),N=l.useCallback(()=>{g(!0);const w=[...n.map(T=>T.workspace),...r.map(T=>T.workspace),...a.map(T=>T.workspace)],A=bl(t.platform,fl(w,t.defaultWorkspacePath,(t.workspaces||[]).map(T=>T.path)));v(A)},[a,r,n,v,t.defaultWorkspacePath,t.platform,t.workspaces]);return s.jsxs(s.Fragment,{children:[s.jsxs(Ls,{padding:"lg",className:"mb-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(En,{size:14})," Workspaces"]}),s.jsx("button",{type:"button",className:"btn bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary px-3 py-1 rounded transition-colors text-xs",disabled:c,onClick:N,children:"+ Add workspace"})]}),(t.workspaces||[]).length===0?s.jsxs("div",{className:"text-[11px] text-text-muted py-4 text-center",children:["No saved workspaces yet. Click ",s.jsx("span",{className:"text-text-secondary",children:"+ Add workspace"})," to pick a folder."]}):s.jsx("ul",{className:"space-y-1.5 max-h-72 overflow-y-auto",children:(t.workspaces||[]).map(w=>{const A=w.id===t.defaultWorkspaceId;return s.jsxs("li",{className:`flex items-start gap-2 text-[11px] rounded-lg border px-2.5 py-2 transition-colors ${A?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[s.jsx("button",{type:"button",title:A?"Default workspace — click to unset":"Set as default workspace",disabled:c,onClick:()=>void d(A?null:w.id),className:`text-base leading-none shrink-0 transition-colors ${A?"text-yellow-400 hover:text-yellow-300":"text-text-muted/40 hover:text-yellow-400"}`,children:"★"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"font-medium text-text-primary truncate",children:Ou(w.path,w.label)}),s.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:w.path,children:w.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void p(w.id),children:m("machine.managedWorkspaces.remove")})]},w.id)})})]}),f&&s.jsx(vl,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:S,directories:x,busy:b,error:j,confirmLabel:"Add workspace",onClose:()=>g(!1),onNavigate:w=>{v(w)},onConfirm:w=>{(async()=>{if(!w)return;await u(w)&&g(!1)})()}})]})}function QD({machine:e,machineId:t,ideSessions:n,cliSessions:r,acpSessions:a,actions:o,sendDaemonCommand:i}){return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-border-subtle mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspaces"}),s.jsx("div",{className:"text-sm text-text-secondary",children:'Save folders as workspaces on this machine. Use the dashboard "+" button to launch a session.'})]}),i&&s.jsx(JD,{machineId:t,machine:e,ideSessions:n,cliSessions:r,acpSessions:a,actions:o,sendDaemonCommand:i})]})}function XD({onNicknameSynced:e}={}){var ge,Ce,ue,z,U,q,Q,me,Ae,de;const{t}=Ne("common"),{id:n}=lf(),r=Mr(),a=Hi(),{sendCommand:o}=St(),i=qn(),c=am(),u=Tp(),p=u.ides||[],d=u.initialLoaded??!0,m=p.find(H=>H.id===n&&H.type==="adhdev-daemon"),f=p.some(H=>H.type==="adhdev-daemon"),g=n?(ge=u.connectionRetryStatuses)==null?void 0:ge[n]:void 0,S=!!(g!=null&&g.blocked),[h,x]=l.useState("workspace"),[y,b]=l.useState(null);l.useCallback((H,he)=>{b({daemonId:H,workspace:he})},[]);const[,C]=l.useState("ide"),j=l.useRef(null),[k,v]=l.useState(null),N=l.useRef("__home__"),[w,A]=l.useState("__home__"),[T,I]=l.useState(!1),P=l.useRef(null);l.useEffect(()=>{!n||!m||!(!m.workspaces||!m.availableProviders||!m.detectedIdes||!m.recentLaunches)||i(n,{minFreshMs:3e4}).catch(()=>{})},[i,m,n]),l.useEffect(()=>{if(!n||!m||h!=="overview")return;const H=m.machine;(typeof(H==null?void 0:H.cpus)!="number"||typeof(H==null?void 0:H.totalMem)!="number"||typeof(H==null?void 0:H.arch)!="string"||typeof(H==null?void 0:H.release)!="string")&&c(n,{minFreshMs:3e4}).catch(()=>{})},[h,c,m,n]),KC(n&&h==="overview"?[n]:[],{enabled:h==="overview",intervalMs:Y0});const D=()=>{if(f){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},_=qM({machineId:n,registeredMachineId:(m==null?void 0:m.machineId)||null,sendDaemonCommand:o,onNicknameSynced:e,logsEndRef:P});l.useEffect(()=>ft.onToast(he=>{u.setToasts(ye=>{if(ye.some(ke=>ke.message===he.message&&he.timestamp-ke.timestamp<3e3))return ye;const He={id:he.id,message:he.message,type:he.type,timestamp:he.timestamp,targetKey:he.targetKey,actions:he.actions};return[...ye.slice(-4),He]});const fe=he.duration||5e3;setTimeout(()=>u.setToasts(ye=>ye.filter(Pe=>Pe.id!==he.id)),fe)}),[u]);const W=(m==null?void 0:m.availableProviders)||[],$={};for(const H of W)$[H.type]=H.icon;const E=m?{id:m.id,hostname:Uu(m,{fallbackId:m.id}),platform:((Ce=m.machine)==null?void 0:Ce.platform)||"unknown",arch:((ue=m.machine)==null?void 0:ue.arch)||"",cpus:((z=m.machine)==null?void 0:z.cpus)||0,totalMem:((U=m.machine)==null?void 0:U.totalMem)||0,freeMem:(q=m.machine)==null?void 0:q.freeMem,availableMem:(Q=m.machine)==null?void 0:Q.availableMem,loadavg:(me=m.machine)==null?void 0:me.loadavg,uptime:(Ae=m.machine)==null?void 0:Ae.uptime,release:((de=m.machine)==null?void 0:de.release)||"",cdpConnected:!!m.cdpConnected,machineNickname:m.machineNickname||null,p2p:m.p2p?{screenshotActive:!1,...m.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:m.detectedIdes||[],workspaces:m.workspaces||[],defaultWorkspaceId:m.defaultWorkspaceId??m.activeWorkspaceId??null,defaultWorkspacePath:m.defaultWorkspacePath??m.activeWorkspacePath??null}:null,B=p.filter(H=>H.daemonId===n&&H.type!=="adhdev-daemon").filter(H=>!Sr(H)&&!Dn(H)).map(H=>({id:H.id,sessionId:H.sessionId,type:H.type,version:H.version||"",instanceId:H.instanceId||"",status:H.status,workspace:H.workspace||null,terminals:H.terminals||0,aiAgents:dw(H.aiAgents||(H.agents||[]).map(he=>({id:he.name,name:he.name,status:he.status,version:he.version}))),activeChat:H.activeChat||null,chats:H.chats||[],childSessions:H.childSessions||[],cdpConnected:H.cdpConnected||!1,daemonId:n,lastMessageAt:H.lastMessageAt})),L=p.filter(H=>H.daemonId===n&&Sr(H)).map(H=>({id:H.id,sessionId:H.sessionId,type:H.type,cliName:H.cliName||H.type,status:H.status,workspace:H.workspace||"",activeChat:H.activeChat||null,providerSessionId:H.providerSessionId,mode:H.mode,runtimeKey:H.runtimeKey,runtimeDisplayName:H.runtimeDisplayName,runtimeWorkspaceLabel:H.runtimeWorkspaceLabel,runtimeWriteOwner:H.runtimeWriteOwner||null,runtimeAttachedClients:H.runtimeAttachedClients||[],daemonId:n,lastMessageAt:H.lastMessageAt})),R=p.filter(H=>H.daemonId===n&&Dn(H)).map(H=>({id:H.id,sessionId:H.sessionId,type:H.type,acpName:H.cliName||H.type,status:H.status,workspace:H.workspace||"",activeChat:H.activeChat||null,providerSessionId:H.providerSessionId,daemonId:n,lastMessageAt:H.lastMessageAt})),M=m?is(m,{fallbackId:n}):"",F="workspace",K=a.state,J=K==null?void 0:K.initialMachineTab,V=K==null?void 0:K.initialWorkspaceCategory;K==null||K.initialWorkspaceId,K==null||K.initialWorkspacePath;const Y=J==="ides"||J==="clis"||J==="acps"?"workspace":J||F,se=J==="ides"?"ide":J==="clis"?"cli":J==="acps"?"acp":V,ie=[...B.map(H=>{var he;return{id:`ide:${H.type}:${H.workspace||""}`,label:((he=H.activeChat)==null?void 0:he.title)||H.type,kind:"ide",providerType:H.type,subtitle:H.workspace||void 0,workspace:H.workspace||void 0,lastLaunchedAt:H.lastMessageAt||0}}),...L.map(H=>{var he;return{id:`cli:${H.type}:${H.workspace||""}`,label:((he=H.activeChat)==null?void 0:he.title)||H.cliName,kind:"cli",providerType:H.type,providerSessionId:H.providerSessionId,subtitle:H.workspace||void 0,workspace:H.workspace||void 0,lastLaunchedAt:H.lastMessageAt||0}}),...R.map(H=>{var he;return{id:`acp:${H.type}:${H.workspace||""}`,label:((he=H.activeChat)==null?void 0:he.title)||H.acpName,kind:"acp",providerType:H.type,providerSessionId:H.providerSessionId,subtitle:mn(H.summaryMetadata)||H.workspace||void 0,workspace:H.workspace||void 0,lastLaunchedAt:H.lastMessageAt||0}})].sort((H,he)=>(he.lastLaunchedAt||0)-(H.lastLaunchedAt||0)),Z=((m==null?void 0:m.recentLaunches)||[]).length>0?((m==null?void 0:m.recentLaunches)||[]).map(H=>({id:H.id,label:H.title||H.providerName||H.providerType,kind:H.kind,providerType:H.providerType,providerSessionId:H.providerSessionId,subtitle:mn(H.summaryMetadata)||H.workspace||void 0,workspace:H.workspace,summaryMetadata:H.summaryMetadata,lastLaunchedAt:H.lastLaunchedAt})):ie,O=l.useMemo(()=>{var he;const H=((he=u.connectionStates)==null?void 0:he[n||""])||void 0;return p.filter(fe=>fe.daemonId===n&&fe.type!=="adhdev-daemon").flatMap(fe=>cl(fe,{connectionStates:n&&H?{[n]:H}:void 0,defaultConnectionState:H})).filter(fe=>!(fe.transport==="pty"&&fe.mode==="terminal")).sort((fe,ye)=>Mi(ye)-Mi(fe))},[p,u.connectionStates,n]),ee=l.useCallback(H=>{const he=xm(H);he&&r(Nr(he))},[r]),G=l.useCallback(()=>{j.current&&(I(!0),j.current().finally(()=>{j.current=null,I(!1),v(null)}))},[]),le=l.useCallback(H=>{if(!E)return;const{options:he,selectedKey:fe}=Cm({machine:E,currentWorkspacePath:H.workspace,homeLabel:t("newSession.homeDirectory"),homeDescription:t("newSession.launchWithoutWorkspace")}),ye=async()=>{C(H.kind),x("workspace")};j.current=async()=>{const Pe=he.find(pe=>pe.key===N.current),He=(Pe==null?void 0:Pe.workspacePath)??null,ke=(Pe==null?void 0:Pe.workspaceId)??null;if(H.kind==="ide"&&H.providerType){await _.handleLaunchIde(H.providerType,He?{workspace:He}:void 0);return}if((H.kind==="cli"||H.kind==="acp")&&H.providerType){await _.runLaunchCliCore({cliType:H.providerType,dir:ke?void 0:He||"",workspaceId:ke||void 0,model:H.kind==="acp"&&qu(H.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:H.providerSessionId});return}await ye()},N.current=fe,A(fe),v({title:H.kind==="ide"?ja(t,"restart-ide",H.label):H.providerSessionId?Fp(t,H.label):ja(t,"start-fresh",H.label),description:H.kind==="ide"?Na(t,"restart-ide"):H.providerSessionId?Bp(t):Na(t,"start-fresh"),confirmLabel:H.kind==="ide"?Aa(t,"restart-ide"):H.providerSessionId?Si(t,!0):Aa(t,"start-fresh"),busyLabel:H.kind==="ide"?Ta(t,"restart-ide"):H.providerSessionId?Hp(t,!0):Ta(t,"start-fresh"),workspaceOptions:he,details:[{label:"Mode",value:H.kind.toUpperCase()},...H.providerType?[{label:"Provider",value:H.providerType}]:[]]})},[_,E]);if(l.useEffect(()=>{x(Y)},[F,Y,n]),l.useEffect(()=>{se&&C(se)},[se,n]),!E)return d?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:t("machine.detail.notFound")}),s.jsx("p",{className:"mt-3",children:t("machine.detail.offlineHint")}),s.jsx("button",{onClick:D,className:"machine-btn-back",children:t("machine.detail.back")})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:t("machine.detail.loading")})});const je=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(xs,{size:14})," ",t("machine.detail.tabWorkspace")]}),count:B.length+L.length+R.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Os,{size:14})," ",t("machine.detail.tabHostedRuntimes")]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ha,{size:14})," ",t("machine.detail.tabProviders")]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(eb,{size:14})," ",t("machine.detail.tabSystem")]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(gu,{size:14})," ",t("machine.detail.tabLogs")]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:D,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[_.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:_.nicknameInput,onChange:H=>_.setNicknameInput(H.target.value),onKeyDown:H=>{H.key==="Enter"&&_.handleSaveNickname(),H.key==="Escape"&&_.setEditingNickname(!1)},placeholder:t("machine.detail.nicknamePlaceholder"),className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:_.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:t("machine.detail.save")}),s.jsx("button",{onClick:()=>_.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:t("machine.detail.cancel")})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{_.setEditingNickname(!0),_.setNicknameInput(E.machineNickname||"")},title:t("machine.detail.clickToSetNickname"),children:M}),S?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),u.retryConnection&&n&&s.jsx("button",{onClick:()=>u.retryConnection(n),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:t("machine.detail.reconnect")})]}):s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[E.platform," · ",E.arch]}),s.jsx("span",{children:t("machine.detail.coresCount",{count:E.cpus})}),(m==null?void 0:m.version)&&s.jsxs("span",{children:["v",m.version]}),E.p2p.available&&s.jsx("span",{children:t("machine.detail.p2pState",{state:E.p2p.state==="connected"?t("machine.detail.p2pConnected"):E.p2p.state})}),E.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:E.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:je.map(H=>s.jsxs("button",{onClick:()=>x(H.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${h===H.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[H.label,H.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${h===H.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:H.count})]},H.id))})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 md:px-8 py-6",children:s.jsx("div",{className:"max-w-7xl mx-auto h-full",children:s.jsxs("div",{className:"h-full",children:[h==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(YD,{machineEntry:m,providers:W,recentLaunches:Z,currentConversations:O,onUpgradeDaemon:async()=>{const H=Qa(m);if(H)try{await o(n,"daemon_upgrade",H)}catch{}},onOpenRecent:le,onOpenConversation:ee}),s.jsx(QD,{machine:E,machineId:n,ideSessions:B,cliSessions:L,acpSessions:R,actions:_,sendDaemonCommand:o})]}),h==="providers"&&s.jsx(rD,{machineId:n,providers:W,sendDaemonCommand:o}),h==="overview"&&s.jsx(zM,{machine:E,ideSessions:B,cliSessions:L,acpSessions:R}),h==="session-host"&&s.jsx(zD,{machineId:n,cliSessions:L,sendDaemonCommand:o}),h==="logs"&&s.jsx(FD,{machineId:n,sendDaemonCommand:o})]})})}),_.launchPick&&E&&s.jsx(KD,{machine:E,launchPick:_.launchPick,actions:_}),k&&s.jsx(Xa,{title:k.title,description:k.description,details:k.details,workspaceOptions:k.workspaceOptions,selectedWorkspaceKey:w,onWorkspaceChange:H=>{N.current=H,A(H)},confirmLabel:k.confirmLabel,busyLabel:k.busyLabel,busy:T,onConfirm:G,onCancel:()=>{j.current=null,v(null)}}),y&&s.jsx(Sh,{daemonId:y.daemonId,workspace:y.workspace,onClose:()=>b(null)}),s.jsx(Op,{toasts:u.toasts||[],onDismiss:H=>u.setToasts(he=>he.filter(fe=>fe.id!==H)),onClickToast:H=>{H.targetKey&&r(Nr(H.targetKey))}}),s.jsx("style",{children:`
115
115
  @keyframes toast-in {
116
116
  from { opacity: 0; transform: translateX(40px); }
117
117
  to { opacity: 1; transform: translateX(0); }
118
118
  }
119
119
  `})]})}function ZD({daemonIds:e,meshId:t,sendData:n,onRevisionAdvance:r}){const a=l.useRef(new Map),o=l.useRef(r);o.current=r;const i=[...new Set(e.filter(Boolean))].sort().join(",");l.useEffect(()=>{a.current=new Map},[i,t]),l.useEffect(()=>{if(!t||!n)return;const c=[...new Set(e.filter(Boolean))];if(c.length===0)return;const u=c.map(p=>fs.subscribe({sendData:n},p,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${p}`,params:{includeSessions:!0}},d=>{if(d.topic!=="daemon.metadata")return;const m=d.meshStateRevisions;if(!m)return;const f=m[t]??m["*"];if(typeof f!="number")return;const g=a.current.get(p);a.current.set(p,f),g!==void 0&&f>g&&o.current()}));return()=>{for(const p of u)p()}},[i,t,n])}const eI={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,queueSection:!0,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},Nh=l.createContext(null);function tI(){const e=l.useContext(Nh);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}function sI({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("polyline",{points:"1 20 1 14 7 14"}),s.jsx("path",{d:"M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"})]})}function nI({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"6",y1:"3",x2:"6",y2:"15"}),s.jsx("circle",{cx:"18",cy:"6",r:"3"}),s.jsx("circle",{cx:"6",cy:"18",r:"3"}),s.jsx("path",{d:"M18 9a9 9 0 0 1-9 9"})]})}function rI({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("polyline",{points:"3 6 5 6 21 6"}),s.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]})}function aI({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function oI({status:e}){const n={online:{color:"#22c55e",label:"Online"},dirty:{color:"#f59e0b",label:"Dirty",title:"Workspace has uncommitted changes"},offline:{color:"#6b7280",label:"Offline"},degraded:{color:"#ef4444",label:"Degraded",title:"P2P connection to this node is down or timed out — often transient. Wait and retry, or re-establish the node's connection."},enabled:{color:"#22c55e",label:"Enabled"},pending:{color:"#a855f7",label:"Pending"},assigned:{color:"#3b82f6",label:"Assigned"},completed:{color:"#22c55e",label:"Completed"},failed:{color:"#ef4444",label:"Failed"},unknown:{color:"#6b7280",label:"Unknown"}}[e]||{color:"#6b7280",label:e};return s.jsxs("span",{className:"inline-flex items-center gap-1 text-[10px] font-semibold px-2 py-0.5 rounded-md",style:{background:n.color+"15",color:n.color,border:`1px solid ${n.color}25`},title:n.title,children:[s.jsx("span",{className:"w-1.5 h-1.5 rounded-full",style:{background:n.color}}),n.label]})}function iI(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function lI({meshes:e,loading:t,error:n,onDismissError:r,daemons:a,features:o,showCreate:i,onToggleCreate:c,createName:u,onCreateNameChange:p,createRepoIdentity:d,onCreateRepoIdentityChange:m,createRepoRemoteUrl:f,onCreateRepoRemoteUrlChange:g,newMeshDaemonId:S,onNewMeshDaemonIdChange:h,newMeshWorkspace:x,onNewMeshWorkspaceChange:y,createPickerWorkspaces:b,createOnboardingPlan:C,createPlanLoading:j,onSelectMesh:k,onCreate:v,onCancelCreate:N}){var D,_;const{t:w}=Ne("common"),A=o.maxMeshes!=null&&e.length>=o.maxMeshes,[T,I]=l.useState(!1),P=T||!!d.trim();return s.jsxs(Lr,{icon:s.jsx(os,{}),title:w("repoMesh.list.title"),subtitle:w("repoMesh.list.count",{count:e.length}),widthClassName:"max-w-5xl",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:c,disabled:A,title:A?w("repoMesh.list.meshLimitReached",{max:o.maxMeshes}):void 0,children:w("repoMesh.list.createMesh")}),children:[A&&s.jsx(Lt,{variant:"info",className:"mb-4",children:w("repoMesh.list.meshLimitBanner",{max:o.maxMeshes})}),n&&s.jsx(Lt,{variant:"error",onDismiss:r,className:"mb-4",children:n}),i&&s.jsxs(gt,{className:"mb-5 border-accent/40 animate-[fadeIn_0.3s_ease-out]",children:[s.jsx("h3",{className:"text-base font-bold mb-4",children:w("repoMesh.list.createTitle")}),o.createDaemonPicker&&s.jsx(At,{label:w("repoMesh.list.createOnMachine"),hint:w("repoMesh.list.createOnMachineHint"),children:s.jsx("select",{className:"input w-full",value:S,onChange:W=>h(W.target.value),disabled:!a.length,children:a.length===0?s.jsx("option",{value:"",children:w("repoMesh.list.noConnectedDaemon")}):a.map(W=>s.jsx("option",{value:W.id,children:iI(W)},W.id))})}),o.createDaemonPicker&&(j||C)&&s.jsx(Lt,{variant:(C==null?void 0:C.success)===!1?"error":"info",className:"mb-4",children:j?"Inspecting Git repository (read-only)…":C!=null&&C.success?`${((D=C.plan)==null?void 0:D.summary)||"Git repository detected."} No changes will be made until you click Create.`:`${(C==null?void 0:C.code)||"onboarding_blocked"}: ${(C==null?void 0:C.error)||"Git discovery failed"} ${(C==null?void 0:C.action)||""}`}),o.createDaemonPicker&&s.jsx(At,{label:w("repoMesh.list.workspace"),hint:w("repoMesh.list.workspaceHint"),children:s.jsx("select",{className:"input w-full",value:x,onChange:W=>y(W.target.value),disabled:!S||!b.length,children:S?b.length===0?s.jsx("option",{value:"",children:w("repoMesh.list.noRegisteredWorkspaces")}):b.map(W=>s.jsx("option",{value:W.path,children:W.label?`${W.label} · ${W.path}`:W.path},W.id||W.path)):s.jsx("option",{value:"",children:w("repoMesh.list.selectMachineFirst")})})}),s.jsx(At,{label:w("repoMesh.list.name"),children:s.jsx(hs,{value:u,onChange:W=>p(W.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(At,{label:w("repoMesh.list.remoteUrl"),hint:w("repoMesh.list.remoteUrlHint"),children:s.jsx(hs,{value:f,onChange:W=>g(W.target.value),placeholder:"https://github.com/user/repo"})}),P?s.jsx(At,{label:w("repoMesh.list.repoIdentity"),hint:w("repoMesh.list.repoIdentityHint"),children:s.jsx(hs,{value:d,onChange:W=>m(W.target.value),placeholder:"github.com/user/repo"})}):s.jsx("button",{type:"button",className:"text-xs text-text-muted hover:text-text-primary underline underline-offset-2 mb-5",onClick:()=>I(!0),children:w("repoMesh.list.advancedIdentityToggle")}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:v,disabled:j||(C==null?void 0:C.success)===!1||(C==null?void 0:C.success)===!0&&((_=C==null?void 0:C.plan)==null?void 0:_.kind)!=="create_mesh_and_onboard"||!u.trim()||!f.trim()&&!d.trim()||o.createDaemonPicker&&(!S||!x),children:w("repoMesh.list.create")}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:N,children:w("repoMesh.list.cancel")})]})]}),t?s.jsx("div",{className:"text-sm text-text-muted p-4",children:w("repoMesh.list.loading")}):e.length===0?s.jsx(Ya,{icon:s.jsx(os,{}),title:w("repoMesh.list.emptyTitle"),description:a.length>0?w("repoMesh.list.emptyWithDaemons"):w("repoMesh.list.emptyNoDaemons"),action:s.jsx("button",{className:"btn btn-primary btn-sm",disabled:!a.length,onClick:c,children:w("repoMesh.list.createFirst")})}):s.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(W=>{var $;return s.jsx("button",{type:"button",onClick:()=>k(W.id),className:"w-full text-left bg-bg-glass border border-border-subtle rounded-xl px-5 py-4 transition-colors hover:border-border-default hover:bg-bg-secondary/70",children:s.jsxs("div",{className:"flex justify-between items-start",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx(os,{size:16}),s.jsx("span",{className:"font-bold text-sm",children:W.name})]}),s.jsxs("div",{className:"text-[12px] text-text-muted flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:W.repoIdentity||W.repo_identity||w("repoMesh.list.noRepoIdentity")}),(W.defaultBranch||W.default_branch)&&s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(nI,{size:11}),W.defaultBranch||W.default_branch]})]})]}),s.jsxs("div",{className:"text-right text-[11px] text-text-muted shrink-0 ml-4",children:[s.jsx("div",{children:new Date(W.createdAt||W.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("div",{className:"text-text-muted/60",children:[(($=W.nodes)==null?void 0:$.length)??W.nodeCount??0," ",w("repoMesh.list.nodesSuffix")]})]})]})},W.id)})})]})}function cI({tabs:e,defaultTabKey:t,ariaLabel:n,className:r}){var i;const[a,o]=l.useState(t??((i=e[0])==null?void 0:i.key));return s.jsxs("div",{className:r,children:[s.jsx("div",{className:"mb-5 inline-flex w-full flex-wrap items-center gap-1 rounded-xl border border-border-subtle bg-bg-secondary/60 p-1 sm:w-fit",role:"tablist","aria-label":n,children:e.map(c=>{const u=c.key===a;return s.jsx("button",{type:"button",role:"tab","aria-selected":u,className:Wt("flex-1 rounded-lg px-3.5 py-1.5 text-[13px] font-medium transition-colors sm:flex-none",u?"bg-bg-card text-text-primary shadow-sm border border-border-default":"text-text-muted border border-transparent hover:text-text-secondary hover:bg-white/[0.03]"),onClick:()=>o(c.key),children:c.label},c.key)})}),e.map(c=>s.jsx("div",{className:c.key===a?"flex flex-col gap-4":"hidden",children:c.content},c.key))]})}const dI=["claude-cli","codex-cli","gemini-cli","hermes-cli","antigravity-cli"],uI=[{kind:"rca",labelKey:"meshGraph.magiKind.kindRca",hint:"rca"},{kind:"design",labelKey:"meshGraph.magiKind.kindDesign",hint:"design"},{kind:"claim_audit",labelKey:"meshGraph.magiKind.kindClaimAudit",hint:"claim_audit"},{kind:"freeform",labelKey:"meshGraph.magiKind.kindFreeform",hint:"freeform"}];function pI(){return{nodeId:"",provider:"",model:"",n:""}}function Gd(e){var t;return(t=e.providers)!=null&&t.length?e.providers.filter(Boolean):(e.providerPriority??[]).filter(Boolean)}function mI(e){return{nodeId:e.nodeId??"",provider:e.provider??"",model:e.model??"",n:e.n!=null?String(e.n):""}}function hI(e){const t=[];for(let n=0;n<e.length;n++){const r=e[n],a=r.provider.trim();if(!a)return{error:{code:"provider_required",slot:n+1}};const o=r.nodeId.trim(),i=r.model.trim(),c=r.n.trim();let u;if(c){const p=Number(c);if(!Number.isFinite(p)||p<1)return{error:{code:"replica_min",slot:n+1}};u=Math.floor(p)}t.push({provider:a,...o?{nodeId:o}:{},...i?{model:i}:{},...u!==void 0?{n:u}:{}})}return t.length===0?{error:{code:"no_slot"}}:{slots:t}}function fI({status:e,daemonId:t,sendDaemonCommand:n,availableProviders:r}){const{t:a}=Ne(),{theme:o}=qs(),i=l.useMemo(()=>zs(o),[o]),c=l.useMemo(()=>Kp(r),[r]),[u,p]=l.useState({}),[d,m]=l.useState(!1),[f,g]=l.useState(null),[S,h]=l.useState({}),[x,y]=l.useState(null),b=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(M=>({nodeId:M.nodeId,machineLabel:M.machineLabel,providers:M.providers,providerPriority:M.providerPriority})),[e==null?void 0:e.nodes]),C=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(M=>M.nodeId),[e==null?void 0:e.nodes]),j=l.useMemo(()=>Object.fromEntries(((e==null?void 0:e.nodes)??[]).map(M=>[M.nodeId,M.machineLabel||M.nodeId])),[e==null?void 0:e.nodes]),k=l.useMemo(()=>{const M={};for(const F of b)M[F.nodeId]=Gd(F);return M},[b]),v=l.useMemo(()=>{const M=[...new Set(b.flatMap(Gd).filter(Boolean))];return[...new Set([...M,...dI])].sort()},[b]),N=!!t&&!!n,w=M=>M&&typeof M=="object"&&"result"in M?M.result:M,A=e==null?void 0:e.meshId,T=l.useCallback(async()=>{if(!(!t||!n)){m(!0),g(null);try{const M=await n(t,"magi_kind_panel_list",{...A?{meshId:A}:{}}),F=w(M);if((F==null?void 0:F.success)===!1)throw new Error(F.error||a("meshGraph.magiKind.errorLoad"));p(F!=null&&F.kindPanels&&typeof F.kindPanels=="object"?F.kindPanels:{}),h({})}catch(M){g((M==null?void 0:M.message)||a("meshGraph.magiKind.errorLoad"))}finally{m(!1)}}},[t,n,A,a]);l.useEffect(()=>{T()},[T]);const I=l.useCallback(M=>{if(S[M])return S[M];const F=u[M];return F?F.map(mI):[]},[S,u]),P=(M,F)=>{h(K=>({...K,[M]:F}))},D=(M,F,K)=>{const J=I(M);P(M,J.map((V,Y)=>Y===F?{...V,...K}:V))},_=M=>{P(M,[...I(M),pI()])},W=(M,F)=>{P(M,I(M).filter((K,J)=>J!==F))},$=l.useCallback(async M=>{if(!t||!n)return;const F=hI(I(M));if("error"in F){const K=F.error,J=K.code==="provider_required"?a("meshGraph.magiKind.errorSlotProvider",{slot:K.slot}):K.code==="replica_min"?a("meshGraph.magiKind.errorSlotReplica",{slot:K.slot}):a("meshGraph.magiKind.errorNoSlot");g(`${M}: ${J}`);return}y(M),g(null);try{const K=await n(t,"magi_kind_panel_set",{kind:M,slots:F.slots,...A?{meshId:A}:{}}),J=w(K);if((J==null?void 0:J.success)===!1)throw new Error(J.error||a("meshGraph.magiKind.errorSave"));await T()}catch(K){g((K==null?void 0:K.message)||a("meshGraph.magiKind.errorSave"))}finally{y(null)}},[t,n,I,T,A,a]),E=l.useCallback(async M=>{if(!(!t||!n)&&confirm(a("meshGraph.magiKind.removeConfirm",{kind:M}))){y(M),g(null);try{const F=await n(t,"magi_kind_panel_remove",{kind:M,...A?{meshId:A}:{}}),K=w(F);if((K==null?void 0:K.success)===!1)throw new Error(K.error||a("meshGraph.magiKind.errorRemove"));await T()}catch(F){g((F==null?void 0:F.message)||a("meshGraph.magiKind.errorRemove"))}finally{y(null)}}},[t,n,T,A,a]),B=`w-full rounded-lg border px-2.5 py-1.5 text-xs ${i.isDark?"border-white/10 bg-slate-950/40 text-slate-100 placeholder:text-slate-500":"border-slate-300 bg-white text-slate-900 placeholder:text-slate-400"}`,L="btn btn-primary btn-sm",R="btn btn-secondary btn-sm";return s.jsxs("div",{className:"flex flex-col gap-3 p-1",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("p",{className:`text-[12px] ${i.textSecondary}`,children:a("meshGraph.magiKind.intro")}),s.jsx("div",{className:"ml-auto flex items-center gap-2",children:s.jsx("button",{type:"button",className:R,onClick:()=>void T(),disabled:d||!N,children:a(d?"meshGraph.magiKind.loading":"meshGraph.magiKind.refresh")})})]}),!N&&s.jsx("div",{className:`rounded-xl border p-3 text-[12px] ${i.textSecondary} ${i.isDark?"border-white/10":"border-slate-200"}`,children:a("meshGraph.magiKind.connectPrompt")}),f&&s.jsx("div",{className:"rounded-xl border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-[12px] text-rose-300",children:f}),s.jsx("div",{className:"flex flex-col gap-3",children:uI.map(({kind:M,labelKey:F,hint:K})=>{const J=I(M),V=!!u[M],Y=x===M;return s.jsxs("div",{className:`${i.cardClass} rounded-2xl p-4 flex flex-col gap-3`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[13px] font-semibold ${i.textPrimary}`,children:a(F)}),s.jsx("span",{className:`font-mono text-[10px] ${i.textMuted}`,children:K}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${V?"border-emerald-400/30 bg-emerald-500/10 text-emerald-300":"border-slate-400/20 bg-slate-500/10 text-slate-300"}`,children:V?a("meshGraph.magiKind.agentCount",{count:u[M].length}):a("meshGraph.magiKind.off")})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[J.length===0&&s.jsx("div",{className:`rounded-xl border p-2.5 text-[11px] ${i.textSecondary} ${i.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:a("meshGraph.magiKind.noAgents")}),J.map((se,ie)=>{const Z=se.nodeId?k[se.nodeId]??[]:[],O=se.nodeId&&Z.length?Z:v;return s.jsxs("div",{className:`rounded-xl border p-2.5 grid grid-cols-1 sm:grid-cols-[1fr_1fr_1fr_auto_auto] gap-x-2 gap-y-1 items-start ${i.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:a("meshGraph.magiKind.machine")}),s.jsxs("select",{className:B,value:se.nodeId,onChange:ee=>D(M,ie,{nodeId:ee.target.value}),title:a("meshGraph.magiKind.machineTitle"),children:[s.jsx("option",{value:"",children:a("meshGraph.magiKind.anyMachine")}),C.map(ee=>s.jsx("option",{value:ee,children:j[ee]??ee},ee)),se.nodeId&&!C.includes(se.nodeId)&&s.jsx("option",{value:se.nodeId,children:a("meshGraph.magiKind.offlineSuffix",{label:j[se.nodeId]??se.nodeId})})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsxs("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:[a("meshGraph.magiKind.provider")," *"]}),s.jsxs("select",{className:B,value:se.provider,onChange:ee=>D(M,ie,{provider:ee.target.value}),title:a("meshGraph.magiKind.providerTitle"),children:[s.jsx("option",{value:"",children:a("meshGraph.magiKind.selectProvider")}),O.map(ee=>s.jsx("option",{value:ee,children:ee},ee)),se.provider&&!O.includes(se.provider)&&s.jsx("option",{value:se.provider,children:se.provider})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:a("meshGraph.magiKind.model")}),(()=>{var le;const ee=(se.provider?(le=c.get(se.provider))==null?void 0:le.models:void 0)??[],G=!!se.model&&ee.length>0&&!ee.includes(se.model);return ee.length>0&&!G?s.jsxs("select",{className:B,value:ee.includes(se.model)?se.model:"",title:a("meshGraph.magiKind.modelTitle"),onChange:je=>D(M,ie,{model:je.target.value==="__custom__"?" ":je.target.value}),children:[s.jsx("option",{value:"",children:a("meshGraph.magiKind.modelDefault")}),ee.map(je=>s.jsx("option",{value:je,children:je},je)),s.jsx("option",{value:"__custom__",children:a("meshGraph.magiKind.modelCustom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:B,value:se.model.trim(),placeholder:a("meshGraph.magiKind.modelDefault"),title:a("meshGraph.magiKind.modelTitle"),onChange:je=>D(M,ie,{model:je.target.value})}),ee.length>0&&s.jsx("button",{type:"button",className:`self-start bg-transparent border-none cursor-pointer p-0 text-[10px] ${i.textSecondary} hover:underline`,onClick:()=>D(M,ie,{model:""}),children:a("meshGraph.magiKind.backToModelList")})]})})()]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:a("meshGraph.magiKind.copies")}),s.jsx("input",{className:`${B} sm:w-16`,value:se.n,placeholder:"1",inputMode:"numeric",title:a("meshGraph.magiKind.copiesTitle"),onChange:ee=>D(M,ie,{n:ee.target.value})})]}),s.jsx("button",{type:"button",className:`${R} sm:mt-[18px] inline-flex h-8 w-8 items-center justify-center p-0`,onClick:()=>W(M,ie),"aria-label":a("meshGraph.magiKind.removeAgent"),title:a("meshGraph.magiKind.removeAgent"),children:"✕"})]},ie)}),s.jsx("div",{children:s.jsx("button",{type:"button",className:R,onClick:()=>_(M),disabled:!N,children:a("meshGraph.magiKind.addAgent")})})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:L,onClick:()=>void $(M),disabled:Y||!N,children:a(Y?"meshGraph.magiKind.saving":"meshGraph.magiKind.save")}),s.jsx("button",{type:"button",className:R,onClick:()=>void E(M),disabled:Y||!N||!V,title:a(V?"meshGraph.magiKind.removeBindingTitle":"meshGraph.magiKind.removeBindingDisabledTitle"),children:a("meshGraph.magiKind.removeBinding")})]})]},M)})})]})}function bI({daemonId:e,meshId:t,cliType:n,sendCommand:r}){const{t:a}=Ne(),[o,i]=l.useState(!1),[c,u]=l.useState(!1),[p,d]=l.useState(null),[m,f]=l.useState(null),[g,S]=l.useState(null),h=l.useCallback(async()=>{if(!e||!t){d(a("repoMesh.promptPreview.connectPrompt"));return}u(!0),d(null);try{const y=await r(e,"coordinator_prompt_preview",{meshId:t,cliType:n}),b=y!=null&&y.result&&typeof y.result=="object"?y.result:y;if(!(b!=null&&b.success)){d((b==null?void 0:b.error)||a("repoMesh.promptPreview.errorRender"));return}f(typeof b.prompt=="string"?b.prompt:""),S(typeof b.bytes=="number"?b.bytes:null)}catch(y){d((y==null?void 0:y.message)||String(y))}finally{u(!1)}},[e,t,n,r,a]),x=l.useCallback(()=>{const y=!o;i(y),y&&m===null&&!c&&h()},[o,m,c,h]);return s.jsxs("div",{className:"mt-2",children:[s.jsxs("button",{type:"button",onClick:x,className:"inline-flex items-center gap-1 text-[12px] text-accent-primary bg-transparent border-none cursor-pointer p-0",children:[s.jsx("span",{className:`transition-transform ${o?"rotate-90":""}`,"aria-hidden":!0,children:"▸"}),a(o?"repoMesh.promptPreview.hide":"repoMesh.promptPreview.view"),s.jsxs("span",{className:"text-text-muted",children:["(",n,")"]})]}),o&&s.jsxs("div",{className:"mt-2",children:[c&&s.jsx("div",{className:"text-[12px] text-text-muted",children:a("repoMesh.promptPreview.rendering")}),p&&s.jsxs("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:[p,s.jsx("button",{type:"button",onClick:()=>void h(),className:"ml-2 underline bg-transparent border-none cursor-pointer text-amber-300",children:a("repoMesh.promptPreview.retry")})]}),!c&&!p&&m!==null&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between text-[11px] text-text-muted",children:[s.jsx("span",{children:a("repoMesh.promptPreview.info")}),g!==null&&s.jsxs("span",{children:[(g/1024).toFixed(1)," KB"]})]}),s.jsx("textarea",{readOnly:!0,value:m,rows:14,className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-secondary font-mono",onFocus:y=>y.currentTarget.select()})]})]})]})}const gI=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function xI(e){const t=gI(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function vI(e){const t=e==null?void 0:e.missions;return Array.isArray(t)?t:[]}function yI(e){return typeof e.goal=="string"&&e.goal?{text:e.goal,truncated:!1}:{text:e.goalPreview??"",truncated:e.goalTruncated===!0}}const wI=["active","paused","completed","abandoned"];function qd(e){return(e.status||"active").toLowerCase()}const kI=8;function SI({status:e,daemonId:t,meshId:n,sendCommand:r}){const{t:a}=Ne("common"),o=l.useMemo(()=>vI(e),[e]),[i,c]=l.useState({}),[u,p]=l.useState({}),[d,m]=l.useState(!1),[f,g]=l.useState(null),[S,h]=l.useState("active"),[x,y]=l.useState(!1),b=l.useMemo(()=>{const A={};for(const T of o){const I=qd(T);A[I]=(A[I]||0)+1}return A},[o]),C=l.useMemo(()=>S==="all"?o:o.filter(A=>qd(A)===S),[o,S]),j=x?C:C.slice(0,kI),k=C.length-j.length,v=!!t&&o.length>0,N=l.useCallback(async()=>{if(t){m(!0),g(null);try{const A=await r(t,"mesh_status",{meshId:n,verbose:!0}),T=xI(A),I=Array.isArray(T==null?void 0:T.missions)?T.missions:[],P={};for(const D of I)D.id&&typeof D.goal=="string"&&D.goal&&(P[D.id]=D.goal);c(D=>({...D,...P}))}catch(A){g(A instanceof Error?A.message:a("repoMesh.missions.errorFetch"))}finally{m(!1)}}},[t,n,r,a]),w=l.useCallback(A=>{p(T=>({...T,[A]:!T[A]})),!u[A]&&!i[A]&&N()},[u,i,N]);return o.length===0?null:s.jsxs(gt,{title:a("repoMesh.missions.title"),description:a("repoMesh.missions.description"),children:[f&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400",children:f}),s.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-1.5",children:[wI.filter(A=>(b[A]||0)>0).map(A=>s.jsxs("button",{type:"button",onClick:()=>{h(A),y(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] capitalize transition-colors ${S===A?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:[A," ",b[A]]},A)),s.jsxs("button",{type:"button",onClick:()=>{h("all"),y(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] transition-colors ${S==="all"?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:["All ",o.length]})]}),C.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:a("repoMesh.missions.empty",{status:S})}),s.jsx("div",{className:"flex flex-col gap-2",children:j.map(A=>{var $;const T=u[A.id]===!0,I=i[A.id],P=yI(A),D=T&&I?I:P.text,_=T&&!I&&P.truncated,W=(($=A.tasks)==null?void 0:$.total)??0;return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 px-3 py-2.5",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:"min-w-0 flex-1 truncate text-sm font-medium text-text-primary",title:A.title,children:A.title||A.id}),A.status&&s.jsx("span",{className:"shrink-0 rounded-full border border-border-subtle px-2 py-0.5 text-[10px] uppercase tracking-wide text-text-muted",children:A.status}),W>0&&s.jsx("span",{className:"shrink-0 text-[11px] text-text-muted",children:a("repoMesh.missions.taskCount",{count:W})})]}),D&&s.jsxs("div",{className:`mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-text-secondary ${T?"max-h-72 overflow-y-auto":"line-clamp-2"}`,children:[D,_&&s.jsx("span",{className:"text-text-muted",children:a("repoMesh.missions.goalUnavailable")})]}),(P.truncated||I)&&v&&s.jsx("button",{type:"button",className:"mt-1.5 text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:()=>w(A.id),disabled:d,children:a(T?"repoMesh.missions.showLess":d&&!I?"repoMesh.missions.loading":"repoMesh.missions.showFullGoal")})]},A.id)})}),k>0&&s.jsx("button",{type:"button",className:"mt-2 text-[12px] text-accent-primary hover:underline",onClick:()=>y(!0),children:a("repoMesh.missions.showMore",{count:k})})]})}function zd(e,t){if(t)return e.modes.find(n=>n.id===t)}function CI(e){return e.modes.find(t=>t.strategy==="pty-parse-default"&&Ps(t)!=="dangerous")}function jI({config:e,requestedModeId:t,machineAutoApproveEnabled:n,machineDangerousAllowed:r}){const a=zd(e,e.default),o=a==null?void 0:a.id,i=(t==null?void 0:t.trim())||void 0;if(!n)return{status:"disabled",requestedModeId:i,providerDefaultModeId:o,requestedModeUnknown:!1,downgraded:!1};const c=zd(e,i),u=!!i&&!c,p=c??a;if(!p||p.strategy==="post-boot-command")return{status:"none",requestedModeId:i,providerDefaultModeId:o,requestedModeUnknown:u,downgraded:!1};if(Ps(p)==="dangerous"&&!r){const d=CI(e);return{status:d?"downgraded":"none",requestedModeId:i,providerDefaultModeId:o,effectiveMode:d,requestedModeUnknown:u,downgraded:!0}}return{status:u?"invalid_fallback":"requested",requestedModeId:i,providerDefaultModeId:o,effectiveMode:p,requestedModeUnknown:u,downgraded:!1}}function NI(e){const t=[];for(const n of e||[]){if(!n||n.category!=="cli")continue;const r=n.autoApproveModes;if(!r||!Array.isArray(r.modes)||r.modes.length===0)continue;const a=String(n.type||n.id||"").trim();a&&t.push({type:a,label:String(n.displayName||n.name||a),autoApproveModes:r})}return t}function AI({hostDaemonId:e,hostOnline:t,hostWorkspace:n,hostProviders:r,machineAutoApproveEnabled:a,machineDangerousAllowed:o,onUpdatePolicy:i,savingPolicy:c,sendCommand:u}){const{t:p}=Ne("common"),d=l.useMemo(()=>NI(r),[r]),[m,f]=l.useState({}),[g,S]=l.useState(!1),[h,x]=l.useState(null),[y,b]=l.useState(!1),[C,j]=l.useState(null),[k,v]=l.useState(!1),[N,w]=l.useState(null),[A,T]=l.useState(!1),I=!!e&&t&&!!n,P=!!i&&!c,D=l.useCallback(async()=>{var B,L,R;if(I){S(!0),x(null);try{const M=await u(e,"read_mesh_json_config",{workspace:n}),F=(M==null?void 0:M.result)??M,K=((B=F==null?void 0:F.providerDefaults)==null?void 0:B.autoApproveModes)||((R=(L=F==null?void 0:F.config)==null?void 0:L.providerDefaults)==null?void 0:R.autoApproveModes),J={};if(K&&typeof K=="object")for(const[V,Y]of Object.entries(K))typeof Y=="string"&&Y.trim()&&(J[V]=Y.trim());f(J)}catch(M){x((M==null?void 0:M.message)||p("repoMesh.providerAutoApprove.loadError"))}finally{S(!1)}}},[I,e,n,u,p]);l.useEffect(()=>{D()},[D]);const _=l.useCallback((B,L)=>{v(!1),f(R=>{const M={...R};return L&&L.trim()?M[B]=L.trim():delete M[B],M})},[]),W=l.useCallback((B,L)=>{if(Ps(L)==="dangerous"){w({type:B,mode:L});return}_(B,L.id)},[_]),$=l.useCallback(()=>{N&&_(N.type,N.mode.id),w(null)},[_,N]),E=l.useCallback(async()=>{if(I){b(!0),j(null),v(!1);try{const B=await u(e,"set_mesh_provider_defaults",{workspace:n,autoApproveModes:m,merge:!1,write:!0}),L=(B==null?void 0:B.result)??B;if((L==null?void 0:L.success)===!1)throw new Error((L==null?void 0:L.error)||p("repoMesh.providerAutoApprove.saveError"));v(!0),await D()}catch(B){j((B==null?void 0:B.message)||p("repoMesh.providerAutoApprove.saveError"))}finally{b(!1)}}},[I,e,n,D,m,u,p]);return s.jsxs(gt,{title:p("repoMesh.providerAutoApprove.title"),description:p("repoMesh.providerAutoApprove.subtitle"),collapsible:!0,defaultOpen:!1,children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/40 p-3.5",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:p("repoMesh.providerAutoApprove.machineSection.title")}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:p("repoMesh.providerAutoApprove.machineSection.hint")}),s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2 text-[11px]",children:[s.jsx("span",{className:`rounded-full border px-2 py-0.5 font-semibold ${a?"border-status-online/25 bg-status-online/10 text-status-online":"border-border-subtle bg-bg-tertiary/40 text-text-muted"}`,children:p(a?"repoMesh.providerAutoApprove.machineSection.autoApproveOn":"repoMesh.providerAutoApprove.machineSection.autoApproveOff")}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 font-semibold ${o?"border-status-error/30 bg-status-error/10 text-status-error":"border-border-subtle bg-bg-tertiary/40 text-text-muted"}`,children:p(o?"repoMesh.providerAutoApprove.machineSection.dangerousOn":"repoMesh.providerAutoApprove.machineSection.dangerousOff")})]}),s.jsxs("div",{className:"mt-3 space-y-2",children:[s.jsx(Kd,{label:p("repoMesh.providerAutoApprove.machineSection.autoApproveToggleLabel"),hint:p("repoMesh.providerAutoApprove.machineSection.autoApproveToggleHint"),checked:a,disabled:!P,onChange:B=>i==null?void 0:i({delegatedWorkerAutoApprove:B})}),s.jsx(Kd,{label:p("repoMesh.providerAutoApprove.machineSection.dangerousToggleLabel"),hint:p(a?"repoMesh.providerAutoApprove.machineSection.dangerousToggleHint":"repoMesh.providerAutoApprove.machineSection.dangerousDisabledHint"),checked:o,disabled:!P||!a,onChange:B=>{B?T(!0):i==null||i({delegatedWorkerDangerousModeAllow:!1})}})]})]}),I?g?s.jsx("div",{className:"text-[13px] text-text-muted",children:p("repoMesh.providerAutoApprove.loading")}):d.length===0?s.jsx("div",{className:"text-[13px] text-text-muted",children:p("repoMesh.providerAutoApprove.noProviders")}):s.jsxs("div",{className:"space-y-6",children:[h&&s.jsx(Lt,{variant:"error",onDismiss:()=>x(null),children:h}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:p("repoMesh.providerAutoApprove.repoSection.title")}),s.jsx("div",{className:"text-[11px] text-text-muted",children:p("repoMesh.providerAutoApprove.repoSection.hint")})]}),s.jsx("div",{className:"space-y-5",children:d.map(B=>{const L=m[B.type],R=jI({config:B.autoApproveModes,requestedModeId:L,machineAutoApproveEnabled:a,machineDangerousAllowed:o});return s.jsxs("div",{className:"rounded-xl border border-border-subtle p-3.5",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary",children:B.label}),s.jsx("button",{type:"button",className:"text-[11px] text-text-muted underline decoration-dotted hover:text-text-primary disabled:opacity-40",onClick:()=>_(B.type,void 0),disabled:!L||y,children:p("repoMesh.providerAutoApprove.repoSection.clear")})]}),s.jsx(Om,{config:B.autoApproveModes,selectedModeId:L||"",disabled:y,onSelectMode:M=>W(B.type,M)}),!L&&s.jsx("div",{className:"mt-1.5 text-[11px] text-text-muted",children:p("repoMesh.providerAutoApprove.repoSection.usesProviderDefault")}),s.jsx(TI,{effective:R,config:B.autoApproveModes})]},B.type)})}),s.jsxs("div",{className:"space-y-1",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:p("repoMesh.providerAutoApprove.effectiveSection.title")}),s.jsx("div",{className:"text-[11px] text-text-muted",children:p("repoMesh.providerAutoApprove.effectiveSection.hint")})]}),C&&s.jsx(Lt,{variant:"error",onDismiss:()=>j(null),children:C}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("button",{type:"button",className:"rounded-lg bg-accent-primary px-4 py-2 text-sm font-semibold text-white disabled:opacity-50",onClick:()=>void E(),disabled:y,children:p(y?"repoMesh.providerAutoApprove.saving":"repoMesh.providerAutoApprove.save")}),k&&s.jsx("span",{className:"text-[12px] text-status-online",children:p("repoMesh.providerAutoApprove.saved")})]})]}):s.jsx("div",{className:"text-[13px] text-text-muted",children:p("repoMesh.providerAutoApprove.noHostDaemon")}),A&&s.jsx(Xa,{title:p("repoMesh.providerAutoApprove.machineSection.confirmTitle"),description:p("repoMesh.providerAutoApprove.machineSection.confirmDescription"),details:[{label:p("repoMesh.providerAutoApprove.machineSection.confirmScopeLabel"),value:p("repoMesh.providerAutoApprove.machineSection.confirmScopeValue")},{label:p("repoMesh.providerAutoApprove.machineSection.confirmEffectLabel"),value:p("repoMesh.providerAutoApprove.machineSection.confirmEffectValue")}],confirmLabel:p("repoMesh.providerAutoApprove.machineSection.confirmConfirm"),onConfirm:()=>{T(!1),i==null||i({delegatedWorkerDangerousModeAllow:!0})},onCancel:()=>T(!1)}),N&&s.jsx(Um,{mode:N.mode,onConfirm:$,onCancel:()=>w(null)}),N&&s.jsx("div",{className:"fixed inset-x-0 bottom-6 z-[60] mx-auto max-w-lg px-4",children:s.jsxs("div",{className:"rounded-xl border border-status-error/40 bg-bg-primary p-3.5 shadow-lg",children:[s.jsx("div",{className:"text-sm font-semibold text-status-error",children:p("repoMesh.providerAutoApprove.dangerous.sharedWarningTitle")}),s.jsx("div",{className:"mt-1 text-[12px] text-text-muted",children:p("repoMesh.providerAutoApprove.dangerous.sharedWarning")})]})})]})}function TI({effective:e,config:t}){var c,u,p;const{t:n}=Ne("common"),r=d=>{var m;return(d?(m=t.modes.find(f=>f.id===d))==null?void 0:m.label:void 0)||d||""};let a,o="ok";switch(e.status){case"requested":a=n("repoMesh.providerAutoApprove.effectiveSection.statusRequested",{mode:((c=e.effectiveMode)==null?void 0:c.label)||""});break;case"invalid_fallback":a=n("repoMesh.providerAutoApprove.effectiveSection.statusInvalidFallback",{mode:((u=e.effectiveMode)==null?void 0:u.label)||""}),o="warn";break;case"downgraded":a=n("repoMesh.providerAutoApprove.effectiveSection.statusDowngraded",{requested:r(e.requestedModeId)||r(e.providerDefaultModeId),mode:((p=e.effectiveMode)==null?void 0:p.label)||""}),o="warn";break;case"disabled":a=n("repoMesh.providerAutoApprove.effectiveSection.statusDisabled"),o="muted";break;default:a=n("repoMesh.providerAutoApprove.effectiveSection.statusNone"),o="muted"}const i=o==="ok"?"border-status-online/25 bg-status-online/5 text-text-secondary":o==="warn"?"border-status-warning/30 bg-status-warning/5 text-status-warning":"border-border-subtle bg-bg-tertiary/30 text-text-muted";return s.jsxs("div",{className:`mt-3 flex items-center gap-2 rounded-lg border px-3 py-2 text-[12px] ${i}`,children:[e.effectiveMode&&s.jsx(Wm,{risk:Ps(e.effectiveMode)}),s.jsx("span",{className:"min-w-0",children:a})]})}function Kd({label:e,hint:t,checked:n,disabled:r=!1,onChange:a}){return s.jsxs("button",{type:"button",role:"switch","aria-checked":n,className:"flex w-full items-center justify-between gap-3 rounded-xl border border-border-subtle bg-bg-primary/60 px-3.5 py-2.5 text-left disabled:opacity-50",onClick:()=>a(!n),disabled:r,children:[s.jsxs("span",{children:[s.jsx("span",{className:"block text-[13px] font-semibold text-text-primary",children:e}),s.jsx("span",{className:"mt-0.5 block text-[11px] text-text-muted",children:t})]}),s.jsx("span",{className:`relative h-6 w-11 shrink-0 rounded-full transition-colors ${n?"bg-accent-primary":"bg-bg-tertiary"}`,children:s.jsx("span",{className:`absolute top-0.5 h-5 w-5 rounded-full bg-white shadow transition-transform ${n?"translate-x-5":"translate-x-0.5"}`})})]})}const MI=["","low","medium","high"],DI={easy:"Easy",medium:"Medium",difficult:"Difficult",freeform:"Freeform"};function Vd(e){return{provider:e.provider||"",model:e.model||"",thinkingLevel:e.thinkingLevel||"",difficulty:Array.isArray(e.difficulty)?e.difficulty:[],capability:Array.isArray(e.capability)?e.capability:[],maxParallel:e.maxParallel!=null?String(e.maxParallel):""}}function Yd(e){const t=e.provider.trim();if(!t)return null;const n=e.model.trim(),r=e.thinkingLevel.trim()||void 0,a=Number(e.maxParallel),o=Number.isFinite(a)&&a>0?Math.floor(a):void 0;return{provider:t,...n?{model:n}:{},...r?{thinkingLevel:r}:{},...e.difficulty.length?{difficulty:e.difficulty}:{},...e.capability.length?{capability:e.capability}:{},...o!==void 0?{maxParallel:o}:{}}}function II(){return{provider:"",model:"",thinkingLevel:"",difficulty:[],capability:[],maxParallel:""}}const Zs="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function PI({slots:e,availableProviders:t,saving:n,onSave:r}){const{t:a}=Ne("common"),[o,i]=l.useState(()=>e.map(Vd)),c=l.useMemo(()=>JSON.stringify(e),[e]);l.useEffect(()=>{i(e.map(Vd))},[c]);const u=l.useMemo(()=>[...new Set(t.map(b=>b.type).filter(Boolean))],[t]),p=l.useMemo(()=>Kp(t),[t]),d=l.useMemo(()=>{const b=o.map(Yd).filter(Boolean);return JSON.stringify(b)!==JSON.stringify(e)},[o,e]),m=(b,C)=>i(j=>j.map((k,v)=>v===b?{...k,...C}:k)),f=(b,C)=>i(j=>j.map((k,v)=>{var A;if(v!==b)return k;const N=((A=p.get(C))==null?void 0:A.models)??[],w=!k.model||N.length===0||N.includes(k.model);return{...k,provider:C,...w?{}:{model:""}}})),g=b=>i(C=>C.filter((j,k)=>k!==b)),S=()=>i(b=>[...b,II()]),h=(b,C)=>i(j=>{const k=b+C;if(k<0||k>=j.length)return j;const v=[...j];return[v[b],v[k]]=[v[k],v[b]],v}),x=(b,C)=>i(j=>j.map((k,v)=>{if(v!==b)return k;const N=k.difficulty.includes(C);return{...k,difficulty:N?k.difficulty.filter(w=>w!==C):[...k.difficulty,C]}})),y=()=>r(o.map(Yd).filter(Boolean));return s.jsxs("div",{className:"flex flex-col gap-2",onClick:b=>b.stopPropagation(),children:[o.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:a("repoMesh.slotEditor.empty")}),o.map((b,C)=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/40 p-2.5",children:[s.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[s.jsxs("span",{className:"text-[11px] font-semibold text-text-muted",children:["#",C+1]}),s.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:C===0,onClick:()=>h(C,-1),title:a("repoMesh.slotEditor.moveUp"),children:"↑"}),s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:C===o.length-1,onClick:()=>h(C,1),title:a("repoMesh.slotEditor.moveDown"),children:"↓"}),s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-status-error/30 text-status-error hover:bg-status-error/10",onClick:()=>g(C),"aria-label":a("repoMesh.slotEditor.removeSlot"),children:s.jsx(Mt,{size:12})})]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:a("repoMesh.slotEditor.provider")}),u.length>0?s.jsxs("select",{className:Zs,value:b.provider,onChange:j=>f(C,j.target.value),children:[s.jsx("option",{value:"",children:a("repoMesh.slotEditor.select")}),u.map(j=>s.jsx("option",{value:j,children:j},j)),b.provider&&!u.includes(b.provider)&&s.jsx("option",{value:b.provider,children:b.provider})]}):s.jsx("input",{className:Zs,value:b.provider,placeholder:"claude-cli",onChange:j=>m(C,{provider:j.target.value})})]}),(()=>{var w;const j=p.get(b.provider),k=(j==null?void 0:j.models)??[],v=(w=j==null?void 0:j.thinking)!=null&&w.length?["",...j.thinking]:MI,N=!!b.model&&k.length>0&&!k.includes(b.model);return s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:a("repoMesh.slotEditor.model")}),k.length>0&&!N?s.jsxs("select",{className:Zs,value:k.includes(b.model)?b.model:"",onChange:A=>m(C,{model:A.target.value==="__custom__"?" ":A.target.value}),children:[s.jsx("option",{value:"",children:a("repoMesh.slotEditor.providerDefault")}),k.map(A=>s.jsx("option",{value:A,children:A},A)),s.jsx("option",{value:"__custom__",children:a("repoMesh.slotEditor.custom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:Zs,value:b.model.trim(),placeholder:b.provider?`${b.provider} model`:a("repoMesh.slotEditor.modelPlaceholder"),onChange:A=>m(C,{model:A.target.value})}),k.length>0&&s.jsx("button",{type:"button",className:"self-start bg-transparent border-none cursor-pointer p-0 text-[10px] text-text-muted hover:underline",onClick:()=>m(C,{model:""}),children:a("repoMesh.slotEditor.backToModelList")})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:a("repoMesh.slotEditor.thinking")}),s.jsx("select",{className:Zs,value:b.thinkingLevel,onChange:A=>m(C,{thinkingLevel:A.target.value}),children:v.map(A=>s.jsx("option",{value:A,children:A||a("repoMesh.slotEditor.thinkingDefault")},A||"_default"))})]})]})})()]}),s.jsxs("div",{className:"mt-2",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:a("repoMesh.slotEditor.difficulty")}),s.jsx("div",{className:"mt-1 flex flex-wrap gap-1.5",children:Qy.map(j=>{const k=b.difficulty.includes(j);return s.jsx("button",{type:"button",className:`rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors ${k?"border-accent-primary/60 bg-accent-primary/15 text-accent-primary":"border-border-subtle bg-bg-primary/60 text-text-muted hover:text-text-primary"}`,onClick:()=>x(C,j),children:DI[j]},j)})})]}),s.jsxs("div",{className:"mt-2 grid grid-cols-1 sm:grid-cols-2 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:a("repoMesh.slotEditor.capabilityTags")}),s.jsx("input",{className:Zs,value:b.capability.join(", "),placeholder:"worktree, os=darwin",onChange:j=>m(C,{capability:j.target.value.split(",").map(k=>k.trim()).filter(Boolean)})})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:a("repoMesh.slotEditor.maxParallel")}),s.jsx("input",{type:"number",inputMode:"numeric",min:1,className:Zs,value:b.maxParallel,placeholder:a("repoMesh.slotEditor.maxParallelPlaceholder"),onChange:j=>m(C,{maxParallel:j.target.value})})]})]})]},C)),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1",onClick:S,children:[s.jsx(zi,{size:13})," ",a("repoMesh.slotEditor.addSlot")]}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:y,disabled:!!n||!d,children:a(n?"repoMesh.slotEditor.saving":"repoMesh.slotEditor.saveSlots")})]})]})}function LI(e){const t=new Map;for(const n of e)n!=null&&n.id&&t.set(n.id,Hn(n.availableProviders||[]));return t}function RI(e,t){const n=String(e.daemon_id||e.daemonId||"");return n&&t.has(n)?t.get(n):!n&&t.size===1?[...t.values()][0]:[]}function EI(e){var u,p,d;const t=e,n=[],r=Array.isArray(t.capabilities)?t.capabilities:[];for(const m of r){const f=typeof m=="string"?m.trim():"";f&&n.push({tag:f,custom:!0})}const a=(((u=t.userOverrides)==null?void 0:u.platform)||t.reportedPlatform||"").toString().trim(),o=(((p=t.userOverrides)==null?void 0:p.arch)||t.reportedArch||"").toString().trim();a&&n.push({tag:`os=${a}`,custom:!1}),o&&n.push({tag:`arch=${o}`,custom:!1});const i=Array.isArray((d=t.policy)==null?void 0:d.providerPriority)?String(t.policy.providerPriority[0]||"").trim():"";i&&n.push({tag:`provider=${i}`,custom:!1});const c=typeof t.worktreeBranch=="string"?t.worktreeBranch.trim():"";return t.isLocalWorktree===!0&&c&&n.push({tag:`worktree=${c}`,custom:!1}),n}function _I(e){const t=e.capabilities;return Array.isArray(t)?t.map(n=>typeof n=="string"?n.trim():"").filter(Boolean):[]}const $I=["os=","arch=","provider=","worktree=","converge="];function HI({node:e,saving:t,onSave:n}){const{t:r}=Ne("common"),a=l.useMemo(()=>EI(e).filter(h=>!h.custom),[e]),o=l.useMemo(()=>_I(e),[e]),[i,c]=l.useState(o),[u,p]=l.useState(""),d=JSON.stringify(i)!==JSON.stringify(o),f=(h=>{const x=h.trim();return x?/\s/.test(x)?r("repoMesh.tagEditor.noSpaces"):$I.some(y=>x.toLowerCase().startsWith(y))?r("repoMesh.tagEditor.reservedPrefix"):i.includes(x)?r("repoMesh.tagEditor.alreadyAdded"):null:null})(u);function g(){const h=u.trim();!h||f||(c(x=>[...x,h]),p(""))}function S(h){c(x=>x.filter(y=>y!==h))}return s.jsxs("div",{className:"mt-2",onClick:h=>h.stopPropagation(),children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wide text-text-muted mr-1",children:r("repoMesh.tagEditor.routingTags")}),a.map(h=>s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-1.5 py-0.5 font-mono text-[10px] text-text-muted",title:r("repoMesh.tagEditor.autoDerivedTitle"),children:h.tag},h.tag)),i.map(h=>s.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 font-mono text-[10px] text-accent-primary",title:r("repoMesh.tagEditor.customTagTitle"),children:[h,s.jsx("button",{type:"button",className:"text-accent-primary/70 hover:text-accent-primary bg-transparent border-none cursor-pointer p-0 leading-none",onClick:()=>S(h),disabled:t,"aria-label":r("repoMesh.tagEditor.remove",{tag:h}),children:"×"})]},h))]}),s.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:h=>p(h.target.value),onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),g())},placeholder:r("repoMesh.tagEditor.addPlaceholder"),disabled:t,className:"min-w-[12rem] flex-1 px-2 py-1 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-primary"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:g,disabled:t||!u.trim()||!!f,children:r("repoMesh.tagEditor.add")}),d&&s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>n(i),disabled:t,children:r(t?"repoMesh.tagEditor.saving":"repoMesh.tagEditor.saveTags")})]}),f&&s.jsx("div",{className:"mt-1 text-[11px] text-amber-400",children:f}),i.length===0&&a.length===0&&s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:r("repoMesh.tagEditor.empty")})]})}function FI(e,t){return t.filter(n=>n.status!=="assigned"?!1:(n.assignedNodeId||n.nodeId)===e.id)}function BI(e){const t=e.assignedSessionId||e.sessionId||"unassigned session",n=e.message.length>80?`${e.message.slice(0,77)}…`:e.message;return`${t}: ${n}`}function WI(e){var r;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>n.has(a)?!1:(n.add(a),!0))}function OI(e){const t=WI(e);return t.length?{configured:!0,label:t.join(" → ")}:{configured:!1,label:"not configured",launchBlockedMessage:"No provider detected on this node — task launch is blocked until a provider is selected or installed. (Empty capability slots alone do not block launch; this means no provider was found.)"}}function UI(e){return e.isLocalWorktree===!0}function GI(e,t){const n=t;return[...Array.isArray(n==null?void 0:n.cliSessions)?n.cliSessions:[],...Array.isArray(n==null?void 0:n.acpSessions)?n.acpSessions:[],...Array.isArray(n==null?void 0:n.sessions)?n.sessions:[]].filter(a=>{var o;return((o=a==null?void 0:a.settings)==null?void 0:o.meshNodeId)===e.id||(a==null?void 0:a.workspace)===e.workspace}).map(a=>{var o;return{id:a.sessionId||a.id||a.instanceId||"unknown",provider:a.providerType||a.cliType||a.acpType||a.type||"unknown",status:a.status||((o=a.activeChat)==null?void 0:o.status)||"unknown"}})}function Jd(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function qI(e,t){var n;return(e==null?void 0:e.ownerName)||(e==null?void 0:e.userName)||((n=e==null?void 0:e.user)==null?void 0:n.name)||t||"You"}function zI({nodes:e,meshQueue:t,activeDaemon:n,daemons:r,selectedMeshId:a,userName:o,features:i,coordinatorDaemonId:c,availableCliProviders:u,savingNodeSlotsId:p,onUpdateNodeSlots:d,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:f,nodeSystemPromptDrafts:g,onNodeSystemPromptDraftChange:S,savingNodeSystemPromptId:h,onSaveNodeSystemPrompt:x,selectedNodeId:y,onSelectNode:b,showAddNode:C,onShowAddNode:j,onCancelAddNode:k,nodeWorkspace:v,onNodeWorkspaceChange:N,nodeProviderPriority:w,onNodeProviderPriorityChange:A,nodeDaemonId:T,onNodeDaemonIdChange:I,nodeCustomPath:P,onNodeCustomPathChange:D,nodePickerWorkspaces:_,nodePickerProviders:W,nodeOnboardingPlan:$,nodePlanLoading:E,attachableDaemons:B,onAddNode:L,onRemoveNode:R}){var J;const{t:M}=Ne("common"),F=l.useMemo(()=>LI(r),[r]),K=l.useMemo(()=>e.filter(V=>!UI(V)),[e]);return s.jsxs(gt,{title:i.addNodeDaemonPicker?M("repoMesh.nodeList.title",{count:K.length}):M("repoMesh.nodeList.titleNoCount"),description:i.addNodeDaemonPicker?M("repoMesh.nodeList.descriptionCloud"):M("repoMesh.nodeList.descriptionStandalone"),children:[i.addNodeDaemonPicker&&s.jsxs("div",{className:"mb-4 rounded-xl border border-border-subtle bg-bg-secondary/60 p-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:M("repoMesh.nodeList.daemonCandidates")}),s.jsx("div",{className:"text-[12px] text-text-muted",children:M("repoMesh.nodeList.daemonCandidatesHint")})]}),s.jsx("span",{className:"text-[11px] text-text-muted",children:M("repoMesh.nodeList.available",{count:B.length})})]}),r.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:M("repoMesh.nodeList.noDaemonsAvailable")}):B.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:M("repoMesh.nodeList.allDaemonsAttached")}):s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:B.map(V=>s.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors ${V.id===c?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{I(V.id),N(""),D(!1),A(jr(Hn(V.availableProviders||[]))),j()},children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-medium truncate",children:Jd(V)}),V.id===c&&s.jsx("span",{className:"text-[10px] text-accent-primary",children:M("repoMesh.nodeList.selectedHost")})]}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted font-mono truncate",children:V.id}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:M("repoMesh.nodeList.workspacesDetected",{count:(V.workspaces||[]).length})})]},V.id))})]}),!C&&s.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:j,children:[s.jsx(aI,{size:13})," ",i.addNodeDaemonPicker?M("repoMesh.nodeList.attachMachine"):M("repoMesh.nodeList.addNode")]}),C&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass animate-[fadeIn_0.3s_ease-out]",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:i.addNodeDaemonPicker?M("repoMesh.nodeList.attachMachineTitle"):M("repoMesh.nodeList.addNodeTitle")}),s.jsx("button",{onClick:()=>{k(),I(""),D(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(Mt,{size:16})})]}),i.addNodeDaemonPicker&&s.jsx(At,{label:M("repoMesh.nodeList.machine"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:T,onChange:V=>{var Y;I(V.target.value),N(""),D(!1),A(jr(Hn(((Y=r.find(se=>se.id===V.target.value))==null?void 0:Y.availableProviders)||[])))},children:[s.jsx("option",{value:"",children:M("repoMesh.nodeList.selectMachine")}),r.map(V=>s.jsx("option",{value:V.id,children:Jd(V)},V.id))]})}),(i.addNodeDaemonPicker?T:!0)&&s.jsx(At,{label:M("repoMesh.nodeList.workspacePath"),children:i.addNodeDaemonPicker&&!P&&_.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:_.map(V=>s.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${v===V.path?"border-accent-primary bg-accent-primary/10 text-text-primary":"border-border-subtle bg-bg-primary hover:bg-violet-500/10 text-text-primary"}`,onClick:()=>N(V.path),children:[s.jsx("span",{className:"font-medium block truncate",children:V.label||V.path.split("/").pop()}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:V.path})]},V.id||V.path))}),s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{D(!0),N("")},children:M("repoMesh.nodeList.enterCustomPath")})]}):s.jsx(s.Fragment,{children:i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[s.jsx(hs,{value:v,onChange:V=>N(V.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:V=>{V.key==="Enter"&&L()}}),_.length>0&&s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0 mt-1",onClick:()=>{D(!1),N("")},children:M("repoMesh.nodeList.pickFromSaved")})]}):(()=>{var se;const V=Array.isArray(n==null?void 0:n.workspaces)?n.workspaces:[],Y=`mesh-add-node-workspaces-${a||"new"}`;return s.jsxs(s.Fragment,{children:[s.jsx(hs,{value:v,onChange:ie=>N(ie.target.value),placeholder:((se=V[0])==null?void 0:se.path)||"/Users/dev/projects/myapp",list:V.length>0?Y:void 0,autoFocus:!0}),V.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:Y,children:V.map(ie=>s.jsx("option",{value:ie.path,children:ie.label||ie.path},ie.id||ie.path))}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:V.slice(0,6).map(ie=>s.jsx("button",{type:"button",onClick:()=>N(ie.path),className:"text-[11px] px-2 py-0.5 rounded-full border border-border-subtle hover:border-accent-primary/50 text-text-muted hover:text-text-primary transition-colors bg-transparent cursor-pointer",title:ie.path,children:ie.label||ie.path.split("/").filter(Boolean).pop()||ie.path},ie.id||ie.path))})]})]})})()})}),(E||$)&&s.jsx(Lt,{variant:($==null?void 0:$.success)===!1?"error":"info",className:"mb-4",children:E?"Inspecting Git repository (read-only)…":$!=null&&$.success?`${((J=$.plan)==null?void 0:J.summary)||"Compatible Git workspace detected."} Adding remains an explicit action.`:`${($==null?void 0:$.code)||"onboarding_blocked"}: ${($==null?void 0:$.error)||"Git discovery failed"} ${($==null?void 0:$.action)||""}`}),s.jsx(At,{label:M("repoMesh.nodeList.preferredTools"),hint:M("repoMesh.nodeList.preferredToolsHint"),children:s.jsx(qS,{value:w,availableProviders:i.addNodeDaemonPicker?W:u,onChange:A})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:L,disabled:E||($==null?void 0:$.success)===!1||!v.trim()||i.addNodeDaemonPicker&&!T,className:"btn btn-primary btn-sm",children:M("repoMesh.nodeList.add")}),s.jsx("button",{onClick:()=>{k(),I(""),D(!1)},className:"btn btn-secondary btn-sm",children:M("repoMesh.nodeList.cancel")})]})]}),K.length===0?s.jsx(Ya,{icon:s.jsx(En,{}),title:M("repoMesh.nodeList.emptyTitle"),description:M("repoMesh.nodeList.emptyDescription")}):s.jsx("div",{className:"flex flex-col gap-2",children:K.map(V=>{var ee;const Y=OI(V),se=FI(V,t),ie=GI(V,n),Z=y===V.id,O=V.status||V.machine_status||(se.length>0||ie.length>0?"active":"enabled");return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary transition-colors ${i.addNodeDaemonPicker?"bg-bg-glass border-border-subtle rounded-xl px-5 py-4":`cursor-pointer ${Z?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`}`,role:i.addNodeDaemonPicker?void 0:"button",tabIndex:i.addNodeDaemonPicker?void 0:0,onClick:i.addNodeDaemonPicker?void 0:()=>b(Z?null:V.id),onKeyDown:i.addNodeDaemonPicker?void 0:G=>{(G.key==="Enter"||G.key===" ")&&(G.preventDefault(),b(Z?null:V.id))},children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[i.addNodeDaemonPicker?s.jsx("span",{className:"font-semibold text-sm text-text-primary truncate",children:V.machine_label||V.machine_nickname||V.hostname||V.workspace}):s.jsx("span",{className:"text-sm font-medium",children:V.workspace.split("/").pop()}),i.addNodeDaemonPicker&&s.jsx(oI,{status:O}),i.addNodeDaemonPicker&&s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:M("repoMesh.nodeList.setupInventory")})]}),i.addNodeDaemonPicker&&s.jsx("div",{className:"text-[11px] text-text-muted",children:M("repoMesh.nodeList.ownerMachine",{owner:qI(r.find(G=>G.id===String(V.daemon_id||"")),o),machine:V.machine_label||V.daemon_id||V.workspace})}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:V.workspace}),s.jsx(HI,{node:V,saving:m===V.id,onSave:G=>f(V,G)}),i.addNodeDaemonPicker&&s.jsx("div",{className:"mt-2 text-[11px] text-amber-300",children:M("repoMesh.nodeList.liveDetailGraphOwned")}),s.jsxs("div",{className:"mt-3 max-w-2xl",onClick:G=>G.stopPropagation(),children:[s.jsx(At,{label:M("repoMesh.nodeList.slotsLabel"),hint:M("repoMesh.nodeList.slotsHint"),children:s.jsx(PI,{slots:Array.isArray((ee=V.policy)==null?void 0:ee.slots)?V.policy.slots:[],availableProviders:RI(V,F),saving:p===V.id,onSave:G=>d(V,G)})}),i.nodeInstruction&&s.jsxs(At,{label:M("repoMesh.nodeList.nodeInstruction"),hint:M("repoMesh.nodeList.nodeInstructionHint"),children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:3,value:g[V.id]??"",onChange:G=>{const le=G.target.value;S(V.id,le)},onClick:G=>G.stopPropagation(),disabled:h===V.id,placeholder:M("repoMesh.nodeList.nodeInstructionPlaceholder")}),s.jsx("div",{className:"mt-2 flex items-center gap-2",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:G=>{G.stopPropagation(),x(V)},disabled:h===V.id,children:h===V.id?M("repoMesh.nodeList.saving"):M("repoMesh.nodeList.saveInstruction")})})]})]})]}),s.jsx("button",{className:`transition-colors bg-transparent border-none cursor-pointer ${i.addNodeDaemonPicker?"btn btn-sm text-text-muted hover:text-red-400":"text-text-muted hover:text-red-400"}`,onClick:G=>{G.stopPropagation(),R(V.id)},title:M("repoMesh.nodeList.removeNode"),children:s.jsx(rI,{size:14})})]}),s.jsxs("details",{className:"mt-3 group",onClick:G=>G.stopPropagation(),children:[s.jsxs("summary",{className:"cursor-pointer select-none text-[12px] text-text-muted hover:text-text-secondary inline-flex items-center gap-1",children:[s.jsx("span",{className:"transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"})," ",M("repoMesh.nodeList.details")]}),s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary/60 p-3 text-[12px] text-text-muted",children:[s.jsxs("div",{className:"grid gap-2 sm:grid-cols-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:M("repoMesh.nodeList.nodeId")})," ",s.jsx("span",{className:"font-mono break-all",children:V.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:M("repoMesh.nodeList.launchReady")})," ",s.jsx("span",{className:Y.configured?"text-green-400":"text-amber-400",children:Y.configured?M("repoMesh.nodeList.launchReadyYes"):M("repoMesh.nodeList.launchReadyNo")})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:M("repoMesh.nodeList.repoRoot")})," ",s.jsx("span",{className:"font-mono break-all",children:V.repoRoot||V.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:M("repoMesh.nodeList.activeSessionsLabel")})," ",ie.length]}),i.addNodeDaemonPicker&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:M("repoMesh.nodeList.added")})," ",new Date(V.created_at||V.createdAt||Date.now()).toLocaleDateString()]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:M("repoMesh.nodeList.activeQueueAssignments")}),se.length===0?s.jsx("div",{children:M("repoMesh.nodeList.noActiveAssignment")}):s.jsx("ul",{className:"m-0 pl-4",children:se.map(G=>s.jsx("li",{className:"font-mono",children:BI(G)},G.id))})]}),ie.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:M("repoMesh.nodeList.activeSessions")}),s.jsx("ul",{className:"m-0 pl-4",children:ie.map(G=>s.jsxs("li",{className:"font-mono",children:[G.provider," / ",G.status," / ",G.id]},G.id))})]})]})]})]},V.id)})})]})}function ta(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function KI({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:n,coordinatorCliType:r,onCoordinatorCliTypeChange:a,launchingCoordinator:o,launchResult:i,isHostNodeAttached:c,selectedHostNode:u,hostPinned:p,hostLabel:d,hostOnline:m,hostRebindDaemonId:f,onHostRebindDaemonIdChange:g,onLaunchCoordinator:S,settingMeshHost:h,onSetMeshHost:x}){const{t:y}=Ne("common"),b=s.jsx(At,{label:y("repoMesh.host.coordinatorProvider"),hint:y("repoMesh.host.coordinatorProviderHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:r,onChange:v=>a(v.target.value),children:[s.jsx("option",{value:"",children:y("repoMesh.host.useNodePriority")}),s.jsx("option",{value:"claude-cli",children:"Claude Code"}),s.jsx("option",{value:"codex-cli",children:"Codex"}),s.jsx("option",{value:"gemini-cli",children:"Gemini"}),s.jsx("option",{value:"hermes-cli",children:"Hermes"})]})}),C=i&&s.jsx("div",{className:"mt-3 text-[12px] text-green-400 bg-green-500/10 border border-green-500/20 rounded-lg px-3 py-2",children:i});if(p)return s.jsxs(gt,{title:y("repoMesh.host.title"),description:y("repoMesh.host.descriptionSet"),children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs("span",{className:`inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-[13px] text-text-primary ${m?"border-accent-primary/40 bg-accent-primary/10":"border-amber-500/40 bg-amber-500/10"}`,children:[s.jsx("span",{className:"text-text-muted",children:y("repoMesh.host.hostLabel")}),s.jsx("span",{className:"font-medium",children:d||y("repoMesh.host.unknown")}),s.jsxs("span",{className:m?"text-text-muted":"text-amber-400",children:["· ",y(m?"repoMesh.host.online":"repoMesh.host.offline")]})]}),(u==null?void 0:u.workspace)&&s.jsxs("span",{className:"text-[12px] text-text-muted",children:[y("repoMesh.host.hostNode")," ",s.jsx("span",{className:"font-mono text-text-secondary",children:u.workspace})]})]}),!m&&s.jsxs("div",{className:"mt-4",children:[s.jsxs(Lt,{variant:"warning",className:"mb-3",children:[s.jsx("strong",{children:y("repoMesh.host.hostOffline")})," ",y("repoMesh.host.hostOfflineText")]}),e.length>0?s.jsx(At,{label:y("repoMesh.host.reconnectToCommand"),hint:y("repoMesh.host.reconnectToCommandHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:f,onChange:v=>g(v.target.value),children:[s.jsx("option",{value:"",children:y("repoMesh.host.waitForHost")}),e.map(v=>s.jsx("option",{value:v.id,children:ta(v)},v.id))]})}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:y("repoMesh.host.noDaemonsToRoute")})]}),s.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-[180px_auto] items-end",children:[b,s.jsx("button",{className:"btn btn-primary btn-sm",onClick:S,disabled:o||!t,title:t?void 0:y("repoMesh.host.noCommandTarget"),children:y(o?"repoMesh.host.launching":"repoMesh.host.launchHost")})]}),C]});const j=e.find(v=>v.id===t),k=x&&t?s.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>x(t),disabled:!!h,children:y(h?"repoMesh.host.settingHost":"repoMesh.host.setHostAction")}):null;return s.jsxs(gt,{title:y("repoMesh.host.title"),description:y("repoMesh.host.descriptionUnset"),children:[s.jsxs(Lt,{variant:"info",className:"mb-4",children:[s.jsx("strong",{children:y("repoMesh.host.setHostBanner")})," ",y("repoMesh.host.setHostBannerText")]}),e.length>0?s.jsxs(s.Fragment,{children:[t?s.jsx("div",{className:"mb-3 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:c?s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:ta(j)}),u!=null&&u.workspace?s.jsxs(s.Fragment,{children:[" · setup node ",s.jsx("span",{className:"font-mono text-text-secondary",children:u.workspace})]}):null,". ",y("repoMesh.host.confirmSetsHost")]}):s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:ta(j)}),". ",y("repoMesh.host.attachNodeThenSetHost")]})}):s.jsx(At,{label:y("repoMesh.host.hostDaemon"),hint:y("repoMesh.host.hostDaemonHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:"",onChange:v=>n(v.target.value),children:[s.jsx("option",{value:"",children:y("repoMesh.host.resolvingHost")}),e.map(v=>s.jsx("option",{value:v.id,children:ta(v)},v.id))]})}),k&&s.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[k,s.jsx("span",{className:"text-[12px] text-text-muted",children:y("repoMesh.host.setHostActionHint")})]}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-[180px_auto] items-end mt-3",children:[b,s.jsx("button",{className:`btn btn-sm ${k?"btn-secondary":"btn-primary"}`,onClick:S,disabled:!t||!c||o,title:t?c?void 0:y("repoMesh.host.attachNodeFirst"):y("repoMesh.host.pickHostFirst"),children:y(o?"repoMesh.host.launching":"repoMesh.host.launchHostSetsHost")})]})]}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:y("repoMesh.host.noDaemonsToHost")}),C]})}function VI({meshId:e,availableCliAgents:t}){const{t:n}=Ne(),r=t.find(o=>{const i=o.id.toLowerCase();return i==="hermes-cli"||i.includes("hermes")||o.name.toLowerCase().includes("hermes")}),a=gm(r==null?void 0:r.meshCoordinator,{meshId:e});return a?s.jsx(gt,{title:n("repoMesh.hermesMcp.title"),description:n("repoMesh.hermesMcp.description"),children:s.jsx(Bm,{setup:a,providerName:(r==null?void 0:r.name)||n("repoMesh.hermesMcp.fallbackProvider")})}):null}const Zo=[{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."}],YI=[{value:"smart",label:"Smart",description:"Match each task to the node whose capability slot best fits it (task difficulty + capability tags), then load-spread among ties. Auto-enabled when any node has capability slots."},{value:"spread",label:"Spread",description:"Distribute work evenly across eligible nodes (prefers the least-loaded, rotating ties fairly). Set a per-node priority below to bias the order."},{value:"in_order",label:"In order",description:"Assign to nodes in the order they were added — the first eligible node takes the work. No load-spreading."}];function JI(e){return e==="smart"?"fitness":e==="spread"?"least_loaded":"first_eligible"}function QI(e,t){const n=e||"first_eligible";return n==="fitness"?"smart":n==="first_eligible"?"in_order":n==="priority_only"?t!=null&&t.priorityConfigured?"spread":"in_order":n==="least_loaded"||n==="round_robin"?"spread":"in_order"}const XI={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,schedulingStrategy:"first_eligible",sessionCleanupOnNodeRemove:"preserve"};function Ri(e){return{...XI,...(e==null?void 0:e.policy)||{}}}function ZI(e){return{routeId:`mesh-settings:${e.meshId}`,daemonId:e.daemonId,agentName:e.meshName,agentType:"mesh",status:"idle",title:e.meshName,messages:[],workspaceName:e.meshName,displayPrimary:e.meshName,displaySecondary:"Mesh observability",streamSource:"native",tabKey:`mesh-settings:${e.meshId}`,coordinator:{meshId:e.meshId,role:"coordinator"},settings:{meshCoordinatorFor:e.meshId}}}function eP({selectedMesh:e,error:t,onDismissError:n,onBack:r,onDelete:a,displayedMeshStatus:o,graphLoading:i,graphError:c,onRefreshGraph:u,savingPolicy:p,onUpdatePolicy:d,coordinatorPromptDraft:m,onCoordinatorPromptDraftChange:f,savingCoordinatorPrompt:g,onSaveCoordinatorPrompt:S,daemons:h,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:y,coordinatorCliType:b,onCoordinatorCliTypeChange:C,launchingCoordinator:j,launchResult:k,isHostNodeAttached:v,selectedHostNode:N,hostPinned:w,hostLabel:A,hostOnline:T,hostRebindDaemonId:I,onHostRebindDaemonIdChange:P,onLaunchCoordinator:D,settingMeshHost:_,onSetMeshHost:W,activeDaemon:$,activeDaemonId:E,meshQueue:B,userName:L,availableCliProviders:R,savingNodeSlotsId:M,onUpdateNodeSlots:F,savingNodeCapabilitiesId:K,onUpdateNodeCapabilities:J,nodeSystemPromptDrafts:V,onNodeSystemPromptDraftChange:Y,savingNodeSystemPromptId:se,onSaveNodeSystemPrompt:ie,selectedNodeId:Z,onSelectNode:O,showAddNode:ee,onShowAddNode:G,onCancelAddNode:le,nodeWorkspace:je,onNodeWorkspaceChange:ge,nodeProviderPriority:Ce,onNodeProviderPriorityChange:ue,nodeDaemonId:z,onNodeDaemonIdChange:U,nodeCustomPath:q,onNodeCustomPathChange:Q,nodePickerWorkspaces:me,nodePickerProviders:Ae,nodeOnboardingPlan:de,nodePlanLoading:H,attachableDaemons:he,onAddNode:fe,onRemoveNode:ye,availableCliAgents:Pe,features:He,sendCommand:ke}){const{t:pe}=Ne("common"),st=Ri(e),De=e.nodes||[],_e=De.some(lt=>{var bt;const at=Number((bt=lt.policy)==null?void 0:bt.schedulingPriority);return Number.isFinite(at)&&at!==0}),ae=!st.schedulingStrategy,we=l.useMemo(()=>De.some(lt=>{var at;return Array.isArray((at=lt.policy)==null?void 0:at.slots)&&lt.policy.slots.length>0}),[De]),Me=ae?we?"smart":De.length>=2?"spread":null:null,[qe,ve]=l.useState(!1),$e=!!E&&!!e.id;return s.jsxs(Lr,{icon:s.jsx(os,{}),title:e.name,subtitle:e.repoIdentity||e.repo_identity||"Repo Mesh",widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"flex gap-2",children:[s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:r,children:pe("repoMesh.detail.back")}),s.jsxs("button",{className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:()=>u(!0),disabled:i,children:[s.jsx(sI,{size:13}),pe(i?"repoMesh.detail.probing":"repoMesh.detail.refresh")]}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>a(e.id),children:pe("repoMesh.detail.delete")})]}),children:[t&&s.jsx(Lt,{variant:"error",onDismiss:n,className:"mb-4",children:t}),(()=>{var oe,be;const lt=s.jsxs(s.Fragment,{children:[He.meshHostDaemonSection&&s.jsx(KI,{daemons:h,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:y,coordinatorCliType:b,onCoordinatorCliTypeChange:C,launchingCoordinator:j,launchResult:k,isHostNodeAttached:v,selectedHostNode:N,hostPinned:w,hostLabel:A,hostOnline:T,hostRebindDaemonId:I,onHostRebindDaemonIdChange:re=>{P(re),u()},onLaunchCoordinator:D,settingMeshHost:_,onSetMeshHost:W}),s.jsxs(gt,{title:pe("repoMesh.detail.observabilityTitle"),description:pe("repoMesh.detail.observabilityDescription"),children:[c&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:c}),s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs("button",{type:"button",className:"btn btn-primary btn-sm inline-flex items-center gap-1.5",onClick:()=>ve(!0),disabled:!$e,title:pe($e?"repoMesh.detail.observabilityOpenTitle":"repoMesh.detail.observabilityDisabledTitle"),children:[s.jsx(os,{size:14}),pe("repoMesh.detail.observabilityOpen")]}),s.jsx("span",{className:"text-[12px] text-text-muted",children:pe("repoMesh.detail.observabilityHint")})]})]}),s.jsx(zI,{nodes:De,meshQueue:B,activeDaemon:$,daemons:h,selectedMeshId:e.id,userName:L,features:{addNodeDaemonPicker:He.addNodeDaemonPicker,nodeInstruction:He.nodeInstruction},coordinatorDaemonId:x,availableCliProviders:R,savingNodeSlotsId:M,onUpdateNodeSlots:F,savingNodeCapabilitiesId:K,onUpdateNodeCapabilities:J,nodeSystemPromptDrafts:V,onNodeSystemPromptDraftChange:Y,savingNodeSystemPromptId:se,onSaveNodeSystemPrompt:ie,selectedNodeId:Z,onSelectNode:O,showAddNode:ee,onShowAddNode:G,onCancelAddNode:le,nodeWorkspace:je,onNodeWorkspaceChange:ge,nodeProviderPriority:Ce,onNodeProviderPriorityChange:ue,nodeDaemonId:z,onNodeDaemonIdChange:U,nodeCustomPath:q,onNodeCustomPathChange:Q,nodePickerWorkspaces:me,nodePickerProviders:Ae,nodeOnboardingPlan:de,nodePlanLoading:H,attachableDaemons:he,onAddNode:fe,onRemoveNode:ye})]}),at=s.jsxs(s.Fragment,{children:[s.jsxs(gt,{title:pe("repoMesh.detail.schedulingTitle"),description:pe("repoMesh.detail.schedulingDescription"),children:[s.jsxs("fieldset",{className:"border-none p-0 m-0",children:[s.jsx("legend",{className:"text-[13px] font-medium text-text-secondary mb-2",children:pe("repoMesh.detail.distribution")}),s.jsx("div",{className:"flex flex-col gap-2",children:YI.map(re=>{const Ee=QI(st.schedulingStrategy,{priorityConfigured:_e})===re.value;return s.jsxs("label",{className:`flex items-start gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${Ee?"border-accent-primary/60 bg-accent-primary/10":"border-border-subtle bg-bg-secondary/60 hover:border-border-default"}`,children:[s.jsx("input",{type:"radio",name:"mesh-distribution",className:"mt-0.5 accent-[var(--accent-primary)]",value:re.value,checked:Ee,disabled:p,onChange:()=>d({schedulingStrategy:JI(re.value)})}),s.jsxs("span",{className:"min-w-0",children:[s.jsxs("span",{className:"flex items-center gap-2 text-sm text-text-primary",children:[re.label,Me===re.value&&s.jsx("span",{className:"rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-accent-primary",children:pe("repoMesh.detail.recommended")})]}),s.jsx("span",{className:"block text-[12px] text-text-muted",children:re.description})]})]},re.value)})})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:pe("repoMesh.detail.saving")})]}),s.jsx(gt,{title:pe("repoMesh.detail.visibilityTitle"),description:pe("repoMesh.detail.visibilityDescription"),children:s.jsx(At,{label:pe("repoMesh.detail.visibilityLabel"),hint:pe("repoMesh.detail.visibilityHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:st.spawnedSessionVisibility==="visible"?"visible":"hidden",onChange:re=>d({spawnedSessionVisibility:re.target.value==="visible"?"visible":"hidden"}),disabled:p,children:[s.jsx("option",{value:"hidden",children:pe("repoMesh.detail.visibilityHidden")}),s.jsx("option",{value:"visible",children:pe("repoMesh.detail.visibilityVisible")})]})})}),o&&s.jsx(gt,{title:pe("repoMesh.detail.magiTitle"),description:pe("repoMesh.detail.magiDescription"),children:s.jsx(fI,{status:o,daemonId:E,sendDaemonCommand:ke,availableProviders:R})}),s.jsx(AI,{hostDaemonId:x,hostOnline:T,hostWorkspace:(N==null?void 0:N.workspace)||"",hostProviders:((oe=h.find(re=>re.id===x))==null?void 0:oe.availableProviders)||[],machineAutoApproveEnabled:st.delegatedWorkerAutoApprove!==!1,machineDangerousAllowed:st.delegatedWorkerDangerousModeAllow===!0,onUpdatePolicy:d,savingPolicy:p,sendCommand:ke})]}),bt=s.jsx(s.Fragment,{children:He.coordinatorPrompt&&s.jsxs(gt,{title:pe("repoMesh.detail.coordinatorPromptTitle"),collapsible:!0,defaultOpen:!1,badge:s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:pe("repoMesh.detail.advanced")}),description:pe("repoMesh.detail.coordinatorPromptDescription"),children:[s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-1",children:pe("repoMesh.detail.thisMesh")}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:pe("repoMesh.detail.thisMeshHint",{name:e.name})}),s.jsxs(At,{label:pe("repoMesh.detail.overrideLabel"),hint:pe("repoMesh.detail.overrideHint"),children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:6,value:m.override,onChange:re=>f({...m,override:re.target.value}),disabled:g,placeholder:pe("repoMesh.detail.overridePlaceholder")}),s.jsx(bI,{daemonId:E,meshId:e.id,cliType:b,sendCommand:ke})]}),s.jsx(At,{label:pe("repoMesh.detail.appendLabel"),hint:pe("repoMesh.detail.appendHint"),children:s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:4,value:m.append,onChange:re=>f({...m,append:re.target.value}),disabled:g,placeholder:pe("repoMesh.detail.appendPlaceholder")})}),s.jsxs("details",{className:"mt-2 text-[12px] text-text-muted",children:[s.jsx("summary",{className:"cursor-pointer select-none",children:pe("repoMesh.detail.availablePlaceholders")}),s.jsx("p",{className:"mt-1 font-mono break-words",children:"{{meshName}}, {{repo}}, {{defaultBranch}}, {{cliType}}, {{nodes}}, {{policy}}, {{tools}}, {{workflow}}, {{rules}}, {{toolExposurePreflight}}"})]}),s.jsxs("div",{className:"mt-3 flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:S,disabled:g,children:pe(g?"repoMesh.detail.saving":"repoMesh.detail.saveCoordinatorPrompt")}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>f({override:"",append:""}),disabled:g,title:pe("repoMesh.detail.clearTitle"),children:pe("repoMesh.detail.clear")})]})]}),s.jsxs("div",{className:"mt-5 border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-1",children:pe("repoMesh.detail.userLevel")}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:pe("repoMesh.detail.userLevelDescription")}),s.jsx(AC,{daemonId:E||void 0})]})]})}),X=s.jsxs(s.Fragment,{children:[s.jsx(SI,{status:o,daemonId:E,meshId:e.id,sendCommand:ke}),s.jsxs(gt,{title:pe("repoMesh.detail.safetyTitle"),collapsible:!0,defaultOpen:!1,badge:s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-2 py-0.5 text-[10px] font-medium text-text-muted",children:pe("repoMesh.detail.advanced")}),description:pe("repoMesh.detail.safetyDescription"),children:[s.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:[{label:pe("repoMesh.detail.checkpointBefore"),key:"requirePreTaskCheckpoint",opts:[["no","No"],["yes","Yes"]],val:re=>re?"yes":"no",parse:re=>re==="yes"},{label:pe("repoMesh.detail.checkpointAfter"),key:"requirePostTaskCheckpoint",opts:[["yes","Yes"],["no","No"]],val:re=>re?"yes":"no",parse:re=>re==="yes"},{label:pe("repoMesh.detail.pushApproval"),key:"requireApprovalForPush",opts:[["required",pe("repoMesh.detail.requireApprovalBeforePush")],["not_required",pe("repoMesh.detail.doNotRequireApproval")]],val:re=>re?"required":"not_required",parse:re=>re==="required"},{label:pe("repoMesh.detail.destructiveGitApproval"),key:"requireApprovalForDestructiveGit",opts:[["required",pe("repoMesh.detail.requireApproval")],["not_required",pe("repoMesh.detail.doNotRequireApproval")]],val:re=>re?"required":"not_required",parse:re=>re==="required"},{label:pe("repoMesh.detail.uncommittedChanges"),key:"dirtyWorkspaceBehavior",opts:[["warn",pe("repoMesh.detail.warnAndContinue")],["block",pe("repoMesh.detail.blockTask")],["checkpoint_then_continue",pe("repoMesh.detail.checkpointThenContinue")]],val:re=>re||"warn",parse:re=>re},{label:pe("repoMesh.detail.autoPublishSubmodule"),key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled",pe("repoMesh.detail.requireExplicitApproval")],["enabled",pe("repoMesh.detail.allowRefineryPublish")]],val:re=>re?"enabled":"disabled",parse:re=>re==="enabled"}].map(({label:re,key:Te,opts:Ee,val:Ie,parse:ze})=>s.jsx(At,{label:re,children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Ie(st[Te]),onChange:Ke=>d({[Te]:ze(Ke.target.value)}),disabled:p,children:Ee.map(([Ke,Qe])=>s.jsx("option",{value:Ke,children:Qe},Ke))})},Te))}),(()=>{const re=st.autoFastForward&&typeof st.autoFastForward=="object"?st.autoFastForward:{},Te=re.enabled!==!1,Ee=re.remoteNodes===!0,Ie=re.mode==="continuous"?"continuous":"idle",ze=Ke=>d({autoFastForward:{...re,...Ke}});return s.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[s.jsx(At,{label:pe("repoMesh.detail.autoFastForward"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Te?"enabled":"disabled",onChange:Ke=>ze({enabled:Ke.target.value==="enabled"}),disabled:p,children:[s.jsx("option",{value:"enabled",children:pe("repoMesh.detail.ffEnabled")}),s.jsx("option",{value:"disabled",children:pe("repoMesh.detail.ffDisabled")})]})}),s.jsx(At,{label:pe("repoMesh.detail.includeRemoteNodes"),hint:pe("repoMesh.detail.includeRemoteNodesHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Ee?"yes":"no",onChange:Ke=>ze({remoteNodes:Ke.target.value==="yes"}),disabled:p||!Te,children:[s.jsx("option",{value:"no",children:pe("repoMesh.detail.remoteNo")}),s.jsx("option",{value:"yes",children:pe("repoMesh.detail.remoteYes")})]})}),s.jsx(At,{label:pe("repoMesh.detail.detectionMode"),hint:pe("repoMesh.detail.detectionModeHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:Ie,onChange:Ke=>ze({mode:Ke.target.value==="continuous"?"continuous":"idle"}),disabled:p||!Te||!Ee,children:[s.jsx("option",{value:"idle",children:pe("repoMesh.detail.idleEdgeOnly")}),s.jsx("option",{value:"continuous",children:pe("repoMesh.detail.continuousScan")})]})})]})})(),s.jsxs("div",{className:"mt-4 rounded-xl border border-amber-500/25 bg-amber-500/10 p-4",children:[s.jsx(At,{label:pe("repoMesh.detail.sessionCleanupLabel"),hint:pe("repoMesh.detail.sessionCleanupHint"),children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:st.sessionCleanupOnNodeRemove||"preserve",onChange:re=>d({sessionCleanupOnNodeRemove:re.target.value}),disabled:p,children:Zo.map(re=>s.jsx("option",{value:re.value,children:re.label},re.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((be=Zo.find(re=>re.value===st.sessionCleanupOnNodeRemove))==null?void 0:be.description)||Zo[0].description})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:pe("repoMesh.detail.saving")})]})]}),te=[{key:"nodes",label:pe("repoMesh.detail.tabNodes"),content:lt},{key:"scheduling",label:pe("repoMesh.detail.tabScheduling"),content:at},{key:"prompts",label:pe("repoMesh.detail.tabPrompts"),content:s.jsxs(s.Fragment,{children:[bt,He.hermesMcpConfig&&s.jsx(VI,{meshId:e.id,availableCliAgents:Pe}),He.meshHostDaemonSection&&s.jsxs(Lt,{variant:"info",className:"mt-4",children:[s.jsx("strong",{children:"MCP Mode:"})," ",s.jsxs("code",{className:"bg-bg-secondary px-1 rounded text-xs",children:["adhdev mcp --repo-mesh ",e.id]})," · The mesh MCP server can be used directly from your CLI agent."]})]})},{key:"advanced",label:pe("repoMesh.detail.tabAdvanced"),content:X}];return s.jsxs(s.Fragment,{children:[s.jsx(cI,{tabs:te,ariaLabel:pe("repoMesh.detail.tabsAriaLabel"),className:"flex flex-col gap-4"}),qe&&$e&&s.jsx(wh,{activeConv:ZI({meshId:e.id,daemonId:E,meshName:e.name}),sendDaemonCommand:ke,onClose:()=>ve(!1)})]})})()]})}const rr=new Map;function tP({daemons:e,primaryDaemonId:t,sendCommand:n,unwrapResult:r,normalizeMesh:a,features:o,loadDaemonMetadata:i}){const c=e.map(J=>J.id).filter(Boolean).sort().join(","),[u,p]=l.useState(()=>rr.get(c)??[]),[d,m]=l.useState(null),[f,g]=l.useState(()=>!rr.has(c)),[S,h]=l.useState(null),[x,y]=l.useState(!1),[b,C]=l.useState(""),[j,k]=l.useState(""),[v,N]=l.useState(""),[w,A]=l.useState(""),[T,I]=l.useState(""),[P,D]=l.useState(null),[_,W]=l.useState(!1),$=l.useMemo(()=>e.find(J=>J.id===w),[e,w]),E=($==null?void 0:$.workspaces)||[],B=l.useMemo(()=>Hn(($==null?void 0:$.availableProviders)||[]),[$]);l.useEffect(()=>{!o.createDaemonPicker||!i||!w||!$||!(!$.workspaces||!$.availableProviders)||Promise.resolve(i(w,{minFreshMs:3e4})).catch(()=>{})},[o.createDaemonPicker,i,w,$]),l.useEffect(()=>{if(!x||!w||!T){D(null);return}let J=!1;return W(!0),n(w,"plan_mesh_onboarding",{workspace:T,operation:"auto",meshInventory:u}).then(V=>{if(J)return;const Y=r(V);D(Y),Y!=null&&Y.success&&(k(se=>{var ie;return se||((ie=Y.discovery)==null?void 0:ie.repoIdentity)||""}),N(se=>{var ie,Z,O,ee,G,le;return se||((O=(Z=(ie=Y.discovery)==null?void 0:ie.origin)==null?void 0:Z.urls)==null?void 0:O[0])||((le=(G=(ee=Y.discovery)==null?void 0:ee.upstream)==null?void 0:G.urls)==null?void 0:le[0])||""}),C(se=>{var ie,Z;return se||`${String(((ie=Y.discovery)==null?void 0:ie.repoIdentity)||((Z=Y.discovery)==null?void 0:Z.repoRoot)||"").split(/[\\/]/).filter(Boolean).pop()||"repo"}-mesh`}))}).catch(V=>{J||D({success:!1,error:(V==null?void 0:V.message)||"Git discovery failed"})}).finally(()=>{J||W(!1)}),()=>{J=!0}},[x,w,T,u,n,r]);const L=l.useMemo(()=>e.map(J=>J.id).filter(Boolean).sort().join(","),[e]),R=l.useCallback(async(J=!1)=>{const V=J||rr.has(L);g(Y=>V?Y:!0);try{if(o.createDaemonPicker){const Y=await Promise.allSettled(e.map(async Z=>{if(!Z.id)return[];const O=await n(Z.id,"list_meshes",{}),ee=r(O);if((ee==null?void 0:ee.success)===!1)throw new Error(ee.error||"Failed to load meshes");return(Array.isArray(ee==null?void 0:ee.meshes)?ee.meshes:[]).map(G=>a(G,Z.id)).filter(G=>G.id)})),se=new Map;for(const Z of Y)if(Z.status==="fulfilled")for(const O of Z.value)se.has(O.id)||se.set(O.id,O);const ie=Array.from(se.values());p(ie),rr.set(L,ie),h(null)}else{if(!t)return;const Y=await n(t,"list_meshes");if(Y!=null&&Y.success){const se=(Y.meshes||[]).map(ie=>a(ie,t));p(se),rr.set(L,se),h(null)}else h((Y==null?void 0:Y.error)||"Failed to load meshes")}}catch(Y){h((Y==null?void 0:Y.message)||"Failed to load meshes")}finally{g(!1)}},[L,t,n,r,a,o.createDaemonPicker]);async function M(){var se,ie,Z,O,ee,G,le,je,ge,Ce,ue,z;const J=o.createDaemonPicker?w:t;if(!J||!b.trim())return;const V=v.trim(),Y=j.trim();if(!(!V&&!Y))try{const U=await n(J,"plan_mesh_onboarding",{workspace:T||void 0,operation:"auto",meshInventory:u}),q=r(U);if(D(q),(q==null?void 0:q.success)===!1)throw new Error(`${q.code||"onboarding_blocked"}: ${q.error}${q.action?` ${q.action}`:""}`);if(((se=q==null?void 0:q.plan)==null?void 0:se.kind)!=="create_mesh_and_onboard")throw new Error(((ie=q==null?void 0:q.plan)==null?void 0:ie.summary)||"A compatible mesh already exists; add this workspace to it instead of creating a duplicate mesh.");const Q={name:b.trim()};(V||(ee=(O=(Z=q==null?void 0:q.discovery)==null?void 0:Z.origin)==null?void 0:O.urls)!=null&&ee[0])&&(Q.repoRemoteUrl=V||q.discovery.origin.urls[0]),(Y||(G=q==null?void 0:q.discovery)!=null&&G.repoIdentity)&&(Q.repoIdentity=Y||q.discovery.repoIdentity),(le=q==null?void 0:q.discovery)!=null&&le.defaultBranch&&(Q.defaultBranch=q.discovery.defaultBranch);const me=await n(J,"create_mesh",Q),Ae=r(me);if((Ae==null?void 0:Ae.success)===!1)throw new Error(Ae.error||"Create failed");const de=typeof((je=Ae==null?void 0:Ae.mesh)==null?void 0:je.id)=="string"?Ae.mesh.id:"";if(de&&o.createDaemonPicker&&T){const H=await n(J,"add_mesh_node",{meshId:de,daemonId:J,machineId:$==null?void 0:$.machineId,workspace:((ge=q==null?void 0:q.discovery)==null?void 0:ge.repoRoot)||T,repoRoot:(Ce=q==null?void 0:q.discovery)==null?void 0:Ce.repoRoot,isLocalWorktree:((ue=q==null?void 0:q.discovery)==null?void 0:ue.isLinkedWorktree)===!0,role:"host",providerPriority:jr(B)}),he=r(H);if((he==null?void 0:he.success)===!1)throw new Error(he.error||"Mesh created but failed to attach workspace")}y(!1),C(""),k(""),N(""),I(""),await R(),(z=Ae==null?void 0:Ae.mesh)!=null&&z.id&&m(Ae.mesh.id)}catch(U){h((U==null?void 0:U.message)||"Create failed")}}async function F(J){var Y;if(!confirm("Delete this mesh? This cannot be undone."))return;const V=((Y=u.find(se=>se.id===J))==null?void 0:Y.__sourceDaemonId)||t;try{const se=await n(V,"delete_mesh",{meshId:J}),ie=r(se);if((ie==null?void 0:ie.success)===!1)throw new Error(ie.error||"Failed to delete");d===J&&m(null),await R()}catch(se){h((se==null?void 0:se.message)||"Delete failed")}}function K(){y(!1),C(""),k(""),N("")}return{meshes:u,setMeshes:p,selectedMeshId:d,setSelectedMeshId:m,loading:f,error:S,setError:h,showCreate:x,setShowCreate:y,createName:b,setCreateName:C,createRepoIdentity:j,setCreateRepoIdentity:k,createRepoRemoteUrl:v,setCreateRepoRemoteUrl:N,newMeshDaemonId:w,setNewMeshDaemonId:A,newMeshWorkspace:T,setNewMeshWorkspace:I,createPickerWorkspaces:E,createPickerProviders:B,createOnboardingPlan:P,createPlanLoading:_,loadMeshes:R,handleCreate:M,handleDelete:F,cancelCreate:K}}function sP({selectedMesh:e,selectedMeshId:t,primaryDaemonId:n,activeDaemonId:r,daemons:a,sendCommand:o,unwrapResult:i,loadLiveMesh:c,resolveCommandTarget:u,launchCoordinator:p,features:d,loadMeshes:m,loadQueue:f,queueSection:g,setError:S}){const[h,x]=l.useState({}),[y,b]=l.useState(null),[C,j]=l.useState(null),[k,v]=l.useState(!1),[N,w]=l.useState(""),[A,T]=l.useState([]),[I,P]=l.useState(""),[D,_]=l.useState(!1),[W,$]=l.useState(null),[E,B]=l.useState(!1),[L,R]=l.useState(""),[M,F]=l.useState(!1),[K,J]=l.useState(!1),[V,Y]=l.useState(null),[se,ie]=l.useState(!1),[Z,O]=l.useState({override:"",append:""}),[ee,G]=l.useState(!1),[le,je]=l.useState({}),[ge,Ce]=l.useState(null),ue=l.useMemo(()=>a.find(De=>De.id===I),[a,I]),z=(ue==null?void 0:ue.workspaces)||[],U=l.useMemo(()=>Hn((ue==null?void 0:ue.availableProviders)||[]),[ue]);l.useEffect(()=>{if(!k||!t||!N.trim()){$(null);return}const De=d.addNodeDaemonPicker?I:(e==null?void 0:e.__sourceDaemonId)||n;if(!De)return;let _e=!1;return B(!0),o(De,"plan_mesh_onboarding",{workspace:N.trim(),meshId:t,inlineMesh:e,operation:"add_existing"}).then(ae=>{_e||$(i(ae))}).catch(ae=>{_e||$({success:!1,error:(ae==null?void 0:ae.message)||"Git discovery failed"})}).finally(()=>{_e||B(!1)}),()=>{_e=!0}},[k,t,e,N,I,n,d.addNodeDaemonPicker,o,i]);async function q(){var ae,we,Me;const De=(e==null?void 0:e.__sourceDaemonId)||n;if(!t||!De)return;const _e=N.trim();if(_e)try{const qe=d.addNodeDaemonPicker?I:De,ve=await o(qe,"plan_mesh_onboarding",{workspace:_e,meshId:t,inlineMesh:e,operation:"add_existing"}),$e=i(ve);if($($e),($e==null?void 0:$e.success)===!1)throw new Error(`${$e.code||"onboarding_blocked"}: ${$e.error}${$e.action?` ${$e.action}`:""}`);const lt={meshId:t,workspace:((ae=$e==null?void 0:$e.discovery)==null?void 0:ae.repoRoot)||_e,repoRoot:(we=$e==null?void 0:$e.discovery)==null?void 0:we.repoRoot,isLocalWorktree:((Me=$e==null?void 0:$e.discovery)==null?void 0:Me.isLinkedWorktree)===!0};d.addNodeDaemonPicker&&I&&(lt.daemonId=I,lt.machineId=ue==null?void 0:ue.machineId),lt.providerPriority=Fn(A);const at=await o(De,"add_mesh_node",lt),bt=i(at);if((bt==null?void 0:bt.success)===!1)throw new Error(bt.error||"Add node failed");v(!1),w(""),T([]),P(""),_(!1),await m(),g||await f(t)}catch(qe){S((qe==null?void 0:qe.message)||"Add node failed")}}async function Q(De){var Me;if(!e)return;const _e=Ri(e),ae=((Me=[{value:"preserve",label:"Preserve history and runtimes"},{value:"stop",label:"Stop live runtimes only"},{value:"delete_stopped",label:"Delete stopped sessions only"},{value:"stop_and_delete",label:"Stop and delete sessions"}].find(qe=>qe.value===_e.sessionCleanupOnNodeRemove))==null?void 0:Me.label)||"Preserve history and runtimes";if(!confirm(`Remove this node?
120
120
 
121
- Node removal cleanup policy: ${ae}`))return;const we=e.__sourceDaemonId||n;try{const qe=await o(we,"remove_mesh_node",{meshId:e.id,nodeId:De}),ve=i(qe);if((ve==null?void 0:ve.success)===!1)throw new Error(ve.error||"Remove failed");C===De&&j(null),await m(),g||await f(t)}catch(qe){S((qe==null?void 0:qe.message)||"Remove node failed")}}async function me(De){if(!e)return;const _e={...Ri(e),...De},ae=e.__sourceDaemonId||n;try{ie(!0),S(null);const we=await o(ae,"update_mesh",{meshId:e.id,policy:_e}),Me=i(we);if((Me==null?void 0:Me.success)===!1)throw new Error(Me.error||"Policy update failed");await m()}catch(we){S((we==null?void 0:we.message)||"Policy update failed")}finally{ie(!1)}}async function Ae(De){if(!t)return;const _e=(e==null?void 0:e.__sourceDaemonId)||n,ae=h[De.id]||nP(De),we=Fn(ae),Me={...De.policy||{}};delete Me.provider_priority,we.length?Me.providerPriority=we:delete Me.providerPriority;try{b(De.id),S(null);const qe=await o(_e,"update_mesh_node",{meshId:t,nodeId:De.id,policy:Me,providerPriority:we}),ve=i(qe);if((ve==null?void 0:ve.success)===!1){S(ve.error||"Node policy update failed");return}await m()}catch(qe){S((qe==null?void 0:qe.message)||"Node policy update failed")}finally{b(null)}}const[de,H]=l.useState(null);async function he(De,_e){if(!t)return;const ae=(e==null?void 0:e.__sourceDaemonId)||n;try{H(De.id),S(null);const we=await o(ae,"update_mesh_node",{meshId:t,nodeId:De.id,policy:{slots:_e}}),Me=i(we);if((Me==null?void 0:Me.success)===!1){S(Me.error||"Node slots update failed");return}await m()}catch(we){S((we==null?void 0:we.message)||"Node slots update failed")}finally{H(null)}}const[fe,ye]=l.useState(null);async function Pe(De,_e){if(!t)return;const ae=(e==null?void 0:e.__sourceDaemonId)||n,we=_e.map(Me=>Me.trim()).filter(Boolean);try{ye(De.id),S(null);const Me=await o(ae,"update_mesh_node",{meshId:t,nodeId:De.id,capabilities:we}),qe=i(Me);if((qe==null?void 0:qe.success)===!1){S(qe.error||"Node tag update failed");return}await m()}catch(Me){S((Me==null?void 0:Me.message)||"Node tag update failed")}finally{ye(null)}}async function He(){if(!n||!t)return;const _e={...(e==null?void 0:e.coordinator)||{}};Z.override.trim()?_e.systemPromptOverride=Z.override:delete _e.systemPromptOverride,Z.append.trim()?_e.systemPromptAppend=Z.append:delete _e.systemPromptAppend,delete _e.systemPromptSuffix;try{G(!0),S(null);const ae=await o(n,"update_mesh",{meshId:t,coordinator:_e}),we=i(ae);if((we==null?void 0:we.success)===!1){S(we.error||"Coordinator prompt save failed");return}await m()}catch(ae){S((ae==null?void 0:ae.message)||"Coordinator prompt save failed")}finally{G(!1)}}async function ke(De){if(!n||!t)return;const _e=(le[De.id]||"").trim();try{Ce(De.id),S(null);const ae=await o(n,"update_mesh_node",{meshId:t,nodeId:De.id,systemPrompt:_e}),we=i(ae);if((we==null?void 0:we.success)===!1){S(we.error||"Node instruction save failed");return}await m()}catch(ae){S((ae==null?void 0:ae.message)||"Node instruction save failed")}finally{Ce(null)}}async function pe(De){if(!(!e||!De)){S(null),Y(null);try{J(!0);const _e=(e.nodes||[]).find(Me=>Fs(String(Me.daemon_id||Me.daemonId||""),De)),ae=await o(De,"set_mesh_host",{meshId:e.id,hostDaemonId:De,..._e!=null&&_e.id?{hostNodeId:_e.id}:{}}),we=i(ae);if((we==null?void 0:we.success)===!1){S(we.error||"Setting the mesh host failed");return}await m()}catch(_e){S((_e==null?void 0:_e.message)||"Setting the mesh host failed")}finally{J(!1)}}}async function st(){if(e){S(null),Y(null);try{F(!0);const De=c?await c(r,e.id,e):null,_e=u(r,e.id,e,e.nodes||[],De);if("error"in _e)throw new Error(_e.error);const ae=await p(_e.targetDaemonId,{meshId:e.id,inlineMesh:_e.inlineMesh,coordinatorNodeId:_e.coordinatorNodeId,cliType:L.trim()||void 0});Y(ae.message)}catch(De){S((De==null?void 0:De.message)||"Coordinator launch failed")}finally{F(!1)}}}return{nodeProviderPriorityDrafts:h,setNodeProviderPriorityDrafts:x,savingNodePolicyId:y,selectedNodeId:C,setSelectedNodeId:j,showAddNode:k,setShowAddNode:v,nodeWorkspace:N,setNodeWorkspace:w,nodeProviderPriority:A,setNodeProviderPriority:T,nodeDaemonId:I,setNodeDaemonId:P,nodeCustomPath:D,setNodeCustomPath:_,nodePickerWorkspaces:z,nodePickerProviders:U,nodeOnboardingPlan:W,nodePlanLoading:E,coordinatorCliType:L,setCoordinatorCliType:R,launchingCoordinator:M,launchResult:V,settingMeshHost:K,savingPolicy:se,coordinatorPromptDraft:Z,setCoordinatorPromptDraft:O,savingCoordinatorPrompt:ee,nodeSystemPromptDrafts:le,setNodeSystemPromptDrafts:je,savingNodeSystemPromptId:ge,savingNodeSlotsId:de,savingNodeCapabilitiesId:fe,handleAddNode:q,handleRemoveNode:Q,handleUpdatePolicy:me,handleUpdateNodeProviderPriority:Ae,handleUpdateNodeSlots:he,handleUpdateNodeCapabilities:Pe,handleSaveCoordinatorPrompt:He,handleSaveNodeSystemPrompt:ke,handleLaunchCoordinator:st,handleSetMeshHost:pe}}function nP(e){var r;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>n.has(a)?!1:(n.add(a),!0))}function rP(e){const t=e.filter(r=>r.status==="pending"||r.status==="assigned"),n=e.filter(r=>r.status==="completed"||r.status==="failed"||r.status==="cancelled");return{active:t.length,historical:n.length,activeCounts:{pending:t.filter(r=>r.status==="pending").length,assigned:t.filter(r=>r.status==="assigned").length},historicalCounts:{completed:n.filter(r=>r.status==="completed").length,failed:n.filter(r=>r.status==="failed").length},counts:{pending:e.filter(r=>r.status==="pending").length,assigned:e.filter(r=>r.status==="assigned").length,completed:e.filter(r=>r.status==="completed").length,failed:e.filter(r=>r.status==="failed").length},staleAssignedCount:e.filter(r=>r.staleAssigned).length,recent:e.slice(0,20)}}function aP({primaryDaemonId:e,activeDaemonId:t,sendCommand:n,unwrapResult:r,loadLiveMesh:a,resolveCommandTarget:o}){const[i,c]=l.useState([]),[u,p]=l.useState(null),[d,m]=l.useState(!1),[f,g]=l.useState(null),S=l.useCallback(async x=>{if(!e||!x){c([]);return}try{const y=await n(e,"get_mesh_queue",{meshId:x});c(y!=null&&y.success?Array.isArray(y.queue)?y.queue:[]:[])}catch{c([])}},[e,n]);async function h(x){var y,b;if(x){m(!0),g(null);try{const C=a?await a(t,x.id,x):null,j=o(t,x.id,x,x.nodes||[],C);if("error"in j)throw new Error(j.error);const k=await n(j.targetDaemonId,"get_mesh_queue",{meshId:x.id}),v=r(k);if((v==null?void 0:v.success)===!1)throw new Error(v.error||"Queue load failed");const N=Array.isArray(((y=v==null?void 0:v.result)==null?void 0:y.rows)??(v==null?void 0:v.rows)??(v==null?void 0:v.queue))?((b=v==null?void 0:v.result)==null?void 0:b.rows)??(v==null?void 0:v.rows)??(v==null?void 0:v.queue):[];p(rP(N))}catch(C){g((C==null?void 0:C.message)||"Queue load failed")}finally{m(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:u,queueLoading:d,queueError:f,loadQueue:S,handleLoadQueue:h}}function oP(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}const Ah=new Map;function Th(e){return e?Ah.get(e)??null:null}function iP(e,t){!e||!t||Ah.set(e,t)}function lP({selectedMeshId:e,loadMeshStatus:t,extractStatus:n,normalizeNode:r,gateIncompleteGraph:a}){const[o,i]=l.useState(()=>Th(e)),[c,u]=l.useState(!1),[p,d]=l.useState(null),[m,f]=l.useState("idle"),[g,S]=l.useState(!1),h=l.useRef(!1);async function x(y,b=e,C=!1){if(!(!y||!b))try{u(!C&&o===null),f(C?"settling":"first_paint"),d(null);const j=await t(y,b,{refresh:C,retryProfile:C?"settled":"interactive"});S(oP(j));const k=n(j),v=r&&k?{...k,nodes:(k.nodes??[]).map(N=>r(N,k.meshId??b,""))}:k;if(v){if(a&&!C&&o!==null&&!fA(rh(v))){f("settling"),h.current||(h.current=!0,Promise.resolve().then(()=>x(y,b,!0)).finally(()=>{h.current=!1}));return}i(v),iP(b,v),f("settled")}else i(null),d("mesh_status returned an unexpected payload."),f("idle")}catch(j){o||i(null),d((j==null?void 0:j.message)||"Failed to load mesh graph"),f("idle")}finally{u(!1)}}return{meshGraphStatus:o,setMeshGraphStatus:i,graphLoading:c,graphError:p,setGraphError:d,graphProvenance:m,graphBootstrapFallback:g,loadGraph:x}}function Qd(e){return!e||e.hostSynthesized?{hostDaemonId:"",hostNodeId:""}:{hostDaemonId:String(e.hostDaemonId||""),hostNodeId:String(e.hostNodeId||"")}}function cP(e,t,n,r,a){if(!e.length)return"";const o=String(a||"");if(o){const u=e.find(p=>Fs(p.id,o));return u?u.id:o}const i=t.find(u=>u.role==="host"),c=String((i==null?void 0:i.daemon_id)||(i==null?void 0:i.daemonId)||"");if(c){const u=e.find(p=>Fs(p.id,c));if(u)return u.id}return""}const dP=7e3,uP=45e3;function pP(){const e=tI(),{sendCommand:t,sendData:n,daemons:r,userName:a,loadMeshStatus:o,launchCoordinator:i,loadLiveMesh:c,extractStatus:u,unwrapResult:p,normalizeMesh:d,normalizeNode:m,resolveCommandTarget:f,features:g,gateIncompleteGraph:S}=e,h=qn(),x=r[0],y=(x==null?void 0:x.id)||"",b=l.useMemo(()=>((x==null?void 0:x.availableProviders)||[]).filter(ot=>ot.category==="cli").map(ot=>({id:ot.type||ot.id,name:ot.displayName||ot.name||ot.type,meshCoordinator:ot.meshCoordinator})),[x]),C=l.useMemo(()=>Hn((x==null?void 0:x.availableProviders)||[]),[x]),{meshes:j,selectedMeshId:k,setSelectedMeshId:v,loading:N,error:w,setError:A,showCreate:T,setShowCreate:I,createName:P,setCreateName:D,createRepoIdentity:_,setCreateRepoIdentity:W,createRepoRemoteUrl:$,setCreateRepoRemoteUrl:E,newMeshDaemonId:B,setNewMeshDaemonId:L,newMeshWorkspace:R,setNewMeshWorkspace:M,createPickerWorkspaces:F,createOnboardingPlan:K,createPlanLoading:J,loadMeshes:V,handleCreate:Y,handleDelete:se,cancelCreate:ie}=tP({daemons:r,primaryDaemonId:y,sendCommand:t,unwrapResult:p,normalizeMesh:d,features:g,loadDaemonMetadata:h}),Z=j.find(We=>We.id===k)||null,{meshGraphStatus:O,setMeshGraphStatus:ee,graphLoading:G,graphError:le,setGraphError:je,loadGraph:ge}=lP({selectedMeshId:k,loadMeshStatus:o,extractStatus:u,normalizeNode:m,gateIncompleteGraph:S}),[Ce,ue]=l.useState(""),[z,U]=l.useState(""),q=g.meshHostDaemonSection?Ce:y,{meshQueue:Q,loadQueue:me}=aP({primaryDaemonId:y,activeDaemonId:q,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f}),{setNodeProviderPriorityDrafts:Ae,selectedNodeId:de,setSelectedNodeId:H,showAddNode:he,setShowAddNode:fe,nodeWorkspace:ye,setNodeWorkspace:Pe,nodeProviderPriority:He,setNodeProviderPriority:ke,nodeDaemonId:pe,setNodeDaemonId:st,nodeCustomPath:De,setNodeCustomPath:_e,nodePickerWorkspaces:ae,nodePickerProviders:we,nodeOnboardingPlan:Me,nodePlanLoading:qe,coordinatorCliType:ve,setCoordinatorCliType:$e,launchingCoordinator:lt,launchResult:at,savingPolicy:bt,coordinatorPromptDraft:X,setCoordinatorPromptDraft:te,savingCoordinatorPrompt:oe,nodeSystemPromptDrafts:be,setNodeSystemPromptDrafts:re,savingNodeSystemPromptId:Te,savingNodeSlotsId:Ee,savingNodeCapabilitiesId:Ie,handleAddNode:ze,handleRemoveNode:Ke,handleUpdatePolicy:Qe,handleUpdateNodeSlots:Ue,handleUpdateNodeCapabilities:Ye,handleSaveCoordinatorPrompt:tt,handleSaveNodeSystemPrompt:Be,handleLaunchCoordinator:ce,settingMeshHost:xe,handleSetMeshHost:Se}=sP({selectedMesh:Z,selectedMeshId:k,primaryDaemonId:y,activeDaemonId:q,daemons:r,availableCliProviders:C,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f,launchCoordinator:i,features:{addNodeDaemonPicker:g.addNodeDaemonPicker},loadMeshes:V,loadQueue:me,queueSection:g.queueSection,setError:A}),Fe=l.useMemo(()=>r.find(We=>We.id===q)||x,[r,q,x]),Je=l.useMemo(()=>new Set(((Z==null?void 0:Z.nodes)||[]).map(We=>String(We.daemon_id||We.daemonId||""))),[Z]),ct=l.useMemo(()=>r.filter(We=>We.id&&!Je.has(We.id)),[r,Je]),Oe=(Z==null?void 0:Z.nodes)||[],yt=l.useMemo(()=>Oe.find(We=>Fs(String(We.daemon_id||We.daemonId||""),Ce)),[Oe,Ce]),zt=g.meshHostDaemonSection?!!yt:!0,wt=l.useMemo(()=>{if(!g.meshHostDaemonSection||!Z)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const We=Z.meshHost,ot=O!=null&&O.meshId&&String(O.meshId)===String(Z.id??"")?O.meshHost:void 0,Vt=ot!=null&&ot.hostDaemonId?ot:We??ot,ss=Qd(Vt),Qt=ss.hostDaemonId,Ys=Oe.find(Xt=>Xt.role==="host"),Js=ss.hostNodeId||String((Ys==null?void 0:Ys.id)||""),Dt=Js?Oe.find(Xt=>String(Xt.id)===Js):void 0,ne=String((Dt==null?void 0:Dt.daemon_id)||(Dt==null?void 0:Dt.daemonId)||""),Ve=Qt||ne;if(!Ve)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const Ge=r.find(Xt=>Qt&&Fs(Xt.id,Qt))||(ne?r.find(Xt=>Fs(Xt.id,ne)):void 0);if(Ge)return{pinned:!0,daemonId:Ge.id,label:mP(Ge),online:!0,hostNode:Dt};const Et=String((Dt==null?void 0:Dt.machineLabel)||"")||String((Dt==null?void 0:Dt.workspace)||"")||Ve;return{pinned:!0,daemonId:Ve,label:Et,online:!1,hostNode:Dt}},[Z,Oe,r,O,g.meshHostDaemonSection]),es=wt.daemonId,Ot=wt.online,Vs=wt.pinned?wt.hostNode:yt,Le=l.useMemo(()=>!g.meshHostDaemonSection||!wt.pinned?"":!Ot&&z&&r.some(We=>We.id===z)?z:es,[g.meshHostDaemonSection,wt.pinned,Ot,z,r,es]),Ze=l.useMemo(()=>O?[...new Set((O.nodes??[]).map(We=>String(We.daemonId||We.daemon_id||"")).filter(Boolean))]:[],[O]),Rt=yh({status:O,daemonId:q||null,extraDaemonIds:Ze,meshId:k,sendData:n});l.useEffect(()=>{Ae(Object.fromEntries(((Z==null?void 0:Z.nodes)||[]).map(We=>[We.id,hP(We)])))},[Z]),l.useEffect(()=>{const We=(Z==null?void 0:Z.coordinator)||{};te({override:typeof We.systemPromptOverride=="string"?We.systemPromptOverride:"",append:typeof We.systemPromptAppend=="string"?We.systemPromptAppend:typeof We.systemPromptSuffix=="string"?We.systemPromptSuffix:""}),re(Object.fromEntries(((Z==null?void 0:Z.nodes)||[]).map(ot=>[ot.id,typeof ot.systemPrompt=="string"?ot.systemPrompt:""])))},[Z]),l.useEffect(()=>{const We=g.addNodeDaemonPicker?jr(we):jr(C);he&&He.length===0&&We.length>0&&ke(We)},[he,C,we,He.length,g.addNodeDaemonPicker]),l.useEffect(()=>{const We=new Set(((Z==null?void 0:Z.nodes)||[]).map(ot=>ot.id));de&&!We.has(de)&&H(null)},[Z,de]);const dt=l.useMemo(()=>{if(!(!(O!=null&&O.meshId)||String(O.meshId)!==String((Z==null?void 0:Z.id)??"")))return Qd(O.meshHost).hostDaemonId||void 0},[O,Z]),ts=l.useMemo(()=>cP(r,Oe,q,y,dt),[r,Oe,q,y,dt]);l.useEffect(()=>{if(!g.meshHostDaemonSection)return;if(!r.length&&!wt.pinned){ue("");return}const We=wt.pinned?Le:ts;We&&!Fs(We,Ce)&&ue(We)},[r,Ce,wt.pinned,Le,ts,g.meshHostDaemonSection]),l.useEffect(()=>{z&&(Ot||!r.some(We=>We.id===z))&&U("")},[Ot,z,r]),l.useEffect(()=>{if(g.createDaemonPicker){if(!r.length){L("");return}(!B||!r.some(We=>We.id===B))&&L(r[0].id)}},[r,B,g.createDaemonPicker]),l.useEffect(()=>{var We;if(!g.createDaemonPicker||!B){M("");return}if(!F.length){M("");return}F.some(ot=>ot.path===R)||M(((We=F[0])==null?void 0:We.path)||"")},[B,R,F,g.createDaemonPicker]);const Ut=l.useRef(null);l.useEffect(()=>{if(!k)return;const We=Ut.current!==k;if(Ut.current=k,We){const ot=Th(k);ee(ot),je(null),ge(q,k,ot!==null)}else je(null),ge(q,k,!0)},[k,q]);const Kt=l.useRef(ge);Kt.current=ge;const ls=l.useRef(!1),vs=l.useRef(()=>{});vs.current=()=>{ls.current||!k||!q||(ls.current=!0,Promise.resolve(Kt.current(q,k,!0)).finally(()=>{ls.current=!1}))};const ys=g.meshStatePushRefresh?uP:dP;ZD({daemonIds:l.useMemo(()=>[q,...Ze].filter(Boolean),[q,Ze]),meshId:k,sendData:n,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||vs.current()}}),l.useEffect(()=>{if(!k||!q||typeof document>"u")return;let We=null;const ot=()=>{document.visibilityState==="visible"&&vs.current()},Vt=()=>{We===null&&(We=setInterval(ot,ys))},ss=()=>{We!==null&&(clearInterval(We),We=null)},Qt=()=>{document.visibilityState==="visible"?Vt():ss()};return document.visibilityState==="visible"&&Vt(),document.addEventListener("visibilitychange",Qt),()=>{ss(),document.removeEventListener("visibilitychange",Qt)}},[k,q,ys]),l.useEffect(()=>{g.queueSection||me(k)},[k,g.queueSection]);const ws=l.useMemo(()=>r.map(We=>We.id).filter(Boolean).sort().join(","),[r]),Ts=l.useRef(!1);return l.useEffect(()=>{V(Ts.current),Ts.current=!0},[ws]),y?Z?s.jsx(eP,{selectedMesh:Z,error:w,onDismissError:()=>A(null),onBack:()=>{v(null),ee(null)},onDelete:se,displayedMeshStatus:Rt,graphLoading:G,graphError:le,onRefreshGraph:()=>ge(q,k,!0),savingPolicy:bt,onUpdatePolicy:Qe,coordinatorPromptDraft:X,onCoordinatorPromptDraftChange:te,savingCoordinatorPrompt:oe,onSaveCoordinatorPrompt:tt,daemons:r,coordinatorDaemonId:Ce,onCoordinatorDaemonIdChange:ue,coordinatorCliType:ve,onCoordinatorCliTypeChange:$e,launchingCoordinator:lt,launchResult:at,isHostNodeAttached:zt,selectedHostNode:Vs,hostPinned:wt.pinned,hostLabel:wt.label,hostOnline:Ot,hostRebindDaemonId:z,onHostRebindDaemonIdChange:We=>U(We),onLaunchCoordinator:ce,settingMeshHost:xe,onSetMeshHost:Se,activeDaemon:Fe,activeDaemonId:q,meshQueue:Q,userName:a,availableCliProviders:C,savingNodeSlotsId:Ee,onUpdateNodeSlots:Ue,savingNodeCapabilitiesId:Ie,onUpdateNodeCapabilities:Ye,nodeSystemPromptDrafts:be,onNodeSystemPromptDraftChange:(We,ot)=>re(Vt=>({...Vt,[We]:ot})),savingNodeSystemPromptId:Te,onSaveNodeSystemPrompt:Be,selectedNodeId:de,onSelectNode:H,showAddNode:he,onShowAddNode:()=>fe(!0),onCancelAddNode:()=>fe(!1),nodeWorkspace:ye,onNodeWorkspaceChange:Pe,nodeProviderPriority:He,onNodeProviderPriorityChange:ke,nodeDaemonId:pe,onNodeDaemonIdChange:st,nodeCustomPath:De,onNodeCustomPathChange:_e,nodePickerWorkspaces:ae,nodePickerProviders:we,nodeOnboardingPlan:Me,nodePlanLoading:qe,attachableDaemons:ct,onAddNode:ze,onRemoveNode:Ke,availableCliAgents:b,features:{coordinatorPrompt:g.coordinatorPrompt,meshHostDaemonSection:g.meshHostDaemonSection,hermesMcpConfig:g.hermesMcpConfig,addNodeDaemonPicker:g.addNodeDaemonPicker,nodeInstruction:g.nodeInstruction},sendCommand:t}):s.jsx(lI,{meshes:j,loading:N,error:w,onDismissError:()=>A(null),daemons:r,features:{createDaemonPicker:g.createDaemonPicker,maxMeshes:g.maxMeshes},showCreate:T,onToggleCreate:()=>I(!T),createName:P,onCreateNameChange:D,createRepoIdentity:_,onCreateRepoIdentityChange:W,createRepoRemoteUrl:$,onCreateRepoRemoteUrlChange:E,newMeshDaemonId:B,onNewMeshDaemonIdChange:L,newMeshWorkspace:R,onNewMeshWorkspaceChange:M,createPickerWorkspaces:F,createOnboardingPlan:K,createPlanLoading:J,onSelectMesh:v,onCreate:Y,onCancelCreate:ie}):s.jsx(Lr,{icon:s.jsx(os,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})})}function mP(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function hP(e){var r;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>n.has(a)?!1:(n.add(a),!0))}function fP({children:e}){const{sendCommand:t,sendData:n}=St(),{ides:r}=As(),a=l.useMemo(()=>r.filter(i=>i.daemonMode||i.type==="adhdev-daemon").map(i=>i),[r]),o=l.useMemo(()=>({sendCommand:t,sendData:n,daemons:a,userName:void 0,loadMeshStatus:async(i,c)=>t(i,"mesh_status",{meshId:c}),launchCoordinator:async(i,c)=>{var f;const u={meshId:c.meshId};c.cliType&&(u.cliType=c.cliType);const p=await t(i,"launch_mesh_coordinator",u),d=(p==null?void 0:p.result)??p;if((d==null?void 0:d.success)===!1)throw new Error(d.error||"Coordinator launch failed");const m=(d==null?void 0:d.sessionId)||((f=d==null?void 0:d.session)==null?void 0:f.id)||(d==null?void 0:d.targetSessionId);return{sessionId:m,message:m?`Coordinator launched (${m})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:sl,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,u)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:eI}),[t,n,a]);return s.jsx(Nh.Provider,{value:o,children:e})}function Il(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function bP(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),n=Il();return n&&!t.searchParams.has("token")&&t.searchParams.set("token",n),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function Cs(e,t){return await fetch(bP(e),{credentials:"same-origin",...t})}function Mh(){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 gP{constructor(){nt(this,"adapters",new Map);nt(this,"states",new Map);nt(this,"runtimeListeners",new Map);nt(this,"screenshotCallbacks",new Map);nt(this,"statusCallbacks",new Set);nt(this,"stateChangeCallbacks",new Set);nt(this,"ptyInputSender",null)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const n of this.adapters.keys())if(n.startsWith("standalone"))return n}return null}register(t,n){this.adapters.set(t,n),this.states.set(t,n.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,n){this.states.set(t,n);const r=this.resolveDaemonId(t)||t;this.stateChangeCallbacks.forEach(a=>a(r,n))}onStateChange(t){return this.stateChangeCallbacks.add(t),()=>{this.stateChangeCallbacks.delete(t)}}retryConnection(t){}get(t){const n=this.resolveDaemonId(t);return n?this.adapters.get(n):void 0}getState(t){const n=this.resolveDaemonId(t);return n&&this.states.get(n)||"disconnected"}registerPtyInputSender(t){this.ptyInputSender=t}sendData(t,n){return!1}sendPtyInput(t,n,r){return this.ptyInputSender?this.ptyInputSender(t,n,r):!1}onScreenshot(t,n){return this.screenshotCallbacks.set(t,n),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,n){this.screenshotCallbacks.forEach(r=>r(t,n))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,n){this.statusCallbacks.forEach(r=>r(t,n))}emitRuntimeSnapshot(t,n,r=0,a=!1,o,i){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:r,text:n,truncated:a,cols:o,rows:i})}emitSessionOutput(t,n,r){!t||typeof n!="string"||!n||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof r=="number"?{seq:r}:{},data:n})}onRuntimeEvent(t,n){const r=this.runtimeListeners.get(t)||new Set;return r.add(n),this.runtimeListeners.set(t,r),()=>{const a=this.runtimeListeners.get(t);a&&(a.delete(n),a.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,n,r){if(!n)return{success:!1,error:"sessionId is required"};const a=new URL(`/api/v1/runtime/${encodeURIComponent(n)}/snapshot`,window.location.origin);typeof(r==null?void 0:r.sinceSeq)=="number"&&a.searchParams.set("sinceSeq",String(r.sinceSeq));const o=await Cs(`${a.pathname}${a.search}`);if(!o.ok){let c=`Runtime snapshot unavailable (${o.status})`;try{const u=await o.json();u!=null&&u.error&&(c=u.error)}catch{}return{success:!1,error:c}}const i=await o.json();return this.emitRuntimeEvent(n,{type:"runtime_snapshot",sessionId:n,seq:typeof i.seq=="number"?i.seq:0,text:typeof i.text=="string"?i.text:"",truncated:!!i.truncated,cols:typeof i.cols=="number"?i.cols:void 0,rows:typeof i.rows=="number"?i.rows:void 0,force:!!(r!=null&&r.force)}),{success:!0}}emitRuntimeEvent(t,n){var r;(r=this.runtimeListeners.get(t))==null||r.forEach(a=>a(n))}}const Ss=new gP;function xP(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=Il();return n?`${t}?token=${encodeURIComponent(n)}`:t}const sa=xP(),Xd=3e3,vP=3e4;let us=null,yP=0;const _a=new Map;let en=null,xr=null;function Zd(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function ar(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function wP(e){return e==="connected"?"connected":e}async function vr(e,t,n){const r=Vp(e,n||{}),a=us;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++yP}_${Date.now()}`;return new Promise((i,c)=>{const u=setTimeout(()=>{_a.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);_a.set(o,{resolve:p=>{clearTimeout(u),i(p)},reject:p=>{clearTimeout(u),c(p)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:r.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Ei(e,t){const n=us;if(!n||n.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return n.send(JSON.stringify(t)),!0}catch{return!1}}function Dh(e,t,n){const r=us;if(!r||r.readyState!==WebSocket.OPEN)return!1;const a=Vp(e,{sessionId:t,targetSessionId:t,data:n});try{return r.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}Ss.registerPtyInputSender(Dh);class kP{constructor(t){nt(this,"daemonId");nt(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(us==null?void 0:us.readyState)===WebSocket.OPEN}get connectionState(){return(us==null?void 0:us.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,n){return vr(this.daemonId,t,n)}async sendInput(t,n){return vr(this.daemonId,"cdp_remote_action",{action:t,params:n,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,en&&(clearInterval(en),en=null);const n=async()=>{if(this.hasCommandChannel)try{const r=await vr(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(r!=null&&r.success&&(r!=null&&r.base64)){const a=await fetch(`data:image/jpeg;base64,${r.base64}`).then(o=>o.blob());Ss.emitScreenshot(this.daemonId,a)}}catch{}};n(),en=setInterval(n,2e3)}stopScreenshots(t){en&&(clearInterval(en),en=null)}}let rs=null;function SP(e){return(!rs||rs.daemonId!==e)&&(rs=new kP(e)),rs}function CP({children:e}){const t=l.useRef(yr()),n=yr();t.current=n;const{setUserName:r}=As(),a=l.useRef(r);a.current=r;const o=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),u=l.useCallback((h,x)=>{c(h),xr==null||xr(h,x)},[]),p=l.useRef(null),d=l.useRef(),m=l.useRef(Xd),f=l.useRef(!0),g=l.useRef(!1),S=l.useRef("initial_connect");return l.useEffect(()=>{f.current=!0,g.current=!1;function h(){var b,C;if(!f.current||((b=p.current)==null?void 0:b.readyState)===WebSocket.OPEN||((C=p.current)==null?void 0:C.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${sa}...`),ar("connect_attempt",{url:sa,reason:S.current,delayMs:m.current});let y;try{y=new WebSocket(sa)}catch(j){console.error("[Standalone WS] Failed to create WebSocket:",j),x();return}p.current=y,y.onopen=()=>{if(!f.current){y.close();return}u("connected"),m.current=Xd,ar("open",{url:sa,reason:S.current}),fs.resubscribeAll({sendData:Ei}),console.log("[Standalone WS] Connected")},us=y,y.onmessage=j=>{var k,v;try{const N=JSON.parse(j.data);if((N.type==="command_result"||N.type==="error")&&N.requestId){const w=_a.get(N.requestId);w&&(_a.delete(N.requestId),N.type==="error"?w.reject(new Error(((k=N.data)==null?void 0:k.message)||"Command failed")):w.resolve(N.data));return}if(N.type==="session_output"){const w=N.sessionId||N.cliId||N.cliType;w&&Ss.emitSessionOutput(w,typeof N.data=="string"?N.data:"",typeof N.seq=="number"?N.seq:void 0);return}if(N.type==="runtime_snapshot"){Ss.emitRuntimeSnapshot(N.sessionId,typeof N.text=="string"?N.text:"",typeof N.seq=="number"?N.seq:0,!!N.truncated,typeof N.cols=="number"?N.cols:void 0,typeof N.rows=="number"?N.rows:void 0);return}if(N.type==="topic_update"){const w=N.update;w&&fs.publish(w);return}if(N.type==="status"||N.type==="initial_state"){const w=N.data;if(!w)return;const{injectEntries:A,markLoaded:T,getIdes:I}=t.current,P=w.instanceId||"standalone",D=I().find($=>$.id===P),_=SP(P);Ss.register(P,_),Ss.setState(P,"connected"),u("connected",P),Ss.emitStatus(P,w);const W=wa(w,{daemonId:P,existingDaemon:D,existingEntries:I()});Zd("ws_status",{type:N.type,daemonId:P,sessions:(w.sessions||[]).map($=>({id:$.id,parentId:$.parentId,providerType:$.providerType,kind:$.kind,transport:$.transport,unread:$.unread,inboxBucket:$.inboxBucket,lastSeenAt:$.lastSeenAt,lastUpdated:$.lastUpdated,title:$.title})),recentLaunches:(w.recentLaunches||[]).map($=>({id:$.id,providerType:$.providerType,kind:$.kind,workspace:$.workspace,lastLaunchedAt:$.lastLaunchedAt}))}),Zd("entries",{daemonId:P,entries:W.filter($=>$.type!=="adhdev-daemon").map($=>({id:$.id,type:$.type,unread:$.unread,inboxBucket:$.inboxBucket,lastSeenAt:$.lastSeenAt,lastUpdated:$.lastUpdated,sessionId:$.sessionId}))}),W.length>0&&A(W,{authoritativeDaemonIds:[P]}),T(),i.current!==P&&((v=o.current)==null||v.call(o),i.current=P,o.current=fs.subscribe({sendData:Ei},P,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${P}`,params:{includeSessions:!0}},$=>{if($.topic!=="daemon.metadata")return;const E=t.current.getIdes(),B=E.find(R=>R.id===P),L=wa($.status,{daemonId:P,existingDaemon:B,existingEntries:E,timestamp:$.timestamp});L.length>0&&t.current.injectEntries(L,{authoritativeDaemonIds:[P]}),$.userName&&a.current&&a.current($.userName)}))}}catch(N){console.error("[Standalone WS] Parse error:",N)}},y.onclose=j=>{f.current&&(rs==null||rs.stopScreenshots(),rs&&Ss.setState(rs.daemonId,"disconnected"),u("disconnected"),p.current=null,S.current=`close:${j.code}${j.wasClean?":clean":":unclean"}`,ar("close",{code:j.code,reason:j.reason||"",wasClean:j.wasClean}),x())},y.onerror=j=>{g.current||!f.current||(S.current="error",ar("error",{message:j instanceof Event?"event":String(j),readyState:y.readyState}),console.warn("[Standalone WS] Error, will reconnect:",j))}}function x(){if(!f.current)return;clearTimeout(d.current);const y=m.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),ar("schedule_reconnect",{reason:S.current,delayMs:y}),d.current=setTimeout(()=>{m.current=Math.min(m.current*1.5,vP),h()},y)}return h(),()=>{var y;f.current=!1,g.current=!0,(y=o.current)==null||y.call(o),o.current=null,i.current=null,clearTimeout(d.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,us=null),rs&&(rs.stopScreenshots(),Ss.unregister(rs.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function jP({children:e}){const[t,n]=l.useState("disconnected"),[r,a]=l.useState(null);l.useEffect(()=>(xr=(i,c)=>{n(i),c&&a(c)},()=>{xr=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=wP(t),u={};return r&&(u[r]=c),u.standalone=c,{wsStatus:t,isConnected:i,connectionStates:u}},[t,r]);return s.jsx(Nf,{connectionOverrides:o,children:s.jsx(CP,{children:e})})}const Ih="adhdev_standalone_font_preferences",dn={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},ao=[{id:"default",label:"Default",family:"var(--font-sans)",description:"Current dashboard sans stack"},{id:"system-ui",label:"System UI",family:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Use the browser/OS default UI font"},{id:"inter",label:"Inter",family:'"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Match the current product default explicitly"},{id:"pretendard",label:"Pretendard",family:'"Pretendard", "Noto Sans KR", system-ui, sans-serif',description:"Crisp Korean-first sans fallback stack"},{id:"noto-sans-kr",label:"Noto Sans KR",family:'"Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic", "Segoe UI", sans-serif',description:"Wide CJK coverage with neutral metrics"},{id:"serif",label:"Serif",family:'"Iowan Old Style", "Apple Garamond", "Times New Roman", serif',description:"Reading-focused serif stack for long replies"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS font-family stack"}],Tr=[{id:"default",label:"Default mono",family:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',description:"Current monospace stack"},{id:"jetbrains-mono",label:"JetBrains Mono",family:'"JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Readable coding font with strong punctuation"},{id:"fira-code",label:"Fira Code",family:'"Fira Code", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Popular ligature-friendly code font"},{id:"cascadia-code",label:"Cascadia Code",family:'"Cascadia Code", "Cascadia Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Windows-friendly modern coding font"},{id:"berkeley-mono",label:"Berkeley Mono",family:'"Berkeley Mono", "SF Mono", ui-monospace, Menlo, Consolas, monospace',description:"Editorial-feeling mono stack if installed"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS monospace stack"}],NP=new Set(ao.map(e=>e.id)),AP=new Set(Tr.map(e=>e.id));function js(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:ha("chat",t.chat),code:ha("code",t.code),terminal:ha("terminal",t.terminal)}}function ha(e,t){const n=dn[e],r=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof r.preset=="string"?r.preset.trim():"",o=typeof r.customFamily=="string"?r.customFamily.trim():"";return(e==="chat"?NP:AP).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:n:{preset:a}:n}function fa(e,t){var a;const n=ha(e,t);if(n.preset==="custom"&&n.customFamily)return n.customFamily;const r=e==="chat"?ao:Tr;return((a=r.find(o=>o.id===n.preset))==null?void 0:a.family)||r[0].family}function TP(e){const t=js(e),n=fa("chat",t.chat),r=fa("code",t.code),a=fa("terminal",t.terminal);return{"--chat-font-family":n,"--chat-code-font-family":r,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function sn(e,t=document.documentElement){const n=js(e),r=TP(n);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(r))t.style.setProperty(a,o);return n}function _i(e){const t=js(e);try{localStorage.setItem(Ih,JSON.stringify(t))}catch{}return t}function MP(){try{const e=localStorage.getItem(Ih);if(e)return js(JSON.parse(e))}catch{}return dn}function DP(){return sn(MP())}function or(e,t){var r;const n=e==="chat"?ao:Tr;return((r=n.find(a=>a.id===t))==null?void 0:r.label)||n[0].label}function IP({children:e}){const t=Mr(),n=Hi(),{t:r}=Ne("common"),a=l.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:s.jsx(hu,{}),label:r("standalone.nav.dashboard"),active:n.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:s.jsx(Os,{}),label:"Burrow",active:n.pathname.startsWith("/machines"),onSelect:()=>t("/machines")},{id:"mesh",path:"/mesh",icon:s.jsx(os,{}),label:"Mesh",active:n.pathname.startsWith("/mesh"),onSelect:()=>t("/mesh")},{id:"settings",path:"/settings",icon:s.jsx(Ha,{}),label:r("standalone.nav.settings"),active:n.pathname.startsWith("/settings"),onSelect:()=>t("/settings")}],[n.pathname,t,r]),o=l.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:r("standalone.nav.docs")}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(bu,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:r("standalone.nav.docs")},{id:"about",label:r("standalone.nav.about"),icon:s.jsx(Oi,{}),active:n.pathname==="/about",onSelect:()=>t("/about"),title:r("standalone.nav.about")}],[n.pathname,t,r]);return s.jsx(cC,{brand:({collapsed:i})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&s.jsx("span",{children:"ADHDev"})]}),navItems:a,footerItems:o,footerInfo:({collapsed:i})=>i?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","1.0.29"]}),footerActions:({collapsed:i,toggleCollapsed:c})=>s.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:r(i?"standalone.layout.expandSidebar":"standalone.layout.collapseSidebar"),children:[s.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&s.jsx("span",{className:"text-xs",children:r("standalone.layout.collapse")})]}),children:e})}const PP=[{icon:s.jsx(Os,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(bn,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(vu,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(xs,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(wr,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(bu,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],LP=[{icon:s.jsx(sb,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(hu,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Un,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Jf,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(fu,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Xf,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],RP=[{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 EP(){const{t:e}=Ne("common");return s.jsxs(Lr,{icon:s.jsx(Oi,{className:"text-text-primary"}),title:e("standalone.about.title"),subtitle:e("standalone.about.subtitle"),widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","1.0.29"]}),children:[s.jsx(gt,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:e("standalone.about.selfHostedEdition")}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:e("standalone.about.headline")}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:e("standalone.about.description")})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.docs")}),s.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.github")}),s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.tryCloud")})]})]})}),s.jsx(gt,{title:e("standalone.about.includedSection"),description:e("standalone.about.includedDescription"),children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:PP.map(t=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:t.icon}),t.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),s.jsx(gt,{title:e("standalone.about.inventorySection"),description:e("standalone.about.inventoryDescription"),children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:Yp.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:Qp.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:Jp.map(t=>`${t.icon} ${t.name}`)}].map(t=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:t.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:t.items.map(n=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:n},n))})]},t.label))})}),s.jsx(gt,{title:e("standalone.about.cloudExtrasSection"),description:e("standalone.about.cloudExtrasDescription"),children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:LP.map(t=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:t.icon}),t.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),s.jsx(gt,{title:e("standalone.about.comparisonSection"),description:e("standalone.about.comparisonDescription"),children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:e("standalone.about.featureHeader")}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:e("standalone.about.selfhostHeader")}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:e("standalone.about.cloudHeader")})]})}),s.jsx("tbody",{children:RP.map((t,n)=>s.jsxs("tr",{className:n%2===0?"bg-bg-glass":"bg-transparent",children:[s.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:t.feature}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:t.selfhost?s.jsx("span",{className:"text-emerald-500",children:"✓"}):s.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:s.jsx("span",{className:"text-emerald-500",children:"✓"})})]},t.feature))})]})})}),s.jsx(Ya,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:e("standalone.about.cloudOptional"),description:e("standalone.about.cloudOptionalDescription"),action:s.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:e("standalone.about.compareCloud")}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(ub,{size:14,className:"mr-1"}),e("standalone.about.discord")]})]})})]})}function ei(e,t,n){return{...e,[t]:n}}function ti({surface:e,title:t,description:n,value:r,options:a,onChange:o}){const{t:i}=Ne("common");return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:n})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(mC,{value:r.preset,onChange:c=>{const u=c.target.value;o(u==="custom"?{preset:"custom",customFamily:r.customFamily||""}:{preset:u})},children:a.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),r.preset==="custom"&&s.jsx(hs,{type:"text",className:"font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:r.customFamily||"",onChange:c=>o({preset:"custom",customFamily:c.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:i("standalone.fonts.resolvedStack")})," ",s.jsx("span",{className:"font-mono break-all",children:fa(e,r)})]})]})]})}function _P({value:e,savedValue:t,saving:n=!1,error:r,notice:a,onChange:o,onSave:i,onResetToSaved:c,onResetToDefaults:u}){const{t:p}=Ne("common"),d=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:p("standalone.fonts.fontOverridesNotice")}),r&&s.jsx(Lt,{variant:"error",children:r}),a&&s.jsx(Lt,{variant:"success",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(ti,{surface:"chat",title:p("standalone.fonts.chat"),description:p("standalone.fonts.chatDescription"),value:e.chat,options:ao,onChange:m=>o(ei(e,"chat",m))}),s.jsx(ti,{surface:"code",title:p("standalone.fonts.code"),description:p("standalone.fonts.codeDescription"),value:e.code,options:Tr,onChange:m=>o(ei(e,"code",m))}),s.jsx(ti,{surface:"terminal",title:p("standalone.fonts.terminal"),description:p("standalone.fonts.terminalDescription"),value:e.terminal,options:Tr,onChange:m=>o(ei(e,"terminal",m))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:p("standalone.fonts.livePreview")}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",or("chat",e.chat.preset)," · Code: ",or("code",e.code.preset)," · Terminal: ",or("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[p("standalone.fonts.defaults")," ",or("chat",dn.chat.preset)," / ",or("code",dn.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(Is,{type:"button",variant:"primary",size:"sm",onClick:i,disabled:n||!d,children:p(n?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),s.jsx(Is,{type:"button",variant:"secondary",size:"sm",onClick:c,disabled:n||!d,children:p("standalone.fonts.revertToSaved")}),s.jsx(Is,{type:"button",variant:"secondary",size:"sm",onClick:u,disabled:n,children:p("standalone.fonts.resetToDefaults")})]})]})}function $P(){const{t:e}=Ne("common"),{ides:t}=As(),n=t.find(O=>O.type==="adhdev-daemon"),r=(n==null?void 0:n.detectedIdes)||[],{sendCommand:a}=St(),{userName:o}=As(),[i,c]=l.useState(o||""),[u,p]=l.useState(null),[d,m]=l.useState(null),[f,g]=l.useState(dn),[S,h]=l.useState(!1),[x,y]=l.useState(""),[b,C]=l.useState(""),[j,k]=l.useState("127.0.0.1"),[v,N]=l.useState(""),[w,A]=l.useState(""),[T,I]=l.useState(""),[P,D]=l.useState(""),[_,W]=l.useState(""),[$,E]=l.useState(!1),B=async()=>{const ee=await(await Cs("/auth/session")).json();p(ee)},L=async()=>{const ee=await(await Cs("/api/v1/standalone/preferences")).json();m(ee),k(ee.standaloneBindHost);const G=js(ee.standaloneFontPreferences);g(G),sn(G),_i(G)};l.useEffect(()=>{o!==void 0&&c(o)},[o]),l.useEffect(()=>{Promise.all([B(),L()]).catch(O=>{D(O instanceof Error?O.message:String(O))})},[]),l.useEffect(()=>{sn(f)},[f]);const R=O=>{const ee=O.target.value.trim();n!=null&&n.id&&ee!==o&&a(n.id,"set_user_name",{userName:ee}).catch(console.error)},[M,F]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),K=O=>{F(O);try{localStorage.setItem("adhdev_sound",O?"1":"0")}catch{}},J=async()=>{y(""),C(""),h(!0);try{const O=js(f),ee=await Cs("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:O})}),G=await ee.json();if(!ee.ok)throw new Error((G==null?void 0:G.error)||"Failed to save standalone font preferences");const le=js(G.standaloneFontPreferences);m(G),g(le),sn(le),_i(le),C(e("standalone.settings.fontsSaved"))}catch(O){y(O instanceof Error?O.message:String(O))}finally{h(!1)}},V=()=>{const O=js(d==null?void 0:d.standaloneFontPreferences);y(""),C(""),g(O),sn(O)},Y=()=>{y(""),C(""),g(dn),sn(dn)},se=async()=>{D(""),W(""),E(!0);try{const O=await Cs("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:j})}),ee=await O.json();if(!O.ok)throw new Error((ee==null?void 0:ee.error)||"Failed to save standalone network preference");m(ee),k(ee.standaloneBindHost),W(ee.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(O){D(O instanceof Error?O.message:String(O))}finally{E(!1)}},ie=async()=>{if(D(""),W(""),w.trim().length<4){D(e("standalone.settings.passwordTooShort"));return}if(w!==T){D(e("standalone.settings.passwordMismatch"));return}E(!0);try{const O=await Cs("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,newPassword:w})}),ee=await O.json();if(!O.ok)throw new Error((ee==null?void 0:ee.error)||"Failed to save password");p(ee),await L(),N(""),A(""),I(""),W(u!=null&&u.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),Mh()}catch(O){D(O instanceof Error?O.message:String(O))}finally{E(!1)}},Z=async()=>{D(""),W(""),E(!0);try{const O=await Cs("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,clear:!0})}),ee=await O.json();if(!O.ok)throw new Error((ee==null?void 0:ee.error)||"Failed to clear password");p(ee),await L(),N(""),A(""),I(""),W(e("standalone.settings.passwordDisabled"))}catch(O){D(O instanceof Error?O.message:String(O))}finally{E(!1)}};return s.jsxs(Lr,{icon:s.jsx(Ha,{className:"text-text-primary"}),title:e("standalone.settings.title"),subtitle:e("standalone.settings.subtitle"),widthClassName:"max-w-5xl",children:[s.jsx(Lt,{variant:"info",children:e("standalone.settings.infoNotice")}),(u==null?void 0:u.publicHostWarning)&&s.jsx(Lt,{variant:"warning",children:e("standalone.settings.publicHostWarning")}),s.jsx(gt,{title:e("standalone.settings.daemonSection"),description:e("standalone.settings.daemonDescription"),children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.versionLabel")}),s.jsxs("span",{className:"font-mono text-xs",children:["v","1.0.29"]}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.statusLabel")}),s.jsx("span",{className:n?"text-green-400":"text-yellow-400",children:e(n?"standalone.settings.statusRunning":"standalone.settings.statusNotConnected")}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.currentBindLabel")}),s.jsx("span",{className:"font-mono text-xs",children:(d==null?void 0:d.currentBindHost)||(u==null?void 0:u.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.defaultBindLabel")}),s.jsx("span",{className:"font-mono text-xs",children:(d==null?void 0:d.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.authLabel")}),s.jsx("span",{className:"text-xs",children:u!=null&&u.hasPasswordAuth?e("standalone.settings.authPassword"):u!=null&&u.hasTokenAuth?e("standalone.settings.authToken"):e("standalone.settings.authNone")})]})}),s.jsx(gt,{title:e("standalone.settings.networkSection"),description:e("standalone.settings.networkDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:e("standalone.settings.networkHint")}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:j==="127.0.0.1",onChange:()=>k("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.localhostLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.localhostHint")})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:j==="0.0.0.0",onChange:()=>k("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.allInterfacesLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.allInterfacesHint")})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(Is,{type:"button",variant:"primary",size:"sm",onClick:()=>{se()},disabled:$,children:e($?"standalone.settings.saving":"standalone.settings.saveNetworkMode")}),s.jsx("span",{className:"text-xs text-text-muted",children:e("standalone.settings.networkRestartHint",{host:(d==null?void 0:d.currentBindHost)||(u==null?void 0:u.boundHost)||"127.0.0.1"})})]})]})}),s.jsx(gt,{title:e("standalone.settings.securitySection"),description:e("standalone.settings.securityDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:u!=null&&u.hasPasswordAuth?e("standalone.settings.passwordSet"):e("standalone.settings.passwordNotSet")}),P&&s.jsx(Lt,{variant:"error",children:P}),_&&s.jsx(Lt,{variant:"success",children:_}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx(hs,{type:"password",placeholder:u!=null&&u.hasPasswordAuth?e("standalone.settings.currentPasswordPlaceholder"):e("standalone.settings.currentPasswordFirstTimePlaceholder"),value:v,onChange:O=>N(O.target.value)}),s.jsx(hs,{type:"password",placeholder:u!=null&&u.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:w,onChange:O=>A(O.target.value)}),s.jsx(hs,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:T,onChange:O=>I(O.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Is,{type:"button",variant:"primary",size:"sm",onClick:()=>{ie()},disabled:$,children:$?e("standalone.settings.saving"):u!=null&&u.hasPasswordAuth?e("standalone.settings.updatePassword"):e("standalone.settings.enablePassword")}),(u==null?void 0:u.hasPasswordAuth)&&s.jsx(Is,{type:"button",variant:"danger",size:"sm",onClick:()=>{Z()},disabled:$,children:e("standalone.settings.disablePassword")})]})]})}),s.jsx(gt,{title:e("standalone.settings.detectedIdesSection"),description:e("standalone.settings.detectedIdesDescription"),children:r.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:e("standalone.settings.noIdesDetected")}):s.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(O=>s.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${O.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:O.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:O.type})]},O.type))})}),s.jsx(gt,{title:e("standalone.settings.machineSection"),description:e("standalone.settings.machineDescription"),children:s.jsx(SC,{ides:t,emptyMessage:e("standalone.settings.daemonNotConnected")})}),s.jsx(gt,{title:e("standalone.settings.appearanceSection"),description:e("standalone.settings.appearanceDescription"),children:s.jsx(UC,{themeDescription:e("standalone.settings.themeDescription"),mobileDescription:e("standalone.settings.mobileDescription"),fontsSlot:s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:e("standalone.settings.fontsLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:e("standalone.settings.fontsDescription")}),s.jsx(_P,{value:f,savedValue:js(d==null?void 0:d.standaloneFontPreferences),saving:S,error:x,notice:b,onChange:g,onSave:()=>{J()},onResetToSaved:V,onResetToDefaults:Y})]})})}),s.jsx(gt,{title:e("standalone.settings.notificationsSection"),description:e("standalone.settings.notificationsDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(gC,{}),s.jsx(tn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(db,{size:15})," ",e("standalone.settings.soundEffectsLabel")]}),description:e("standalone.settings.soundEffectsDescription"),checked:M,onChange:K})]})}),s.jsx(gt,{title:e("standalone.settings.profileSection"),description:e("standalone.settings.profileDescription"),children:s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(Yf,{size:16,className:"text-text-secondary"})," ",e("standalone.settings.displayNameLabel")]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:e("standalone.settings.displayNameHint")})]}),s.jsx(hs,{type:"text",className:"w-48 text-right",placeholder:e("standalone.settings.displayNamePlaceholder"),value:i,onChange:O=>c(O.target.value),onBlur:R,onKeyDown:O=>{O.key==="Enter"&&O.currentTarget.blur()}})]})})})]})}const HP=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],dr="adhdev_onboarding_done",FP=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],BP={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function WP({onDone:e}){const{t}=Ne("common"),[n,r]=l.useState([]),[a,o]=l.useState(new Set(HP)),[i,c]=l.useState(!0),[u,p]=l.useState(null),[d,m]=l.useState(!1),[f,g]=l.useState(null),[S,h]=l.useState("all");l.useEffect(()=>{let v=!1;const N=window.location.hostname==="localhost"?"/registry":"https://api.adhf.dev/api/v1/registry";return fetch(`${N}/providers?sort=popular&limit=100`).then(w=>{if(!w.ok)throw new Error(`HTTP ${w.status}`);return w.json()}).then(w=>{v||r(w.providers??[])}).catch(w=>{v||p(w instanceof Error?w.message:String(w))}).finally(()=>{v||c(!1)}),()=>{v=!0}},[]);const x=n.filter(v=>S==="all"||v.category===S),y=["cli","ide","extension","acp"].map(v=>({category:v,items:x.filter(N=>N.category===v)})).filter(v=>v.items.length>0),b=l.useCallback(v=>{o(N=>{const w=new Set(N);return w.has(v)?w.delete(v):w.add(v),w})},[]),C=l.useCallback(async()=>{if(a.size===0){localStorage.setItem(dr,"1"),e();return}m(!0);const v=[];for(const N of a)try{const A=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:N})})).json().catch(()=>({}));v.push({type:N,ok:!!A.success,error:A.error})}catch(w){v.push({type:N,ok:!1,error:w instanceof Error?w.message:String(w)})}g(v),m(!1),v.every(N=>N.ok)&&localStorage.setItem(dr,"1")},[a,e]),j=l.useCallback(()=>{localStorage.setItem(dr,"1"),e()},[e]),k=l.useCallback(()=>{f&&f.every(v=>v.ok)?e():d||j()},[f,d,e,j]);return s.jsx(tp,{open:!0,onClose:k,size:"lg",contentClassName:"max-w-2xl",title:t("standalone.onboarding.title"),footer:s.jsxs("div",{className:"flex w-full items-center gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:t(a.size!==1?"standalone.onboarding.selectedCount_other":"standalone.onboarding.selectedCount_one",{count:a.size})}),s.jsxs("div",{className:"ml-auto flex gap-2",children:[s.jsx(Is,{variant:"secondary",size:"sm",onClick:j,disabled:d,children:t("standalone.onboarding.skip")}),s.jsx(Is,{variant:"primary",size:"sm",onClick:()=>{f?(localStorage.setItem(dr,"1"),e()):C()},disabled:d||!f&&a.size===0,children:d?t("standalone.onboarding.installing"):f?t("standalone.onboarding.done"):t("standalone.onboarding.installCount",{count:a.size})})]})]}),children:s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsx("div",{className:"text-[12px] text-text-muted",children:t("standalone.onboarding.intro")}),!i&&!u&&n.length>0&&s.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:FP.map(v=>{const N=v.key==="all"?n.length:n.filter(w=>w.category===v.key).length;return N===0&&v.key!=="all"?null:s.jsxs("button",{onClick:()=>h(v.key),className:`machine-btn text-[10px] px-2 py-0.5 ${S===v.key?"bg-accent-primary/12 border-accent-primary/40 text-accent-primary":""}`,children:[v.label," ",s.jsxs("span",{className:"opacity-60",children:["(",N,")"]})]},v.key)})}),i&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.loadingRegistry")}),!i&&u&&s.jsx(Lt,{variant:"error",children:t("standalone.onboarding.loadError",{error:u})}),!i&&!u&&x.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.noProviders")}),!i&&!u&&x.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:y.map(v=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:BP[v.category]??v.category}),s.jsx("div",{className:"grid gap-1.5",children:v.items.map(N=>{var P,D;const w=a.has(N.type),A=f==null?void 0:f.find(_=>_.type===N.type),T=((P=N.manifest)==null?void 0:P.icon)??"📦",I=((D=N.manifest)==null?void 0:D.details)??"";return s.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${w?"bg-accent-primary/[0.06] border-accent-primary/30":"bg-bg-glass border-border-subtle hover:bg-bg-glass-hover"}`,children:[s.jsx("input",{type:"checkbox",checked:w,onChange:()=>b(N.type),disabled:d,className:"shrink-0"}),s.jsx("span",{className:"text-base shrink-0",children:T}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[13px] font-medium text-text-primary truncate",children:N.displayName}),I&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:I})]}),A&&s.jsx("span",{className:`text-[10px] font-semibold ${A.ok?"text-status-online":"text-status-error"}`,children:A.ok?t("standalone.onboarding.installed"):t("standalone.onboarding.installFailed",{error:A.error??"failed"})})]},N.type)})})]},v.category))})]})})}function OP(){try{return localStorage.getItem(dr)==="1"}catch{return!1}}XS();EC();Fy();DP();const UP=iu({baseUrl:"",getToken:Il});function GP({children:e}){const{t}=Ne("common"),[n,r]=l.useState(null),[a,o]=l.useState(!0),[i,c]=l.useState(""),[u,p]=l.useState(""),[d,m]=l.useState(!1),f=async()=>{o(!0),p("");try{const h=await(await Cs("/auth/session")).json();r(h)}catch(S){p(S instanceof Error?S.message:String(S))}finally{o(!1)}};l.useEffect(()=>{f()},[]),l.useEffect(()=>{if(!n||n.required&&!n.authenticated)return;let S=!1;return(async()=>{try{const h=await Cs("/api/v1/standalone/preferences");if(!h.ok)return;const x=await h.json();if(S)return;const y=js(x.standaloneFontPreferences);sn(y),_i(y)}catch{}})(),()=>{S=!0}},[n==null?void 0:n.authenticated,n==null?void 0:n.required]);const g=async S=>{S.preventDefault(),m(!0),p("");try{const h=await Cs("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),x=await h.json();if(!h.ok)throw new Error((x==null?void 0:x.error)||"Login failed");r(x),c(""),Mh()}catch(h){p(h instanceof Error?h.message:String(h))}finally{m(!1)}};return a?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:t("standalone.auth.loading")}):n?!n.required||n.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:t("standalone.auth.signInTitle")}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:n.hasPasswordAuth?t("standalone.auth.passwordProtected"):t("standalone.auth.tokenProtected")})]}),n.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:g,children:[s.jsx(hs,{type:"password",value:i,onChange:S=>c(S.target.value),placeholder:t("standalone.auth.passwordPlaceholder"),autoFocus:!0}),s.jsx(Is,{type:"submit",variant:"primary",disabled:d||!i,className:"justify-center",children:t(d?"standalone.auth.signingIn":"standalone.auth.unlock")})]}):s.jsx(Lt,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),u&&s.jsx(Lt,{variant:"error",children:u})]})}):s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:t("standalone.auth.loadError",{error:u||"unknown error"})})}function eu(){const{t:e}=Ne("common"),{ides:t,initialLoaded:n}=As();if(!n)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:e("standalone.machine.loading")});const r=t.find(a=>a.daemonMode||a.type==="adhdev-daemon");return r?s.jsx(ai,{to:`/machines/${r.id}`,replace:!0}):s.jsx(ai,{to:"/dashboard",replace:!0})}function qP(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let n=!1;if(!OP())return fetch("/api/v1/providers/installed").then(r=>r.ok?r.json():{providers:[]}).then(r=>{n||(r.providers??[]).length===0&&t(!0)}).catch(()=>{}),()=>{n=!0}},[]),e?s.jsx(WP,{onDone:()=>t(!1)}):null}function zP(){const{t:e}=Ne("common"),{ides:t}=As(),n=l.useMemo(()=>{for(const d of t)if(d.activeInteractivePrompt)return d.instanceId??d.id;return null},[t]),{promptSession:r,hasActivePrompt:a,responseError:o,isSubmitting:i,submit:c,cancel:u,reopen:p}=im(n);return a?s.jsxs("div",{className:"relative",children:[!r&&s.jsx("button",{type:"button",onClick:p,className:"fixed bottom-4 right-4 z-[79] btn btn-primary btn-sm shadow-lg",children:e("standalone.machine.awaitingInput")}),s.jsx(Lu,{promptSession:r,isSubmitting:i,error:o,onSubmit:c,onCancel:u})]}):null}function KP(){const e=l.useMemo(()=>({sendCommand:vr,sendData:Ei,sendPtyInput:Dh}),[]);return s.jsx(cf,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Mf,{client:UP,children:s.jsx(GP,{children:s.jsx(jP,{children:s.jsx(If,{value:e,children:s.jsxs(Ef,{sendDaemonCommand:vr,children:[s.jsx(zP,{}),s.jsxs(IP,{children:[s.jsx(qP,{}),s.jsxs(df,{children:[s.jsx(_s,{path:"/dashboard",element:s.jsx(GM,{})}),s.jsx(_s,{path:"/machine",element:s.jsx(eu,{})}),s.jsx(_s,{path:"/machines/:id",element:s.jsx(XD,{})}),s.jsx(_s,{path:"/machines",element:s.jsx(eu,{})}),s.jsx(_s,{path:"/about",element:s.jsx(EP,{})}),s.jsx(_s,{path:"/settings",element:s.jsx($P,{})}),s.jsx(_s,{path:"/mesh",element:s.jsx(fP,{children:s.jsx(pP,{})})}),s.jsx(_s,{path:"*",element:s.jsx(ai,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}Uk({connectionManager:Ss});uf(document.getElementById("root")).render(s.jsx(KP,{}));
121
+ Node removal cleanup policy: ${ae}`))return;const we=e.__sourceDaemonId||n;try{const qe=await o(we,"remove_mesh_node",{meshId:e.id,nodeId:De}),ve=i(qe);if((ve==null?void 0:ve.success)===!1)throw new Error(ve.error||"Remove failed");C===De&&j(null),await m(),g||await f(t)}catch(qe){S((qe==null?void 0:qe.message)||"Remove node failed")}}async function me(De){if(!e)return;const _e={...Ri(e),...De},ae=e.__sourceDaemonId||n;try{ie(!0),S(null);const we=await o(ae,"update_mesh",{meshId:e.id,policy:_e}),Me=i(we);if((Me==null?void 0:Me.success)===!1)throw new Error(Me.error||"Policy update failed");await m()}catch(we){S((we==null?void 0:we.message)||"Policy update failed")}finally{ie(!1)}}async function Ae(De){if(!t)return;const _e=(e==null?void 0:e.__sourceDaemonId)||n,ae=h[De.id]||nP(De),we=Fn(ae),Me={...De.policy||{}};delete Me.provider_priority,we.length?Me.providerPriority=we:delete Me.providerPriority;try{b(De.id),S(null);const qe=await o(_e,"update_mesh_node",{meshId:t,nodeId:De.id,policy:Me,providerPriority:we}),ve=i(qe);if((ve==null?void 0:ve.success)===!1){S(ve.error||"Node policy update failed");return}await m()}catch(qe){S((qe==null?void 0:qe.message)||"Node policy update failed")}finally{b(null)}}const[de,H]=l.useState(null);async function he(De,_e){if(!t)return;const ae=(e==null?void 0:e.__sourceDaemonId)||n;try{H(De.id),S(null);const we=await o(ae,"update_mesh_node",{meshId:t,nodeId:De.id,policy:{slots:_e}}),Me=i(we);if((Me==null?void 0:Me.success)===!1){S(Me.error||"Node slots update failed");return}await m()}catch(we){S((we==null?void 0:we.message)||"Node slots update failed")}finally{H(null)}}const[fe,ye]=l.useState(null);async function Pe(De,_e){if(!t)return;const ae=(e==null?void 0:e.__sourceDaemonId)||n,we=_e.map(Me=>Me.trim()).filter(Boolean);try{ye(De.id),S(null);const Me=await o(ae,"update_mesh_node",{meshId:t,nodeId:De.id,capabilities:we}),qe=i(Me);if((qe==null?void 0:qe.success)===!1){S(qe.error||"Node tag update failed");return}await m()}catch(Me){S((Me==null?void 0:Me.message)||"Node tag update failed")}finally{ye(null)}}async function He(){if(!n||!t)return;const _e={...(e==null?void 0:e.coordinator)||{}};Z.override.trim()?_e.systemPromptOverride=Z.override:delete _e.systemPromptOverride,Z.append.trim()?_e.systemPromptAppend=Z.append:delete _e.systemPromptAppend,delete _e.systemPromptSuffix;try{G(!0),S(null);const ae=await o(n,"update_mesh",{meshId:t,coordinator:_e}),we=i(ae);if((we==null?void 0:we.success)===!1){S(we.error||"Coordinator prompt save failed");return}await m()}catch(ae){S((ae==null?void 0:ae.message)||"Coordinator prompt save failed")}finally{G(!1)}}async function ke(De){if(!n||!t)return;const _e=(le[De.id]||"").trim();try{Ce(De.id),S(null);const ae=await o(n,"update_mesh_node",{meshId:t,nodeId:De.id,systemPrompt:_e}),we=i(ae);if((we==null?void 0:we.success)===!1){S(we.error||"Node instruction save failed");return}await m()}catch(ae){S((ae==null?void 0:ae.message)||"Node instruction save failed")}finally{Ce(null)}}async function pe(De){if(!(!e||!De)){S(null),Y(null);try{J(!0);const _e=(e.nodes||[]).find(Me=>Fs(String(Me.daemon_id||Me.daemonId||""),De)),ae=await o(De,"set_mesh_host",{meshId:e.id,hostDaemonId:De,..._e!=null&&_e.id?{hostNodeId:_e.id}:{}}),we=i(ae);if((we==null?void 0:we.success)===!1){S(we.error||"Setting the mesh host failed");return}await m()}catch(_e){S((_e==null?void 0:_e.message)||"Setting the mesh host failed")}finally{J(!1)}}}async function st(){if(e){S(null),Y(null);try{F(!0);const De=c?await c(r,e.id,e):null,_e=u(r,e.id,e,e.nodes||[],De);if("error"in _e)throw new Error(_e.error);const ae=await p(_e.targetDaemonId,{meshId:e.id,inlineMesh:_e.inlineMesh,coordinatorNodeId:_e.coordinatorNodeId,cliType:L.trim()||void 0});Y(ae.message)}catch(De){S((De==null?void 0:De.message)||"Coordinator launch failed")}finally{F(!1)}}}return{nodeProviderPriorityDrafts:h,setNodeProviderPriorityDrafts:x,savingNodePolicyId:y,selectedNodeId:C,setSelectedNodeId:j,showAddNode:k,setShowAddNode:v,nodeWorkspace:N,setNodeWorkspace:w,nodeProviderPriority:A,setNodeProviderPriority:T,nodeDaemonId:I,setNodeDaemonId:P,nodeCustomPath:D,setNodeCustomPath:_,nodePickerWorkspaces:z,nodePickerProviders:U,nodeOnboardingPlan:W,nodePlanLoading:E,coordinatorCliType:L,setCoordinatorCliType:R,launchingCoordinator:M,launchResult:V,settingMeshHost:K,savingPolicy:se,coordinatorPromptDraft:Z,setCoordinatorPromptDraft:O,savingCoordinatorPrompt:ee,nodeSystemPromptDrafts:le,setNodeSystemPromptDrafts:je,savingNodeSystemPromptId:ge,savingNodeSlotsId:de,savingNodeCapabilitiesId:fe,handleAddNode:q,handleRemoveNode:Q,handleUpdatePolicy:me,handleUpdateNodeProviderPriority:Ae,handleUpdateNodeSlots:he,handleUpdateNodeCapabilities:Pe,handleSaveCoordinatorPrompt:He,handleSaveNodeSystemPrompt:ke,handleLaunchCoordinator:st,handleSetMeshHost:pe}}function nP(e){var r;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>n.has(a)?!1:(n.add(a),!0))}function rP(e){const t=e.filter(r=>r.status==="pending"||r.status==="assigned"),n=e.filter(r=>r.status==="completed"||r.status==="failed"||r.status==="cancelled");return{active:t.length,historical:n.length,activeCounts:{pending:t.filter(r=>r.status==="pending").length,assigned:t.filter(r=>r.status==="assigned").length},historicalCounts:{completed:n.filter(r=>r.status==="completed").length,failed:n.filter(r=>r.status==="failed").length},counts:{pending:e.filter(r=>r.status==="pending").length,assigned:e.filter(r=>r.status==="assigned").length,completed:e.filter(r=>r.status==="completed").length,failed:e.filter(r=>r.status==="failed").length},staleAssignedCount:e.filter(r=>r.staleAssigned).length,recent:e.slice(0,20)}}function aP({primaryDaemonId:e,activeDaemonId:t,sendCommand:n,unwrapResult:r,loadLiveMesh:a,resolveCommandTarget:o}){const[i,c]=l.useState([]),[u,p]=l.useState(null),[d,m]=l.useState(!1),[f,g]=l.useState(null),S=l.useCallback(async x=>{if(!e||!x){c([]);return}try{const y=await n(e,"get_mesh_queue",{meshId:x});c(y!=null&&y.success?Array.isArray(y.queue)?y.queue:[]:[])}catch{c([])}},[e,n]);async function h(x){var y,b;if(x){m(!0),g(null);try{const C=a?await a(t,x.id,x):null,j=o(t,x.id,x,x.nodes||[],C);if("error"in j)throw new Error(j.error);const k=await n(j.targetDaemonId,"get_mesh_queue",{meshId:x.id}),v=r(k);if((v==null?void 0:v.success)===!1)throw new Error(v.error||"Queue load failed");const N=Array.isArray(((y=v==null?void 0:v.result)==null?void 0:y.rows)??(v==null?void 0:v.rows)??(v==null?void 0:v.queue))?((b=v==null?void 0:v.result)==null?void 0:b.rows)??(v==null?void 0:v.rows)??(v==null?void 0:v.queue):[];p(rP(N))}catch(C){g((C==null?void 0:C.message)||"Queue load failed")}finally{m(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:u,queueLoading:d,queueError:f,loadQueue:S,handleLoadQueue:h}}function oP(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}const Ah=new Map;function Th(e){return e?Ah.get(e)??null:null}function iP(e,t){!e||!t||Ah.set(e,t)}function lP({selectedMeshId:e,loadMeshStatus:t,extractStatus:n,normalizeNode:r,gateIncompleteGraph:a}){const[o,i]=l.useState(()=>Th(e)),[c,u]=l.useState(!1),[p,d]=l.useState(null),[m,f]=l.useState("idle"),[g,S]=l.useState(!1),h=l.useRef(!1);async function x(y,b=e,C=!1){if(!(!y||!b))try{u(!C&&o===null),f(C?"settling":"first_paint"),d(null);const j=await t(y,b,{refresh:C,retryProfile:C?"settled":"interactive"});S(oP(j));const k=n(j),v=r&&k?{...k,nodes:(k.nodes??[]).map(N=>r(N,k.meshId??b,""))}:k;if(v){if(a&&!C&&o!==null&&!fA(rh(v))){f("settling"),h.current||(h.current=!0,Promise.resolve().then(()=>x(y,b,!0)).finally(()=>{h.current=!1}));return}i(v),iP(b,v),f("settled")}else i(null),d("mesh_status returned an unexpected payload."),f("idle")}catch(j){o||i(null),d((j==null?void 0:j.message)||"Failed to load mesh graph"),f("idle")}finally{u(!1)}}return{meshGraphStatus:o,setMeshGraphStatus:i,graphLoading:c,graphError:p,setGraphError:d,graphProvenance:m,graphBootstrapFallback:g,loadGraph:x}}function Qd(e){return!e||e.hostSynthesized?{hostDaemonId:"",hostNodeId:""}:{hostDaemonId:String(e.hostDaemonId||""),hostNodeId:String(e.hostNodeId||"")}}function cP(e,t,n,r,a){if(!e.length)return"";const o=String(a||"");if(o){const u=e.find(p=>Fs(p.id,o));return u?u.id:o}const i=t.find(u=>u.role==="host"),c=String((i==null?void 0:i.daemon_id)||(i==null?void 0:i.daemonId)||"");if(c){const u=e.find(p=>Fs(p.id,c));if(u)return u.id}return""}const dP=7e3,uP=45e3;function pP(){const e=tI(),{sendCommand:t,sendData:n,daemons:r,userName:a,loadMeshStatus:o,launchCoordinator:i,loadLiveMesh:c,extractStatus:u,unwrapResult:p,normalizeMesh:d,normalizeNode:m,resolveCommandTarget:f,features:g,gateIncompleteGraph:S}=e,h=qn(),x=r[0],y=(x==null?void 0:x.id)||"",b=l.useMemo(()=>((x==null?void 0:x.availableProviders)||[]).filter(ot=>ot.category==="cli").map(ot=>({id:ot.type||ot.id,name:ot.displayName||ot.name||ot.type,meshCoordinator:ot.meshCoordinator})),[x]),C=l.useMemo(()=>Hn((x==null?void 0:x.availableProviders)||[]),[x]),{meshes:j,selectedMeshId:k,setSelectedMeshId:v,loading:N,error:w,setError:A,showCreate:T,setShowCreate:I,createName:P,setCreateName:D,createRepoIdentity:_,setCreateRepoIdentity:W,createRepoRemoteUrl:$,setCreateRepoRemoteUrl:E,newMeshDaemonId:B,setNewMeshDaemonId:L,newMeshWorkspace:R,setNewMeshWorkspace:M,createPickerWorkspaces:F,createOnboardingPlan:K,createPlanLoading:J,loadMeshes:V,handleCreate:Y,handleDelete:se,cancelCreate:ie}=tP({daemons:r,primaryDaemonId:y,sendCommand:t,unwrapResult:p,normalizeMesh:d,features:g,loadDaemonMetadata:h}),Z=j.find(We=>We.id===k)||null,{meshGraphStatus:O,setMeshGraphStatus:ee,graphLoading:G,graphError:le,setGraphError:je,loadGraph:ge}=lP({selectedMeshId:k,loadMeshStatus:o,extractStatus:u,normalizeNode:m,gateIncompleteGraph:S}),[Ce,ue]=l.useState(""),[z,U]=l.useState(""),q=g.meshHostDaemonSection?Ce:y,{meshQueue:Q,loadQueue:me}=aP({primaryDaemonId:y,activeDaemonId:q,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f}),{setNodeProviderPriorityDrafts:Ae,selectedNodeId:de,setSelectedNodeId:H,showAddNode:he,setShowAddNode:fe,nodeWorkspace:ye,setNodeWorkspace:Pe,nodeProviderPriority:He,setNodeProviderPriority:ke,nodeDaemonId:pe,setNodeDaemonId:st,nodeCustomPath:De,setNodeCustomPath:_e,nodePickerWorkspaces:ae,nodePickerProviders:we,nodeOnboardingPlan:Me,nodePlanLoading:qe,coordinatorCliType:ve,setCoordinatorCliType:$e,launchingCoordinator:lt,launchResult:at,savingPolicy:bt,coordinatorPromptDraft:X,setCoordinatorPromptDraft:te,savingCoordinatorPrompt:oe,nodeSystemPromptDrafts:be,setNodeSystemPromptDrafts:re,savingNodeSystemPromptId:Te,savingNodeSlotsId:Ee,savingNodeCapabilitiesId:Ie,handleAddNode:ze,handleRemoveNode:Ke,handleUpdatePolicy:Qe,handleUpdateNodeSlots:Ue,handleUpdateNodeCapabilities:Ye,handleSaveCoordinatorPrompt:tt,handleSaveNodeSystemPrompt:Be,handleLaunchCoordinator:ce,settingMeshHost:xe,handleSetMeshHost:Se}=sP({selectedMesh:Z,selectedMeshId:k,primaryDaemonId:y,activeDaemonId:q,daemons:r,availableCliProviders:C,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f,launchCoordinator:i,features:{addNodeDaemonPicker:g.addNodeDaemonPicker},loadMeshes:V,loadQueue:me,queueSection:g.queueSection,setError:A}),Fe=l.useMemo(()=>r.find(We=>We.id===q)||x,[r,q,x]),Je=l.useMemo(()=>new Set(((Z==null?void 0:Z.nodes)||[]).map(We=>String(We.daemon_id||We.daemonId||""))),[Z]),ct=l.useMemo(()=>r.filter(We=>We.id&&!Je.has(We.id)),[r,Je]),Oe=(Z==null?void 0:Z.nodes)||[],yt=l.useMemo(()=>Oe.find(We=>Fs(String(We.daemon_id||We.daemonId||""),Ce)),[Oe,Ce]),zt=g.meshHostDaemonSection?!!yt:!0,wt=l.useMemo(()=>{if(!g.meshHostDaemonSection||!Z)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const We=Z.meshHost,ot=O!=null&&O.meshId&&String(O.meshId)===String(Z.id??"")?O.meshHost:void 0,Vt=ot!=null&&ot.hostDaemonId?ot:We??ot,ss=Qd(Vt),Qt=ss.hostDaemonId,Ys=Oe.find(Xt=>Xt.role==="host"),Js=ss.hostNodeId||String((Ys==null?void 0:Ys.id)||""),Dt=Js?Oe.find(Xt=>String(Xt.id)===Js):void 0,ne=String((Dt==null?void 0:Dt.daemon_id)||(Dt==null?void 0:Dt.daemonId)||""),Ve=Qt||ne;if(!Ve)return{pinned:!1,daemonId:"",label:"",online:!1,hostNode:void 0};const Ge=r.find(Xt=>Qt&&Fs(Xt.id,Qt))||(ne?r.find(Xt=>Fs(Xt.id,ne)):void 0);if(Ge)return{pinned:!0,daemonId:Ge.id,label:mP(Ge),online:!0,hostNode:Dt};const Et=String((Dt==null?void 0:Dt.machineLabel)||"")||String((Dt==null?void 0:Dt.workspace)||"")||Ve;return{pinned:!0,daemonId:Ve,label:Et,online:!1,hostNode:Dt}},[Z,Oe,r,O,g.meshHostDaemonSection]),es=wt.daemonId,Ot=wt.online,Vs=wt.pinned?wt.hostNode:yt,Le=l.useMemo(()=>!g.meshHostDaemonSection||!wt.pinned?"":!Ot&&z&&r.some(We=>We.id===z)?z:es,[g.meshHostDaemonSection,wt.pinned,Ot,z,r,es]),Ze=l.useMemo(()=>O?[...new Set((O.nodes??[]).map(We=>String(We.daemonId||We.daemon_id||"")).filter(Boolean))]:[],[O]),Rt=yh({status:O,daemonId:q||null,extraDaemonIds:Ze,meshId:k,sendData:n});l.useEffect(()=>{Ae(Object.fromEntries(((Z==null?void 0:Z.nodes)||[]).map(We=>[We.id,hP(We)])))},[Z]),l.useEffect(()=>{const We=(Z==null?void 0:Z.coordinator)||{};te({override:typeof We.systemPromptOverride=="string"?We.systemPromptOverride:"",append:typeof We.systemPromptAppend=="string"?We.systemPromptAppend:typeof We.systemPromptSuffix=="string"?We.systemPromptSuffix:""}),re(Object.fromEntries(((Z==null?void 0:Z.nodes)||[]).map(ot=>[ot.id,typeof ot.systemPrompt=="string"?ot.systemPrompt:""])))},[Z]),l.useEffect(()=>{const We=g.addNodeDaemonPicker?jr(we):jr(C);he&&He.length===0&&We.length>0&&ke(We)},[he,C,we,He.length,g.addNodeDaemonPicker]),l.useEffect(()=>{const We=new Set(((Z==null?void 0:Z.nodes)||[]).map(ot=>ot.id));de&&!We.has(de)&&H(null)},[Z,de]);const dt=l.useMemo(()=>{if(!(!(O!=null&&O.meshId)||String(O.meshId)!==String((Z==null?void 0:Z.id)??"")))return Qd(O.meshHost).hostDaemonId||void 0},[O,Z]),ts=l.useMemo(()=>cP(r,Oe,q,y,dt),[r,Oe,q,y,dt]);l.useEffect(()=>{if(!g.meshHostDaemonSection)return;if(!r.length&&!wt.pinned){ue("");return}const We=wt.pinned?Le:ts;We&&!Fs(We,Ce)&&ue(We)},[r,Ce,wt.pinned,Le,ts,g.meshHostDaemonSection]),l.useEffect(()=>{z&&(Ot||!r.some(We=>We.id===z))&&U("")},[Ot,z,r]),l.useEffect(()=>{if(g.createDaemonPicker){if(!r.length){L("");return}(!B||!r.some(We=>We.id===B))&&L(r[0].id)}},[r,B,g.createDaemonPicker]),l.useEffect(()=>{var We;if(!g.createDaemonPicker||!B){M("");return}if(!F.length){M("");return}F.some(ot=>ot.path===R)||M(((We=F[0])==null?void 0:We.path)||"")},[B,R,F,g.createDaemonPicker]);const Ut=l.useRef(null);l.useEffect(()=>{if(!k)return;const We=Ut.current!==k;if(Ut.current=k,We){const ot=Th(k);ee(ot),je(null),ge(q,k,ot!==null)}else je(null),ge(q,k,!0)},[k,q]);const Kt=l.useRef(ge);Kt.current=ge;const ls=l.useRef(!1),vs=l.useRef(()=>{});vs.current=()=>{ls.current||!k||!q||(ls.current=!0,Promise.resolve(Kt.current(q,k,!0)).finally(()=>{ls.current=!1}))};const ys=g.meshStatePushRefresh?uP:dP;ZD({daemonIds:l.useMemo(()=>[q,...Ze].filter(Boolean),[q,Ze]),meshId:k,sendData:n,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||vs.current()}}),l.useEffect(()=>{if(!k||!q||typeof document>"u")return;let We=null;const ot=()=>{document.visibilityState==="visible"&&vs.current()},Vt=()=>{We===null&&(We=setInterval(ot,ys))},ss=()=>{We!==null&&(clearInterval(We),We=null)},Qt=()=>{document.visibilityState==="visible"?Vt():ss()};return document.visibilityState==="visible"&&Vt(),document.addEventListener("visibilitychange",Qt),()=>{ss(),document.removeEventListener("visibilitychange",Qt)}},[k,q,ys]),l.useEffect(()=>{g.queueSection||me(k)},[k,g.queueSection]);const ws=l.useMemo(()=>r.map(We=>We.id).filter(Boolean).sort().join(","),[r]),Ts=l.useRef(!1);return l.useEffect(()=>{V(Ts.current),Ts.current=!0},[ws]),y?Z?s.jsx(eP,{selectedMesh:Z,error:w,onDismissError:()=>A(null),onBack:()=>{v(null),ee(null)},onDelete:se,displayedMeshStatus:Rt,graphLoading:G,graphError:le,onRefreshGraph:()=>ge(q,k,!0),savingPolicy:bt,onUpdatePolicy:Qe,coordinatorPromptDraft:X,onCoordinatorPromptDraftChange:te,savingCoordinatorPrompt:oe,onSaveCoordinatorPrompt:tt,daemons:r,coordinatorDaemonId:Ce,onCoordinatorDaemonIdChange:ue,coordinatorCliType:ve,onCoordinatorCliTypeChange:$e,launchingCoordinator:lt,launchResult:at,isHostNodeAttached:zt,selectedHostNode:Vs,hostPinned:wt.pinned,hostLabel:wt.label,hostOnline:Ot,hostRebindDaemonId:z,onHostRebindDaemonIdChange:We=>U(We),onLaunchCoordinator:ce,settingMeshHost:xe,onSetMeshHost:Se,activeDaemon:Fe,activeDaemonId:q,meshQueue:Q,userName:a,availableCliProviders:C,savingNodeSlotsId:Ee,onUpdateNodeSlots:Ue,savingNodeCapabilitiesId:Ie,onUpdateNodeCapabilities:Ye,nodeSystemPromptDrafts:be,onNodeSystemPromptDraftChange:(We,ot)=>re(Vt=>({...Vt,[We]:ot})),savingNodeSystemPromptId:Te,onSaveNodeSystemPrompt:Be,selectedNodeId:de,onSelectNode:H,showAddNode:he,onShowAddNode:()=>fe(!0),onCancelAddNode:()=>fe(!1),nodeWorkspace:ye,onNodeWorkspaceChange:Pe,nodeProviderPriority:He,onNodeProviderPriorityChange:ke,nodeDaemonId:pe,onNodeDaemonIdChange:st,nodeCustomPath:De,onNodeCustomPathChange:_e,nodePickerWorkspaces:ae,nodePickerProviders:we,nodeOnboardingPlan:Me,nodePlanLoading:qe,attachableDaemons:ct,onAddNode:ze,onRemoveNode:Ke,availableCliAgents:b,features:{coordinatorPrompt:g.coordinatorPrompt,meshHostDaemonSection:g.meshHostDaemonSection,hermesMcpConfig:g.hermesMcpConfig,addNodeDaemonPicker:g.addNodeDaemonPicker,nodeInstruction:g.nodeInstruction},sendCommand:t}):s.jsx(lI,{meshes:j,loading:N,error:w,onDismissError:()=>A(null),daemons:r,features:{createDaemonPicker:g.createDaemonPicker,maxMeshes:g.maxMeshes},showCreate:T,onToggleCreate:()=>I(!T),createName:P,onCreateNameChange:D,createRepoIdentity:_,onCreateRepoIdentityChange:W,createRepoRemoteUrl:$,onCreateRepoRemoteUrlChange:E,newMeshDaemonId:B,onNewMeshDaemonIdChange:L,newMeshWorkspace:R,onNewMeshWorkspaceChange:M,createPickerWorkspaces:F,createOnboardingPlan:K,createPlanLoading:J,onSelectMesh:v,onCreate:Y,onCancelCreate:ie}):s.jsx(Lr,{icon:s.jsx(os,{}),title:"Repo Mesh",subtitle:"Multi-workspace orchestration",children:s.jsx("div",{className:"text-sm text-text-muted p-4",children:"Waiting for daemon connection..."})})}function mP(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function hP(e){var r;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>n.has(a)?!1:(n.add(a),!0))}function fP({children:e}){const{sendCommand:t,sendData:n}=St(),{ides:r}=As(),a=l.useMemo(()=>r.filter(i=>i.daemonMode||i.type==="adhdev-daemon").map(i=>i),[r]),o=l.useMemo(()=>({sendCommand:t,sendData:n,daemons:a,userName:void 0,loadMeshStatus:async(i,c)=>t(i,"mesh_status",{meshId:c}),launchCoordinator:async(i,c)=>{var f;const u={meshId:c.meshId};c.cliType&&(u.cliType=c.cliType);const p=await t(i,"launch_mesh_coordinator",u),d=(p==null?void 0:p.result)??p;if((d==null?void 0:d.success)===!1)throw new Error(d.error||"Coordinator launch failed");const m=(d==null?void 0:d.sessionId)||((f=d==null?void 0:d.session)==null?void 0:f.id)||(d==null?void 0:d.targetSessionId);return{sessionId:m,message:m?`Coordinator launched (${m})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:sl,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,u)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:eI}),[t,n,a]);return s.jsx(Nh.Provider,{value:o,children:e})}function Il(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function bP(e){if(typeof window>"u")return e;const t=e.startsWith("http://")||e.startsWith("https://")?new URL(e):new URL(e,window.location.origin),n=Il();return n&&!t.searchParams.has("token")&&t.searchParams.set("token",n),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function Cs(e,t){return await fetch(bP(e),{credentials:"same-origin",...t})}function Mh(){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 gP{constructor(){nt(this,"adapters",new Map);nt(this,"states",new Map);nt(this,"runtimeListeners",new Map);nt(this,"screenshotCallbacks",new Map);nt(this,"statusCallbacks",new Set);nt(this,"stateChangeCallbacks",new Set);nt(this,"ptyInputSender",null)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const n of this.adapters.keys())if(n.startsWith("standalone"))return n}return null}register(t,n){this.adapters.set(t,n),this.states.set(t,n.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,n){this.states.set(t,n);const r=this.resolveDaemonId(t)||t;this.stateChangeCallbacks.forEach(a=>a(r,n))}onStateChange(t){return this.stateChangeCallbacks.add(t),()=>{this.stateChangeCallbacks.delete(t)}}retryConnection(t){}get(t){const n=this.resolveDaemonId(t);return n?this.adapters.get(n):void 0}getState(t){const n=this.resolveDaemonId(t);return n&&this.states.get(n)||"disconnected"}registerPtyInputSender(t){this.ptyInputSender=t}sendData(t,n){return!1}sendPtyInput(t,n,r){return this.ptyInputSender?this.ptyInputSender(t,n,r):!1}onScreenshot(t,n){return this.screenshotCallbacks.set(t,n),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,n){this.screenshotCallbacks.forEach(r=>r(t,n))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,n){this.statusCallbacks.forEach(r=>r(t,n))}emitRuntimeSnapshot(t,n,r=0,a=!1,o,i){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:r,text:n,truncated:a,cols:o,rows:i})}emitSessionOutput(t,n,r){!t||typeof n!="string"||!n||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof r=="number"?{seq:r}:{},data:n})}onRuntimeEvent(t,n){const r=this.runtimeListeners.get(t)||new Set;return r.add(n),this.runtimeListeners.set(t,r),()=>{const a=this.runtimeListeners.get(t);a&&(a.delete(n),a.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,n,r){if(!n)return{success:!1,error:"sessionId is required"};const a=new URL(`/api/v1/runtime/${encodeURIComponent(n)}/snapshot`,window.location.origin);typeof(r==null?void 0:r.sinceSeq)=="number"&&a.searchParams.set("sinceSeq",String(r.sinceSeq));const o=await Cs(`${a.pathname}${a.search}`);if(!o.ok){let c=`Runtime snapshot unavailable (${o.status})`;try{const u=await o.json();u!=null&&u.error&&(c=u.error)}catch{}return{success:!1,error:c}}const i=await o.json();return this.emitRuntimeEvent(n,{type:"runtime_snapshot",sessionId:n,seq:typeof i.seq=="number"?i.seq:0,text:typeof i.text=="string"?i.text:"",truncated:!!i.truncated,cols:typeof i.cols=="number"?i.cols:void 0,rows:typeof i.rows=="number"?i.rows:void 0,force:!!(r!=null&&r.force)}),{success:!0}}emitRuntimeEvent(t,n){var r;(r=this.runtimeListeners.get(t))==null||r.forEach(a=>a(n))}}const Ss=new gP;function xP(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=Il();return n?`${t}?token=${encodeURIComponent(n)}`:t}const sa=xP(),Xd=3e3,vP=3e4;let us=null,yP=0;const _a=new Map;let en=null,xr=null;function Zd(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function ar(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function wP(e){return e==="connected"?"connected":e}async function vr(e,t,n){const r=Vp(e,n||{}),a=us;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++yP}_${Date.now()}`;return new Promise((i,c)=>{const u=setTimeout(()=>{_a.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);_a.set(o,{resolve:p=>{clearTimeout(u),i(p)},reject:p=>{clearTimeout(u),c(p)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:r.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function Ei(e,t){const n=us;if(!n||n.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return n.send(JSON.stringify(t)),!0}catch{return!1}}function Dh(e,t,n){const r=us;if(!r||r.readyState!==WebSocket.OPEN)return!1;const a=Vp(e,{sessionId:t,targetSessionId:t,data:n});try{return r.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}Ss.registerPtyInputSender(Dh);class kP{constructor(t){nt(this,"daemonId");nt(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(us==null?void 0:us.readyState)===WebSocket.OPEN}get connectionState(){return(us==null?void 0:us.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,n){return vr(this.daemonId,t,n)}async sendInput(t,n){return vr(this.daemonId,"cdp_remote_action",{action:t,params:n,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,en&&(clearInterval(en),en=null);const n=async()=>{if(this.hasCommandChannel)try{const r=await vr(this.daemonId,"screenshot",{width:1280,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}});if(r!=null&&r.success&&(r!=null&&r.base64)){const a=await fetch(`data:image/jpeg;base64,${r.base64}`).then(o=>o.blob());Ss.emitScreenshot(this.daemonId,a)}}catch{}};n(),en=setInterval(n,2e3)}stopScreenshots(t){en&&(clearInterval(en),en=null)}}let rs=null;function SP(e){return(!rs||rs.daemonId!==e)&&(rs=new kP(e)),rs}function CP({children:e}){const t=l.useRef(yr()),n=yr();t.current=n;const{setUserName:r}=As(),a=l.useRef(r);a.current=r;const o=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),u=l.useCallback((h,x)=>{c(h),xr==null||xr(h,x)},[]),p=l.useRef(null),d=l.useRef(),m=l.useRef(Xd),f=l.useRef(!0),g=l.useRef(!1),S=l.useRef("initial_connect");return l.useEffect(()=>{f.current=!0,g.current=!1;function h(){var b,C;if(!f.current||((b=p.current)==null?void 0:b.readyState)===WebSocket.OPEN||((C=p.current)==null?void 0:C.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${sa}...`),ar("connect_attempt",{url:sa,reason:S.current,delayMs:m.current});let y;try{y=new WebSocket(sa)}catch(j){console.error("[Standalone WS] Failed to create WebSocket:",j),x();return}p.current=y,y.onopen=()=>{if(!f.current){y.close();return}u("connected"),m.current=Xd,ar("open",{url:sa,reason:S.current}),fs.resubscribeAll({sendData:Ei}),console.log("[Standalone WS] Connected")},us=y,y.onmessage=j=>{var k,v;try{const N=JSON.parse(j.data);if((N.type==="command_result"||N.type==="error")&&N.requestId){const w=_a.get(N.requestId);w&&(_a.delete(N.requestId),N.type==="error"?w.reject(new Error(((k=N.data)==null?void 0:k.message)||"Command failed")):w.resolve(N.data));return}if(N.type==="session_output"){const w=N.sessionId||N.cliId||N.cliType;w&&Ss.emitSessionOutput(w,typeof N.data=="string"?N.data:"",typeof N.seq=="number"?N.seq:void 0);return}if(N.type==="runtime_snapshot"){Ss.emitRuntimeSnapshot(N.sessionId,typeof N.text=="string"?N.text:"",typeof N.seq=="number"?N.seq:0,!!N.truncated,typeof N.cols=="number"?N.cols:void 0,typeof N.rows=="number"?N.rows:void 0);return}if(N.type==="topic_update"){const w=N.update;w&&fs.publish(w);return}if(N.type==="status"||N.type==="initial_state"){const w=N.data;if(!w)return;const{injectEntries:A,markLoaded:T,getIdes:I}=t.current,P=w.instanceId||"standalone",D=I().find($=>$.id===P),_=SP(P);Ss.register(P,_),Ss.setState(P,"connected"),u("connected",P),Ss.emitStatus(P,w);const W=wa(w,{daemonId:P,existingDaemon:D,existingEntries:I()});Zd("ws_status",{type:N.type,daemonId:P,sessions:(w.sessions||[]).map($=>({id:$.id,parentId:$.parentId,providerType:$.providerType,kind:$.kind,transport:$.transport,unread:$.unread,inboxBucket:$.inboxBucket,lastSeenAt:$.lastSeenAt,lastUpdated:$.lastUpdated,title:$.title})),recentLaunches:(w.recentLaunches||[]).map($=>({id:$.id,providerType:$.providerType,kind:$.kind,workspace:$.workspace,lastLaunchedAt:$.lastLaunchedAt}))}),Zd("entries",{daemonId:P,entries:W.filter($=>$.type!=="adhdev-daemon").map($=>({id:$.id,type:$.type,unread:$.unread,inboxBucket:$.inboxBucket,lastSeenAt:$.lastSeenAt,lastUpdated:$.lastUpdated,sessionId:$.sessionId}))}),W.length>0&&A(W,{authoritativeDaemonIds:[P]}),T(),i.current!==P&&((v=o.current)==null||v.call(o),i.current=P,o.current=fs.subscribe({sendData:Ei},P,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${P}`,params:{includeSessions:!0}},$=>{if($.topic!=="daemon.metadata")return;const E=t.current.getIdes(),B=E.find(R=>R.id===P),L=wa($.status,{daemonId:P,existingDaemon:B,existingEntries:E,timestamp:$.timestamp});L.length>0&&t.current.injectEntries(L,{authoritativeDaemonIds:[P]}),$.userName&&a.current&&a.current($.userName)}))}}catch(N){console.error("[Standalone WS] Parse error:",N)}},y.onclose=j=>{f.current&&(rs==null||rs.stopScreenshots(),rs&&Ss.setState(rs.daemonId,"disconnected"),u("disconnected"),p.current=null,S.current=`close:${j.code}${j.wasClean?":clean":":unclean"}`,ar("close",{code:j.code,reason:j.reason||"",wasClean:j.wasClean}),x())},y.onerror=j=>{g.current||!f.current||(S.current="error",ar("error",{message:j instanceof Event?"event":String(j),readyState:y.readyState}),console.warn("[Standalone WS] Error, will reconnect:",j))}}function x(){if(!f.current)return;clearTimeout(d.current);const y=m.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),ar("schedule_reconnect",{reason:S.current,delayMs:y}),d.current=setTimeout(()=>{m.current=Math.min(m.current*1.5,vP),h()},y)}return h(),()=>{var y;f.current=!1,g.current=!0,(y=o.current)==null||y.call(o),o.current=null,i.current=null,clearTimeout(d.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,us=null),rs&&(rs.stopScreenshots(),Ss.unregister(rs.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function jP({children:e}){const[t,n]=l.useState("disconnected"),[r,a]=l.useState(null);l.useEffect(()=>(xr=(i,c)=>{n(i),c&&a(c)},()=>{xr=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=wP(t),u={};return r&&(u[r]=c),u.standalone=c,{wsStatus:t,isConnected:i,connectionStates:u}},[t,r]);return s.jsx(Nf,{connectionOverrides:o,children:s.jsx(CP,{children:e})})}const Ih="adhdev_standalone_font_preferences",dn={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},ao=[{id:"default",label:"Default",family:"var(--font-sans)",description:"Current dashboard sans stack"},{id:"system-ui",label:"System UI",family:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Use the browser/OS default UI font"},{id:"inter",label:"Inter",family:'"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Match the current product default explicitly"},{id:"pretendard",label:"Pretendard",family:'"Pretendard", "Noto Sans KR", system-ui, sans-serif',description:"Crisp Korean-first sans fallback stack"},{id:"noto-sans-kr",label:"Noto Sans KR",family:'"Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic", "Segoe UI", sans-serif',description:"Wide CJK coverage with neutral metrics"},{id:"serif",label:"Serif",family:'"Iowan Old Style", "Apple Garamond", "Times New Roman", serif',description:"Reading-focused serif stack for long replies"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS font-family stack"}],Tr=[{id:"default",label:"Default mono",family:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',description:"Current monospace stack"},{id:"jetbrains-mono",label:"JetBrains Mono",family:'"JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Readable coding font with strong punctuation"},{id:"fira-code",label:"Fira Code",family:'"Fira Code", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Popular ligature-friendly code font"},{id:"cascadia-code",label:"Cascadia Code",family:'"Cascadia Code", "Cascadia Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Windows-friendly modern coding font"},{id:"berkeley-mono",label:"Berkeley Mono",family:'"Berkeley Mono", "SF Mono", ui-monospace, Menlo, Consolas, monospace',description:"Editorial-feeling mono stack if installed"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS monospace stack"}],NP=new Set(ao.map(e=>e.id)),AP=new Set(Tr.map(e=>e.id));function js(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:ha("chat",t.chat),code:ha("code",t.code),terminal:ha("terminal",t.terminal)}}function ha(e,t){const n=dn[e],r=t&&typeof t=="object"&&!Array.isArray(t)?t:{},a=typeof r.preset=="string"?r.preset.trim():"",o=typeof r.customFamily=="string"?r.customFamily.trim():"";return(e==="chat"?NP:AP).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:n:{preset:a}:n}function fa(e,t){var a;const n=ha(e,t);if(n.preset==="custom"&&n.customFamily)return n.customFamily;const r=e==="chat"?ao:Tr;return((a=r.find(o=>o.id===n.preset))==null?void 0:a.family)||r[0].family}function TP(e){const t=js(e),n=fa("chat",t.chat),r=fa("code",t.code),a=fa("terminal",t.terminal);return{"--chat-font-family":n,"--chat-code-font-family":r,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function sn(e,t=document.documentElement){const n=js(e),r=TP(n);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(r))t.style.setProperty(a,o);return n}function _i(e){const t=js(e);try{localStorage.setItem(Ih,JSON.stringify(t))}catch{}return t}function MP(){try{const e=localStorage.getItem(Ih);if(e)return js(JSON.parse(e))}catch{}return dn}function DP(){return sn(MP())}function or(e,t){var r;const n=e==="chat"?ao:Tr;return((r=n.find(a=>a.id===t))==null?void 0:r.label)||n[0].label}function IP({children:e}){const t=Mr(),n=Hi(),{t:r}=Ne("common"),a=l.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:s.jsx(hu,{}),label:r("standalone.nav.dashboard"),active:n.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:s.jsx(Os,{}),label:"Burrow",active:n.pathname.startsWith("/machines"),onSelect:()=>t("/machines")},{id:"mesh",path:"/mesh",icon:s.jsx(os,{}),label:"Mesh",active:n.pathname.startsWith("/mesh"),onSelect:()=>t("/mesh")},{id:"settings",path:"/settings",icon:s.jsx(Ha,{}),label:r("standalone.nav.settings"),active:n.pathname.startsWith("/settings"),onSelect:()=>t("/settings")}],[n.pathname,t,r]),o=l.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:r("standalone.nav.docs")}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(bu,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:r("standalone.nav.docs")},{id:"about",label:r("standalone.nav.about"),icon:s.jsx(Oi,{}),active:n.pathname==="/about",onSelect:()=>t("/about"),title:r("standalone.nav.about")}],[n.pathname,t,r]);return s.jsx(cC,{brand:({collapsed:i})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&s.jsx("span",{children:"ADHDev"})]}),navItems:a,footerItems:o,footerInfo:({collapsed:i})=>i?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","1.0.30"]}),footerActions:({collapsed:i,toggleCollapsed:c})=>s.jsxs("div",{className:`nav-item cursor-pointer ${i?"justify-center py-2.5 px-0":"mt-1"}`,onClick:c,title:r(i?"standalone.layout.expandSidebar":"standalone.layout.collapseSidebar"),children:[s.jsx("span",{className:"nav-icon text-base",children:i?"›":"‹"}),!i&&s.jsx("span",{className:"text-xs",children:r("standalone.layout.collapse")})]}),children:e})}const PP=[{icon:s.jsx(Os,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(bn,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(vu,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(xs,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(wr,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(bu,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],LP=[{icon:s.jsx(sb,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(hu,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Un,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Jf,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(fu,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Xf,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],RP=[{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 EP(){const{t:e}=Ne("common");return s.jsxs(Lr,{icon:s.jsx(Oi,{className:"text-text-primary"}),title:e("standalone.about.title"),subtitle:e("standalone.about.subtitle"),widthClassName:"max-w-5xl",actions:s.jsxs("div",{className:"px-3 py-1 text-[11px] font-semibold tracking-wide rounded-full bg-emerald-500/10 text-emerald-500 border border-emerald-500/20",children:["SELFHOST v","1.0.30"]}),children:[s.jsx(gt,{children:s.jsxs("div",{className:"flex flex-col gap-4 md:flex-row md:items-start md:justify-between",children:[s.jsxs("div",{className:"max-w-2xl",children:[s.jsx("div",{className:"text-[11px] font-semibold tracking-[0.18em] uppercase text-emerald-400 mb-2",children:e("standalone.about.selfHostedEdition")}),s.jsx("h2",{className:"text-2xl font-semibold tracking-tight text-text-primary mb-2",children:e("standalone.about.headline")}),s.jsx("p",{className:"text-sm text-text-muted leading-relaxed",children:e("standalone.about.description")})]}),s.jsxs("div",{className:"grid gap-2 min-w-[220px]",children:[s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.docs")}),s.jsx("a",{href:"https://github.com/vilmire/adhdev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.github")}),s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm inline-flex justify-center no-underline",children:e("standalone.about.tryCloud")})]})]})}),s.jsx(gt,{title:e("standalone.about.includedSection"),description:e("standalone.about.includedDescription"),children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:PP.map(t=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4 transition-colors hover:border-border-default",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-bg-secondary text-text-secondary border border-border-subtle",children:t.icon}),t.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),s.jsx(gt,{title:e("standalone.about.inventorySection"),description:e("standalone.about.inventoryDescription"),children:s.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:[{label:"IDEs",items:Yp.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:Qp.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:Jp.map(t=>`${t.icon} ${t.name}`)}].map(t=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-4",children:[s.jsx("div",{className:"text-[11px] font-bold tracking-wider text-text-muted mb-3 uppercase",children:t.label}),s.jsx("div",{className:"flex flex-col gap-1.5",children:t.items.map(n=>s.jsx("div",{className:"rounded-md border border-border-subtle bg-bg-card px-2.5 py-1.5 text-[12px] text-text-secondary",children:n},n))})]},t.label))})}),s.jsx(gt,{title:e("standalone.about.cloudExtrasSection"),description:e("standalone.about.cloudExtrasDescription"),children:s.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:LP.map(t=>s.jsxs("div",{className:"rounded-xl border border-accent-primary/20 bg-accent-primary/5 px-4 py-4",children:[s.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold text-text-primary mb-2",children:[s.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary",children:t.icon}),t.title]}),s.jsx("p",{className:"text-[13px] leading-relaxed text-text-muted",children:t.desc})]},t.title))})}),s.jsx(gt,{title:e("standalone.about.comparisonSection"),description:e("standalone.about.comparisonDescription"),children:s.jsx("div",{className:"overflow-x-auto rounded-xl border border-border-subtle",children:s.jsxs("table",{className:"w-full text-[13px]",children:[s.jsx("thead",{children:s.jsxs("tr",{className:"bg-bg-secondary",children:[s.jsx("th",{className:"text-left px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider",children:e("standalone.about.featureHeader")}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-text-muted text-[11px] uppercase tracking-wider w-[110px]",children:e("standalone.about.selfhostHeader")}),s.jsx("th",{className:"text-center px-4 py-3 font-semibold text-accent-primary text-[11px] uppercase tracking-wider w-[110px]",children:e("standalone.about.cloudHeader")})]})}),s.jsx("tbody",{children:RP.map((t,n)=>s.jsxs("tr",{className:n%2===0?"bg-bg-glass":"bg-transparent",children:[s.jsx("td",{className:"px-4 py-2.5 text-text-secondary",children:t.feature}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:t.selfhost?s.jsx("span",{className:"text-emerald-500",children:"✓"}):s.jsx("span",{className:"text-text-muted opacity-40",children:"—"})}),s.jsx("td",{className:"px-4 py-2.5 text-center",children:s.jsx("span",{className:"text-emerald-500",children:"✓"})})]},t.feature))})]})})}),s.jsx(Ya,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"mx-auto h-12 w-12 opacity-80"}),title:e("standalone.about.cloudOptional"),description:e("standalone.about.cloudOptionalDescription"),action:s.jsxs("div",{className:"flex flex-wrap justify-center gap-3",children:[s.jsx("a",{href:"https://adhf.dev",target:"_blank",rel:"noopener noreferrer",className:"btn btn-primary btn-sm no-underline",children:e("standalone.about.compareCloud")}),s.jsxs("a",{href:"https://discord.gg/WJD3tCfBzk",target:"_blank",rel:"noopener noreferrer",className:"btn btn-secondary btn-sm no-underline",children:[s.jsx(ub,{size:14,className:"mr-1"}),e("standalone.about.discord")]})]})})]})}function ei(e,t,n){return{...e,[t]:n}}function ti({surface:e,title:t,description:n,value:r,options:a,onChange:o}){const{t:i}=Ne("common");return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:n})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(mC,{value:r.preset,onChange:c=>{const u=c.target.value;o(u==="custom"?{preset:"custom",customFamily:r.customFamily||""}:{preset:u})},children:a.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),r.preset==="custom"&&s.jsx(hs,{type:"text",className:"font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:r.customFamily||"",onChange:c=>o({preset:"custom",customFamily:c.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:i("standalone.fonts.resolvedStack")})," ",s.jsx("span",{className:"font-mono break-all",children:fa(e,r)})]})]})]})}function _P({value:e,savedValue:t,saving:n=!1,error:r,notice:a,onChange:o,onSave:i,onResetToSaved:c,onResetToDefaults:u}){const{t:p}=Ne("common"),d=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:p("standalone.fonts.fontOverridesNotice")}),r&&s.jsx(Lt,{variant:"error",children:r}),a&&s.jsx(Lt,{variant:"success",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(ti,{surface:"chat",title:p("standalone.fonts.chat"),description:p("standalone.fonts.chatDescription"),value:e.chat,options:ao,onChange:m=>o(ei(e,"chat",m))}),s.jsx(ti,{surface:"code",title:p("standalone.fonts.code"),description:p("standalone.fonts.codeDescription"),value:e.code,options:Tr,onChange:m=>o(ei(e,"code",m))}),s.jsx(ti,{surface:"terminal",title:p("standalone.fonts.terminal"),description:p("standalone.fonts.terminalDescription"),value:e.terminal,options:Tr,onChange:m=>o(ei(e,"terminal",m))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:p("standalone.fonts.livePreview")}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",or("chat",e.chat.preset)," · Code: ",or("code",e.code.preset)," · Terminal: ",or("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[p("standalone.fonts.defaults")," ",or("chat",dn.chat.preset)," / ",or("code",dn.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(Is,{type:"button",variant:"primary",size:"sm",onClick:i,disabled:n||!d,children:p(n?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),s.jsx(Is,{type:"button",variant:"secondary",size:"sm",onClick:c,disabled:n||!d,children:p("standalone.fonts.revertToSaved")}),s.jsx(Is,{type:"button",variant:"secondary",size:"sm",onClick:u,disabled:n,children:p("standalone.fonts.resetToDefaults")})]})]})}function $P(){const{t:e}=Ne("common"),{ides:t}=As(),n=t.find(O=>O.type==="adhdev-daemon"),r=(n==null?void 0:n.detectedIdes)||[],{sendCommand:a}=St(),{userName:o}=As(),[i,c]=l.useState(o||""),[u,p]=l.useState(null),[d,m]=l.useState(null),[f,g]=l.useState(dn),[S,h]=l.useState(!1),[x,y]=l.useState(""),[b,C]=l.useState(""),[j,k]=l.useState("127.0.0.1"),[v,N]=l.useState(""),[w,A]=l.useState(""),[T,I]=l.useState(""),[P,D]=l.useState(""),[_,W]=l.useState(""),[$,E]=l.useState(!1),B=async()=>{const ee=await(await Cs("/auth/session")).json();p(ee)},L=async()=>{const ee=await(await Cs("/api/v1/standalone/preferences")).json();m(ee),k(ee.standaloneBindHost);const G=js(ee.standaloneFontPreferences);g(G),sn(G),_i(G)};l.useEffect(()=>{o!==void 0&&c(o)},[o]),l.useEffect(()=>{Promise.all([B(),L()]).catch(O=>{D(O instanceof Error?O.message:String(O))})},[]),l.useEffect(()=>{sn(f)},[f]);const R=O=>{const ee=O.target.value.trim();n!=null&&n.id&&ee!==o&&a(n.id,"set_user_name",{userName:ee}).catch(console.error)},[M,F]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),K=O=>{F(O);try{localStorage.setItem("adhdev_sound",O?"1":"0")}catch{}},J=async()=>{y(""),C(""),h(!0);try{const O=js(f),ee=await Cs("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:O})}),G=await ee.json();if(!ee.ok)throw new Error((G==null?void 0:G.error)||"Failed to save standalone font preferences");const le=js(G.standaloneFontPreferences);m(G),g(le),sn(le),_i(le),C(e("standalone.settings.fontsSaved"))}catch(O){y(O instanceof Error?O.message:String(O))}finally{h(!1)}},V=()=>{const O=js(d==null?void 0:d.standaloneFontPreferences);y(""),C(""),g(O),sn(O)},Y=()=>{y(""),C(""),g(dn),sn(dn)},se=async()=>{D(""),W(""),E(!0);try{const O=await Cs("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:j})}),ee=await O.json();if(!O.ok)throw new Error((ee==null?void 0:ee.error)||"Failed to save standalone network preference");m(ee),k(ee.standaloneBindHost),W(ee.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(O){D(O instanceof Error?O.message:String(O))}finally{E(!1)}},ie=async()=>{if(D(""),W(""),w.trim().length<4){D(e("standalone.settings.passwordTooShort"));return}if(w!==T){D(e("standalone.settings.passwordMismatch"));return}E(!0);try{const O=await Cs("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,newPassword:w})}),ee=await O.json();if(!O.ok)throw new Error((ee==null?void 0:ee.error)||"Failed to save password");p(ee),await L(),N(""),A(""),I(""),W(u!=null&&u.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),Mh()}catch(O){D(O instanceof Error?O.message:String(O))}finally{E(!1)}},Z=async()=>{D(""),W(""),E(!0);try{const O=await Cs("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,clear:!0})}),ee=await O.json();if(!O.ok)throw new Error((ee==null?void 0:ee.error)||"Failed to clear password");p(ee),await L(),N(""),A(""),I(""),W(e("standalone.settings.passwordDisabled"))}catch(O){D(O instanceof Error?O.message:String(O))}finally{E(!1)}};return s.jsxs(Lr,{icon:s.jsx(Ha,{className:"text-text-primary"}),title:e("standalone.settings.title"),subtitle:e("standalone.settings.subtitle"),widthClassName:"max-w-5xl",children:[s.jsx(Lt,{variant:"info",children:e("standalone.settings.infoNotice")}),(u==null?void 0:u.publicHostWarning)&&s.jsx(Lt,{variant:"warning",children:e("standalone.settings.publicHostWarning")}),s.jsx(gt,{title:e("standalone.settings.daemonSection"),description:e("standalone.settings.daemonDescription"),children:s.jsxs("div",{className:"grid grid-cols-[100px_1fr] gap-x-4 gap-y-2.5 text-sm",children:[s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.versionLabel")}),s.jsxs("span",{className:"font-mono text-xs",children:["v","1.0.30"]}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.statusLabel")}),s.jsx("span",{className:n?"text-green-400":"text-yellow-400",children:e(n?"standalone.settings.statusRunning":"standalone.settings.statusNotConnected")}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.currentBindLabel")}),s.jsx("span",{className:"font-mono text-xs",children:(d==null?void 0:d.currentBindHost)||(u==null?void 0:u.boundHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.defaultBindLabel")}),s.jsx("span",{className:"font-mono text-xs",children:(d==null?void 0:d.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.authLabel")}),s.jsx("span",{className:"text-xs",children:u!=null&&u.hasPasswordAuth?e("standalone.settings.authPassword"):u!=null&&u.hasTokenAuth?e("standalone.settings.authToken"):e("standalone.settings.authNone")})]})}),s.jsx(gt,{title:e("standalone.settings.networkSection"),description:e("standalone.settings.networkDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:e("standalone.settings.networkHint")}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:j==="127.0.0.1",onChange:()=>k("127.0.0.1")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.localhostLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.localhostHint")})]})]}),s.jsxs("label",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm flex gap-3 items-start cursor-pointer",children:[s.jsx("input",{type:"radio",name:"standalone-bind-host",checked:j==="0.0.0.0",onChange:()=>k("0.0.0.0")}),s.jsxs("span",{children:[s.jsx("span",{className:"block font-medium text-text-primary",children:e("standalone.settings.allInterfacesLabel")}),s.jsx("span",{className:"block text-text-muted text-xs mt-1",children:e("standalone.settings.allInterfacesHint")})]})]})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(Is,{type:"button",variant:"primary",size:"sm",onClick:()=>{se()},disabled:$,children:e($?"standalone.settings.saving":"standalone.settings.saveNetworkMode")}),s.jsx("span",{className:"text-xs text-text-muted",children:e("standalone.settings.networkRestartHint",{host:(d==null?void 0:d.currentBindHost)||(u==null?void 0:u.boundHost)||"127.0.0.1"})})]})]})}),s.jsx(gt,{title:e("standalone.settings.securitySection"),description:e("standalone.settings.securityDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:u!=null&&u.hasPasswordAuth?e("standalone.settings.passwordSet"):e("standalone.settings.passwordNotSet")}),P&&s.jsx(Lt,{variant:"error",children:P}),_&&s.jsx(Lt,{variant:"success",children:_}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx(hs,{type:"password",placeholder:u!=null&&u.hasPasswordAuth?e("standalone.settings.currentPasswordPlaceholder"):e("standalone.settings.currentPasswordFirstTimePlaceholder"),value:v,onChange:O=>N(O.target.value)}),s.jsx(hs,{type:"password",placeholder:u!=null&&u.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:w,onChange:O=>A(O.target.value)}),s.jsx(hs,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:T,onChange:O=>I(O.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Is,{type:"button",variant:"primary",size:"sm",onClick:()=>{ie()},disabled:$,children:$?e("standalone.settings.saving"):u!=null&&u.hasPasswordAuth?e("standalone.settings.updatePassword"):e("standalone.settings.enablePassword")}),(u==null?void 0:u.hasPasswordAuth)&&s.jsx(Is,{type:"button",variant:"danger",size:"sm",onClick:()=>{Z()},disabled:$,children:e("standalone.settings.disablePassword")})]})]})}),s.jsx(gt,{title:e("standalone.settings.detectedIdesSection"),description:e("standalone.settings.detectedIdesDescription"),children:r.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:e("standalone.settings.noIdesDetected")}):s.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(O=>s.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${O.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:O.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:O.type})]},O.type))})}),s.jsx(gt,{title:e("standalone.settings.machineSection"),description:e("standalone.settings.machineDescription"),children:s.jsx(SC,{ides:t,emptyMessage:e("standalone.settings.daemonNotConnected")})}),s.jsx(gt,{title:e("standalone.settings.appearanceSection"),description:e("standalone.settings.appearanceDescription"),children:s.jsx(UC,{themeDescription:e("standalone.settings.themeDescription"),mobileDescription:e("standalone.settings.mobileDescription"),fontsSlot:s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:e("standalone.settings.fontsLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:e("standalone.settings.fontsDescription")}),s.jsx(_P,{value:f,savedValue:js(d==null?void 0:d.standaloneFontPreferences),saving:S,error:x,notice:b,onChange:g,onSave:()=>{J()},onResetToSaved:V,onResetToDefaults:Y})]})})}),s.jsx(gt,{title:e("standalone.settings.notificationsSection"),description:e("standalone.settings.notificationsDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(gC,{}),s.jsx(tn,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(db,{size:15})," ",e("standalone.settings.soundEffectsLabel")]}),description:e("standalone.settings.soundEffectsDescription"),checked:M,onChange:K})]})}),s.jsx(gt,{title:e("standalone.settings.profileSection"),description:e("standalone.settings.profileDescription"),children:s.jsx("div",{className:"flex flex-col gap-3",children:s.jsxs("div",{className:"flex items-center justify-between px-3.5 py-4 bg-bg-glass rounded-xl border border-border-subtle hover:border-border-default transition-colors",children:[s.jsxs("div",{className:"flex flex-col gap-1 pr-4 max-w-[500px]",children:[s.jsxs("span",{className:"text-sm font-semibold flex items-center gap-2",children:[s.jsx(Yf,{size:16,className:"text-text-secondary"})," ",e("standalone.settings.displayNameLabel")]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:e("standalone.settings.displayNameHint")})]}),s.jsx(hs,{type:"text",className:"w-48 text-right",placeholder:e("standalone.settings.displayNamePlaceholder"),value:i,onChange:O=>c(O.target.value),onBlur:R,onKeyDown:O=>{O.key==="Enter"&&O.currentTarget.blur()}})]})})})]})}const HP=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],dr="adhdev_onboarding_done",FP=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],BP={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function WP({onDone:e}){const{t}=Ne("common"),[n,r]=l.useState([]),[a,o]=l.useState(new Set(HP)),[i,c]=l.useState(!0),[u,p]=l.useState(null),[d,m]=l.useState(!1),[f,g]=l.useState(null),[S,h]=l.useState("all");l.useEffect(()=>{let v=!1;const N=window.location.hostname==="localhost"?"/registry":"https://api.adhf.dev/api/v1/registry";return fetch(`${N}/providers?sort=popular&limit=100`).then(w=>{if(!w.ok)throw new Error(`HTTP ${w.status}`);return w.json()}).then(w=>{v||r(w.providers??[])}).catch(w=>{v||p(w instanceof Error?w.message:String(w))}).finally(()=>{v||c(!1)}),()=>{v=!0}},[]);const x=n.filter(v=>S==="all"||v.category===S),y=["cli","ide","extension","acp"].map(v=>({category:v,items:x.filter(N=>N.category===v)})).filter(v=>v.items.length>0),b=l.useCallback(v=>{o(N=>{const w=new Set(N);return w.has(v)?w.delete(v):w.add(v),w})},[]),C=l.useCallback(async()=>{if(a.size===0){localStorage.setItem(dr,"1"),e();return}m(!0);const v=[];for(const N of a)try{const A=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:N})})).json().catch(()=>({}));v.push({type:N,ok:!!A.success,error:A.error})}catch(w){v.push({type:N,ok:!1,error:w instanceof Error?w.message:String(w)})}g(v),m(!1),v.every(N=>N.ok)&&localStorage.setItem(dr,"1")},[a,e]),j=l.useCallback(()=>{localStorage.setItem(dr,"1"),e()},[e]),k=l.useCallback(()=>{f&&f.every(v=>v.ok)?e():d||j()},[f,d,e,j]);return s.jsx(tp,{open:!0,onClose:k,size:"lg",contentClassName:"max-w-2xl",title:t("standalone.onboarding.title"),footer:s.jsxs("div",{className:"flex w-full items-center gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:t(a.size!==1?"standalone.onboarding.selectedCount_other":"standalone.onboarding.selectedCount_one",{count:a.size})}),s.jsxs("div",{className:"ml-auto flex gap-2",children:[s.jsx(Is,{variant:"secondary",size:"sm",onClick:j,disabled:d,children:t("standalone.onboarding.skip")}),s.jsx(Is,{variant:"primary",size:"sm",onClick:()=>{f?(localStorage.setItem(dr,"1"),e()):C()},disabled:d||!f&&a.size===0,children:d?t("standalone.onboarding.installing"):f?t("standalone.onboarding.done"):t("standalone.onboarding.installCount",{count:a.size})})]})]}),children:s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsx("div",{className:"text-[12px] text-text-muted",children:t("standalone.onboarding.intro")}),!i&&!u&&n.length>0&&s.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:FP.map(v=>{const N=v.key==="all"?n.length:n.filter(w=>w.category===v.key).length;return N===0&&v.key!=="all"?null:s.jsxs("button",{onClick:()=>h(v.key),className:`machine-btn text-[10px] px-2 py-0.5 ${S===v.key?"bg-accent-primary/12 border-accent-primary/40 text-accent-primary":""}`,children:[v.label," ",s.jsxs("span",{className:"opacity-60",children:["(",N,")"]})]},v.key)})}),i&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.loadingRegistry")}),!i&&u&&s.jsx(Lt,{variant:"error",children:t("standalone.onboarding.loadError",{error:u})}),!i&&!u&&x.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.noProviders")}),!i&&!u&&x.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:y.map(v=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:BP[v.category]??v.category}),s.jsx("div",{className:"grid gap-1.5",children:v.items.map(N=>{var P,D;const w=a.has(N.type),A=f==null?void 0:f.find(_=>_.type===N.type),T=((P=N.manifest)==null?void 0:P.icon)??"📦",I=((D=N.manifest)==null?void 0:D.details)??"";return s.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${w?"bg-accent-primary/[0.06] border-accent-primary/30":"bg-bg-glass border-border-subtle hover:bg-bg-glass-hover"}`,children:[s.jsx("input",{type:"checkbox",checked:w,onChange:()=>b(N.type),disabled:d,className:"shrink-0"}),s.jsx("span",{className:"text-base shrink-0",children:T}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[13px] font-medium text-text-primary truncate",children:N.displayName}),I&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:I})]}),A&&s.jsx("span",{className:`text-[10px] font-semibold ${A.ok?"text-status-online":"text-status-error"}`,children:A.ok?t("standalone.onboarding.installed"):t("standalone.onboarding.installFailed",{error:A.error??"failed"})})]},N.type)})})]},v.category))})]})})}function OP(){try{return localStorage.getItem(dr)==="1"}catch{return!1}}XS();EC();Fy();DP();const UP=iu({baseUrl:"",getToken:Il});function GP({children:e}){const{t}=Ne("common"),[n,r]=l.useState(null),[a,o]=l.useState(!0),[i,c]=l.useState(""),[u,p]=l.useState(""),[d,m]=l.useState(!1),f=async()=>{o(!0),p("");try{const h=await(await Cs("/auth/session")).json();r(h)}catch(S){p(S instanceof Error?S.message:String(S))}finally{o(!1)}};l.useEffect(()=>{f()},[]),l.useEffect(()=>{if(!n||n.required&&!n.authenticated)return;let S=!1;return(async()=>{try{const h=await Cs("/api/v1/standalone/preferences");if(!h.ok)return;const x=await h.json();if(S)return;const y=js(x.standaloneFontPreferences);sn(y),_i(y)}catch{}})(),()=>{S=!0}},[n==null?void 0:n.authenticated,n==null?void 0:n.required]);const g=async S=>{S.preventDefault(),m(!0),p("");try{const h=await Cs("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),x=await h.json();if(!h.ok)throw new Error((x==null?void 0:x.error)||"Login failed");r(x),c(""),Mh()}catch(h){p(h instanceof Error?h.message:String(h))}finally{m(!1)}};return a?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:t("standalone.auth.loading")}):n?!n.required||n.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:t("standalone.auth.signInTitle")}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:n.hasPasswordAuth?t("standalone.auth.passwordProtected"):t("standalone.auth.tokenProtected")})]}),n.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:g,children:[s.jsx(hs,{type:"password",value:i,onChange:S=>c(S.target.value),placeholder:t("standalone.auth.passwordPlaceholder"),autoFocus:!0}),s.jsx(Is,{type:"submit",variant:"primary",disabled:d||!i,className:"justify-center",children:t(d?"standalone.auth.signingIn":"standalone.auth.unlock")})]}):s.jsx(Lt,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),u&&s.jsx(Lt,{variant:"error",children:u})]})}):s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:t("standalone.auth.loadError",{error:u||"unknown error"})})}function eu(){const{t:e}=Ne("common"),{ides:t,initialLoaded:n}=As();if(!n)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:e("standalone.machine.loading")});const r=t.find(a=>a.daemonMode||a.type==="adhdev-daemon");return r?s.jsx(ai,{to:`/machines/${r.id}`,replace:!0}):s.jsx(ai,{to:"/dashboard",replace:!0})}function qP(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let n=!1;if(!OP())return fetch("/api/v1/providers/installed").then(r=>r.ok?r.json():{providers:[]}).then(r=>{n||(r.providers??[]).length===0&&t(!0)}).catch(()=>{}),()=>{n=!0}},[]),e?s.jsx(WP,{onDone:()=>t(!1)}):null}function zP(){const{t:e}=Ne("common"),{ides:t}=As(),n=l.useMemo(()=>{for(const d of t)if(d.activeInteractivePrompt)return d.instanceId??d.id;return null},[t]),{promptSession:r,hasActivePrompt:a,responseError:o,isSubmitting:i,submit:c,cancel:u,reopen:p}=im(n);return a?s.jsxs("div",{className:"relative",children:[!r&&s.jsx("button",{type:"button",onClick:p,className:"fixed bottom-4 right-4 z-[79] btn btn-primary btn-sm shadow-lg",children:e("standalone.machine.awaitingInput")}),s.jsx(Lu,{promptSession:r,isSubmitting:i,error:o,onSubmit:c,onCancel:u})]}):null}function KP(){const e=l.useMemo(()=>({sendCommand:vr,sendData:Ei,sendPtyInput:Dh}),[]);return s.jsx(cf,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(Mf,{client:UP,children:s.jsx(GP,{children:s.jsx(jP,{children:s.jsx(If,{value:e,children:s.jsxs(Ef,{sendDaemonCommand:vr,children:[s.jsx(zP,{}),s.jsxs(IP,{children:[s.jsx(qP,{}),s.jsxs(df,{children:[s.jsx(_s,{path:"/dashboard",element:s.jsx(GM,{})}),s.jsx(_s,{path:"/machine",element:s.jsx(eu,{})}),s.jsx(_s,{path:"/machines/:id",element:s.jsx(XD,{})}),s.jsx(_s,{path:"/machines",element:s.jsx(eu,{})}),s.jsx(_s,{path:"/about",element:s.jsx(EP,{})}),s.jsx(_s,{path:"/settings",element:s.jsx($P,{})}),s.jsx(_s,{path:"/mesh",element:s.jsx(fP,{children:s.jsx(pP,{})})}),s.jsx(_s,{path:"*",element:s.jsx(ai,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}Uk({connectionManager:Ss});uf(document.getElementById("root")).render(s.jsx(KP,{}));