@adhdev/daemon-standalone 1.0.10-rc.1 → 1.0.12

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 kh=Object.defineProperty;var Sh=(e,t,n)=>t in e?kh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var st=(e,t,n)=>Sh(e,typeof t!="symbol"?t+"":t,n);import{r as l,j as s,u as Ne,M as Si,a as Ch,b as jh,c as Nh,t as Ah,d as Mh,i as wt,e as Th,f as fn,R as Rt,T as Bo,g as mr,h as Oo,k as Wo,D as Ph,E as Ih,l as Dh,C as Lh,m as Rh,B as Eh,n as _h,o as $h,p as Hh,H as yr,P as Cs,q as Fh,s as Bh,v as Oh,w as jl,x as Wh,y as Uh,z as Ci,A as Gh,F as qh,G as zh,I as Kh,J as js,N as Uo,K as Vh}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 Yh(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 bn=Yh();function Nl(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 Jh(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function Al(e){return Array.isArray(e)?[...e]:[]}function _d(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?Al(e.messages):i?[]:t.messages,activeModal:r?e.activeModal??null:t.activeModal,inputContent:e.inputContent??t.inputContent}:{...e,...n?{messages:Al(e.messages)}:{},...r?{activeModal:e.activeModal??null}:{}}}function zn(e,t){const n=Jh(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:_d(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 $d(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?zn(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 Ml(e){return!!e&&typeof e=="object"&&"text"in e}function ji(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:Ml(o)?String(o.text||""):"").join(n):Ml(e)?a=String(e.text||""):a=String(e||""),r?a.replace(/\s+/g," ").trim():a}function gn(e){return ji(e,{normalizeWhitespace:!0})}function Qh(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 kh=Object.defineProperty;var Sh=(e,t,n)=>t in e?kh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var st=(e,t,n)=>Sh(e,typeof t!="symbol"?t+"":t,n);import{r as l,j as s,u as Ne,M as Si,a as Ch,b as jh,c as Nh,t as Ah,d as Mh,i as wt,e as Th,f as fn,R as Rt,T as Bo,g as mr,h as Oo,k as Wo,D as Ph,E as Ih,l as Dh,C as Lh,m as Rh,B as Eh,n as _h,o as $h,p as Hh,H as yr,P as Cs,q as Fh,s as Bh,v as Oh,w as jl,x as Wh,y as Uh,z as Ci,A as Gh,F as qh,G as zh,I as Kh,J as js,N as Uo,K as Vh}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 Yh(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 bn=Yh();function Nl(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 Jh(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function Al(e){return Array.isArray(e)?[...e]:[]}function _d(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?Al(e.messages):i?[]:t.messages,activeModal:r?e.activeModal??null:t.activeModal,inputContent:e.inputContent??t.inputContent}:{...e,...n?{messages:Al(e.messages)}:{},...r?{activeModal:e.activeModal??null}:{}}}function zn(e,t){const n=Jh(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:_d(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 $d(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?zn(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 Ml(e){return!!e&&typeof e=="object"&&"text"in e}function ji(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:Ml(o)?String(o.text||""):"").join(n):Ml(e)?a=String(e.text||""):a=String(e||""),r?a.replace(/\s+/g," ").trim():a}function gn(e){return ji(e,{normalizeWhitespace:!0})}function Qh(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 Tl(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 Hd(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 Xh(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 Ua(e){if(!e||typeof e!="object")return"";const t=e,n=Xh(gn(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 Zh(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=Ua(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:Ua(e[0]),last:Ua(e[e.length-1])}}function Go(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function qo(e,t,n){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(Go(e)&&Go(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)qo(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"&&qo(r[i],a[i],n)}function Jn(e,t){return Array.isArray(e)?e.map(n=>Jn(n,t)):!e||typeof e!="object"?e:Go(e)?Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[a])=>r.localeCompare(a)).map(([r,a])=>[r,r==="messages"?Zh(a,t):Jn(a,t)])):Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,Jn(r,t)]))}function ef(e,t){try{const n=new WeakSet;return qo(e,t,n),JSON.stringify(Jn(e,n))===JSON.stringify(Jn(t,n))}catch{return!1}}function zo(e,t,n){return ef(e,t)?(e._lastUpdate=n,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function Fd(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function tf(e,t,n){t[n]!==void 0&&(e[n]=t[n])}function Pl(e,t,n,r){var u;const a=(u=t.chats)!=null&&u.length?t.chats:e.chats,o=$d(e.childSessions,t.childSessions,{preserveMissing:r}),i=_d(t.activeChat,e.activeChat),c=t.workspace||e.workspace;return Hd(e,t,{...e,...t,chats:a,childSessions:o,activeChat:i,workspace:c,_lastUpdate:n})}function sf(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=$d(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"])tf(r,t,i);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(r.machineNickname=t.machineNickname),t.versionMismatch===!0&&(r.versionMismatch=!0),r}function nf(e,t,n,r){const a=sf(e,t,r),o=Object.keys(a).length>0?Hd(e,t,{...e,...a,_lastUpdate:n}):{...e,_lastUpdate:n};return zo(e,o,n)}function rf(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=Fd(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 af(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 of(e,t,n,r,a){return e.transport?n.has(t)&&!r.has(t)?!0:a.has(t):!1}function lf(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}=rf(e);for(const f of e){const g=o.get(f.id);if(!g){o.set(f.id,{...f,_lastUpdate:r});continue}const w=Tl(f),h=Tl(g),x=Fd(f),k=!a.has(x);if(w>h){const j=Pl(g,f,r,k);o.set(f.id,zo(g,j,r));continue}if(w<h){o.set(f.id,nf(g,f,r,k));continue}const b=f.timestamp||r,S=g._lastUpdate||g.timestamp||0;if(b>=S){const j=Pl(g,f,r,k);o.set(f.id,zo(g,j,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 w=g.daemonId||f.split(":")[0];if(!c.has(w))continue;if(a.has(w)&&p.has(w)&&!i.has(f)){o.delete(f);continue}const h=r-(g._lastUpdate||g.timestamp||0);af(g,w,h,i,a,u)&&o.delete(f)}for(const[f,g]of o){const w=g.daemonId||f.split(":")[0];if(of(g,w,c,u,o))continue;r-(g._lastUpdate||g.timestamp||0)>3e5&&g.status!=="online"&&o.delete(f)}return Array.from(o.values())}function cf(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 Bd=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}),Od=l.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function df({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((k,b)=>{r(S=>{let j=!1;const y=S.map(v=>v.id!==k||v.chats===b?v:(j=!0,{...v,chats:b}));return j?y:S})},[]),f=l.useCallback((k,b)=>{r(S=>{const j=S.length===0?k:lf(k,S,b),y=!cf(S,j);return y&&bn.record({kind:"dashboard.entries_applied",payload:{incoming:Nl(k),next:Nl(j)}}),y?j:S})},[]),g=l.useCallback(()=>o(!0),[]),w=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(Od.Provider,{value:w,children:s.jsx(Bd.Provider,{value:x,children:e})})}function gs(){return l.useContext(Bd)}function ar(){return l.useContext(Od)}function Wd(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 w=await fetch(m,{...u,headers:p,signal:f.signal});if(w.status===401)throw r==null||r(),new Error("Unauthorized");if(!w.ok){const h=await w.json().catch(()=>({error:w.statusText}));throw new Error(h.error||`API Error: ${w.status}`)}return w.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 uf=Wd({baseUrl:"http://localhost:3847"}),pf=l.createContext(uf);function mf({client:e,children:t}){return s.jsx(pf.Provider,{value:e,children:t})}const hf={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Ud=l.createContext(hf);function ff({value:e,children:t}){return s.jsx(Ud.Provider,{value:e,children:t})}function vt(){return l.useContext(Ud)}function Gd(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function bf(e){const t=Gd(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 gf(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=bf(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=Gd(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 xf({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 qd=l.createContext(null);function vf({sendDaemonCommand:e,children:t}){const n=gf(e),r=l.useMemo(()=>({launchCli:n.launchCli}),[n.launchCli]);return s.jsxs(qd.Provider,{value:r,children:[t,n.pending&&s.jsx(xf,{providerType:n.pending.providerType,sourceName:n.pending.sourceName,description:n.pending.description,onConfirm:n.confirm,onCancel:n.cancel})]})}function ka(){const e=l.useContext(qd);return e||{launchCli:async()=>{throw new Error("useLaunchCli must be used inside <LaunchCliProvider>")}}}function zd(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function yf(e,t,n){return Number(e.receivedAt||n[sa(e)]||0)||0}function Kd(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function wf(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function Dn(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 Ga(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 kf(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 sa(e,t){const n=e,r=ji(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:${kf(r)}`,o?`ts:${o}`:""].filter(Boolean).join("|")}function Sf(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 Cf(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Vd(e){return e?Sf([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),Cf(e.content)]):""}const Ni=200,jf=80,Il=650,Ln=new Map;function na(e,t){if(!e)return!1;const n=String(e.messageFingerprint||"");return n?n===String(t||""):!0}function Nf(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}:${Vd(r)}`}function Af(e,t,n,r){return e||!t?!1:na(n,r)}function Mf({scrollTop:e,scrollHeight:t,clientHeight:n,topThresholdPx:r=jf,bottomThresholdPx:a=Ni}){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 Tf(e){return Mf({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function Kn(e,t=Ni){return!!e&&e.fromBottom>=t}function Pf(e,t){return na(e,t)?!Kn(e):!0}function If({hasSelection:e,userScrolledUp:t,hasChatContentChanged:n=!0}){return!(e||t||!n)}function Df({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:n}){return e?!1:n||!t}function qa(e,t){const n=Math.max(0,e.scrollHeight-e.clientHeight-t.fromBottom);e.scrollTop=Number.isFinite(n)?n:t.top}const Je={size:18};function Yd({size:e=Je.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 Ai({size:e=Je.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 Ts({size:e=Je.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 Jd({size:e=Je.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 Lf({size:e=Je.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 Rf({size:e=Je.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 Qd({size:e=Je.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 Xd({size:e=Je.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 Zd({size:e=Je.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 Sa({size:e=Je.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 Mi({size:e=Je.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 Ef({size:e=Je.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 _f({size:e=Je.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 Zs({size:e=Je.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 us({size:e=Je.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 Ti({size:e=Je.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 xn({size:e=Je.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 Ca({size:e=Je.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 Ys({size:e=Je.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 or({size:e=Je.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 es({size:e=Je.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 $f({size:e=Je.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 eu({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"}),s.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}function Pi({size:e=Je.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 tu({size:e=Je.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 Hf({size:e=Je.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 Ii({size:e=Je.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 Ff({size:e=Je.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 su({size:e=Je.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 Di({size:e=Je.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 At({size:e=Je.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 Bf({size:e=Je.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 Of({size:e=Je.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 Wf({size:e=Je.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 Uf({size:e=Je.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 Nn({size:e=Je.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 nu({size:e=Je.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 Gf({size:e=Je.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 qf({size:e=Je.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 zf({size:e=Je.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 ru({size:e=Je.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 Kf({size:e=Je.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 Vf({size:e=Je.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 Yf({size:e=Je.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 Jf({size:e=Je.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 Qf({size:e=Je.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 Xf({size:e=Je.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 Zf({size:e=Je.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 eb({size:e=Je.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 tb({size:e=Je.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 au="adhdev_chat_activity_visible",Dl=new Set(["hidden","debug","internal"]),Ll=new Set(["visible","user","chat"]),sb=new Set(["debug","trace","internal"]),nb=new Set(["tool_call","terminal_command","runtime_activity"]),rb=new Set(["runtime_status","provider_chrome","control"]),ab=new Set(["thought","tool","terminal"]);function ou(e){const t=e.meta;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function rn(e){return typeof e=="string"?e.trim().toLowerCase():""}function za(e,t,n){return e[n]??(t==null?void 0:t[n])}function Rl(e,t,n){const r=e;return n.some(a=>r[a]===!0||(t==null?void 0:t[a])===!0)}function ob(e,t){const n=rn(e.kind);return n||(t==="tool"?"tool":"standard")}function Ka(e,t,n){const r=ou(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 ib(e){const t=e.content;return Array.isArray(t)&&t.some(n=>!!n&&typeof n=="object"&&n.type!=="text")}function Li(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal"};const t=ou(e),n=rn(e.role),r=ob(e,n),a=rn(za(e,t,"visibility")),o=rn(e.transcriptVisibility??(t==null?void 0:t.transcriptVisibility)??a),i=rn(za(e,t,"audience")),c=rn(za(e,t,"source")),u=Dl.has(a)||Dl.has(o)||sb.has(i)||Rl(e,t,["internal","isInternal","debug","statusOnly","controlOnly"]),p=Ll.has(a)||Ll.has(o)||i==="chat"||Rl(e,t,["userFacing"]),d=ab.has(r)||nb.has(c);if(u)return{surface:d?"activity":"internal",isUserFacing:!1,isActivityFacing:d,isInternal:!d,role:n,kind:r,label:Ka(e,r,c)};if(p)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:n,kind:r,label:Ka(e,r,c)};if((n==="system"||r==="system")&&ib(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:n,kind:r,label:"Chat"};if(rb.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:Ka(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 lb(e){return(Array.isArray(e)?e:[]).filter(t=>Li(t).isUserFacing)}function iu(e){return(Array.isArray(e)?e:[]).filter(t=>Li(t).isActivityFacing)}function lu(e){const t=e.content;return typeof t=="string"?t:(()=>{try{return JSON.stringify(t??"")}catch{return String(t??"")}})()}function cb(e){return`${String(e.role||"")}::${lu(e)}`}function db(e){if(e.length<2)return e;const t=[];let n="";for(const r of e){const a=cb(r);lu(r).trim().length>0&&a===n||(t.push(r),n=a)}return t}function ub(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 El(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(au))==="1"}catch{return!1}}function pb({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(Zd,{size:11}):s.jsx(Xd,{size:11})})}const cu=[Ch,{singleTilde:!1}],du=[cu,jh,Nh],mb=[cu];function wr(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 _l(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):Kd(e)?s.jsx(Si,{remarkPlugins:du,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}const hb=l.memo(function({content:t,renderAsPreformatted:n,renderAsMarkdown:r}){return n?s.jsx("pre",{className:"chat-preformatted",children:t}):r?s.jsx(Si,{remarkPlugins:du,children:t}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:t})});function Rn({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:_l(String(n.text||""),t)},`text-${r}`);if(n.type==="image"){const a=Ga(n),o=n.alt||n.description||Dn(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:wr("Image",o,n.mimeType)},`image-fallback-${r}`)}if(n.type==="audio"){const a=Ga(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:wr("Audio",Dn(n.uri,"audio"),n.transcript||n.mimeType)},`audio-fallback-${r}`)}if(n.type==="video"){const a=Ga(n),o=n.title||n.name||n.alt||Dn(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"}):wr("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||Dn(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}):wr("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=Dn(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}),_l(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 fb=l.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(Si,{remarkPlugins:mb,children:t.text}),s.jsx("span",{className:"action-time",children:zd(t.timestamp)})]})},(e,t)=>e.log===t.log);function $l(e){const t=e.meta;return[Vd(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 bb=l.memo(function({message:t,receivedAt:n,agentName:r,userName:a,isCliMode:o,isTextExpanded:i,onToggleTextExpanded:c}){var C,A,M;const u=(t.role||"").toLowerCase(),p=u==="user"||u==="human",d=t.kind||(u==="tool"?"tool":"standard"),m=Li(t),f=wf(t.content)?t.content:null,g=!!(f!=null&&f.some(T=>T.type!=="text")),w=ji(t.content,{joiner:`
8
- `});if(m.isActivityFacing&&d!=="thought"&&d!=="tool"&&d!=="terminal"){const T=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:T})]}),g&&f?s.jsx("div",{className:"chat-msg-activity-body",children:s.jsx(Rn,{parts:f,renderAsPreformatted:!1})}):s.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:w})]})}if(d==="thought"){const T=typeof((C=t.meta)==null?void 0:C.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(Wf,{size:13}),s.jsx("span",{children:T})]}),s.jsx("div",{className:"chat-msg-body",children:w})]})}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(Rn,{parts:f,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:w})]});if(d==="terminal"){const T=(A=t.meta)!=null&&A.isRunning?"⏳":"✅",R=typeof((M=t.meta)==null?void 0:M.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:T}),s.jsx("span",{children:R})]}),g&&f?s.jsx("div",{className:"chat-msg-body",children:s.jsx(Rn,{parts:f,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:w})]})}if(d==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:g&&f?s.jsx(Rn,{parts:f,renderAsPreformatted:!1}):w.slice(0,100)});const h=t.meta,k=(typeof(h==null?void 0:h.renderMode)=="string"?h.renderMode.trim():"")==="preformatted",b=w,S=!1,j=b,y=k,v=!p&&!y&&Kd(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(pb,{text:w}),n!=null&&s.jsx("span",{className:"chat-time",children:zd(n)})]})]}),(b||g)&&s.jsx("div",{className:"chat-markdown",children:g&&f?s.jsx(Rn,{parts:f,renderAsPreformatted:y}):s.jsx(hb,{content:j,renderAsPreformatted:y,renderAsMarkdown:v})}),S]})})},(e,t)=>(e.message===t.message||$l(e.message)===$l(t.message))&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded),gb=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:w,hiddenLiveCount:h=0,loadError:x,scrollToBottomRequestNonce:k,isVisible:b=!0},S){const{t:j}=Ne("common"),y=l.useRef(null),v=l.useRef(null),N=l.useRef(null),C=l.useRef(0),A=l.useRef(""),M=l.useRef(""),T=l.useRef(!1),R=l.useRef(null),E=l.useRef(!1),_=l.useRef(null),z=l.useRef(!1),[F,D]=l.useState(new Set),[W,L]=l.useState({showTop:!1,showBottom:!1}),P=l.useRef(!1),$=l.useRef(!1),I=l.useRef(b),U=l.useRef(b),J=l.useRef(null);U.current=b;const re=()=>{const ce=y.current;return ce?ce.scrollHeight-ce.scrollTop-ce.clientHeight<Ni:!0},Y=l.useCallback(()=>{const ce=y.current,H=ce?Tf(ce):{showTop:!1,showBottom:!1};L(pe=>pe.showTop===H.showTop&&pe.showBottom===H.showBottom?pe:H)},[]),X=l.useCallback((ce="auto")=>{var pe;const H=y.current;H&&(H.scrollTo({top:H.scrollHeight,behavior:ce}),(pe=H.ownerDocument.defaultView)==null||pe.requestAnimationFrame(()=>Y()))},[Y]),de=l.useCallback((ce="auto")=>{var pe;const H=y.current;H&&(H.scrollTo({top:0,behavior:ce}),(pe=H.ownerDocument.defaultView)==null||pe.requestAnimationFrame(()=>Y()))},[Y]),ne=l.useCallback(()=>{var B;const ce=y.current,H=(B=window.getSelection)==null?void 0:B.call(window);if(!ce||!H||H.rangeCount===0||H.isCollapsed){z.current=!1;return}const pe=H.anchorNode,le=H.focusNode;z.current=!!(pe&&le&&ce.contains(pe)&&ce.contains(le))},[]),O=l.useMemo(()=>{const ce=lb(t),H=iu(t);return db(ub(ce,H,d))},[t,d]),ie=O.length===t.length?p:void 0,K=Nf(O,ie),ae=l.useCallback(()=>{const ce=y.current;if(!ce||!c||!U.current)return;const H={top:ce.scrollTop,fromBottom:Math.max(0,ce.scrollHeight-ce.scrollTop-ce.clientHeight),messageFingerprint:K};J.current={contextKey:c,snapshot:H},Ln.set(c,H)},[c,K]),Ce=l.useCallback((ce="auto")=>{R.current!=null&&cancelAnimationFrame(R.current),R.current=requestAnimationFrame(()=>{R.current=null,X(ce)})},[X]),ye=l.useCallback(()=>{P.current=!1,E.current=!0,$.current=!0,_.current!=null&&window.clearTimeout(_.current),_.current=window.setTimeout(()=>{E.current=!1,_.current=null},Il)},[]);l.useEffect(()=>{const ce=!T.current,H=M.current!==c;if(M.current=c,ce||H){T.current=!0;const le=c?Ln.get(c):null,B=!!le&&na(le,K);P.current=B?Kn(le):!1,E.current=Pf(le,K),z.current||(B?requestAnimationFrame(()=>{const be=y.current;be&&(qa(be,le),P.current=Kn(le),Y(),$.current=!0)}):Ce("auto")),C.current=O.length,A.current=K;return}O.length>C.current;const pe=K!==A.current;If({hasSelection:z.current,userScrolledUp:P.current,hasChatContentChanged:pe})&&Ce("auto"),C.current=O.length,A.current=K},[K,c,O.length,Ce,Y]),l.useEffect(()=>{k&&(ye(),z.current||Ce("auto"))},[ye,Ce,k]),l.useEffect(()=>{const ce=I.current;ce&&!b&&ae(),U.current=b,I.current=b;const H=c?Ln.get(c):null;if(Af(ce,b,H,K)){if(!H)return;P.current=Kn(H),E.current=!1,z.current||requestAnimationFrame(()=>{const pe=y.current;pe&&(qa(pe,H),Y())});return}},[b,c,K,ye,ae,Ce,Y]),l.useEffect(()=>()=>{const ce=J.current;ce&&Ln.set(ce.contextKey,ce.snapshot),R.current!=null&&cancelAnimationFrame(R.current),_.current!=null&&window.clearTimeout(_.current)},[]),l.useEffect(()=>{const ce=v.current,H=y.current;if(!ce||!H)return;const pe=()=>{_.current!=null&&window.clearTimeout(_.current),_.current=window.setTimeout(()=>{E.current=!1,_.current=null},Il)},le=new ResizeObserver(()=>{Y();const B=E.current;Df({hasSelection:z.current,userScrolledUp:P.current,contextAutoScrollActive:B})&&(Ce("auto"),B&&pe())});return le.observe(ce),H!==ce&&le.observe(H),()=>{le.disconnect(),_.current!=null&&(window.clearTimeout(_.current),_.current=null)}},[Ce,c,Y]),l.useImperativeHandle(S,()=>({scrollToBottom:(ce="smooth")=>{X(ce)}}),[X]),l.useEffect(()=>{const ce=y.current;if(!ce)return;let H;const pe=()=>{ae(),clearTimeout(H),H=setTimeout(()=>{P.current=!re(),Y()},50)};return ce.addEventListener("scroll",pe,{passive:!0}),()=>{ce.removeEventListener("scroll",pe),clearTimeout(H)}},[ae,Y]),l.useEffect(()=>(document.addEventListener("selectionchange",ne),()=>document.removeEventListener("selectionchange",ne)),[ne]);const ke=l.useRef(0),me=l.useRef(!1);l.useEffect(()=>{const ce=y.current;if(!ce||!me.current||ke.current===0)return;const H=ce.scrollHeight-ke.current;H>0&&(ce.scrollTop=H),Y(),ae(),ke.current=0,me.current=!1},[O.length,ae,Y]),l.useEffect(()=>{if($.current||!c)return;const ce=Ln.get(c),H=y.current;if(!(!ce||!H)){if(!na(ce,K)){X("auto"),$.current=!0;return}qa(H,ce),P.current=Kn(ce),Y(),$.current=!0}},[c,K,O.length,X,Y]);const q=()=>{const ce=y.current;ce&&(ke.current=ce.scrollHeight),me.current=!0,f==null||f()},G=()=>{P.current=!0,de("smooth"),ae()},Z=()=>{ye(),X("smooth"),ae()},V=l.useMemo(()=>{const ce=O.map((B,be)=>({type:"message",data:B,index:be,ts:yf(B,be,u)}));if(!n||n.length===0)return ce;const H=[...n].sort((B,be)=>B.timestamp-be.timestamp).map((B,be)=>({type:"action",data:B,index:be,ts:B.timestamp})),pe=[];let le=0;for(const B of ce){for(;le<H.length&&B.ts>0&&H[le].ts<B.ts;)pe.push(H[le++]);pe.push(B)}for(;le<H.length;)pe.push(H[le++]);return pe},[O,n,u]),fe=h>0||!!w,Te=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:y,"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")}),fe&&!g&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:q,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:Te})}),V.length===0&&!fe&&(m||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:j("chatList.waitingForMessages")})),V.map(ce=>{if(ce.type==="action"){const je=ce.data;return s.jsx(fb,{log:je},`action-${ce.index}`)}const H=ce.data;ce.index;const pe=sa(H),le=H.receivedAt||u[pe],B=`${c}-${pe}`,be=F.has(B);return s.jsx(bb,{message:H,receivedAt:le,agentName:r,userName:a,isCliMode:o,isTextExpanded:be,onToggleTextExpanded:()=>D(je=>{const Se=new Set(je);return be?Se.delete(B):Se.add(B),Se})},`msg-${pe}`)}),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})]})}),(W.showTop||W.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":j("chatList.jumpToTop"),children:[W.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:G,"aria-label":j("chatList.jumpToOldestMessages"),title:j("chatList.jumpToTop"),children:j("chatList.top")}),W.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:Z,"aria-label":j("chatList.jumpToLatestMessages"),title:j("chatList.jumpToBottom"),children:j("chatList.latest")})]})]})}),xb=l.memo(gb,(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),vb="modulepreload",yb=function(e){return"/"+e},Hl={},wb=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=yb(u),u in Hl)return;Hl[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":vb,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 Fl=!1;const uu=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),w=l.useRef(!1),h=()=>{const x=c.current;if(x){m.current&&(x.clear(),m.current=!1);for(const k of d.current)x.write(k.data,k.onProcessed);d.current=[],f.current&&(x.fit(),f.current=!1),g.current&&(x.bumpResize(),g.current=!1),w.current&&(x.scrollToTop(),w.current=!1)}};return l.useImperativeHandle(i,()=>({write:(x,k)=>{c.current?c.current.write(x,k):d.current.push({data:x,onProcessed:k})},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,k)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(x,k)},fit:()=>{c.current?c.current.fit():f.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():g.current=!0},scrollToTop:()=>{c.current?c.current.scrollToTop():w.current=!0},getSelection:()=>{var x,k;return((k=(x=c.current)==null?void 0:x.getSelection)==null?void 0:k.call(x))||""},getVisibleText:()=>{var x,k;return((k=(x=c.current)==null?void 0:x.getVisibleText)==null?void 0:k.call(x))||""}}),[]),l.useEffect(()=>{u&&h()},[u]),l.useEffect(()=>{let x=!1;return wb(()=>import("./terminal-DiXj2eIR.js"),__vite__mapDeps([0,1,2])).then(k=>{Fl||(Fl=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),x||p(()=>k.GhosttyTerminalView)}).catch(k=>{console.error("[CliTerminal] failed to load terminal renderer",k)}),()=>{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"}})});uu.displayName="CliTerminal";function Bt(...e){return Ah(Mh(e))}const kb={lg:"rounded-lg",xl:"rounded-xl","2xl":"rounded-2xl"},Sb={none:"",sm:"p-3",md:"px-4 py-3.5",lg:"px-5 py-4"},Ss=l.forwardRef(function({radius:t="xl",padding:n="md",className:r,...a},o){return s.jsx("div",{ref:o,className:Bt("border border-border-subtle bg-bg-secondary",kb[t],Sb[n],r),...a})});function kr({label:e,value:t,sub:n,icon:r}){return s.jsxs(Ss,{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 Bl({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 Cb({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 w=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,w)),k=Math.max(8,Math.min(o.height-8,h));return s.jsxs("div",{style:{position:"absolute",left:x-8,top:k-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 jb({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:w,onZoomIn:h,transportType:x,screenshotUsage:k,lastActionStatus:b}){const{t:S}=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:S(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:S("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:S(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:S("remote.directP2PTitle"),children:S("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:S("remote.turnRelayTitle"),children:S("remote.relay")}),k&&k.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:k.budgetExhausted?"#ef4444":"#c4b5fd",background:k.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:S("remote.dailyTurnTitle"),children:k.budgetExhausted?S("remote.turnBlocked"):S("remote.turnUsage",{used:k.dailyUsedMinutes,budget:k.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:S("remote.settings")}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:[S("remote.zoom")," ",d<=(m?f:1)+.01?S(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(),w()},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:S(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 Nb({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 Ab(){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 Ol(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 hr(e,t){const n=l.useRef(null),r=l.useRef(0);l.useEffect(()=>{if(!Ab())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,Ol(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,Ol(t[i])]))}),n.current=t})}function Mb({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:w,spawnRippleFromNormalized:h,clampPan:x,isMobile:k,mobileFillZoom:b}){const[S,j]=l.useState(null),y=l.useRef(null),v=l.useRef(null),N=l.useRef(null),C=l.useRef(!1),A=l.useRef(null),M=l.useRef(0),T=l.useRef(null),R=l.useRef(1),E=l.useRef({x:0,y:0}),_=l.useRef(!1),z=l.useRef(r),F=l.useRef(g),D=30,W=550,L=18,P=60,$=400,I=12,U=()=>{if(y.current)return;const Y={nx:.5,ny:.5};y.current=Y,j(Y)};return l.useEffect(()=>{z.current=r,r==="mouse"&&U()},[r]),l.useEffect(()=>{F.current=g},[g]),l.useEffect(()=>{const Y=e.current;if(!Y)return;const X=ae=>{if(!n.current)return null;const Ce=n.current.getBoundingClientRect();return!Ce.width||!Ce.height?null:{nx:Math.max(0,Math.min(1,(ae.clientX-Ce.left)/Ce.width)),ny:Math.max(0,Math.min(1,(ae.clientY-Ce.top)/Ce.height))}},de=(ae,Ce)=>{if(!n.current)return{dnx:0,dny:0};const ye=n.current,ke=ye.getBoundingClientRect(),me=ye.naturalWidth||ke.width,q=ye.naturalHeight||ke.height,G=me/q,Z=ke.width/ke.height;let V,fe;return G>Z?(V=ke.width,fe=ke.width/G):(fe=ke.height,V=ke.height*G),{dnx:ae/V,dny:Ce/fe}},ne=(ae,Ce,ye)=>{if(ye<=1.05)return;const ke=-(ae-.5)*100,me=-(Ce-.5)*100,q=x(ke,me,ye);(Math.abs(q.x-c.current)>.1||Math.abs(q.y-u.current)>.1)&&(p(q.x),d(q.y),c.current=q.x,u.current=q.y)},O=ae=>{const Ce=t.current;if(Ce&&ae.target instanceof Node&&Ce.contains(ae.target))ae.preventDefault();else return;if(ae.touches.length===1){const ye=ae.touches[0];v.current={x:ye.clientX,y:ye.clientY,time:Date.now()},N.current={x:ye.clientX,y:ye.clientY},_.current||(C.current=!1),A.current=setTimeout(()=>{if(!C.current&&!_.current)if(C.current=!0,z.current==="mouse"){const ke=y.current||{nx:.5,ny:.5};w("Right Click"),h(ke.nx,ke.ny,"right"),F.current("input_click",{...ke,button:"right"}).catch(()=>{})}else{const ke=X(ye);ke&&(w("Right Click"),h(ke.nx,ke.ny,"right"),F.current("input_click",{...ke,button:"right"}).catch(()=>{}))}},500);return}if(ae.touches.length===2){A.current&&clearTimeout(A.current),C.current=!0,_.current=!0;const ye=ae.touches[1].clientX-ae.touches[0].clientX,ke=ae.touches[1].clientY-ae.touches[0].clientY;T.current=Math.sqrt(ye*ye+ke*ke),R.current=i.current,E.current={x:(ae.touches[0].clientX+ae.touches[1].clientX)/2,y:(ae.touches[0].clientY+ae.touches[1].clientY)/2}}},ie=ae=>{const Ce=t.current;if(Ce&&ae.target instanceof Node&&Ce.contains(ae.target)&&ae.preventDefault(),ae.touches.length===1&&N.current){const ye=ae.touches[0],ke=ye.clientX-N.current.x,me=ye.clientY-N.current.y;if(!C.current&&v.current){const q=ye.clientX-v.current.x,G=ye.clientY-v.current.y;Math.sqrt(q*q+G*G)>8&&(C.current=!0,A.current&&clearTimeout(A.current))}if(C.current)if(z.current==="mouse"){const q=de(ke,me),G=y.current||{nx:.5,ny:.5},Z=Math.max(0,Math.min(1,G.nx+q.dnx)),V=Math.max(0,Math.min(1,G.ny+q.dny));y.current={nx:Z,ny:V},j({nx:Z,ny:V}),w(`Cursor: ${Math.round(Z*100)}%, ${Math.round(V*100)}%`),ne(Z,V,i.current);const fe=Date.now();fe-f.current>=30&&(f.current=fe,F.current("input_mouseMoved",{nx:Z,ny:V}).catch(()=>{}))}else if(i.current>1){const q=t.current;if(q){const G=q.clientWidth,Z=q.clientHeight,V=c.current+ke/G*100,fe=u.current+me/Z*100,Te=x(V,fe,i.current);p(Te.x),d(Te.y),c.current=Te.x,u.current=Te.y}}else{const q=X(ye);if(q){const G=Date.now();G-f.current>=40&&(f.current=G,w("Scroll"),F.current("input_wheel",{nx:q.nx,ny:q.ny,deltaX:Math.round(-ke*2.5),deltaY:Math.round(-me*2.5)}).catch(()=>{}))}}N.current={x:ye.clientX,y:ye.clientY};return}if(ae.touches.length===2&&T.current!==null){const ye=ae.touches[1].clientX-ae.touches[0].clientX,ke=ae.touches[1].clientY-ae.touches[0].clientY,q=Math.sqrt(ye*ye+ke*ke)/T.current,G=(ae.touches[0].clientX+ae.touches[1].clientX)/2,Z=(ae.touches[0].clientY+ae.touches[1].clientY)/2,V=G-E.current.x,fe=Z-E.current.y,Te=Math.abs(q-1)>.03;if(z.current==="mouse"){if(Te){const ce=Math.max(o,Math.min(5,R.current*q));m(ce),i.current=ce}else if(Math.abs(V)>2||Math.abs(fe)>2){const ce=y.current||{nx:.5,ny:.5},H=Date.now();H-f.current>=30&&(f.current=H,w("Scroll"),F.current("input_wheel",{nx:ce.nx,ny:ce.ny,deltaX:Math.round(-V*3),deltaY:Math.round(-fe*3)}).catch(()=>{}))}}else{const ce=Math.max(o,Math.min(5,R.current*q));m(ce),i.current=ce;const H=t.current;if(H&&ce>1){const pe=H.clientWidth,le=H.clientHeight,B=c.current+V/pe*100,be=u.current+fe/le*100,je=x(B,be,ce);p(je.x),d(je.y),c.current=je.x,u.current=je.y}}E.current={x:G,y:Z}}},K=ae=>{var Ce;if(A.current&&clearTimeout(A.current),T.current=null,ae.touches.length===1&&_.current){const ye=ae.touches[0];v.current={x:ye.clientX,y:ye.clientY,time:Date.now()},N.current={x:ye.clientX,y:ye.clientY},C.current=!0;return}if(ae.touches.length===0){if(_.current){_.current=!1,C.current=!1;return}if(ae.changedTouches.length===1){const ye=ae.changedTouches[0],ke=Date.now(),me=ke-(((Ce=v.current)==null?void 0:Ce.time)||0),q=v.current?ye.clientX-v.current.x:0,G=v.current?ye.clientY-v.current.y:0,Z=Math.sqrt(q*q+G*G);if(z.current==="mouse"){if(me<D||me>W||Z>L){C.current=!1;return}const V=y.current||X(ye);V&&(w(`Click: ${Math.round(V.nx*100)}%, ${Math.round(V.ny*100)}%`),h(V.nx,V.ny,"left"),F.current("input_click",{...V}).catch(()=>{}))}else{if(C.current){C.current=!1;return}if(me<P||me>$||Z>I){C.current=!1;return}const V=X(ye);if(!V)return;ke-M.current<300?(w("Double tap"),h(V.nx,V.ny,"double"),F.current("input_click",{...V,clickCount:2}).catch(()=>{}),M.current=0):(w(`Tap: ${Math.round(V.nx*100)}%, ${Math.round(V.ny*100)}%`),h(V.nx,V.ny,"left"),F.current("input_click",{...V}).catch(()=>{}),M.current=ke)}}C.current=!1}};return Y.addEventListener("touchstart",O,{passive:!1}),Y.addEventListener("touchmove",ie,{passive:!1}),Y.addEventListener("touchend",K,{passive:!1}),()=>{Y.removeEventListener("touchstart",O),Y.removeEventListener("touchmove",ie),Y.removeEventListener("touchend",K),A.current&&clearTimeout(A.current)}},[e,t,n,o,i,c,u,p,d,m,f,w,h,x]),{cursorPos:S,cursorPosRef:y,handleToggleInputMode:()=>{a(Y=>{const X=Y==="touch"?"mouse":"touch";return X==="mouse"&&U(),X})},handleZoomReset:()=>{const Y=k?b:1;m(Y),i.current=Y,p(0),d(0),c.current=0,u.current=0}}}function pu({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),[w,h]=l.useState([]),x=l.useRef(0),[k,b]=l.useState(!1),[S,j]=l.useState(!1),y=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[v,N]=l.useState(y?"mouse":"touch"),[C,A]=l.useState(1),M=l.useRef(!1),[T,R]=l.useState(1),[E,_]=l.useState(0),[z,F]=l.useState(0);hr("RemoteView",{connState:n,hasScreenshot:!!r,inputMode:v,zoom:T,panX:E,panY:z,isMenuOpen:k,isImeOpen:S});const D=l.useRef(0),W=l.useRef(T),L=l.useRef(E),P=l.useRef(z);l.useEffect(()=>{W.current=T},[T]),l.useEffect(()=>{L.current=E},[E]),l.useEffect(()=>{P.current=z},[z]),l.useEffect(()=>{var me;(me=i.current)==null||me.focus()},[]);const $=n==="connected",I=r,U=$?"Connected. Waiting for first frame...":n==="connecting"?"Connecting to Host...":"Reconnecting to Host...",J=$?"The remote stream is warming up":"Waiting for the remote stream to catch up";l.useEffect(()=>{if(!y||M.current||!I)return;const me=u.current,q=c.current;if(!me||!q)return;const G=()=>{const Z=q.clientWidth,V=q.clientHeight,fe=me.naturalWidth,Te=me.naturalHeight;if(!fe||!Te||!Z||!V)return;const ce=Math.min(Z/fe,V/Te),pe=Math.max(Z/fe,V/Te)/ce;pe>1.01&&(A(pe),R(pe),W.current=pe),M.current=!0};me.complete&&me.naturalWidth?G():me.addEventListener("load",G,{once:!0})},[I,y]);const re=.5;l.useEffect(()=>{T<=re&&(_(0),F(0))},[T,re]);const Y=(me,q,G)=>{if(G<=re)return{x:0,y:0};const Z=(G-1)/(2*G)*100,V=(G-1)/(2*G)*100;return{x:Math.max(-Z,Math.min(Z,me)),y:Math.max(-V,Math.min(V,q))}},X=(me,q)=>{if(!u.current)return null;const G=u.current.getBoundingClientRect();return!G.width||!G.height?null:{nx:Math.max(0,Math.min(1,(me-G.left)/G.width)),ny:Math.max(0,Math.min(1,(q-G.top)/G.height))}},de=(me,q,G)=>{const Z=c.current;if(!Z)return;const V=Z.getBoundingClientRect(),fe=++x.current;h(Te=>[...Te,{id:fe,x:me-V.left,y:q-V.top,type:G}]),setTimeout(()=>h(Te=>Te.filter(ce=>ce.id!==fe)),600)},ne=(me,q,G)=>{const Z=u.current,V=c.current;if(!Z||!V)return;const fe=Z.getBoundingClientRect(),Te=V.getBoundingClientRect(),ce=Z.naturalWidth||fe.width,H=Z.naturalHeight||fe.height,pe=ce/H,le=fe.width/fe.height;let B,be,je,Se;pe>le?(B=fe.width,be=fe.width/pe,je=0,Se=(fe.height-be)/2):(be=fe.height,B=fe.height*pe,je=(fe.width-B)/2,Se=0);const He=fe.left-Te.left+je+B*me,Xe=fe.top-Te.top+Se+be*q,dt=++x.current;h(it=>[...it,{id:dt,x:He,y:Xe,type:G}]),setTimeout(()=>h(it=>it.filter(he=>he.id!==dt)),600)},O=async me=>{var G;const q=X(me.clientX,me.clientY);if(q){d(`Click: ${Math.round(q.nx*100)}%, ${Math.round(q.ny*100)}%`),de(me.clientX,me.clientY,"left"),(G=i.current)==null||G.focus();try{const Z=await e("input_click",{nx:q.nx,ny:q.ny});Z!=null&&Z.success||t(`❌ Click failed: ${Z==null?void 0:Z.error}`)}catch(Z){t(`❌ Click error: ${Z.message||Z}`)}}},ie=async(me,q,G,Z=0)=>{try{await e("input_key",{type:G?"char":"keyDown",key:me,code:q,text:G?me:void 0,unmodifiedText:G?me:void 0,modifiers:Z})}catch(V){t(`❌ Key error: ${V.message||V}`)}},K=async me=>{if(me.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(me.key)&&me.preventDefault();let G=0;me.altKey&&(G|=1),me.ctrlKey&&(G|=2),me.metaKey&&(G|=4),me.shiftKey&&(G|=8),d(`Key: ${me.key}`),await ie(me.key,me.code,me.key.length===1,G)},ae=async me=>{if(me.key==="Enter"){if(me.nativeEvent.isComposing)return;if(m){const q=m;f(""),d(`IME Sent: ${q}`);try{const G=await e("input_type",{text:q});G!=null&&G.success||t(`❌ IME error: ${G==null?void 0:G.error}`)}catch(G){t(`❌ IME error: ${G.message}`)}}else d("Key: Enter"),await ie("Enter","Enter",!1)}};l.useEffect(()=>{const me=i.current;if(!me)return;const q=G=>{var Z;if((Z=u.current)!=null&&Z.contains(G.target)){G.preventDefault();const V=Date.now();if(V-D.current<40)return;D.current=V;const fe=X(G.clientX,G.clientY);if(!fe)return;d(`Scroll: ${Math.round(G.deltaY)}`),e("input_wheel",{nx:fe.nx,ny:fe.ny,deltaX:Math.round(G.deltaX),deltaY:Math.round(G.deltaY)}).catch(()=>{})}};return me.addEventListener("wheel",q,{passive:!1}),()=>me.removeEventListener("wheel",q)},[e]);const{cursorPos:Ce,handleToggleInputMode:ye,handleZoomReset:ke}=Mb({containerRef:i,viewportRef:c,imgRef:u,inputMode:v,setInputMode:N,minZoom:re,zoomRef:W,panXRef:L,panYRef:P,setPanX:_,setPanY:F,setZoom:R,lastWheelTimeRef:D,onAction:e,setLastActionStatus:d,spawnRippleFromNormalized:ne,clampPan:Y,isMobile:y,mobileFillZoom:C});return s.jsxs("div",{ref:i,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:K,onContextMenu:me=>me.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:[I?s.jsx("img",{ref:u,src:I,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${T}) translate(${E}%, ${z}%)`,transformOrigin:"center center",cursor:v==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:O,onContextMenu:me=>me.preventDefault(),onDragStart:me=>me.preventDefault()}):s.jsx(Nb,{waitingLabel:U,waitingHint:J,transportType:o}),v==="mouse"&&I&&s.jsx(Cb,{cursorPos:Ce,viewportRef:c,imgRef:u}),w.map(me=>{const G={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[me.type];return s.jsxs("div",{style:{position:"absolute",left:me.x,top:me.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${G}, 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(${G}, 0.9)`,boxShadow:`0 0 12px rgba(${G}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},me.id)})]}),s.jsx(jb,{inputMode:v,onToggleInputMode:ye,isImeOpen:S,setIsImeOpen:j,isMenuOpen:k,setIsMenuOpen:b,imeText:m,setImeText:f,handleImeSubmit:ae,isConnActive:$,zoom:T,isMobile:y,mobileFillZoom:C,onZoomOut:()=>R(me=>Math.max(.5,me-.25)),onZoomReset:ke,onZoomIn:()=>R(me=>Math.min(5,me+.25)),transportType:o,screenshotUsage:a,lastActionStatus:p}),s.jsx("style",{children:`
8
+ `});if(m.isActivityFacing&&d!=="thought"&&d!=="tool"&&d!=="terminal"){const T=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:T})]}),g&&f?s.jsx("div",{className:"chat-msg-activity-body",children:s.jsx(Rn,{parts:f,renderAsPreformatted:!1})}):s.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:w})]})}if(d==="thought"){const T=typeof((C=t.meta)==null?void 0:C.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(Wf,{size:13}),s.jsx("span",{children:T})]}),s.jsx("div",{className:"chat-msg-body",children:w})]})}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(Rn,{parts:f,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:w})]});if(d==="terminal"){const T=(A=t.meta)!=null&&A.isRunning?"⏳":"✅",R=typeof((M=t.meta)==null?void 0:M.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:T}),s.jsx("span",{children:R})]}),g&&f?s.jsx("div",{className:"chat-msg-body",children:s.jsx(Rn,{parts:f,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:w})]})}if(d==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:g&&f?s.jsx(Rn,{parts:f,renderAsPreformatted:!1}):w.slice(0,100)});const h=t.meta,k=(typeof(h==null?void 0:h.renderMode)=="string"?h.renderMode.trim():"")==="preformatted",b=w,S=!1,j=b,y=k,v=!p&&!y&&Kd(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(pb,{text:w}),n!=null&&s.jsx("span",{className:"chat-time",children:zd(n)})]})]}),(b||g)&&s.jsx("div",{className:"chat-markdown",children:g&&f?s.jsx(Rn,{parts:f,renderAsPreformatted:y}):s.jsx(hb,{content:j,renderAsPreformatted:y,renderAsMarkdown:v})}),S]})})},(e,t)=>(e.message===t.message||$l(e.message)===$l(t.message))&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded),gb=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:w,hiddenLiveCount:h=0,loadError:x,scrollToBottomRequestNonce:k,isVisible:b=!0},S){const{t:j}=Ne("common"),y=l.useRef(null),v=l.useRef(null),N=l.useRef(null),C=l.useRef(0),A=l.useRef(""),M=l.useRef(""),T=l.useRef(!1),R=l.useRef(null),E=l.useRef(!1),_=l.useRef(null),z=l.useRef(!1),[F,D]=l.useState(new Set),[W,L]=l.useState({showTop:!1,showBottom:!1}),P=l.useRef(!1),$=l.useRef(!1),I=l.useRef(b),U=l.useRef(b),J=l.useRef(null);U.current=b;const re=()=>{const ce=y.current;return ce?ce.scrollHeight-ce.scrollTop-ce.clientHeight<Ni:!0},Y=l.useCallback(()=>{const ce=y.current,H=ce?Tf(ce):{showTop:!1,showBottom:!1};L(pe=>pe.showTop===H.showTop&&pe.showBottom===H.showBottom?pe:H)},[]),X=l.useCallback((ce="auto")=>{var pe;const H=y.current;H&&(H.scrollTo({top:H.scrollHeight,behavior:ce}),(pe=H.ownerDocument.defaultView)==null||pe.requestAnimationFrame(()=>Y()))},[Y]),de=l.useCallback((ce="auto")=>{var pe;const H=y.current;H&&(H.scrollTo({top:0,behavior:ce}),(pe=H.ownerDocument.defaultView)==null||pe.requestAnimationFrame(()=>Y()))},[Y]),ne=l.useCallback(()=>{var B;const ce=y.current,H=(B=window.getSelection)==null?void 0:B.call(window);if(!ce||!H||H.rangeCount===0||H.isCollapsed){z.current=!1;return}const pe=H.anchorNode,le=H.focusNode;z.current=!!(pe&&le&&ce.contains(pe)&&ce.contains(le))},[]),O=l.useMemo(()=>{const ce=lb(t),H=iu(t);return db(ub(ce,H,d))},[t,d]),ie=O.length===t.length?p:void 0,K=Nf(O,ie),ae=l.useCallback(()=>{const ce=y.current;if(!ce||!c||!U.current)return;const H={top:ce.scrollTop,fromBottom:Math.max(0,ce.scrollHeight-ce.scrollTop-ce.clientHeight),messageFingerprint:K};J.current={contextKey:c,snapshot:H},Ln.set(c,H)},[c,K]),Ce=l.useCallback((ce="auto")=>{R.current!=null&&cancelAnimationFrame(R.current),R.current=requestAnimationFrame(()=>{R.current=null,X(ce)})},[X]),ye=l.useCallback(()=>{P.current=!1,E.current=!0,$.current=!0,_.current!=null&&window.clearTimeout(_.current),_.current=window.setTimeout(()=>{E.current=!1,_.current=null},Il)},[]);l.useEffect(()=>{const ce=!T.current,H=M.current!==c;if(M.current=c,ce||H){T.current=!0;const le=c?Ln.get(c):null,B=!!le&&na(le,K);P.current=B?Kn(le):!1,E.current=Pf(le,K),z.current||(B?requestAnimationFrame(()=>{const be=y.current;be&&(qa(be,le),P.current=Kn(le),Y(),$.current=!0)}):Ce("auto")),C.current=O.length,A.current=K;return}O.length>C.current;const pe=K!==A.current;If({hasSelection:z.current,userScrolledUp:P.current,hasChatContentChanged:pe})&&Ce("auto"),C.current=O.length,A.current=K},[K,c,O.length,Ce,Y]),l.useEffect(()=>{k&&(ye(),z.current||Ce("auto"))},[ye,Ce,k]),l.useEffect(()=>{const ce=I.current;ce&&!b&&ae(),U.current=b,I.current=b;const H=c?Ln.get(c):null;if(Af(ce,b,H,K)){if(!H)return;P.current=Kn(H),E.current=!1,z.current||requestAnimationFrame(()=>{const pe=y.current;pe&&(qa(pe,H),Y())});return}},[b,c,K,ye,ae,Ce,Y]),l.useEffect(()=>()=>{const ce=J.current;ce&&Ln.set(ce.contextKey,ce.snapshot),R.current!=null&&cancelAnimationFrame(R.current),_.current!=null&&window.clearTimeout(_.current)},[]),l.useEffect(()=>{const ce=v.current,H=y.current;if(!ce||!H)return;const pe=()=>{_.current!=null&&window.clearTimeout(_.current),_.current=window.setTimeout(()=>{E.current=!1,_.current=null},Il)},le=new ResizeObserver(()=>{Y();const B=E.current;Df({hasSelection:z.current,userScrolledUp:P.current,contextAutoScrollActive:B})&&(Ce("auto"),B&&pe())});return le.observe(ce),H!==ce&&le.observe(H),()=>{le.disconnect(),_.current!=null&&(window.clearTimeout(_.current),_.current=null)}},[Ce,c,Y]),l.useImperativeHandle(S,()=>({scrollToBottom:(ce="smooth")=>{X(ce)}}),[X]),l.useEffect(()=>{const ce=y.current;if(!ce)return;let H;const pe=()=>{ae(),clearTimeout(H),H=setTimeout(()=>{P.current=!re(),Y()},50)};return ce.addEventListener("scroll",pe,{passive:!0}),()=>{ce.removeEventListener("scroll",pe),clearTimeout(H)}},[ae,Y]),l.useEffect(()=>(document.addEventListener("selectionchange",ne),()=>document.removeEventListener("selectionchange",ne)),[ne]);const ke=l.useRef(0),me=l.useRef(!1);l.useEffect(()=>{const ce=y.current;if(!ce||!me.current||ke.current===0)return;const H=ce.scrollHeight-ke.current;H>0&&(ce.scrollTop=H),Y(),ae(),ke.current=0,me.current=!1},[O.length,ae,Y]),l.useEffect(()=>{if($.current||!c)return;const ce=Ln.get(c),H=y.current;if(!(!ce||!H)){if(!na(ce,K)){X("auto"),$.current=!0;return}qa(H,ce),P.current=Kn(ce),Y(),$.current=!0}},[c,K,O.length,X,Y]);const q=()=>{const ce=y.current;ce&&(ke.current=ce.scrollHeight),me.current=!0,f==null||f()},G=()=>{P.current=!0,de("smooth"),ae()},Z=()=>{ye(),X("smooth"),ae()},V=l.useMemo(()=>{const ce=O.map((B,be)=>({type:"message",data:B,index:be,ts:yf(B,be,u)}));if(!n||n.length===0)return ce;const H=[...n].sort((B,be)=>B.timestamp-be.timestamp).map((B,be)=>({type:"action",data:B,index:be,ts:B.timestamp})),pe=[];let le=0;for(const B of ce){for(;le<H.length&&B.ts>0&&H[le].ts<B.ts;)pe.push(H[le++]);pe.push(B)}for(;le<H.length;)pe.push(H[le++]);return pe},[O,n,u]),fe=h>0||!!w,Te=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:y,"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")}),fe&&!g&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:q,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:Te})}),V.length===0&&!fe&&(m||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:j("chatList.waitingForMessages")})),V.map(ce=>{if(ce.type==="action"){const je=ce.data;return s.jsx(fb,{log:je},`action-${ce.index}`)}const H=ce.data;ce.index;const pe=sa(H),le=H.receivedAt||u[pe],B=`${c}-${pe}`,be=F.has(B);return s.jsx(bb,{message:H,receivedAt:le,agentName:r,userName:a,isCliMode:o,isTextExpanded:be,onToggleTextExpanded:()=>D(je=>{const Se=new Set(je);return be?Se.delete(B):Se.add(B),Se})},`msg-${pe}`)}),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})]})}),(W.showTop||W.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":j("chatList.jumpToTop"),children:[W.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:G,"aria-label":j("chatList.jumpToOldestMessages"),title:j("chatList.jumpToTop"),children:j("chatList.top")}),W.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:Z,"aria-label":j("chatList.jumpToLatestMessages"),title:j("chatList.jumpToBottom"),children:j("chatList.latest")})]})]})}),xb=l.memo(gb,(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),vb="modulepreload",yb=function(e){return"/"+e},Hl={},wb=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=yb(u),u in Hl)return;Hl[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":vb,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 Fl=!1;const uu=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),w=l.useRef(!1),h=()=>{const x=c.current;if(x){m.current&&(x.clear(),m.current=!1);for(const k of d.current)x.write(k.data,k.onProcessed);d.current=[],f.current&&(x.fit(),f.current=!1),g.current&&(x.bumpResize(),g.current=!1),w.current&&(x.scrollToTop(),w.current=!1)}};return l.useImperativeHandle(i,()=>({write:(x,k)=>{c.current?c.current.write(x,k):d.current.push({data:x,onProcessed:k})},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,k)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(x,k)},fit:()=>{c.current?c.current.fit():f.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():g.current=!0},scrollToTop:()=>{c.current?c.current.scrollToTop():w.current=!0},getSelection:()=>{var x,k;return((k=(x=c.current)==null?void 0:x.getSelection)==null?void 0:k.call(x))||""},getVisibleText:()=>{var x,k;return((k=(x=c.current)==null?void 0:x.getVisibleText)==null?void 0:k.call(x))||""}}),[]),l.useEffect(()=>{u&&h()},[u]),l.useEffect(()=>{let x=!1;return wb(()=>import("./terminal-BZj_X5zy.js"),__vite__mapDeps([0,1,2])).then(k=>{Fl||(Fl=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),x||p(()=>k.GhosttyTerminalView)}).catch(k=>{console.error("[CliTerminal] failed to load terminal renderer",k)}),()=>{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"}})});uu.displayName="CliTerminal";function Bt(...e){return Ah(Mh(e))}const kb={lg:"rounded-lg",xl:"rounded-xl","2xl":"rounded-2xl"},Sb={none:"",sm:"p-3",md:"px-4 py-3.5",lg:"px-5 py-4"},Ss=l.forwardRef(function({radius:t="xl",padding:n="md",className:r,...a},o){return s.jsx("div",{ref:o,className:Bt("border border-border-subtle bg-bg-secondary",kb[t],Sb[n],r),...a})});function kr({label:e,value:t,sub:n,icon:r}){return s.jsxs(Ss,{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 Bl({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 Cb({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 w=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,w)),k=Math.max(8,Math.min(o.height-8,h));return s.jsxs("div",{style:{position:"absolute",left:x-8,top:k-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 jb({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:w,onZoomIn:h,transportType:x,screenshotUsage:k,lastActionStatus:b}){const{t:S}=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:S(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:S("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:S(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:S("remote.directP2PTitle"),children:S("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:S("remote.turnRelayTitle"),children:S("remote.relay")}),k&&k.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:k.budgetExhausted?"#ef4444":"#c4b5fd",background:k.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:S("remote.dailyTurnTitle"),children:k.budgetExhausted?S("remote.turnBlocked"):S("remote.turnUsage",{used:k.dailyUsedMinutes,budget:k.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:S("remote.settings")}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:[S("remote.zoom")," ",d<=(m?f:1)+.01?S(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(),w()},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:S(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 Nb({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 Ab(){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 Ol(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 hr(e,t){const n=l.useRef(null),r=l.useRef(0);l.useEffect(()=>{if(!Ab())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,Ol(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,Ol(t[i])]))}),n.current=t})}function Mb({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:w,spawnRippleFromNormalized:h,clampPan:x,isMobile:k,mobileFillZoom:b}){const[S,j]=l.useState(null),y=l.useRef(null),v=l.useRef(null),N=l.useRef(null),C=l.useRef(!1),A=l.useRef(null),M=l.useRef(0),T=l.useRef(null),R=l.useRef(1),E=l.useRef({x:0,y:0}),_=l.useRef(!1),z=l.useRef(r),F=l.useRef(g),D=30,W=550,L=18,P=60,$=400,I=12,U=()=>{if(y.current)return;const Y={nx:.5,ny:.5};y.current=Y,j(Y)};return l.useEffect(()=>{z.current=r,r==="mouse"&&U()},[r]),l.useEffect(()=>{F.current=g},[g]),l.useEffect(()=>{const Y=e.current;if(!Y)return;const X=ae=>{if(!n.current)return null;const Ce=n.current.getBoundingClientRect();return!Ce.width||!Ce.height?null:{nx:Math.max(0,Math.min(1,(ae.clientX-Ce.left)/Ce.width)),ny:Math.max(0,Math.min(1,(ae.clientY-Ce.top)/Ce.height))}},de=(ae,Ce)=>{if(!n.current)return{dnx:0,dny:0};const ye=n.current,ke=ye.getBoundingClientRect(),me=ye.naturalWidth||ke.width,q=ye.naturalHeight||ke.height,G=me/q,Z=ke.width/ke.height;let V,fe;return G>Z?(V=ke.width,fe=ke.width/G):(fe=ke.height,V=ke.height*G),{dnx:ae/V,dny:Ce/fe}},ne=(ae,Ce,ye)=>{if(ye<=1.05)return;const ke=-(ae-.5)*100,me=-(Ce-.5)*100,q=x(ke,me,ye);(Math.abs(q.x-c.current)>.1||Math.abs(q.y-u.current)>.1)&&(p(q.x),d(q.y),c.current=q.x,u.current=q.y)},O=ae=>{const Ce=t.current;if(Ce&&ae.target instanceof Node&&Ce.contains(ae.target))ae.preventDefault();else return;if(ae.touches.length===1){const ye=ae.touches[0];v.current={x:ye.clientX,y:ye.clientY,time:Date.now()},N.current={x:ye.clientX,y:ye.clientY},_.current||(C.current=!1),A.current=setTimeout(()=>{if(!C.current&&!_.current)if(C.current=!0,z.current==="mouse"){const ke=y.current||{nx:.5,ny:.5};w("Right Click"),h(ke.nx,ke.ny,"right"),F.current("input_click",{...ke,button:"right"}).catch(()=>{})}else{const ke=X(ye);ke&&(w("Right Click"),h(ke.nx,ke.ny,"right"),F.current("input_click",{...ke,button:"right"}).catch(()=>{}))}},500);return}if(ae.touches.length===2){A.current&&clearTimeout(A.current),C.current=!0,_.current=!0;const ye=ae.touches[1].clientX-ae.touches[0].clientX,ke=ae.touches[1].clientY-ae.touches[0].clientY;T.current=Math.sqrt(ye*ye+ke*ke),R.current=i.current,E.current={x:(ae.touches[0].clientX+ae.touches[1].clientX)/2,y:(ae.touches[0].clientY+ae.touches[1].clientY)/2}}},ie=ae=>{const Ce=t.current;if(Ce&&ae.target instanceof Node&&Ce.contains(ae.target)&&ae.preventDefault(),ae.touches.length===1&&N.current){const ye=ae.touches[0],ke=ye.clientX-N.current.x,me=ye.clientY-N.current.y;if(!C.current&&v.current){const q=ye.clientX-v.current.x,G=ye.clientY-v.current.y;Math.sqrt(q*q+G*G)>8&&(C.current=!0,A.current&&clearTimeout(A.current))}if(C.current)if(z.current==="mouse"){const q=de(ke,me),G=y.current||{nx:.5,ny:.5},Z=Math.max(0,Math.min(1,G.nx+q.dnx)),V=Math.max(0,Math.min(1,G.ny+q.dny));y.current={nx:Z,ny:V},j({nx:Z,ny:V}),w(`Cursor: ${Math.round(Z*100)}%, ${Math.round(V*100)}%`),ne(Z,V,i.current);const fe=Date.now();fe-f.current>=30&&(f.current=fe,F.current("input_mouseMoved",{nx:Z,ny:V}).catch(()=>{}))}else if(i.current>1){const q=t.current;if(q){const G=q.clientWidth,Z=q.clientHeight,V=c.current+ke/G*100,fe=u.current+me/Z*100,Te=x(V,fe,i.current);p(Te.x),d(Te.y),c.current=Te.x,u.current=Te.y}}else{const q=X(ye);if(q){const G=Date.now();G-f.current>=40&&(f.current=G,w("Scroll"),F.current("input_wheel",{nx:q.nx,ny:q.ny,deltaX:Math.round(-ke*2.5),deltaY:Math.round(-me*2.5)}).catch(()=>{}))}}N.current={x:ye.clientX,y:ye.clientY};return}if(ae.touches.length===2&&T.current!==null){const ye=ae.touches[1].clientX-ae.touches[0].clientX,ke=ae.touches[1].clientY-ae.touches[0].clientY,q=Math.sqrt(ye*ye+ke*ke)/T.current,G=(ae.touches[0].clientX+ae.touches[1].clientX)/2,Z=(ae.touches[0].clientY+ae.touches[1].clientY)/2,V=G-E.current.x,fe=Z-E.current.y,Te=Math.abs(q-1)>.03;if(z.current==="mouse"){if(Te){const ce=Math.max(o,Math.min(5,R.current*q));m(ce),i.current=ce}else if(Math.abs(V)>2||Math.abs(fe)>2){const ce=y.current||{nx:.5,ny:.5},H=Date.now();H-f.current>=30&&(f.current=H,w("Scroll"),F.current("input_wheel",{nx:ce.nx,ny:ce.ny,deltaX:Math.round(-V*3),deltaY:Math.round(-fe*3)}).catch(()=>{}))}}else{const ce=Math.max(o,Math.min(5,R.current*q));m(ce),i.current=ce;const H=t.current;if(H&&ce>1){const pe=H.clientWidth,le=H.clientHeight,B=c.current+V/pe*100,be=u.current+fe/le*100,je=x(B,be,ce);p(je.x),d(je.y),c.current=je.x,u.current=je.y}}E.current={x:G,y:Z}}},K=ae=>{var Ce;if(A.current&&clearTimeout(A.current),T.current=null,ae.touches.length===1&&_.current){const ye=ae.touches[0];v.current={x:ye.clientX,y:ye.clientY,time:Date.now()},N.current={x:ye.clientX,y:ye.clientY},C.current=!0;return}if(ae.touches.length===0){if(_.current){_.current=!1,C.current=!1;return}if(ae.changedTouches.length===1){const ye=ae.changedTouches[0],ke=Date.now(),me=ke-(((Ce=v.current)==null?void 0:Ce.time)||0),q=v.current?ye.clientX-v.current.x:0,G=v.current?ye.clientY-v.current.y:0,Z=Math.sqrt(q*q+G*G);if(z.current==="mouse"){if(me<D||me>W||Z>L){C.current=!1;return}const V=y.current||X(ye);V&&(w(`Click: ${Math.round(V.nx*100)}%, ${Math.round(V.ny*100)}%`),h(V.nx,V.ny,"left"),F.current("input_click",{...V}).catch(()=>{}))}else{if(C.current){C.current=!1;return}if(me<P||me>$||Z>I){C.current=!1;return}const V=X(ye);if(!V)return;ke-M.current<300?(w("Double tap"),h(V.nx,V.ny,"double"),F.current("input_click",{...V,clickCount:2}).catch(()=>{}),M.current=0):(w(`Tap: ${Math.round(V.nx*100)}%, ${Math.round(V.ny*100)}%`),h(V.nx,V.ny,"left"),F.current("input_click",{...V}).catch(()=>{}),M.current=ke)}}C.current=!1}};return Y.addEventListener("touchstart",O,{passive:!1}),Y.addEventListener("touchmove",ie,{passive:!1}),Y.addEventListener("touchend",K,{passive:!1}),()=>{Y.removeEventListener("touchstart",O),Y.removeEventListener("touchmove",ie),Y.removeEventListener("touchend",K),A.current&&clearTimeout(A.current)}},[e,t,n,o,i,c,u,p,d,m,f,w,h,x]),{cursorPos:S,cursorPosRef:y,handleToggleInputMode:()=>{a(Y=>{const X=Y==="touch"?"mouse":"touch";return X==="mouse"&&U(),X})},handleZoomReset:()=>{const Y=k?b:1;m(Y),i.current=Y,p(0),d(0),c.current=0,u.current=0}}}function pu({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),[w,h]=l.useState([]),x=l.useRef(0),[k,b]=l.useState(!1),[S,j]=l.useState(!1),y=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[v,N]=l.useState(y?"mouse":"touch"),[C,A]=l.useState(1),M=l.useRef(!1),[T,R]=l.useState(1),[E,_]=l.useState(0),[z,F]=l.useState(0);hr("RemoteView",{connState:n,hasScreenshot:!!r,inputMode:v,zoom:T,panX:E,panY:z,isMenuOpen:k,isImeOpen:S});const D=l.useRef(0),W=l.useRef(T),L=l.useRef(E),P=l.useRef(z);l.useEffect(()=>{W.current=T},[T]),l.useEffect(()=>{L.current=E},[E]),l.useEffect(()=>{P.current=z},[z]),l.useEffect(()=>{var me;(me=i.current)==null||me.focus()},[]);const $=n==="connected",I=r,U=$?"Connected. Waiting for first frame...":n==="connecting"?"Connecting to Host...":"Reconnecting to Host...",J=$?"The remote stream is warming up":"Waiting for the remote stream to catch up";l.useEffect(()=>{if(!y||M.current||!I)return;const me=u.current,q=c.current;if(!me||!q)return;const G=()=>{const Z=q.clientWidth,V=q.clientHeight,fe=me.naturalWidth,Te=me.naturalHeight;if(!fe||!Te||!Z||!V)return;const ce=Math.min(Z/fe,V/Te),pe=Math.max(Z/fe,V/Te)/ce;pe>1.01&&(A(pe),R(pe),W.current=pe),M.current=!0};me.complete&&me.naturalWidth?G():me.addEventListener("load",G,{once:!0})},[I,y]);const re=.5;l.useEffect(()=>{T<=re&&(_(0),F(0))},[T,re]);const Y=(me,q,G)=>{if(G<=re)return{x:0,y:0};const Z=(G-1)/(2*G)*100,V=(G-1)/(2*G)*100;return{x:Math.max(-Z,Math.min(Z,me)),y:Math.max(-V,Math.min(V,q))}},X=(me,q)=>{if(!u.current)return null;const G=u.current.getBoundingClientRect();return!G.width||!G.height?null:{nx:Math.max(0,Math.min(1,(me-G.left)/G.width)),ny:Math.max(0,Math.min(1,(q-G.top)/G.height))}},de=(me,q,G)=>{const Z=c.current;if(!Z)return;const V=Z.getBoundingClientRect(),fe=++x.current;h(Te=>[...Te,{id:fe,x:me-V.left,y:q-V.top,type:G}]),setTimeout(()=>h(Te=>Te.filter(ce=>ce.id!==fe)),600)},ne=(me,q,G)=>{const Z=u.current,V=c.current;if(!Z||!V)return;const fe=Z.getBoundingClientRect(),Te=V.getBoundingClientRect(),ce=Z.naturalWidth||fe.width,H=Z.naturalHeight||fe.height,pe=ce/H,le=fe.width/fe.height;let B,be,je,Se;pe>le?(B=fe.width,be=fe.width/pe,je=0,Se=(fe.height-be)/2):(be=fe.height,B=fe.height*pe,je=(fe.width-B)/2,Se=0);const He=fe.left-Te.left+je+B*me,Xe=fe.top-Te.top+Se+be*q,dt=++x.current;h(it=>[...it,{id:dt,x:He,y:Xe,type:G}]),setTimeout(()=>h(it=>it.filter(he=>he.id!==dt)),600)},O=async me=>{var G;const q=X(me.clientX,me.clientY);if(q){d(`Click: ${Math.round(q.nx*100)}%, ${Math.round(q.ny*100)}%`),de(me.clientX,me.clientY,"left"),(G=i.current)==null||G.focus();try{const Z=await e("input_click",{nx:q.nx,ny:q.ny});Z!=null&&Z.success||t(`❌ Click failed: ${Z==null?void 0:Z.error}`)}catch(Z){t(`❌ Click error: ${Z.message||Z}`)}}},ie=async(me,q,G,Z=0)=>{try{await e("input_key",{type:G?"char":"keyDown",key:me,code:q,text:G?me:void 0,unmodifiedText:G?me:void 0,modifiers:Z})}catch(V){t(`❌ Key error: ${V.message||V}`)}},K=async me=>{if(me.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(me.key)&&me.preventDefault();let G=0;me.altKey&&(G|=1),me.ctrlKey&&(G|=2),me.metaKey&&(G|=4),me.shiftKey&&(G|=8),d(`Key: ${me.key}`),await ie(me.key,me.code,me.key.length===1,G)},ae=async me=>{if(me.key==="Enter"){if(me.nativeEvent.isComposing)return;if(m){const q=m;f(""),d(`IME Sent: ${q}`);try{const G=await e("input_type",{text:q});G!=null&&G.success||t(`❌ IME error: ${G==null?void 0:G.error}`)}catch(G){t(`❌ IME error: ${G.message}`)}}else d("Key: Enter"),await ie("Enter","Enter",!1)}};l.useEffect(()=>{const me=i.current;if(!me)return;const q=G=>{var Z;if((Z=u.current)!=null&&Z.contains(G.target)){G.preventDefault();const V=Date.now();if(V-D.current<40)return;D.current=V;const fe=X(G.clientX,G.clientY);if(!fe)return;d(`Scroll: ${Math.round(G.deltaY)}`),e("input_wheel",{nx:fe.nx,ny:fe.ny,deltaX:Math.round(G.deltaX),deltaY:Math.round(G.deltaY)}).catch(()=>{})}};return me.addEventListener("wheel",q,{passive:!1}),()=>me.removeEventListener("wheel",q)},[e]);const{cursorPos:Ce,handleToggleInputMode:ye,handleZoomReset:ke}=Mb({containerRef:i,viewportRef:c,imgRef:u,inputMode:v,setInputMode:N,minZoom:re,zoomRef:W,panXRef:L,panYRef:P,setPanX:_,setPanY:F,setZoom:R,lastWheelTimeRef:D,onAction:e,setLastActionStatus:d,spawnRippleFromNormalized:ne,clampPan:Y,isMobile:y,mobileFillZoom:C});return s.jsxs("div",{ref:i,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:K,onContextMenu:me=>me.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:[I?s.jsx("img",{ref:u,src:I,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${T}) translate(${E}%, ${z}%)`,transformOrigin:"center center",cursor:v==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:O,onContextMenu:me=>me.preventDefault(),onDragStart:me=>me.preventDefault()}):s.jsx(Nb,{waitingLabel:U,waitingHint:J,transportType:o}),v==="mouse"&&I&&s.jsx(Cb,{cursorPos:Ce,viewportRef:c,imgRef:u}),w.map(me=>{const G={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[me.type];return s.jsxs("div",{style:{position:"absolute",left:me.x,top:me.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${G}, 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(${G}, 0.9)`,boxShadow:`0 0 12px rgba(${G}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},me.id)})]}),s.jsx(jb,{inputMode:v,onToggleInputMode:ye,isImeOpen:S,setIsImeOpen:j,isMenuOpen:k,setIsMenuOpen:b,imeText:m,setImeText:f,handleImeSubmit:ae,isConnActive:$,zoom:T,isMobile:y,mobileFillZoom:C,onZoomOut:()=>R(me=>Math.max(.5,me-.25)),onZoomReset:ke,onZoomIn:()=>R(me=>Math.min(5,me+.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
  `),fe=((Te=V[0])==null?void 0:Te.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:()=>K(q),children:[s.jsx("span",{className:"text-[10px] text-text-muted w-3",children:Z?"▾":"▸"}),s.jsx("span",{className:"font-mono text-accent-primary w-20 shrink-0 text-[11px]",children:q}),!Z&&s.jsx("span",{className:"text-text-secondary truncate font-mono text-[11px]",children:fe}),s.jsxs("span",{className:"ml-auto text-text-muted text-[10px] shrink-0",children:[V.length,"L"]})]}),Z&&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:G||"(empty)"})]},q)})})]}),s.jsx(Mr,{}),O.stateHistory&&O.stateHistory.length>0&&s.jsxs("div",{children:[s.jsxs(Ar,{children:["State History (",O.stateHistory.length,")"]}),s.jsx("div",{className:"space-y-px",children:[...O.stateHistory].reverse().slice(0,20).map((q,G)=>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 ${ro(q.stateId)}`,children:q.stateId}),s.jsx("span",{className:"text-text-secondary text-[11px] shrink-0 tabular-nums",children:Hn(q.at)}),q.durationMs>0&&s.jsxs("span",{className:"text-text-muted text-[11px]",children:["held ",s.jsx("span",{className:"text-text-secondary",children:kc(q.durationMs)})]}),q.reason&&s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-mono shrink-0 ${_k[String(q.reason)]??"text-text-secondary bg-bg-glass border border-border-default"}`,children:String(q.reason)}),q.debounceKind&&String(q.debounceKind)!=="none"&&s.jsxs("span",{className:"text-text-muted text-[10px] font-mono",children:["debounce:",String(q.debounceKind)]}),q.matchedStateId&&String(q.matchedStateId)!==q.stateId&&s.jsxs("span",{className:"text-text-muted text-[10px] font-mono",children:["eval→",s.jsx("span",{className:"text-text-secondary",children:String(q.matchedStateId)})]})]}),q.matchedRules&&q.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:[q.matchedRules.slice(0,3).map((Z,V)=>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 Z=="string"?Z:JSON.stringify(Z)},V)),q.matchedRules.length>3&&s.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",q.matchedRules.length-3," more"]})]})]},G))})]}),s.jsx(Mr,{}),(()=>{const q=O.messages??O.committedMessages??[];if(q.length===0)return null;const G=q.filter(fe=>fe.role==="user").length,Z=q.filter(fe=>fe.role==="assistant").length,V=[...q].reverse().find(fe=>fe.role==="assistant");return s.jsxs("div",{children:[s.jsxs(Ar,{children:["Transcript (",q.length," — ",G,"u / ",Z,"a)"]}),V&&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 ",V.receivedAt?Hn(V.receivedAt):""]}),s.jsxs("div",{className:"text-text-secondary font-mono whitespace-pre-wrap line-clamp-4 break-all",children:[V.content.slice(0,400),V.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(q=>!q),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 Bk({activeConv:e,clearToken:t=0,terminalRef:n,handleSendChat:r,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:i=!0,isInputActive:c=!0}){var et;const{t:u}=Ne("common");gs();const{sendPtyInput:p}=vt(),[d,m]=l.useState(!1),f=l.useRef(!1);f.current=d;const[g,w]=l.useState("Runtime terminal unavailable"),[h,x]=l.useState(!1),[k,b]=l.useState(null),[S,j]=l.useState(!1),[y,v]=l.useState(!1),[N,C]=l.useState(1),[A,M]=l.useState(!1),[T,R]=l.useState(!1),[E,_]=l.useState(!1),[z,F]=l.useState(!1),[D,W]=l.useState(!1),[L,P]=l.useState({width:0,height:0}),[$,I]=l.useState({width:0,height:0}),[U,J]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[re,Y]=l.useState(null),X=l.useRef(null),de=l.useRef(null),ne=l.useRef(!1),O=l.useRef(!1),ie=l.useRef(i),K=l.useRef(0),ae=l.useRef(!1),Ce=l.useRef(""),ye=l.useRef(null),ke=l.useRef(!1),me=l.useRef(!1),q=l.useRef(null),G=l.useRef(null),Z=l.useRef(null),V=32*1024,fe=()=>{var te,ge,we,ze;return((ge=(te=X.current)==null?void 0:te.ownerDocument)==null?void 0:ge.defaultView)||((ze=(we=de.current)==null?void 0:we.ownerDocument)==null?void 0:ze.defaultView)||window},Te=te=>{const ge=fe();return{ownerWindow:ge,frameId:ge.requestAnimationFrame(te)}},ce=()=>{const te=q.current;if(te){try{te.ownerWindow.cancelAnimationFrame(te.frameId)}catch{}q.current=null}},H=()=>{const te=G.current;if(te){try{te.ownerWindow.clearTimeout(te.timeoutId)}catch{}G.current=null}},pe=()=>{const te=Z.current;if(te){try{te.ownerWindow.clearTimeout(te.timeoutId)}catch{}Z.current=null}},le=()=>{i&&q.current===null&&(q.current=Te(()=>{Q()}))},B=e.tabKey,be=e.sessionId||"",je=e.daemonId||((et=e.routeId)==null?void 0:et.split(":")[0])||e.routeId||"",Se=Gi(e),He=d?o||Se:g,Xe=yk,dt=wk,it=.05,he=()=>{const te=$.width,ge=$.height;if(!Number.isFinite(L.width)||L.width<=0||!Number.isFinite(L.height)||L.height<=0||!Number.isFinite(te)||te<=0||!Number.isFinite(ge)||ge<=0)return 1;const we=L.width/te,ze=L.height/ge;return Number(Math.min(dt,Math.max(Xe,Math.min(we,ze))).toFixed(2))},$e=he(),Be=ne.current&&N>$e,Pe=Number.isFinite($.width)&&$.width>0?Math.max(L.width,Math.round($.width*N)):L.width,ve=Number.isFinite($.height)&&$.height>0?Math.max(L.height,Math.round($.height*N)):L.height,Ue=()=>{Te(()=>{const te=de.current;te&&(te.scrollLeft=0,te.scrollTop=te.scrollHeight-te.clientHeight)})},ut=()=>{var te,ge;K.current=0,ae.current=!1,Ce.current="",ye.current=null,ke.current=!1,me.current=!1,ne.current||(O.current=!1,C(1)),q.current!==null&&ce(),m(!1),w("Runtime terminal unavailable"),pe(),H(),b(null),Y(null),M(!1),x(!1),j(!1),v(!1),(ge=(te=n.current)==null?void 0:te.reset)==null||ge.call(te)},ot=()=>{var te,ge;K.current=0,ae.current=!1,Ce.current="",ye.current=null,ke.current=!1,me.current=!1,q.current!==null&&ce(),m(!0),w(""),pe(),H(),b(null),Y(null),M(!1),x(!1),j(!1),v(!1),(ge=(te=n.current)==null?void 0:te.reset)==null||ge.call(te)},pt=()=>{me.current&&(me.current=!1,Te(()=>{var te,ge;(ge=(te=n.current)==null?void 0:te.scrollToTop)==null||ge.call(te)}))},Q=()=>{if(q.current=null,!i)return;const te=Ce.current;if(!te)return;const ge=te.slice(0,V);Ce.current=te.slice(ge.length);const we=n.current;if(!we){Ce.current=ge+Ce.current,le();return}we.write(ge,()=>{if(Ce.current.length>0){le();return}pt()})},ee=te=>{te&&(Ce.current+=te,le())},oe=(te,ge=0,we,ze,We={})=>{var Ke,Ye,Mt,Wt;const tt=!!We.force;!tt&&ge>0&&K.current>=ge||!tt&&ge===0&&ae.current||(K.current=ge,ge>0&&j(!0),m(!0),w(""),typeof we=="number"&&typeof ze=="number"&&we>0&&ze>0&&((Ye=(Ke=n.current)==null?void 0:Ke.resize)==null||Ye.call(Ke,we,ze)),Ce.current="",(Wt=(Mt=n.current)==null?void 0:Mt.reset)==null||Wt.call(Mt),te?ee(te):pt())};l.useEffect(()=>{ut()},[be]),l.useEffect(()=>{var ge;if(!be)return;const te=((ge=kt.onRuntimeEvent)==null?void 0:ge.call(kt,be,we=>{if(!(!we||we.sessionId!==be)){if(we.type==="runtime_snapshot"){if(!i){ye.current={text:we.text||"",seq:we.seq||0,cols:we.cols,rows:we.rows,force:!!we.force};return}oe(we.text||"",we.seq||0,we.cols,we.rows,{force:!!we.force});return}if(we.type==="session_output"){ae.current=!0,typeof we.seq=="number"&&(K.current=Math.max(K.current,we.seq),we.seq>0&&j(!0)),f.current||m(!0),f.current||w(""),typeof we.data=="string"&&ee(we.data);return}if(we.type==="session_cleared"){if(!i){ke.current=!0,Ce.current="",ye.current=null;return}ot();return}if(we.type==="session_io_error"){const ze=typeof we.error=="string"&&we.error?we.error:typeof we.reason=="string"&&we.reason?we.reason:"unknown error";m(!1),w(`Runtime input failed: ${ze}`);return}}},je))||(()=>{});return()=>{te()}},[je,be,n,i]);const ue=async(te={})=>{var ge;if(!je||!be)return{success:!1,error:"daemonId and sessionId are required"};te.preserveStatus||w(te.loadingMessage||"Loading runtime terminal...");try{const we=await((ge=kt.requestRuntimeSnapshot)==null?void 0:ge.call(kt,je,be,{sinceSeq:te.sinceSeq,force:te.force}));return we&&we.success===!1?(te.preserveStatus||(m(!1),w(`Runtime terminal unavailable: ${we.error}`)),we):we||{success:!0}}catch(we){const ze=(we==null?void 0:we.message)||String(we);return te.preserveStatus||(m(!1),w(`Runtime terminal unavailable: ${ze}`)),{success:!1,error:ze}}},xe=async te=>{var tt,Ke;const ge=((tt=X.current)==null?void 0:tt.ownerDocument)||document,we=ge.defaultView||window,ze=(Ke=we.navigator)==null?void 0:Ke.clipboard;if(ze!=null&&ze.writeText&&we.isSecureContext)try{return await ze.writeText(te),!0}catch{}let We=null;try{return We=ge.createElement("textarea"),We.value=te,We.setAttribute("readonly","true"),We.style.position="fixed",We.style.left="-9999px",We.style.top="0",ge.body.appendChild(We),We.focus(),We.select(),ge.execCommand("copy")}catch{return!1}finally{We==null||We.remove()}},Me=te=>{H(),Y(te);const ge=fe();G.current={ownerWindow:ge,timeoutId:ge.setTimeout(()=>{G.current=null,Y(we=>we===te?null:we)},2200)}},Le=te=>{pe(),b(te);const ge=fe();Z.current={ownerWindow:ge,timeoutId:ge.setTimeout(()=>{Z.current=null,b(we=>we===te?null:we)},2200)}},Ae=async()=>{var We,tt,Ke,Ye;const te=((tt=(We=n.current)==null?void 0:We.getSelection)==null?void 0:tt.call(We))||"",ge=((Ye=(Ke=n.current)==null?void 0:Ke.getVisibleText)==null?void 0:Ye.call(Ke))||"",we=te.trimEnd()||ge.trimEnd();if(!we){Me("Nothing to copy");return}if(!await xe(we)){Me("Copy failed");return}Me(te.trimEnd()?"Copied selection":"Copied visible terminal")},Oe=te=>{if(!d||!i)return;((p==null?void 0:p(je,be,te))??!1)||Me("Terminal input failed")},qe=te=>{Oe(Sk({ctrl:T,alt:E,shift:z},te)),R(!1),_(!1),F(!1)},Ze=async()=>{if(h)return;x(!0),b("Loading older terminal output..."),me.current=!0;const te=await ue({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:d});if(x(!1),(te==null?void 0:te.success)===!1){me.current=!1,b(`Older terminal output unavailable: ${te.error}`);return}v(!0),Le("Older terminal output loaded"),Te(()=>{var ge;(ge=n.current)==null||ge.bumpResize()})};l.useEffect(()=>{var ge,we;if(!be)return;je&&((ge=kt.getState)==null?void 0:ge.call(kt,je))==="connected"&&ue();const te=(we=kt.onStateChange)==null?void 0:we.call(kt,(ze,We)=>{ze!==je||We!=="connected"||ue()});return()=>{te==null||te()}},[je,be,n]),l.useEffect(()=>{t&&ut()},[t,B,n]),l.useEffect(()=>{var ze,We;const te=X.current,ge=(We=(ze=te==null?void 0:te.ownerDocument)==null?void 0:ze.defaultView)==null?void 0:We.ResizeObserver;if(!te||!ge)return;const we=new ge(tt=>{const Ke=tt[0];if(!Ke)return;const{width:Ye,height:Mt}=Ke.contentRect;P(Wt=>{const ss=Math.round(Ye),Ie=Math.round(Mt);return Wt.width===ss&&Wt.height===Ie?Wt:{width:ss,height:Ie}})});return we.observe(te),()=>we.disconnect()},[]),l.useEffect(()=>{if(ne.current)return;const te=he();!Number.isFinite(te)||te<=0||C(ge=>O.current?te<ge-it?te:ge:(O.current=!0,te))},[$.height,$.width,L.height,L.width]),l.useEffect(()=>{Be&&Ue()},[Be,ve,Pe]),l.useEffect(()=>{var we;const te=ie.current;if(ie.current=i,!i)return;te||v(!1),ke.current&&(ke.current=!1,ot());const ge=ye.current;ge&&(ye.current=null,oe(ge.text,ge.seq,ge.cols,ge.rows,{force:!!ge.force})),je&&be&&((we=kt.getState)==null?void 0:we.call(kt,je))==="connected"&&ue(),Ce.current&&q.current===null&&le(),Te(()=>{var ze;(ze=n.current)==null||ze.bumpResize()})},[je,i,be]),l.useEffect(()=>()=>{q.current!==null&&ce(),H(),pe()},[]),l.useEffect(()=>{const te=ze=>{var tt;const We=ze.detail;We!=null&&We.sessionId&&We.sessionId!==be||d&&((tt=n.current)==null||tt.bumpResize())},ge=fe(),we=ge===window?[window]:[window,ge];for(const ze of we)ze.addEventListener("adhdev:fit-cli-terminal",te);return()=>{for(const ze of we)ze.removeEventListener("adhdev:fit-cli-terminal",te)}},[d,be,n]);const Ge=d&&S&&!y&&(U.atTop||!U.canScroll)||h||!!k;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:X,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[Ge&&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:()=>{Ze()},disabled:!be||h,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:u(h?"terminal.loadingOlder":"terminal.loadOlderOutput")}),k&&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:k})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[re&&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:re}),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:()=>W(te=>!te),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:()=>{Ae()},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:()=>M(te=>!te),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:()=>M(!1),"aria-label":u("terminal.closeControlKeys"),children:"×"})]}),s.jsx("div",{className:"mb-2 grid grid-cols-3 gap-1.5",children:[["Ctrl",T,R],["Alt",E,_],["Shift",z,F]].map(([te,ge,we])=>s.jsx("button",{type:"button","aria-pressed":ge,className:`h-9 rounded-lg border text-[12px] font-semibold transition-colors ${ge?"border-sky-400/50 bg-sky-400/25 text-white":"border-white/10 bg-white/[0.06] hover:bg-white/[0.12]"}`,onClick:()=>we(ze=>!ze),children:te},te))}),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:()=>Oe(""),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:()=>{ne.current=!0,C(te=>{const ge=Math.max($e,Number((te-.1).toFixed(2)));return ge>$e&&Ue(),ge})},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:()=>{ne.current=!0,C(te=>{const ge=Math.min(dt,Number((te+.1).toFixed(2)));return ge>$e&&Ue(),ge})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:de,className:Be?"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:Pe>0?`${Pe}px`:"100%",height:ve>0?`${ve}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:$.width>0?`${$.width}px`:"100%",height:$.height>0?`${$.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:N},children:s.jsx(uu,{ref:n,readOnly:!d||!i,sizingMode:"measured",onViewportMetrics:I,onScrollMetrics:J,onInput:te=>{!d||(p==null||p(je,be,te))}})})})}),!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(Iu,{contextKey:e.tabKey,panelLabel:xt(e),isSending:a,isBusy:!!Se,statusMessage:He,inlineStatusMessage:He,onSend:async te=>Se?!1:r(te),isActive:c&&i,showControlsToggle:!1,animateVisibility:!1}),D&&s.jsx(Fk,{activeConv:e,onClose:()=>W(!1)})]})}const Ok=5e3,Wk=12e3;function Uk(e){return e==="disconnected"||e==="reconnecting"}function Gk({wsStatus:e,showReconnected:t,loginUrl:n,onReconnect:r,reconnectDelayMs:a=Ok,reconnectActionDelayMs:o=Wk}){const{t:i}=Ne(),c=Uk(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",w=!!(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",k={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)"},S={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},j="fixed left-1/2 top-4 z-[var(--z-toast)] flex items-center justify-center pointer-events-none",y={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[g&&s.jsx("div",{className:j,style:y,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:k[x],border:b[x],color:S[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"))]}),w&&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:y,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 bp({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(Ii,{size:a}):s.jsx(Zs,{size:a})})}function qk(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 zk(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 Kk(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 da({git:e,className:t="",compact:n=!1}){const r=qk(e),a=zk(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 ${Kk(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 Vk({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 Sc({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function Cc({notification:e,shortcutIndex:t,onOpen:n,onMarkRead:r,onMarkUnread:a,onDelete:o}){const{t:i}=Ne(),c=ja(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 Yk({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:w,onInboxOpenChange:h,hiddenOpen:x,onHiddenOpenChange:k,onOpenNewSession:b,onOpenDashboardGuide:S,guideNudgeVisible:j=!1,actionShortcuts:y,notifications:v,notificationUnreadCount:N,onOpenNotification:C,onMarkNotificationRead:A,onMarkNotificationUnread:M,onDeleteNotification:T,onOpenGitDialog:R,onOpenMeshGraph:E}){var Z;const{t:_}=Ne(),{ides:z,p2pStates:F={}}=gs(),D=!!e&&ct(e)&&!lt(e),W=!!e&&lt(e),L=!!(e!=null&&e.daemonId)&&!!((Z=e==null?void 0:e.coordinator)!=null&&Z.meshId),P=c||(e?Fu(e)?"terminal":"chat":null),[$,I]=l.useState(!1),[U,J]=l.useState(!1),re=l.useRef(null),Y=l.useRef(null),X=l.useRef(null),de=z.filter(V=>V.type==="adhdev-daemon"),ne=Vk({wsStatus:t,isConnected:n,daemonCount:de.length,p2pStates:F}),O=_(ne.titleKey),ie=ne.subtitleKey?_(ne.subtitleKey):null,K=ne.tone==="connected"?"#22c55e":ne.tone==="limited"?"#eab308":"#ef4444",ae=ne.tone==="connected"?"0 0 4px #22c55e80":ne.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",Ce=l.useMemo(()=>v.filter(V=>!V.readAt),[v]),ye=l.useMemo(()=>v.filter(V=>!!V.readAt),[v]),ke=l.useMemo(()=>Ce.slice(0,9),[Ce]),me=N;l.useEffect(()=>{if(!w)return;const V=fe=>{var Te;(Te=Y.current)!=null&&Te.contains(fe.target)||h(!1)};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[w,h]),l.useEffect(()=>{if(!x)return;const V=fe=>{var Te;(Te=X.current)!=null&&Te.contains(fe.target)||k(!1)};return document.addEventListener("mousedown",V),()=>document.removeEventListener("mousedown",V)},[x,k]),l.useEffect(()=>{if(!x&&!w)return;const V=fe=>{if(!fe.altKey)return;const Te=fe.code.match(/^Digit([1-9])$/);if(!Te)return;const ce=Number(Te[1])-1,H=x?d[ce]:void 0,pe=w?ke[ce]:void 0;if(!(!H&&!pe)){if(fe.preventDefault(),fe.stopPropagation(),H){m==null||m(H),k(!1);return}pe&&(C(pe),h(!1))}};return window.addEventListener("keydown",V,!0),()=>window.removeEventListener("keydown",V,!0)},[d,x,w,ke,k,h,C,m]),l.useEffect(()=>{const V=d.length;if(re.current===null){re.current=V;return}V>re.current&&J(!0),re.current=V},[d.length]);const q=()=>J(!1),G=V=>{if(!V)return;const fe=r.find(Te=>Te.tabKey===V);fe&&(p==null||p(fe))};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(Zs,{size:18}),s.jsx("span",{className:"header-title-desktop",children:_("dashboard.header.title")}),s.jsx("span",{className:"header-title-mobile",children:e?xt(e):_("dashboard.header.title")}),s.jsx("span",{title:O,"aria-label":O,className:"header-title-status-dot",style:{background:K,boxShadow:ae}}),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:K,boxShadow:ae}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[ie&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",ie]}),b&&s.jsx("button",{type:"button",onClick:b,className:"btn btn-secondary btn-sm ml-2",title:`${_("paneGroup.newSession")}${y!=null&&y.openNewSession?` (${y.openNewSession})`:""}`,"aria-label":_("paneGroup.newSession"),children:s.jsx(Di,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[S&&s.jsxs("button",{type:"button",onClick:S,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&&(D||W||!lt(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:yn(e)||xt(e),children:xt(e)}),R&&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:()=>R(e.daemonId,e.workspacePath),children:s.jsx(da,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(da,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),L&&E&&s.jsxs("button",{type:"button",onClick:()=>E(e),className:"btn btn-secondary btn-sm dashboard-header-mesh-button",title:_("dashboard.header.openMeshGraph"),children:[s.jsx(es,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:_("dashboard.header.meshGraph")})]}),(D||W)&&i&&s.jsxs(s.Fragment,{children:[D&&u&&P&&s.jsx(bp,{mode:P,onChange:u,compact:!0}),s.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:_(W?"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(At,{size:14})})]}),!lt(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:_("dashboard.header.chatHistory"),children:s.jsx(Ti,{size:14})}),!D&&!lt(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:_("dashboard.header.remoteControl"),children:s.jsx(us,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:Y,children:[s.jsxs("div",{className:`dashboard-header-hidden${$?" is-drop-target":""}${U?" hidden-spawn-flash":""}${(d??[]).some(V=>V.status==="generating")?" hidden-generating-spin":""}`,onAnimationEnd:q,ref:X,onDragEnter:V=>{V.dataTransfer.types.includes("text/tab-key")&&(V.preventDefault(),I(!0))},onDragOver:V=>{V.dataTransfer.types.includes("text/tab-key")&&(V.preventDefault(),V.dataTransfer.dropEffect="move",I(!0))},onDragLeave:V=>{V.currentTarget.contains(V.relatedTarget)||I(!1)},onDrop:V=>{const fe=V.dataTransfer.getData("text/tab-key");V.preventDefault(),I(!1),G(fe)},children:[s.jsxs("button",{type:"button",onClick:()=>k(!x),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`${_("dashboard.hidden.title")}${y!=null&&y.toggleHiddenTabs?` (${y.toggleHiddenTabs})`:""}. ${_("dashboard.hidden.dragHint")}`,children:[s.jsx(Pi,{size:16}),d.length>0&&s.jsx("span",{className:`dashboard-header-hidden-badge${U?" 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(Sc,{value:y==null?void 0:y.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(),k(!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(Sc,{value:y==null?void 0:y.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:xt(e)})]}),d.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:d.map(V=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{m==null||m(V),k(!1)},children:[s.jsxs("span",{className:"dashboard-header-inbox-item-title",children:[V.status==="generating"&&s.jsx("span",{className:"tab-spinner dashboard-header-inbox-item-spinner","aria-label":_("dashboard.header.generating")}),xt(V)]}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[d.indexOf(V)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",d.indexOf(V)+1]}):null,yn(V)]})]},V.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:_("dashboard.hidden.empty")})]})]}),s.jsxs("button",{type:"button",onClick:()=>h(!w),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:_("dashboard.header.activityInbox"),children:[s.jsx(Nn,{size:16}),me>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:me})]}),w&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[Ce.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:_("dashboard.inbox.unread")}),Ce.map(V=>s.jsx(Cc,{notification:V,shortcutIndex:ke.indexOf(V)>=0?ke.indexOf(V)+1:void 0,onOpen:()=>C(V),onMarkRead:()=>A(V.id),onMarkUnread:()=>M(V.id),onDelete:()=>T(V.id)},V.id))]}),ye.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:_("dashboard.inbox.read")}),ye.map(V=>s.jsx(Cc,{notification:V,onOpen:()=>C(V),onMarkRead:()=>A(V.id),onMarkUnread:()=>M(V.id),onDelete:()=>T(V.id)},V.id))]}),v.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:_("dashboard.inbox.empty")})]})]})]})]})}function Ft(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function Jk(e,t){return String(e||"")!==String(t||"")}function Qk(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&&!ju(i.summaryMetadata).map(u=>u.toLowerCase()).join(`
58
- `).includes(a)))}function Xk(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 gp(e,t={}){return Xk(Qk(e,t),t.sortMode||"recent")}function ii(e,t){return typeof e=="function"?e(t??!1?"launch.resumeSavedHistory":"launch.startFresh"):e?"Resume saved history":"Start fresh"}function xp(e,t){return typeof e=="function"?e(t??!1?"launch.resumingSavedHistory":"launch.startingFresh"):e?"Resuming saved history…":"Starting fresh…"}function Zk(e){return e?e("launch.startFresh"):"Start fresh"}function eS(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 sS(e){return e?e("launch.savedHistoryTitle"):"Saved History"}function Vi(e){return e?e("launch.savedHistoryHelper"):"Use saved history when you want continuity in the same provider conversation."}function nS(e){return e?e("launch.savedHistoryEmpty"):"No saved history found yet."}function rS(e){return e?e("launch.refreshSavedHistory"):"Refresh saved history"}function aS(e){return e?e("launch.refreshingSavedHistory"):"Refreshing saved history…"}function ua(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 pa(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 ma(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartFresh":"launch.confirmRestart"):e==="start-fresh"?"Start fresh":"Restart"}function ha(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartingFresh":"launch.confirmRestarting"):e==="start-fresh"?"Starting fresh…":"Restarting…"}function vp(e,t){return typeof e=="function"?e("launch.resumeWith",{label:t}):`Resume saved history with ${e}?`}function yp(e){return e?e("launch.resumeReview"):"Review or change the target workspace before resuming saved history."}function oS(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:w}){var R;const{t:h}=Ne("common"),x=t.find(E=>E.id===e.routeId),k=(x==null?void 0:x.chats)||[],b=(R=x==null?void 0:x.activeChat)==null?void 0:R.id,S=ct(e)&&!lt(e),[j,y]=l.useState(()=>Ft()),v=c||j,N=String(u||"").trim(),C=E=>{if(p){p(E);return}y(E)},A=l.useMemo(()=>a.map(E=>{const _=String(E.workspace||"").trim();return E.canResume||_||!N?E:{...E,workspace:N,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[N,a]),M=l.useMemo(()=>gp(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]),T=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:S?sS(h):h("historyModal.chatHistory")}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Mk(e)}),S&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Vi(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(At,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!S&&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")}),S?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:E=>C({...v,textQuery:E.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:E=>C({...v,workspaceQuery:E.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:E=>C({...v,modelQuery:E.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:E=>C({...v,sortMode:E.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:E=>C({...v,resumableOnly:E.target.checked})}),h("historyModal.resumeReadyOnly")]})]}),M.map(E=>{const _=e.providerSessionId===E.providerSessionId,z=_||!E.canResume||!!i,F=E.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{z||!w||w(E)},disabled:z,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"} ${z?"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:E.title||h("historyModal.untitledSession")}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:E.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:oS(E.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:E.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:[E.workspace||h("historyModal.workspaceUnknown"),F?h("historyModal.selectedWorkspaceSuffix"):"",Js(E.summaryMetadata)?` · ${Js(E.summaryMetadata)}`:"",E.messageCount>0?` · ${h("historyModal.msgCount",{count:E.messageCount})}`:""]}),s.jsx("div",{className:"shrink-0",children:_?h("historyModal.statusActive"):E.canResume?F?h("historyModal.statusResumeSelectedWorkspace"):i===E.providerSessionId?h("historyModal.statusResuming"):h("historyModal.statusResume"):h("historyModal.statusMissingWorkspace")})]})]},E.id)})]}):k.map(E=>s.jsxs("div",{onClick:()=>{f(e.routeId,E.id),d()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${b===E.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===E.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:E.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:[E.id.substring(0,12),"..."]}),b===E.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:h("historyModal.statusActive")})]})]},E.id)),(S&&!o&&M.length===0||!S&&k.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(Uf,{size:32})}),s.jsx("div",{className:"text-[13px]",children:S?a.length>0?h("historyModal.noMatchingHistory"):nS(h):h("historyModal.noRecentChats")})]}),S&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:aS(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(Ca,{size:13})," ",S?rS(h):h("historyModal.refreshHistory")]})})})]})]});return typeof document>"u"?T:fn.createPortal(T,document.body)}const jc={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 kp({toasts:e,onDismiss:t,onClickToast:n}){const{t:r}=Ne();return s.jsx("div",{className:"fixed right-4 z-[var(--z-toast)] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(a=>{const o=jc[a.type]||jc.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(At,{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 iS=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function lS(e){const t=e.workspace||"";if(!t)return"";const n=t.split(/[/\\]/).filter(Boolean);return n.length>0?n[n.length-1]:t}function cS(e,t){return Sp(e)||t}function Sp(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 dS(e){return Sp(e)||void 0}function uS(e){return e.sessionId||e.instanceId||e.agentType}function Cp(e=[]){const t={};for(const n of e)n.type==="adhdev-daemon"&&(t[n.id]=ts(n,{fallbackId:n.id}));return t}function jp(e,t={}){var r;const n=e.daemonId||((r=e.id)==null?void 0:r.split(":")[0])||e.id;return{machineName:Iy(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[n]||t.defaultConnectionState||"new":t.defaultConnectionState}}function Yi(e,t={}){return pS(e,jp(e,t))}function pS(e,t={}){var f,g,w,h,x,k,b,S,j;const n=[],r=t.machineName,a=t.connectionState,o=lS(e),i=e.workspace||"",c=$y(e.type,{agentName:e.cliName}),u=ct(e)||lt(e)?c:$t(e.type),p=cS(e,u),d=Array.isArray(e.childSessions)?e.childSessions.map(y=>{var v,N,C;return{sessionId:y.id,instanceId:y.id,providerSessionId:y.providerSessionId,activeChatId:(v=y.activeChat)==null?void 0:v.id,transport:y.transport,sessionCapabilities:y.capabilities,agentType:y.providerType,agentName:y.providerName||$t(y.providerType),model:dS(y),status:y.status,title:y.title,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,messages:((N=y.activeChat)==null?void 0:N.messages)||[],activeModal:((C=y.activeChat)==null?void 0:C.activeModal)||void 0,unread:y.unread,lastSeenAt:y.lastSeenAt,lastUpdated:y.lastUpdated,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,surfaceHidden:y.surfaceHidden,muted:y.muted,git:y.git,settings:y.settings,coordinator:y.coordinator,messageInput:y.messageInput}}):[],m=iS(e);if(m){const y=e.sessionId||e.instanceId,v=(f=e.settings)==null?void 0:f.meshCoordinatorFor,N=((g=e.settings)==null?void 0:g.meshNodeFor)||!((w=e.settings)!=null&&w.meshCoordinatorFor)&&((h=e.settings)==null?void 0:h.launchedByCoordinator),C=v?" (Coordinator)":N?" (Mesh Node)":"",A=c+C,M=(x=e.activeChat)==null?void 0:x.activeModal,T=M&&Array.isArray(M.buttons)&&M.buttons.length>0,R=Hy(e.activeChat,[{status:e.status,activeModal:(k=e.activeChat)==null?void 0:k.activeModal}],e.agents||[]),E=e.activeChat||{title:"",messages:[]};let _=E.title&&String(E.title).trim()?String(E.title).trim():"";const z=(b=e.activeChat)==null?void 0:b.id,F=e.chats;if(z&&Array.isArray(F)&&F.length>0){const J=F.find(re=>re.id===z||re.id&&String(re.id)===String(z));J!=null&&J.title&&String(J.title).trim()&&(_=String(J.title).trim())}const D=(ct(e)||lt(e),e.type),W=(ct(e)||lt(e))&&Yl(_,A,D)?"":_,L=E.messages||[],P=typeof z=="string"?z.trim():"",$=(ct(e)||lt(e))&&P===String(e.type||"").trim(),I=P&&!$?P:e.providerSessionId,U=e.coordinator||(typeof((S=e.settings)==null?void 0:S.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:y,providerSessionId:e.providerSessionId,historySessionId:I,nativeSessionId:y,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:ct(e)&&e.mode||"chat",agentName:A,agentType:D,status:R,title:W,messages:L,resume:e.resume,hostIdeType:!ct(e)&&!lt(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||W||(ct(e)?e.mode==="chat"?A:`Terminal${C}`: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:T?M.buttons:void 0,modalMessage:T?M.message:void 0,streamSource:"native",tabKey:Ja(y,e.id),machineName:r,connectionState:a,settings:e.settings,coordinator:U,messageInput:e.messageInput})}if(m&&(ct(e)||lt(e)))return n;for(const y of d){const v=y.activeModal&&Array.isArray(y.activeModal.buttons)&&y.activeModal.buttons.length>0,N=Fy(y),C=uS(y),A=`${e.id}:${C}`,M=y.title&&String(y.title).trim()||"",T=Yl(M,y.agentName,y.agentType)?"":M,R=y.messages||[];if(!(y.transport==="cdp-webview"||!!y.sessionId||!!y.providerSessionId||R.length>0||v||!!T||!["idle","panel_hidden","disconnected","not_monitored"].includes(N)))continue;const _=y.coordinator||(typeof((j=y.settings)==null?void 0:j.meshCoordinatorFor)=="string"&&y.settings.meshCoordinatorFor?{meshId:y.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:y.sessionId||y.instanceId,providerSessionId:y.providerSessionId,historySessionId:y.activeChatId||y.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:y.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:y.sessionCapabilities,mode:"chat",agentName:y.agentName,agentType:y.agentType,status:N,title:T,messages:R,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:y.git||e.git,displayPrimary:o||T||y.agentName||u,displaySecondary:y.model&&y.model.trim()?y.model.trim():`${u} · ${y.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,lastUpdated:y.lastUpdated||e.lastUpdated,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,modalButtons:v?y.activeModal.buttons:void 0,modalMessage:v?y.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Ja(y.sessionId||y.instanceId,A),machineName:r,connectionState:a,settings:y.settings,coordinator:_,messageInput:y.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:Ja(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),n}function Np(e){return String(e.type||e.id||"").trim()}function fa(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function mS(e,t){const n=(t||"").trim();if(!n)return[];const r=(e||[]).find(a=>a.type===n);return fa(r==null?void 0:r.modelOptions)}function hS(e,t){const n=(t||"").trim();if(!n)return[];const r=(e||[]).find(a=>a.type===n);return fa(r==null?void 0:r.thinkingLevelOptions)}function Ap(e){const t=new Map;for(const n of e||[])n!=null&&n.type&&t.set(n.type,{models:fa(n.modelOptions),thinking:fa(n.thinkingLevelOptions)});return t}function fS(e){var t;return e.category!=="cli"||!Np(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 wn(e){var r;const t=new Set,n=[];for(const a of e||[]){if(!fS(a))continue;const o=Np(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 kn(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 cr(e){return e.map(t=>t.type)}function bS(e,t){const n=kn(e),r=t.trim();return!r||n.includes(r)?n:[...n,r]}function gS(e,t){return kn(e).filter(n=>n!==t)}function Nc(e,t,n){const r=kn(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 Ac({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 xS({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(()=>kn(e),[e]),d=p.filter(g=>!u.has(g)).length,m=t.filter(g=>!p.includes(g.type)),f=()=>{i&&(n(bS(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,w)=>{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:["#",w+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||w===0,title:"Move up",onClick:()=>n(Nc(p,g,"up")),children:s.jsx(Ac,{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||w===p.length-1,title:"Move down",onClick:()=>n(Nc(p,g,"down")),children:s.jsx(Ac,{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 vS(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 Mp(e,t){const n=vS(e);return{daemonId:n.daemonId,payload:{...t,...n.targetSessionId&&!t.targetSessionId?{targetSessionId:n.targetSessionId}:{}}}}const Tp=[{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:"🏄"}],Pp=[{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:"◆"}],Ip=[{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:"🟠"}],yS=Tp,wS=Pp,kS=Ip;function SS({icon:e,title:t,subtitle:n,badge:r,actions:a,className:o}){return s.jsxs("div",{className:Bt("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 gr({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(SS,{icon:e,title:t,subtitle:n,badge:r,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Bt("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const li="adhdev:themechange";function CS(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function ln(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function cn(e){return e==="system"?CS():e}function Dp(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Kr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(li,{detail:{preference:e,theme:t}}))}function jS(){const e=ln(),t=cn(e);Dp(t),Kr(e,t)}function Ls(){const[e,t]=l.useState(ln),[n,r]=l.useState(()=>cn(ln()));l.useEffect(()=>{Dp(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),Kr("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:ln()),r(m==="dark"||m==="light"?m:cn(ln()))},c=u=>{if(u.key!=="theme")return;const p=ln(),d=cn(p);t(p),r(d)};return window.addEventListener(li,i),window.addEventListener("storage",c),()=>{window.removeEventListener(li,i),window.removeEventListener("storage",c)}},[]);const a=l.useCallback(i=>{const c=cn(i);t(i),r(c);try{localStorage.setItem("theme",i)}catch{}Kr(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",u=cn(c);r(u);try{localStorage.setItem("theme",c)}catch{}return Kr(c,u),c})},[]);return{theme:n,preference:e,setPreference:a,cycleTheme:o,isDark:n==="dark"}}const Mc={dark:"Dark",light:"Light",system:"System"};function NS({collapsed:e}){const{preference:t,cycleTheme:n}=Ls(),r=t==="dark"?s.jsx(qf,{size:16}):t==="light"?s.jsx(Gf,{size:16}):s.jsx(zf,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:n,title:`Theme: ${Mc[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:r}),!e&&s.jsx("span",{className:"text-xs",children:Mc[t]})]})}const ci="adhdev:langchange";function AS(){const e=wt.language;return un(e)?e:vu()}function MS(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(ci,{detail:{language:e}}))}function TS(){const[e,t]=l.useState(AS);l.useEffect(()=>{const r=i=>{un(i)&&t(i)},a=i=>{const c=i.detail||{};un(c.language)&&t(c.language)},o=i=>{if(i.key!==Vo)return;const c=i.newValue;un(c)&&c!==wt.language&&(wt.changeLanguage(c),Yo(c))};return wt.on("languageChanged",r),window.addEventListener(ci,a),window.addEventListener("storage",o),()=>{wt.off("languageChanged",r),window.removeEventListener(ci,a),window.removeEventListener("storage",o)}},[]);const n=l.useCallback(r=>{if(un(r)){t(r);try{localStorage.setItem(Vo,r)}catch{}wt.changeLanguage(r),Yo(r),MS(r)}},[]);return{language:e,setLanguage:n}}function PS({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 IS({collapsed:e,variant:t="sidebar"}){const{language:n,setLanguage:r}=TS(),{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=Math.max(0,tn.findIndex(A=>A.code===n)),w=tn[g]??tn[0],h=a("language.label",{defaultValue:"Language"}),x=a("language.select",{defaultValue:"Select language"}),k=A=>`${f}-opt-${A}`,b=l.useCallback(()=>{u(g),i(!0)},[g]),S=l.useCallback((A=!0)=>{var M;i(!1),A&&((M=d.current)==null||M.focus())},[]),j=l.useCallback(A=>{const M=tn[A];M&&r(M.code),S()},[r,S]);l.useEffect(()=>{if(!o)return;const A=T=>{var R;(R=p.current)!=null&&R.contains(T.target)||i(!1)},M=T=>{var R;(R=p.current)!=null&&R.contains(T.target)||i(!1)};return document.addEventListener("pointerdown",A,!0),document.addEventListener("focusin",M,!0),()=>{document.removeEventListener("pointerdown",A,!0),document.removeEventListener("focusin",M,!0)}},[o]),l.useEffect(()=>{var A;o&&((A=m.current)==null||A.focus())},[o]);const y=A=>{const M=tn.length-1;switch(A.key){case"ArrowDown":A.preventDefault(),u(T=>T>=M?0:T+1);break;case"ArrowUp":A.preventDefault(),u(T=>T<=0?M:T-1);break;case"Home":A.preventDefault(),u(0);break;case"End":A.preventDefault(),u(M);break;case"Enter":case" ":A.preventDefault(),j(c);break;case"Escape":A.preventDefault(),S();break;case"Tab":i(!1);break}},v=A=>{o||(A.key==="ArrowDown"||A.key==="ArrowUp"||A.key==="Enter"||A.key===" ")&&(A.preventDefault(),b())},N=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":""}`,C=t==="landing"||!e;return s.jsxs("div",{ref:p,className:"lang-switch",children:[s.jsxs("button",{ref:d,type:"button",className:N,"aria-haspopup":"listbox","aria-expanded":o,"aria-label":`${h}: ${w.label}`,title:`${h}: ${w.label}`,onClick:()=>o?S(!1):b(),onKeyDown:v,children:[s.jsx("span",{className:"nav-icon lang-switch-icon",children:s.jsx(tb,{size:16})}),C&&s.jsx("span",{className:"lang-switch-label text-xs",children:w.label}),C&&s.jsx(PS,{open:o})]}),o&&s.jsx("ul",{ref:m,role:"listbox",tabIndex:-1,"aria-label":x,"aria-activedescendant":k(c),className:`lang-switch-menu lang-switch-menu--${t}`,onKeyDown:y,children:tn.map((A,M)=>{const T=A.code===w.code,R=M===c;return s.jsxs("li",{id:k(M),role:"option","aria-selected":T,className:`lang-switch-option${R?" is-active":""}${T?" is-selected":""}`,onMouseEnter:()=>u(M),onClick:()=>j(M),children:[s.jsx("span",{className:"lang-switch-check","aria-hidden":"true",children:T?s.jsx(Zd,{size:14}):null}),s.jsx("span",{className:"lang-switch-option-label",children:A.label})]},A.code)})})]})}const DS=[],LS=[];function ao(e,t){return e?typeof e=="function"?e(t):e:null}const RS=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=w=>`nav-item${w.active?" active":""} cursor-pointer ${d?"justify-center py-2.5 px-0":""}${w.className?` ${w.className}`:""}`,g=w=>s.jsxs("div",{className:f(w),id:`nav-${w.id}`,onClick:()=>{w.onSelect(),u()},title:d?w.title??(typeof w.label=="string"?w.label:void 0):w.title,children:[s.jsx("span",{className:"nav-icon",children:w.icon}),!d&&w.label]},w.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:ao(n,t)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":p("app.closeMenu"),onClick:u,children:s.jsx(At,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(g)}),a.map(w=>s.jsxs("div",{className:w.className??"border-t border-border-subtle pt-2 mt-2",children:[!d&&w.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:w.title}):null,w.items.map(g)]},w.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[o.map(g),ao(i,t),s.jsx(NS,{collapsed:d}),s.jsx(IS,{collapsed:d}),ao(c,t)]})]})});function ES({children:e,brand:t,navItems:n,sidebarSections:r=DS,footerItems:a=LS,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}}),w=l.useCallback(()=>m(!0),[]),h=l.useCallback(()=>m(!1),[]),x=l.useCallback(()=>{g(b=>{const S=!b;try{localStorage.setItem(u,S?"1":"0")}catch{}return S})},[u]),k=l.useMemo(()=>({collapsed:f,mobileMenuOpen:d,openMobileMenu:w,closeMobileMenu:h,toggleCollapsed:x}),[f,d,w,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:w,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(RS,{renderState:k,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 bt({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:Bt("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:Bt("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:Bt("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 Ra({icon:e,title:t,description:n,action:r,className:a}){return s.jsxs("div",{className:Bt("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 _S={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"},$S={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Ot({variant:e,children:t,onDismiss:n,className:r}){return s.jsxs("div",{className:Bt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",_S[e],r),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:$S[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 Ct({label:e,hint:t,children:n,className:r}){return s.jsxs("div",{className:Bt("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 is(e){const{className:t,...n}=e;return s.jsx("input",{...n,className:Bt("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 HS={primary:"btn-primary",secondary:"btn-secondary",warning:"btn-warning",danger:"btn-danger",ghost:"btn-ghost"},ks=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:Bt("btn",HS[t],n==="sm"&&"btn-sm",a),...o})}),FS=l.forwardRef(function({options:t,children:n,className:r,...a},o){return s.jsx("select",{ref:o,className:Bt("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)))})}),BS={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"},OS={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function WS({status:e,label:t,className:n}){const r=t||e;return s.jsxs("span",{className:Bt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",BS[e],n),children:[s.jsx("span",{className:Bt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",OS[e])}),r]})}function Fs({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 US({onPrefChange:e}){const{t}=Ne("common"),[n,r]=Yy(),[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(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Nn,{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(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(us,{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:()=>{Mu().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(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ru,{size:15})," ",t("notifications.completionAlertsLabel")]}),description:t("notifications.completionAlertsDesc"),checked:n.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Kf,{size:15})," ",t("notifications.approvalAlertsLabel")]}),description:t("notifications.approvalAlertsDesc"),checked:n.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(or,{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 di(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 ba(e){var t;return((t=di(e))==null?void 0:t.base)??null}function GS(e,t){const n=ba(e),r=ba(t);if(!n||!r)return e.localeCompare(t);for(let a=0;a<3;a+=1){if(n[a]<r[a])return-1;if(n[a]>r[a])return 1}return 0}function qS(e,t){const n=di(e),r=di(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 Ji(e,t){const n=e.version||null;return e.versionMismatch===!0?!0:!n||!t?!1:qS(n,t)}function tr(e,t){if(e.versionUpdateRequired===!0)return!0;const n=e.version||null;if(!n||!t||n===t||GS(n,t)>=0)return!1;const r=ba(n),a=ba(t);return!r||!a?!1:r[0]!==a[0]||r[1]!==a[1]}function zS(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function oo(e,t){return e instanceof Error?e.message:t}function KS({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(Ra,{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(YS,{ide:c,allIdes:e,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:a},c.id))})}function Tc({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 fn.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 VS(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),r=[...yS,...wS,...kS].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 YS({ide:e,allIdes:t,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:a}){var z,F;const{t:o}=Ne("common"),[i,c]=l.useState("idle"),[u,p]=l.useState(""),[d,m]=l.useState(null),[f,g]=l.useState("idle"),[w,h]=l.useState(""),x=e.version||null,k=((z=e.machine)==null?void 0:z.platform)||((F=e.system)==null?void 0:F.platform)||"",b=ts(e,{fallbackId:e.id}),S=k==="win32"?"🪟":k==="darwin"?"🍎":"🐧",j=t.filter(D=>D.daemonId===e.id&&D.transport==="cdp-page"),y=t.filter(D=>D.daemonId===e.id&&D.transport==="pty"),v=t.filter(D=>D.daemonId===e.id&&D.transport==="acp"),N=e.p2p,C=async()=>{if(n){c("upgrading"),p(o("machine.connectedMachines.startingUpgrade"));try{const D=zS(await n(e.id,"daemon_upgrade",{}));D.alreadyLatest?(c("done"),p(`Already on v${D.version||"latest"}.`)):D.upgraded||D.success?(c("done"),p(`Upgrade to v${D.version||"latest"} started. Daemon is restarting...`)):(c("error"),p(D.error||"Upgrade failed"))}catch(D){c("error"),p(oo(D,"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(D){g("error"),h(oo(D,o("machine.connectedMachines.failedToDisconnect")))}}},M=async()=>{if(m(null),!!a){g("loading");try{await a(e.id),g("done"),h(o("machine.connectedMachines.tokenRevoked"))}catch(D){g("error"),h(oo(D,o("machine.connectedMachines.failedToRevokeToken")))}}},T="1.0.9",R=Ji(e,T),E=tr(e,T),_=j.length+y.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:S}),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] ${R?"":"bg-bg-secondary"}`,style:R?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",x,!R&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[n&&R&&s.jsx("button",{onClick:C,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${T}`,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"):E?o("machine.connectedMachines.updateNow"):o("machine.connectedMachines.updateTo",{version:T})}),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(WS,{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&&_>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),_>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[j.map(D=>{const W=VS(D.type),L=D.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:W.icon}),s.jsx("span",{children:W.name}),L!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${L?"bg-status-online":"animate-pulse"}`,style:L?void 0:{background:"var(--status-warning)"},title:o(L?"machine.connectedMachines.cdpConnected":"machine.connectedMachines.cdpConnecting")})]},D.id)}),y.map(D=>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:D.cliName||"CLI"})]},D.id)),v.map(D=>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:D.cliName||"ACP"})]},D.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:o("machine.connectedMachines.noIdesConnected")})]}),(u||w)&&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:w||u})]}),d==="disconnect"&&s.jsx(Tc,{title:o("machine.connectedMachines.disconnectTitle"),message:`Disconnect "${b}" from ADHDev?
58
+ `).includes(a)))}function Xk(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 gp(e,t={}){return Xk(Qk(e,t),t.sortMode||"recent")}function ii(e,t){return typeof e=="function"?e(t??!1?"launch.resumeSavedHistory":"launch.startFresh"):e?"Resume saved history":"Start fresh"}function xp(e,t){return typeof e=="function"?e(t??!1?"launch.resumingSavedHistory":"launch.startingFresh"):e?"Resuming saved history…":"Starting fresh…"}function Zk(e){return e?e("launch.startFresh"):"Start fresh"}function eS(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 sS(e){return e?e("launch.savedHistoryTitle"):"Saved History"}function Vi(e){return e?e("launch.savedHistoryHelper"):"Use saved history when you want continuity in the same provider conversation."}function nS(e){return e?e("launch.savedHistoryEmpty"):"No saved history found yet."}function rS(e){return e?e("launch.refreshSavedHistory"):"Refresh saved history"}function aS(e){return e?e("launch.refreshingSavedHistory"):"Refreshing saved history…"}function ua(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 pa(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 ma(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartFresh":"launch.confirmRestart"):e==="start-fresh"?"Start fresh":"Restart"}function ha(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartingFresh":"launch.confirmRestarting"):e==="start-fresh"?"Starting fresh…":"Restarting…"}function vp(e,t){return typeof e=="function"?e("launch.resumeWith",{label:t}):`Resume saved history with ${e}?`}function yp(e){return e?e("launch.resumeReview"):"Review or change the target workspace before resuming saved history."}function oS(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:w}){var R;const{t:h}=Ne("common"),x=t.find(E=>E.id===e.routeId),k=(x==null?void 0:x.chats)||[],b=(R=x==null?void 0:x.activeChat)==null?void 0:R.id,S=ct(e)&&!lt(e),[j,y]=l.useState(()=>Ft()),v=c||j,N=String(u||"").trim(),C=E=>{if(p){p(E);return}y(E)},A=l.useMemo(()=>a.map(E=>{const _=String(E.workspace||"").trim();return E.canResume||_||!N?E:{...E,workspace:N,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[N,a]),M=l.useMemo(()=>gp(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]),T=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:S?sS(h):h("historyModal.chatHistory")}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Mk(e)}),S&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Vi(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(At,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!S&&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")}),S?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:E=>C({...v,textQuery:E.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:E=>C({...v,workspaceQuery:E.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:E=>C({...v,modelQuery:E.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:E=>C({...v,sortMode:E.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:E=>C({...v,resumableOnly:E.target.checked})}),h("historyModal.resumeReadyOnly")]})]}),M.map(E=>{const _=e.providerSessionId===E.providerSessionId,z=_||!E.canResume||!!i,F=E.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{z||!w||w(E)},disabled:z,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"} ${z?"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:E.title||h("historyModal.untitledSession")}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:E.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:oS(E.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:E.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:[E.workspace||h("historyModal.workspaceUnknown"),F?h("historyModal.selectedWorkspaceSuffix"):"",Js(E.summaryMetadata)?` · ${Js(E.summaryMetadata)}`:"",E.messageCount>0?` · ${h("historyModal.msgCount",{count:E.messageCount})}`:""]}),s.jsx("div",{className:"shrink-0",children:_?h("historyModal.statusActive"):E.canResume?F?h("historyModal.statusResumeSelectedWorkspace"):i===E.providerSessionId?h("historyModal.statusResuming"):h("historyModal.statusResume"):h("historyModal.statusMissingWorkspace")})]})]},E.id)})]}):k.map(E=>s.jsxs("div",{onClick:()=>{f(e.routeId,E.id),d()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${b===E.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===E.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:E.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:[E.id.substring(0,12),"..."]}),b===E.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:h("historyModal.statusActive")})]})]},E.id)),(S&&!o&&M.length===0||!S&&k.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(Uf,{size:32})}),s.jsx("div",{className:"text-[13px]",children:S?a.length>0?h("historyModal.noMatchingHistory"):nS(h):h("historyModal.noRecentChats")})]}),S&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:aS(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(Ca,{size:13})," ",S?rS(h):h("historyModal.refreshHistory")]})})})]})]});return typeof document>"u"?T:fn.createPortal(T,document.body)}const jc={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 kp({toasts:e,onDismiss:t,onClickToast:n}){const{t:r}=Ne();return s.jsx("div",{className:"fixed right-4 z-[var(--z-toast)] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(a=>{const o=jc[a.type]||jc.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(At,{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 iS=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function lS(e){const t=e.workspace||"";if(!t)return"";const n=t.split(/[/\\]/).filter(Boolean);return n.length>0?n[n.length-1]:t}function cS(e,t){return Sp(e)||t}function Sp(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 dS(e){return Sp(e)||void 0}function uS(e){return e.sessionId||e.instanceId||e.agentType}function Cp(e=[]){const t={};for(const n of e)n.type==="adhdev-daemon"&&(t[n.id]=ts(n,{fallbackId:n.id}));return t}function jp(e,t={}){var r;const n=e.daemonId||((r=e.id)==null?void 0:r.split(":")[0])||e.id;return{machineName:Iy(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[n]||t.defaultConnectionState||"new":t.defaultConnectionState}}function Yi(e,t={}){return pS(e,jp(e,t))}function pS(e,t={}){var f,g,w,h,x,k,b,S,j;const n=[],r=t.machineName,a=t.connectionState,o=lS(e),i=e.workspace||"",c=$y(e.type,{agentName:e.cliName}),u=ct(e)||lt(e)?c:$t(e.type),p=cS(e,u),d=Array.isArray(e.childSessions)?e.childSessions.map(y=>{var v,N,C;return{sessionId:y.id,instanceId:y.id,providerSessionId:y.providerSessionId,activeChatId:(v=y.activeChat)==null?void 0:v.id,transport:y.transport,sessionCapabilities:y.capabilities,agentType:y.providerType,agentName:y.providerName||$t(y.providerType),model:dS(y),status:y.status,title:y.title,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,messages:((N=y.activeChat)==null?void 0:N.messages)||[],activeModal:((C=y.activeChat)==null?void 0:C.activeModal)||void 0,unread:y.unread,lastSeenAt:y.lastSeenAt,lastUpdated:y.lastUpdated,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,surfaceHidden:y.surfaceHidden,muted:y.muted,git:y.git,settings:y.settings,coordinator:y.coordinator,messageInput:y.messageInput}}):[],m=iS(e);if(m){const y=e.sessionId||e.instanceId,v=(f=e.settings)==null?void 0:f.meshCoordinatorFor,N=((g=e.settings)==null?void 0:g.meshNodeFor)||!((w=e.settings)!=null&&w.meshCoordinatorFor)&&((h=e.settings)==null?void 0:h.launchedByCoordinator),C=v?" (Coordinator)":N?" (Mesh Node)":"",A=c+C,M=(x=e.activeChat)==null?void 0:x.activeModal,T=M&&Array.isArray(M.buttons)&&M.buttons.length>0,R=Hy(e.activeChat,[{status:e.status,activeModal:(k=e.activeChat)==null?void 0:k.activeModal}],e.agents||[]),E=e.activeChat||{title:"",messages:[]};let _=E.title&&String(E.title).trim()?String(E.title).trim():"";const z=(b=e.activeChat)==null?void 0:b.id,F=e.chats;if(z&&Array.isArray(F)&&F.length>0){const J=F.find(re=>re.id===z||re.id&&String(re.id)===String(z));J!=null&&J.title&&String(J.title).trim()&&(_=String(J.title).trim())}const D=(ct(e)||lt(e),e.type),W=(ct(e)||lt(e))&&Yl(_,A,D)?"":_,L=E.messages||[],P=typeof z=="string"?z.trim():"",$=(ct(e)||lt(e))&&P===String(e.type||"").trim(),I=P&&!$?P:e.providerSessionId,U=e.coordinator||(typeof((S=e.settings)==null?void 0:S.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:y,providerSessionId:e.providerSessionId,historySessionId:I,nativeSessionId:y,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:ct(e)&&e.mode||"chat",agentName:A,agentType:D,status:R,title:W,messages:L,resume:e.resume,hostIdeType:!ct(e)&&!lt(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||W||(ct(e)?e.mode==="chat"?A:`Terminal${C}`: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:T?M.buttons:void 0,modalMessage:T?M.message:void 0,streamSource:"native",tabKey:Ja(y,e.id),machineName:r,connectionState:a,settings:e.settings,coordinator:U,messageInput:e.messageInput})}if(m&&(ct(e)||lt(e)))return n;for(const y of d){const v=y.activeModal&&Array.isArray(y.activeModal.buttons)&&y.activeModal.buttons.length>0,N=Fy(y),C=uS(y),A=`${e.id}:${C}`,M=y.title&&String(y.title).trim()||"",T=Yl(M,y.agentName,y.agentType)?"":M,R=y.messages||[];if(!(y.transport==="cdp-webview"||!!y.sessionId||!!y.providerSessionId||R.length>0||v||!!T||!["idle","panel_hidden","disconnected","not_monitored"].includes(N)))continue;const _=y.coordinator||(typeof((j=y.settings)==null?void 0:j.meshCoordinatorFor)=="string"&&y.settings.meshCoordinatorFor?{meshId:y.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:y.sessionId||y.instanceId,providerSessionId:y.providerSessionId,historySessionId:y.activeChatId||y.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:y.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:y.sessionCapabilities,mode:"chat",agentName:y.agentName,agentType:y.agentType,status:N,title:T,messages:R,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:y.git||e.git,displayPrimary:o||T||y.agentName||u,displaySecondary:y.model&&y.model.trim()?y.model.trim():`${u} · ${y.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:y.lastMessagePreview,lastMessageRole:y.lastMessageRole,lastMessageAt:y.lastMessageAt,lastMessageHash:y.lastMessageHash,lastUpdated:y.lastUpdated||e.lastUpdated,inboxBucket:y.inboxBucket,completionMarker:y.completionMarker,modalButtons:v?y.activeModal.buttons:void 0,modalMessage:v?y.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Ja(y.sessionId||y.instanceId,A),machineName:r,connectionState:a,settings:y.settings,coordinator:_,messageInput:y.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:Ja(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),n}function Np(e){return String(e.type||e.id||"").trim()}function fa(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function mS(e,t){const n=(t||"").trim();if(!n)return[];const r=(e||[]).find(a=>a.type===n);return fa(r==null?void 0:r.modelOptions)}function hS(e,t){const n=(t||"").trim();if(!n)return[];const r=(e||[]).find(a=>a.type===n);return fa(r==null?void 0:r.thinkingLevelOptions)}function Ap(e){const t=new Map;for(const n of e||[])n!=null&&n.type&&t.set(n.type,{models:fa(n.modelOptions),thinking:fa(n.thinkingLevelOptions)});return t}function fS(e){var t;return e.category!=="cli"||!Np(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 wn(e){var r;const t=new Set,n=[];for(const a of e||[]){if(!fS(a))continue;const o=Np(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 kn(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 cr(e){return e.map(t=>t.type)}function bS(e,t){const n=kn(e),r=t.trim();return!r||n.includes(r)?n:[...n,r]}function gS(e,t){return kn(e).filter(n=>n!==t)}function Nc(e,t,n){const r=kn(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 Ac({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 xS({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(()=>kn(e),[e]),d=p.filter(g=>!u.has(g)).length,m=t.filter(g=>!p.includes(g.type)),f=()=>{i&&(n(bS(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,w)=>{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:["#",w+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||w===0,title:"Move up",onClick:()=>n(Nc(p,g,"up")),children:s.jsx(Ac,{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||w===p.length-1,title:"Move down",onClick:()=>n(Nc(p,g,"down")),children:s.jsx(Ac,{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 vS(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 Mp(e,t){const n=vS(e);return{daemonId:n.daemonId,payload:{...t,...n.targetSessionId&&!t.targetSessionId?{targetSessionId:n.targetSessionId}:{}}}}const Tp=[{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:"🏄"}],Pp=[{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:"◆"}],Ip=[{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:"🟠"}],yS=Tp,wS=Pp,kS=Ip;function SS({icon:e,title:t,subtitle:n,badge:r,actions:a,className:o}){return s.jsxs("div",{className:Bt("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 gr({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(SS,{icon:e,title:t,subtitle:n,badge:r,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Bt("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const li="adhdev:themechange";function CS(){return typeof window>"u"?"dark":window.matchMedia("(prefers-color-scheme: light)").matches?"light":"dark"}function ln(){try{const e=localStorage.getItem("theme");if(e==="dark"||e==="light"||e==="system")return e}catch{}return"system"}function cn(e){return e==="system"?CS():e}function Dp(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function Kr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(li,{detail:{preference:e,theme:t}}))}function jS(){const e=ln(),t=cn(e);Dp(t),Kr(e,t)}function Ls(){const[e,t]=l.useState(ln),[n,r]=l.useState(()=>cn(ln()));l.useEffect(()=>{Dp(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),Kr("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:ln()),r(m==="dark"||m==="light"?m:cn(ln()))},c=u=>{if(u.key!=="theme")return;const p=ln(),d=cn(p);t(p),r(d)};return window.addEventListener(li,i),window.addEventListener("storage",c),()=>{window.removeEventListener(li,i),window.removeEventListener("storage",c)}},[]);const a=l.useCallback(i=>{const c=cn(i);t(i),r(c);try{localStorage.setItem("theme",i)}catch{}Kr(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",u=cn(c);r(u);try{localStorage.setItem("theme",c)}catch{}return Kr(c,u),c})},[]);return{theme:n,preference:e,setPreference:a,cycleTheme:o,isDark:n==="dark"}}const Mc={dark:"Dark",light:"Light",system:"System"};function NS({collapsed:e}){const{preference:t,cycleTheme:n}=Ls(),r=t==="dark"?s.jsx(qf,{size:16}):t==="light"?s.jsx(Gf,{size:16}):s.jsx(zf,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:n,title:`Theme: ${Mc[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:r}),!e&&s.jsx("span",{className:"text-xs",children:Mc[t]})]})}const ci="adhdev:langchange";function AS(){const e=wt.language;return un(e)?e:vu()}function MS(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(ci,{detail:{language:e}}))}function TS(){const[e,t]=l.useState(AS);l.useEffect(()=>{const r=i=>{un(i)&&t(i)},a=i=>{const c=i.detail||{};un(c.language)&&t(c.language)},o=i=>{if(i.key!==Vo)return;const c=i.newValue;un(c)&&c!==wt.language&&(wt.changeLanguage(c),Yo(c))};return wt.on("languageChanged",r),window.addEventListener(ci,a),window.addEventListener("storage",o),()=>{wt.off("languageChanged",r),window.removeEventListener(ci,a),window.removeEventListener("storage",o)}},[]);const n=l.useCallback(r=>{if(un(r)){t(r);try{localStorage.setItem(Vo,r)}catch{}wt.changeLanguage(r),Yo(r),MS(r)}},[]);return{language:e,setLanguage:n}}function PS({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 IS({collapsed:e,variant:t="sidebar"}){const{language:n,setLanguage:r}=TS(),{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=Math.max(0,tn.findIndex(A=>A.code===n)),w=tn[g]??tn[0],h=a("language.label",{defaultValue:"Language"}),x=a("language.select",{defaultValue:"Select language"}),k=A=>`${f}-opt-${A}`,b=l.useCallback(()=>{u(g),i(!0)},[g]),S=l.useCallback((A=!0)=>{var M;i(!1),A&&((M=d.current)==null||M.focus())},[]),j=l.useCallback(A=>{const M=tn[A];M&&r(M.code),S()},[r,S]);l.useEffect(()=>{if(!o)return;const A=T=>{var R;(R=p.current)!=null&&R.contains(T.target)||i(!1)},M=T=>{var R;(R=p.current)!=null&&R.contains(T.target)||i(!1)};return document.addEventListener("pointerdown",A,!0),document.addEventListener("focusin",M,!0),()=>{document.removeEventListener("pointerdown",A,!0),document.removeEventListener("focusin",M,!0)}},[o]),l.useEffect(()=>{var A;o&&((A=m.current)==null||A.focus())},[o]);const y=A=>{const M=tn.length-1;switch(A.key){case"ArrowDown":A.preventDefault(),u(T=>T>=M?0:T+1);break;case"ArrowUp":A.preventDefault(),u(T=>T<=0?M:T-1);break;case"Home":A.preventDefault(),u(0);break;case"End":A.preventDefault(),u(M);break;case"Enter":case" ":A.preventDefault(),j(c);break;case"Escape":A.preventDefault(),S();break;case"Tab":i(!1);break}},v=A=>{o||(A.key==="ArrowDown"||A.key==="ArrowUp"||A.key==="Enter"||A.key===" ")&&(A.preventDefault(),b())},N=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":""}`,C=t==="landing"||!e;return s.jsxs("div",{ref:p,className:"lang-switch",children:[s.jsxs("button",{ref:d,type:"button",className:N,"aria-haspopup":"listbox","aria-expanded":o,"aria-label":`${h}: ${w.label}`,title:`${h}: ${w.label}`,onClick:()=>o?S(!1):b(),onKeyDown:v,children:[s.jsx("span",{className:"nav-icon lang-switch-icon",children:s.jsx(tb,{size:16})}),C&&s.jsx("span",{className:"lang-switch-label text-xs",children:w.label}),C&&s.jsx(PS,{open:o})]}),o&&s.jsx("ul",{ref:m,role:"listbox",tabIndex:-1,"aria-label":x,"aria-activedescendant":k(c),className:`lang-switch-menu lang-switch-menu--${t}`,onKeyDown:y,children:tn.map((A,M)=>{const T=A.code===w.code,R=M===c;return s.jsxs("li",{id:k(M),role:"option","aria-selected":T,className:`lang-switch-option${R?" is-active":""}${T?" is-selected":""}`,onMouseEnter:()=>u(M),onClick:()=>j(M),children:[s.jsx("span",{className:"lang-switch-check","aria-hidden":"true",children:T?s.jsx(Zd,{size:14}):null}),s.jsx("span",{className:"lang-switch-option-label",children:A.label})]},A.code)})})]})}const DS=[],LS=[];function ao(e,t){return e?typeof e=="function"?e(t):e:null}const RS=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=w=>`nav-item${w.active?" active":""} cursor-pointer ${d?"justify-center py-2.5 px-0":""}${w.className?` ${w.className}`:""}`,g=w=>s.jsxs("div",{className:f(w),id:`nav-${w.id}`,onClick:()=>{w.onSelect(),u()},title:d?w.title??(typeof w.label=="string"?w.label:void 0):w.title,children:[s.jsx("span",{className:"nav-icon",children:w.icon}),!d&&w.label]},w.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:ao(n,t)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":p("app.closeMenu"),onClick:u,children:s.jsx(At,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:r.map(g)}),a.map(w=>s.jsxs("div",{className:w.className??"border-t border-border-subtle pt-2 mt-2",children:[!d&&w.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:w.title}):null,w.items.map(g)]},w.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[o.map(g),ao(i,t),s.jsx(NS,{collapsed:d}),s.jsx(IS,{collapsed:d}),ao(c,t)]})]})});function ES({children:e,brand:t,navItems:n,sidebarSections:r=DS,footerItems:a=LS,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}}),w=l.useCallback(()=>m(!0),[]),h=l.useCallback(()=>m(!1),[]),x=l.useCallback(()=>{g(b=>{const S=!b;try{localStorage.setItem(u,S?"1":"0")}catch{}return S})},[u]),k=l.useMemo(()=>({collapsed:f,mobileMenuOpen:d,openMobileMenu:w,closeMobileMenu:h,toggleCollapsed:x}),[f,d,w,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:w,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(RS,{renderState:k,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 bt({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:Bt("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:Bt("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:Bt("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 Ra({icon:e,title:t,description:n,action:r,className:a}){return s.jsxs("div",{className:Bt("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 _S={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"},$S={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Ot({variant:e,children:t,onDismiss:n,className:r}){return s.jsxs("div",{className:Bt("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",_S[e],r),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:$S[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 Ct({label:e,hint:t,children:n,className:r}){return s.jsxs("div",{className:Bt("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 is(e){const{className:t,...n}=e;return s.jsx("input",{...n,className:Bt("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 HS={primary:"btn-primary",secondary:"btn-secondary",warning:"btn-warning",danger:"btn-danger",ghost:"btn-ghost"},ks=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:Bt("btn",HS[t],n==="sm"&&"btn-sm",a),...o})}),FS=l.forwardRef(function({options:t,children:n,className:r,...a},o){return s.jsx("select",{ref:o,className:Bt("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)))})}),BS={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"},OS={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function WS({status:e,label:t,className:n}){const r=t||e;return s.jsxs("span",{className:Bt("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",BS[e],n),children:[s.jsx("span",{className:Bt("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",OS[e])}),r]})}function Fs({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 US({onPrefChange:e}){const{t}=Ne("common"),[n,r]=Yy(),[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(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Nn,{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(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(us,{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:()=>{Mu().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(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ru,{size:15})," ",t("notifications.completionAlertsLabel")]}),description:t("notifications.completionAlertsDesc"),checked:n.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Kf,{size:15})," ",t("notifications.approvalAlertsLabel")]}),description:t("notifications.approvalAlertsDesc"),checked:n.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(or,{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 di(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 ba(e){var t;return((t=di(e))==null?void 0:t.base)??null}function GS(e,t){const n=ba(e),r=ba(t);if(!n||!r)return e.localeCompare(t);for(let a=0;a<3;a+=1){if(n[a]<r[a])return-1;if(n[a]>r[a])return 1}return 0}function qS(e,t){const n=di(e),r=di(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 Ji(e,t){const n=e.version||null;return e.versionMismatch===!0?!0:!n||!t?!1:qS(n,t)}function tr(e,t){if(e.versionUpdateRequired===!0)return!0;const n=e.version||null;if(!n||!t||n===t||GS(n,t)>=0)return!1;const r=ba(n),a=ba(t);return!r||!a?!1:r[0]!==a[0]||r[1]!==a[1]}function zS(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function oo(e,t){return e instanceof Error?e.message:t}function KS({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(Ra,{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(YS,{ide:c,allIdes:e,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:a},c.id))})}function Tc({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 fn.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 VS(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),r=[...yS,...wS,...kS].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 YS({ide:e,allIdes:t,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:a}){var z,F;const{t:o}=Ne("common"),[i,c]=l.useState("idle"),[u,p]=l.useState(""),[d,m]=l.useState(null),[f,g]=l.useState("idle"),[w,h]=l.useState(""),x=e.version||null,k=((z=e.machine)==null?void 0:z.platform)||((F=e.system)==null?void 0:F.platform)||"",b=ts(e,{fallbackId:e.id}),S=k==="win32"?"🪟":k==="darwin"?"🍎":"🐧",j=t.filter(D=>D.daemonId===e.id&&D.transport==="cdp-page"),y=t.filter(D=>D.daemonId===e.id&&D.transport==="pty"),v=t.filter(D=>D.daemonId===e.id&&D.transport==="acp"),N=e.p2p,C=async()=>{if(n){c("upgrading"),p(o("machine.connectedMachines.startingUpgrade"));try{const D=zS(await n(e.id,"daemon_upgrade",{}));D.alreadyLatest?(c("done"),p(`Already on v${D.version||"latest"}.`)):D.upgraded||D.success?(c("done"),p(`Upgrade to v${D.version||"latest"} started. Daemon is restarting...`)):(c("error"),p(D.error||"Upgrade failed"))}catch(D){c("error"),p(oo(D,"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(D){g("error"),h(oo(D,o("machine.connectedMachines.failedToDisconnect")))}}},M=async()=>{if(m(null),!!a){g("loading");try{await a(e.id),g("done"),h(o("machine.connectedMachines.tokenRevoked"))}catch(D){g("error"),h(oo(D,o("machine.connectedMachines.failedToRevokeToken")))}}},T="1.0.12",R=Ji(e,T),E=tr(e,T),_=j.length+y.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:S}),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] ${R?"":"bg-bg-secondary"}`,style:R?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",x,!R&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[n&&R&&s.jsx("button",{onClick:C,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${T}`,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"):E?o("machine.connectedMachines.updateNow"):o("machine.connectedMachines.updateTo",{version:T})}),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(WS,{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&&_>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),_>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[j.map(D=>{const W=VS(D.type),L=D.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:W.icon}),s.jsx("span",{children:W.name}),L!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${L?"bg-status-online":"animate-pulse"}`,style:L?void 0:{background:"var(--status-warning)"},title:o(L?"machine.connectedMachines.cdpConnected":"machine.connectedMachines.cdpConnecting")})]},D.id)}),y.map(D=>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:D.cliName||"CLI"})]},D.id)),v.map(D=>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:D.cliName||"ACP"})]},D.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:o("machine.connectedMachines.noIdesConnected")})]}),(u||w)&&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:w||u})]}),d==="disconnect"&&s.jsx(Tc,{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:M,onCancel:()=>m(null)})]})}const JS=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli","gemini-cli"];function QS({daemonId:e,knownCliTypes:t=JS}){const{t:n}=Ne("common"),{sendCommand:r}=vt(),[a,o]=l.useState({}),[i,c]=l.useState({}),[u,p]=l.useState(!0),[d,m]=l.useState(null),[f,g]=l.useState(null),[w,h]=l.useState(""),x=l.useCallback(async()=>{if(e){p(!0),g(null);try{const S=await r(e,"list_coordinator_prompts",{}),j=S!=null&&S.result&&typeof S.result=="object"?S.result:S;if(!(j!=null&&j.success)){g((j==null?void 0:j.error)||"Failed to load");return}const y=j.entries||{};h(j.dir||"");const v={};for(const N of t)v[N]=y[N]||{override:"",append:""};for(const N of Object.keys(y))v[N]||(v[N]=y[N]);o(v),c(JSON.parse(JSON.stringify(v)))}catch(S){g((S==null?void 0:S.message)||String(S))}finally{p(!1)}}},[r,e,t]);l.useEffect(()=>{x()},[x]);const k=l.useCallback(async(S,j)=>{var y;if(e){m(`${S}:${j}`),g(null);try{const v=((y=a[S])==null?void 0:y[j])||"",N=await r(e,"write_coordinator_prompt",{key:S,kind:j,content:v}),C=N!=null&&N.result&&typeof N.result=="object"?N.result:N;if(!(C!=null&&C.success)){g((C==null?void 0:C.error)||"Save failed");return}c(A=>({...A,[S]:{...A[S]||{override:"",append:""},[j]:v}}))}catch(v){g((v==null?void 0:v.message)||String(v))}finally{m(null)}}},[r,e,a]),b=l.useMemo(()=>(S,j)=>{var y,v;return(((y=a[S])==null?void 0:y[j])||"")!==(((v=i[S])==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:w||"~/.adhdev/coordinator-prompts/"})]}),s.jsxs("p",{className:"mt-1",children:[s.jsx(Bo,{i18nKey:"settings.coordinatorPrompts.overrideDesc",ns:"common",components:{strong:s.jsx("strong",{})}})," ",s.jsx(Bo,{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(([S,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:S}),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:y=>o(v=>({...v,[S]:{...v[S],override:y.target.value}})),placeholder:"(empty — use daemon default base prompt)",disabled:d===`${S}: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 k(S,"override"),disabled:d===`${S}:override`||!b(S,"override"),children:d===`${S}:override`?"Saving…":b(S,"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:y=>o(v=>({...v,[S]:{...v[S],append:y.target.value}})),placeholder:"(empty — nothing appended at this layer)",disabled:d===`${S}:append`}),s.jsx("div",{className:"mt-1 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void k(S,"append"),disabled:d===`${S}:append`||!b(S,"append"),children:d===`${S}:append`?"Saving…":b(S,"append")?"Save append":"Saved"})})]},S))})]}):s.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const XS=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function ZS(){const{preference:e,setPreference:t}=Ls();return s.jsx("div",{className:"flex gap-2",children:XS.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 eC(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 tC(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function io(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Pc(e){const{r:t,g:n,b:r}=tC(e);return .2126*io(t)+.7152*io(n)+.0722*io(r)}function Ic(e,t){const n=Pc(e),r=Pc(t),a=Math.max(n,r),o=Math.min(n,r);return(a+.05)/(o+.05)}function Lp(e){const t=eC(e);if(!t)return"#111827";const n="#111827",r="#ffffff";return Ic(t,n)>=Ic(t,r)?n:r}const ui={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},pi={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},sC=[{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"}}}],Rp="adhdev-chat-theme",Ep="adhdev-chat-theme-custom";function Vr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Rp)||"ember"}catch{return"ember"}}function os(e){try{const t=localStorage.getItem(Ep);if(t){const n=JSON.parse(t);return{...e==="dark"?ui:pi,...n[e]}}}catch{}return e==="dark"?ui:pi}function Tr(e,t){try{localStorage.setItem(Ep,JSON.stringify({dark:e,light:t}))}catch{}}function Qt(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 ga(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 nC={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function sr(e,t){var a;const n=(a=nC[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",ga(n,24)),r.style.setProperty("--accent-on-primary",Lp(n)),r.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${n}, ${ga(n,18)})`),r.style.setProperty("--border-accent",Qt(n,.35)),r.style.setProperty("--nav-active-bg",Qt(n,.1)),r.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${n}, 0 0 12px ${Qt(n,.06)}`)}function qs(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Qt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Qt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Qt(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",Qt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Qt(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",ga(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Lp(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${ga(e.accentColor,40)})`),t.style.setProperty("--border-accent",Qt(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Qt(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Qt(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 ${Qt(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 Qi(){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(Rp,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=zs()?"dark":"light";qs(os(t))}else Qi(),sr(e,zs()?"dark":"light")}function aC(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Vr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=zs()?"dark":"light";qs(os(t))}else Qi(),sr(e,zs()?"dark":"light")}function zs(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Ht({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 Fn({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 oC({dark:e,onColorsChange:t}){const{t:n}=Ne("common"),r=e?"dark":"light",[a,o]=l.useState(()=>os(r));l.useEffect(()=>{o(os(r))},[r]);const i=l.useCallback((c,u)=>{o(p=>{const d={...p,[c]:u},f=os(r==="dark"?"light":"dark");return r==="dark"?Tr(d,f):Tr(f,d),qs(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(Fn,{title:n("settings.theme.sectionAppBackground"),children:[s.jsx(Ht,{label:n("settings.theme.colorBackground"),value:a.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(Ht,{label:n("settings.theme.colorSurface"),value:a.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(Ht,{label:n("settings.theme.colorCard"),value:a.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(Fn,{title:n("settings.theme.sectionAppText"),children:[s.jsx(Ht,{label:n("settings.theme.colorPrimary"),value:a.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(Ht,{label:n("settings.theme.colorSecondary"),value:a.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(Ht,{label:n("settings.theme.colorMuted"),value:a.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(Fn,{title:n("settings.theme.sectionBordersAccent"),children:[s.jsx(Ht,{label:n("settings.theme.colorBorderSubtle"),value:a.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(Ht,{label:n("settings.theme.colorBorderDefault"),value:a.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(Ht,{label:n("settings.theme.colorAccent"),value:a.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Fn,{title:n("settings.theme.sectionChatBubbles"),children:[s.jsx(Ht,{label:n("settings.theme.colorUserBubble"),value:a.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(Ht,{label:n("settings.theme.colorUserText"),value:a.userText,onChange:c=>i("userText",c)}),s.jsx(Ht,{label:n("settings.theme.colorAgentBubble"),value:a.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(Ht,{label:n("settings.theme.colorAgentText"),value:a.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(Fn,{title:n("settings.theme.sectionChatLayout"),children:[s.jsx(Ht,{label:n("settings.theme.colorChatBg"),value:a.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(Ht,{label:n("settings.theme.colorSendButton"),value:a.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(Ht,{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?ui:pi,p=os(e?"light":"dark");e?Tr(c,p):Tr(p,c),o(c),qs(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 iC(){const{t:e}=Ne("common"),[t,n]=l.useState(Vr),[r,a]=l.useState(!0),[o,i]=l.useState(()=>os("dark"));l.useEffect(()=>{a(zs());const p=new MutationObserver(()=>{const f=zs();a(f);const g=Vr();g==="custom"?qs(os(f?"dark":"light")):sr(g,f?"dark":"light")});p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const d=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const f=zs();a(f);const g=Vr();g==="custom"?qs(os(f?"dark":"light")):sr(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"?qs(os(r?"dark":"light")):(Qi(),sr(t,r?"dark":"light"))},[t,r]),l.useEffect(()=>{i(os(r?"dark":"light"))},[r]);const c=p=>{n(p),rC(p)},u=[...sC,{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(oC,{dark:r,onColorsChange:p=>i(p)})]})}const Xi="adhdev_mobileDashboardMode_v1",mi="adhdev:mobile-dashboard-mode-change";function Zi(){try{return localStorage.getItem(Xi)==="workspace"?"workspace":"chat"}catch{return"chat"}}function lC(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??Zi())},n=a=>{const o=a.detail;t(o)},r=a=>{a.key&&a.key!==Xi||t()};return window.addEventListener(mi,n),window.addEventListener("storage",r),()=>{window.removeEventListener(mi,n),window.removeEventListener("storage",r)}}function cC(e){try{localStorage.setItem(Xi,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(mi,{detail:e}))}function dC(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(Zi()==="chat")},[]),s.jsx(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Zs,{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),cC(n?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const uC="Choose a preset or create a fully custom theme. Custom themes control the entire app — backgrounds, text, borders, and chat bubbles.",pC="Choose whether the dashboard opens like a chat app on phones or keeps the full workspace layout.";function mC({themeDescription:e=uC,mobileDescription:t=pC,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(ZS,{})]}),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(iC,{})]}),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(dC,{})]})]})}const lo=new Map,Dc=new Map;function hC(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 fC(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 _p(){const{sendCommand:e}=vt(),{injectEntries:t,getIdes:n}=ar();return l.useCallback(async(r,a)=>{if(!r)return;const o=(a==null?void 0:a.minFreshMs)??N0,i=Dc.get(r)||0;if(!(a!=null&&a.force)&&i>0&&Date.now()-i<o)return;const c=lo.get(r);if(c)return c;const u=(async()=>{const p=await e(r,"get_machine_runtime_stats"),d=hC(p);if(!d)return;const m=n().find(g=>g.id===r),f=fC(m,r,d.machine,d.timestamp||Date.now());t([f]),Dc.set(r,Date.now())})().finally(()=>{lo.delete(r)});return lo.set(r,u),u},[n,t,e])}function bC(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 gC(e,t){const{sendData:n}=vt(),{injectEntries:r,getIdes:a}=ar(),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=>ls.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=bC(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 xC(e,t){const{sendData:n}=vt(),[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=ls.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)},T0):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 vC(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function $p(e){const{sendData:t}=vt(),[n,r]=l.useState({});return l.useEffect(()=>{const a=vC(e);if(!a||!e.sessionId||!t){r({});return}const o=ls.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}),bn.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 yC(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function wC(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 kC(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 SC({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(!yC(o))throw new Error(wC(o));return}await kC(e.sessionId,t,a)}function Hp(e){const{ides:t,isP2PActive:n,p2pStates:r}=gs(),{sendCommand:a}=vt(),[o,i]=l.useState(null),[c,u]=l.useState(!1),[p,d]=l.useState(null),m=l.useRef(!1),f=l.useMemo(()=>Ib(t,e),[t,e]),g=!!f,w=l.useMemo(()=>f?f.prompt.promptId===o?null:f:null,[o,f]),h=l.useCallback(async b=>{if(!w||m.current)return;m.current=!0;const S=mu(w.prompt,b);u(!0),d(null);try{const j=(r==null?void 0:r[w.daemonId])==="connected"||n===!0;await SC({promptSession:w,response:S,useP2PCommand:j,sendCommand:a}),i(w.prompt.promptId)}catch(j){throw d(j instanceof Error?j.message:String(j)),j}finally{u(!1),m.current=!1}},[n,r,w,a]),x=l.useCallback(()=>{w&&i(w.prompt.promptId)},[w]),k=l.useCallback(()=>{i(null),d(null)},[]);return{promptSession:w,hasActivePrompt:g,responseError:p,isSubmitting:c,submit:h,cancel:x,reopen:k}}function Fp(e){return e instanceof Error?e.message:String(e||"")}function CC(e){const t=Fp(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 jC(e){const t=Fp(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Bp({conversation:e,mode:t,ides:n,sendDaemonCommand:r,setCliViewModeOverrides:a}){if(!e||!ct(e)||lt(e))return;const o=Mn(e);if(o===t)return;const i=e.sessionId;i&&a(c=>({...c,[i]:t}));try{await r(Ds(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:bs(e),mode:t})}catch(c){const u=jC(c);i&&!u&&a(p=>{const d={...p};return o===AC(n,i)?delete d[i]:d[i]=o,d}),CC(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 Lc(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 NC(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=Lc(a,t),i=Array.isArray(a.childSessions)?a.childSessions.map(u=>Lc(u,t)):a.childSessions,c=i!==a.childSessions;return o!==a||c?(n=!0,{...o,...c?{childSessions:i}:{}}):a});return n?r:e}function AC(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 MC({visibleConversations:e,clearedTabs:t,setClearedTabs:n,setActionLogs:r,isConversationMuted:a}){l.useEffect(()=>{Mu()},[]);const o=l.useMemo(()=>e.map(i=>({id:i.tabKey,name:mp(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 Zy(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 Rc(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 Ks(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=Rc(t==null?void 0:t.receivedAt)||Rc(t==null?void 0:t.timestamp)||0;return Math.max(n,r)}function hi(e,t=0){return Ks(e)||e.lastUpdated||t||0}function Op(e){return Ks(e)||e.lastUpdated||0}function Wp(e,t,n=Op){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 fi(e){var n;const t=Zt(e.status,{activeModal:(n=e.modalButtons)!=null&&n.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function TC(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!fi(e)&&!e.title.trim()}function PC(e){return e.length===0?null:[...e].sort((t,n)=>{const r=Number(fi(n))-Number(fi(t));if(r!==0)return r;const a=n.messages.length-t.messages.length;return a!==0?a:Wp(t,n)})[0]||null}function cs(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=PC(a);return r?o&&TC(r)?o:r:o||n[0]||null}function IC(e){const t=e.filter(a=>a.type!=="adhdev-daemon"),n=new Set;for(const a of t){if(!Zo(a))continue;const o=ku(a);o&&n.add(o)}const r=new Map;for(const a of t){const o=Py(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,DC(d,d===a?i:a))}return Array.from(r.values())}function DC(e,t){const n=Zo(t),r=Zo(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 co(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 LC(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 Ec(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],n=t[t.length-1],r=n?LC(gn(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 RC(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||""),Ec(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||""),Ec(n.activeChat)].join(":"))].join("|")}function EC(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 _C(e,t){const n=new Map;for(const r of e){const a=t.get(r.routeId)||r;for(const o of Xn({routeId:r.routeId}))n.set(o,a);for(const o of Xn({providerSessionId:r.providerSessionId,sessionId:r.sessionId}))n.set(o,r.streamSource==="native"?a:r);for(const o of Xn({tabKey:r.tabKey}))n.set(o,r)}return n}function $C(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function HC(e){const t=$C(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=gn(t.content).slice(0,240);return`${e.messages.length}:${n}:${r}`}function FC({ides:e,connectionStates:t,clearedTabs:n}){const r=l.useMemo(()=>IC(e),[e]),a=l.useMemo(()=>bu(e),[e]),o=l.useMemo(()=>Cp(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,y=[];for(const A of r){const{connectionState:M="new",machineName:T}=jp(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),R=RC(A),E=p.current.get(A.id);if(E&&E.ide===A&&E.sourceSignature===R&&E.connectionState===M&&E.machineName===T){j.set(A.id,E),y.push(...E.conversations);continue}const _=Yi(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),z={ide:A,sourceSignature:R,connectionState:M,machineName:T,conversations:_};j.set(A.id,z),y.push(..._)}p.current=j;const v=new Map,N=A=>{const M=HC(A),T=d.current.get(A.tabKey);if(T&&T.signature===M)return v.set(A.tabKey,T),T.timestamp;const R={signature:M,timestamp:Op(A)||(T==null?void 0:T.timestamp)||0};return v.set(A.tabKey,R),R.timestamp},C=[...y].sort((A,M)=>Wp(A,M,N));return d.current=v,C},[r,t,o]),f=l.useMemo(()=>{const j=EC(m,n);return co(i.current,j)?i.current:(i.current=j,j)},[m,n]),g=l.useMemo(()=>{const j=new Map,y=Array.from(new Set(f.map(v=>v.routeId)));for(const v of y){const N=cs(f,v);N&&j.set(v,N)}return j},[f]),w=l.useMemo(()=>{const j=new Map;for(const y of f){const v=g.get(y.routeId),N=y.streamSource==="native"&&v?v:y;for(const C of Xn({providerSessionId:y.providerSessionId,sessionId:y.sessionId,tabKey:y.tabKey}))j.set(C,N)}return j},[f,g]),h=l.useMemo(()=>_C(f,g),[f,g]),x=l.useCallback(j=>{if(j)return w.get(j)},[w]),k=l.useCallback(j=>{if(j)return h.get(j)},[h]),b=l.useMemo(()=>{const j=f.filter(y=>!Is(y,a).surfaceHidden);return co(c.current,j)?c.current:(c.current=j,j)},[f,a]),S=l.useMemo(()=>{const j=b.map(y=>y.tabKey);return co(u.current,j)?u.current:(u.current=j,j)},[b]);return{chatIdes:r,conversations:f,visibleConversations:b,visibleTabKeys:S,resolveConversationBySessionId:x,resolveConversationByTarget:k}}function BC({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 OC({ides:e,sendDaemonCommand:t,setToasts:n,resolveConversationByTarget:r}){l.useEffect(()=>{mt.setIdes(e)},[e]),l.useEffect(()=>{mt.setResolveAction((a,o,i)=>{t(a,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const a=mt.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=cp.on("status_event",o=>{mt.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(),w=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(g);t(d,"resolve_action",{action:w?"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 WC="adhdev_dashboardLayout_v1",UC="adhdev_dashboardDockview_v1",GC="adhdev_dashboardDockviewHiddenRestore_v1",Bn={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function el(e,t){try{const n=localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}}function qC(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Up(e){return`${WC}:${e}`}function zC(e){const t=Up(e);return el(t,null)}function KC(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=Up(e);if(n){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Gp(e){return`${UC}:${e}`}function VC(e){const t=Gp(e);return el(t,null)}function YC(e,t){try{const n=Gp(e);if(!t){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function qp(e){return`${GC}:${e}`}function JC(e){const t=qp(e);return el(t,{})}function QC(e,t){try{const n=qp(e);if(Object.keys(t).length===0){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function XC(){return{groupAssignments:[...Bn.groupAssignments],focusedGroup:Bn.focusedGroup,groupActiveTabIds:{...Bn.groupActiveTabIds},groupTabOrders:{...Bn.groupTabOrders},groupSizes:[...Bn.groupSizes]}}function ZC(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):t.length===0}function ej(){const[e]=l.useState(()=>qC(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,w]=l.useState(!1),h=l.useCallback(()=>{if(g)return;const A=zC(e)??XC();n(new Map(A.groupAssignments)),a(A.focusedGroup),i(A.groupActiveTabIds),u(A.groupTabOrders),d(A.groupSizes),w(!0)},[g,e]);l.useEffect(()=>{g&&KC(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)"),M=T=>f(T.matches);return A.addEventListener("change",M),()=>A.removeEventListener("change",M)},[]);const x=l.useCallback(A=>{n(A)},[]),k=l.useCallback(A=>{a(A)},[]),b=l.useCallback(A=>{i(A)},[]),S=l.useCallback(A=>{u(A)},[]),j=l.useCallback(A=>{d(A)},[]),y=l.useCallback(A=>{k(A)},[k]),v=l.useCallback((A,M)=>{i(T=>(T[A]??null)===(M??null)?T:{...T,[A]:M})},[]),N=l.useCallback((A,M)=>{u(T=>{const R=T[A];return ZC(R,M)?T:{...T,[A]:M}})},[]),C=l.useCallback((A,M)=>{const T=M.get(A)??0;return v(T,A),y(T),T},[y,v]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:x,focusedGroup:r,updateFocusedGroup:k,focusGroup:y,groupActiveTabIds:o,updateGroupActiveTabIds:b,setGroupActiveTab:v,groupTabOrders:c,updateGroupTabOrders:S,setGroupTabOrder:N,groupSizes:p,updateGroupSizes:j,isMobile:m,hasHydratedStoredLayout:g,hydrateStoredLayout:h,focusConversationTab:C}}function tj(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0],r=Aa(t);return typeof(n==null?void 0:n.id)=="string"&&r.includes(n.id)}function sj({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),w=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 k=n(e);k&&(i(k.tabKey,r),g.current=!0,w.current=!0,h.current!=null&&(window.clearTimeout(h.current),h.current=null),c(b=>{const S=new URLSearchParams(b);return S.delete("activeTab"),S},{replace:!0}))},[e,t,n,r,a,o,i,c]),l.useEffect(()=>{if(!(w.current||a)&&t.length!==0){if(!e){o(),w.current=!0;return}if(g.current){w.current=!0;return}if(h.current==null)return h.current=window.setTimeout(()=>{h.current=null,!(w.current||a)&&(o(),w.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 k=m.find(b=>b.id===p.routeId);k&&(!k.chats||k.chats.length===0||tj(k.chats,p))&&(x.current=!0,f())},[u,p,d,m,f])}function uo(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=Aa(t);return typeof(n==null?void 0:n.id)=="string"&&r.includes(n.id)}function zp({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 w=>{try{await e("standalone","launch_ide",{ideType:w,enableCdp:!0})}catch(h){console.error("Launch failed",h)}},[e]),m=l.useCallback(async(w,h)=>{try{const x=w||(t==null?void 0:t.daemonId)||"",k=await e(x,"switch_chat",{id:h,sessionId:h,...Ws(t)}),b=k==null?void 0:k.result;if((k==null?void 0:k.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?on(a,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?on(a,`⚠️ Switch error: ${b}`):on(a,"⚠️ Session switch failed")}catch(x){console.error("Switch failed",x),on(a,`❌ Switch failed: ${x.message||"connection error"}`)}},[t,e,a]),f=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const w=Us(t);await e(w,"new_chat",{...Ws(t)}),V0(w,t.sessionId,Aa(t)[0]),o(h=>({...h,[t.tabKey]:Date.now()}))}catch(w){console.error("New chat failed",w)}finally{c(!1)}}},[t,i,e,o]),g=l.useCallback(async()=>{var w,h;if(!(!t||u)){p(!0);try{const x=Us(t),k=async()=>e(x,"list_chats",{forceExpand:!0,...Ws(t)});let b=await k(),S=(b==null?void 0:b.chats)||((w=b==null?void 0:b.result)==null?void 0:w.chats);uo(S,t)&&(await new Promise(j=>setTimeout(j,450)),b=await k(),S=(b==null?void 0:b.chats)||((h=b==null?void 0:b.result)==null?void 0:h.chats)),b!=null&&b.success&&Array.isArray(S)&&(r(t.routeId,S),uo(S,t)&&!uo(n,t)&&on(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 nj(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 _c(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 Pr(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 $c(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 aj(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 oj(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 Hc(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 Fc(e){return Array(e).fill(100/e)}function ij({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(()=>Pr(e,p),[e,p]),f=m.assignments,g=l.useMemo(()=>c?1:m.groupCount,[m.groupCount,c]),w=g>1,h=l.useCallback((y,v)=>{t(N=>{const C=new Map(Pr(N,p).assignments);return v===0?C.delete(y):C.set(y,v),C}),r(N=>({...N,[v]:y})),n(v)},[t,p,r,n]),x=l.useCallback(y=>{t(v=>{const N=Pr(v,p).assignments,C=new Map;for(const[A,M]of N)M!==y&&(M>y?C.set(A,M-1):C.set(A,M));return C}),i(v=>{if(v.length<=1)return[];const N=[...v];N.splice(y,1);const C=N.reduce((A,M)=>A+M,0);return C>0?N.map(A=>A/C*100):[]}),n(0)},[t,p,i,n]),k=l.useCallback((y,v)=>{v.preventDefault();const N=d.current;if(!N)return;const C=v.clientX,A=N.offsetWidth,M=o.length===g?[...o]:Fc(g),T=E=>{const z=(E.clientX-C)/A*100,F=[...M];F[y]=Math.max(15,M[y]+z),F[y+1]=Math.max(15,M[y+1]-z),i(F)},R=()=>{document.removeEventListener("mousemove",T),document.removeEventListener("mouseup",R),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",T),document.addEventListener("mouseup",R)},[o,g,i]),b=l.useCallback((y,v,N)=>{if(g>=4)return;const C=N==="left"?v:v+1;t(A=>{const M=Pr(A,p).assignments,T=new Map;for(const R of u){const E=M.get(R.tabKey)??0,_=E>=C?E+1:E;_>0&&T.set(R.tabKey,_)}return C>0&&T.set(y,C),T}),i(A=>{const M=A.length===g?[...A]:Fc(g),T=M[v]??100/g,R=Math.max(15,T/2),E=Math.max(15,T/2),_=[...M];_[v]=R,_.splice(C,0,E);const z=_.reduce((F,D)=>F+D,0);return _.map(F=>F/z*100)}),r(A=>{const M=Hc(A,C);return M[C]=y,M}),a(A=>{const M=Hc(A,C);return M[C]=[y],M}),n(C)},[g,t,p,u,i,r,a,n]);l.useEffect(()=>{nj(e,f)||t(f)},[e,f,t]),l.useEffect(()=>{const{mapping:y,usedGroups:v}=m;r(N=>{const C=$c(N,y);return _c(N,C)?N:C}),a(N=>{const C=$c(N,y);return _c(N,C)?N:C}),n(N=>{const C=c?0:aj(N,v,y);return N===C?N:C}),i(N=>{const C=c?[]:oj(N,v,m.groupCount);return rj(N,C)?N:C})},[m,c,r,a,n,i]);const S=l.useMemo(()=>{const y=Array.from({length:g},()=>[]);for(const v of u){const N=f.get(v.tabKey)??0,C=Math.min(N,g-1);y[C].push(v)}return y},[u,f,g]),j=l.useCallback(()=>{t(new Map),n(0)},[t,n]);return{containerRef:d,normalizedGroupAssignments:f,numGroups:g,isSplitMode:w,groupedConvs:S,moveTabToGroup:h,closeGroup:x,handleResizeStart:k,splitTabRelative:b,clearAllSplits:j}}function po(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 lj(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 Ir(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function tl(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},n=po(t.channel)||po(e.updateChannel)||po(e.releaseChannel)||void 0,r=lj(t.npmTag)||(n==="preview"?"next":n==="stable"?"latest":void 0),a=Ir(t.targetVersion)||Ir(e.serverVersion)||void 0,o=Ir(t.minVersion)||void 0,i=Ir(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 dn(e,t=null){return tl(e).targetVersion||t}function Kp(e){return tl(e).channel||null}function Vp(e){const t=tl(e);return{...t.channel?{channel:t.channel}:{},...t.npmTag?{npmTag:t.npmTag}:{},...t.targetVersion?{targetVersion:t.targetVersion}:{},...Object.keys(t).length>0?{updatePolicy:t}:{}}}function cj({ides:e,sendDaemonCommand:t}){const n="1.0.9",r=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:Ji(m,dn(m,n))).sort((m,f)=>Number(tr(f,dn(f,n)))-Number(tr(m,dn(m,n)))),[n,e]),a=l.useMemo(()=>r.some(m=>tr(m,dn(m,n))),[n,r]),o=l.useMemo(()=>r.map(m=>dn(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 g,w;const f=e.find(h=>h.id===m);if(f){p(h=>({...h,[m]:"upgrading"}));try{const h=await t(m,"daemon_upgrade",Vp(f));(g=h==null?void 0:h.result)!=null&&g.upgraded||(w=h==null?void 0:h.result)!=null&&w.success?p(x=>({...x,[m]:"done"})):p(x=>({...x,[m]:"error"}))}catch{p(h=>({...h,[m]:"error"}))}}},[e,t]);return{versionMismatchDaemons:r,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:u,handleBannerUpgrade:d}}const Yp=80;function Yr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function dj(e){return{...e,createdAt:Yr(e.createdAt),updatedAt:Yr(e.updatedAt,e.createdAt),lastEventAt:Yr(e.lastEventAt,e.updatedAt||e.createdAt)}}function uj(e){const t=wu(e);return t==="unknown:"?e.id:t}function pj(e){return[e.type,yu(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function mj(e,t=Yp){const n=new Map;for(const r of e){if(r.deletedAt)continue;const a=uj(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 hj(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=Na(a,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const u=Yr(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,n),p=pj({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(dj({id:p,dedupKey:p,type:c,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Ou(a),preview:o0(a),createdAt:u,updatedAt:u,lastEventAt:u}))}return mj(r)}function fj(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function bj(e){const{conversations:t,liveSessionInboxState:n,maxItems:r=Yp}=e,a=l.useMemo(()=>hj(t,n).slice(0,Math.max(0,r)),[t,n,r]),o=l.useMemo(()=>fj(a),[a]);return{notifications:a,unreadCount:o}}function gj({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 sl(...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 xj(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 nl(e,t=[]){if(e==="win32"){for(const n of t){if(typeof n!="string")continue;const r=xj(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 rl(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 Bc(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 Jp(e,t={}){const n=e==null?void 0:e.mcpConfig;if((n==null?void 0:n.mode)!=="manual")return null;const a=Bc(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:Bc(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"})}}function wj(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 dr(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Qp(e){return Ma(e)||e.tabKey||e.routeId||null}function Xp(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=cs(e.conversations,r)||e.conversations.find(i=>i.routeId===r);if(o!=null&&o.tabKey)return o.tabKey}return t||n||r||null}function Ns(e){return String(e||"").trim()}function Zp(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function xa(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function kj(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function Sj(e,t){const n=Ns(e.providerSessionId),r=Ns(e.targetSessionId),a=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(Ns).filter(Boolean);return!!(n&&i.includes(n)||r&&i.includes(r))});return a?a.tabKey:r||n||null}function Cj(e,t,n){if(t.event!=="agent:generating_completed")return null;const r=Zp(t.daemonId);if(r&&r!==e.machineId)return null;const a=Ns(t.providerType);if(e.providerType&&a!==e.providerType)return null;const o=Ns(e.resumeSessionId),i=Ns(e.launchedSessionId),c=Ns(t.providerSessionId),u=Ns(t.targetSessionId);if(o&&o!==c&&o!==u||i&&i!==c&&i!==u)return null;const p=xa(e.workspacePath);if(p){const d=xa(t.workspaceName);if(d&&!kj(d,p))return null}return Sj(t,n)}function Oc(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function jj({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=xa(r.workspacePath),p=e.find(m=>{var x,k,b,S;if(!m||m.type==="adhdev-daemon"||Zp(m.daemonId||m.id)!==r.machineId||(ir(m)?"cli":mn(m)?"acp":"ide")!==r.kind)return!1;const w=String(m.agentType||m.type||"");if(r.providerType&&w!==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=xa(m.workspace||m.runtimeWorkspaceLabel);return j?j===u:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((S=(b=(k=(x=m.activeChat)==null?void 0:x.messages)==null?void 0:k.at)==null?void 0:b.call(k,-1))==null?void 0:S.timestamp)||0)>=r.startedAt-5e3});if(!p)return;const d=Xp({entrySessionId:p.sessionId,entryInstanceId:p.instanceId,entryRouteId:p.id,conversations:t});d&&(i(),n(d))},[i,t,e,n,r]),l.useEffect(()=>mt.onStatusEvent(u=>{const p=o.current;if(!p)return;const d=Cj(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 Nj({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:n,activeConv:r,ides:a,setCliViewModeOverrides:o}){const i=Bi(),{launchCli:c}=ka(),u=l.useCallback(async(x,k)=>rl(e,x,k),[e]),p=l.useCallback(async(x,k)=>{if(!k.trim())return{ok:!1,error:"Choose a workspace path first."};try{const b=await e(x,"workspace_add",{path:k.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,k,b)=>{var S;try{const j={ideType:k,enableCdp:!0};(S=b==null?void 0:b.workspacePath)!=null&&S.trim()&&(j.workspace=b.workspacePath.trim());const y=await e(x,"launch_ide",j);return!(y!=null&&y.success)&&(y==null?void 0:y.success)!==void 0?{ok:!1,error:(y==null?void 0:y.error)||"Could not launch IDE"}:(t({machineId:x,kind:"ide",providerType:k,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,k,b,S)=>{var y,v,N,C;const j=Date.now();try{const A={cliType:b};(y=S==null?void 0:S.workspacePath)!=null&&y.trim()?A.dir=S.workspacePath.trim():S!=null&&S.workspaceId?A.workspaceId=S.workspaceId:S!=null&&S.useHome&&(A.useHome=!0),(v=S==null?void 0:S.resumeSessionId)!=null&&v.trim()&&(A.resumeSessionId=S.resumeSessionId.trim()),Array.isArray(S==null?void 0:S.cliArgs)&&S.cliArgs.length>0&&(A.cliArgs=S.cliArgs),(N=S==null?void 0:S.initialModel)!=null&&N.trim()&&(A.initialModel=S.initialModel.trim()),(C=S==null?void 0:S.initialThinkingLevel)!=null&&C.trim()&&(A.initialThinkingLevel=S.initialThinkingLevel.trim());const M=await c(x,A),T=(M==null?void 0:M.result)||M,R=(T==null?void 0:T.sessionId)||(T==null?void 0:T.id);return M!=null&&M.success&&R?(t({machineId:x,kind:k,providerType:b,workspacePath:(S==null?void 0:S.workspacePath)||null,resumeSessionId:(S==null?void 0:S.resumeSessionId)||null,launchedSessionId:R,startedAt:j}),{ok:!0}):M!=null&&M.success?(t({machineId:x,kind:k,providerType:b,workspacePath:(S==null?void 0:S.workspacePath)||null,resumeSessionId:(S==null?void 0:S.resumeSessionId)||null,startedAt:j}),{ok:!0}):{ok:!1,error:(M==null?void 0:M.error)||(T==null?void 0:T.error)||`Could not launch ${k.toUpperCase()} session`,code:(M==null?void 0:M.code)||(T==null?void 0:T.code)||void 0}}catch(A){return Oc(A)?(t({machineId:x,kind:k,providerType:b,workspacePath:(S==null?void 0:S.workspacePath)||null,resumeSessionId:(S==null?void 0:S.resumeSessionId)||null,startedAt:j}),{ok:!0}):{ok:!1,error:A instanceof Error?A.message:`Could not launch ${k.toUpperCase()} session`}}},[c,e,t]),f=l.useCallback(async x=>{var k;if(i!=null&&i.listMeshes)return i.listMeshes(x);if(!x)return[];try{const b=await e(x,"list_meshes",{}),S=(b==null?void 0:b.result)??b;if((S==null?void 0:S.success)===!1)throw new Error((S==null?void 0:S.error)||"Could not load meshes");return(Array.isArray(S==null?void 0:S.meshes)?S.meshes:Array.isArray((k=S==null?void 0:S.result)==null?void 0:k.meshes)?S.result.meshes:[]).map(y=>{var v;return{id:String((y==null?void 0:y.id)||""),name:String((y==null?void 0:y.name)||(y==null?void 0:y.id)||"Untitled mesh"),repoIdentity:(y==null?void 0:y.repoIdentity)||(y==null?void 0:y.repo_identity)||null,workspace:Array.isArray(y==null?void 0:y.nodes)&&y.nodes.length>0?String(((v=y.nodes[0])==null?void 0:v.workspace)||""):null,nodesCount:Array.isArray(y==null?void 0:y.nodes)?y.nodes.length:void 0,status:(y==null?void 0:y.status)||null}}).filter(y=>y.id)}catch(b){throw console.error("List meshes failed",b),b}},[i,e]),g=l.useCallback(async(x,k,b,S)=>{var y,v;if(!k.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(x,k,b,S);const j=Date.now();try{const N={meshId:k.trim()};b.trim()&&(N.cliType=b.trim());const C=(y=S==null?void 0:S.initialModel)==null?void 0:y.trim(),A=(v=S==null?void 0:S.initialThinkingLevel)==null?void 0:v.trim();C&&(N.initialModel=C),A&&(N.initialThinkingLevel=A);const M=await e(x,"launch_mesh_coordinator",N),T=(M==null?void 0:M.result)??M;if((T==null?void 0:T.success)===!1||(M==null?void 0:M.success)===!1){const E=String((T==null?void 0:T.code)||(M==null?void 0:M.code)||""),_=wj((T==null?void 0:T.meshCoordinatorSetup)||(T==null?void 0:T.manualSetup)||(M==null?void 0:M.meshCoordinatorSetup)||(M==null?void 0:M.manualSetup));return{ok:!1,error:(T==null?void 0:T.error)||(M==null?void 0:M.error)||"Could not launch mesh coordinator",code:E||void 0,manualSetup:_}}const R=(T==null?void 0:T.sessionId)||(T==null?void 0:T.id);return R?n(R):t({machineId:x,kind:"cli",providerType:(T==null?void 0:T.cliType)||b.trim()||void 0,workspacePath:(T==null?void 0:T.workspace)||null,startedAt:j}),{ok:!0}}catch(N){return Oc(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]),w=l.useCallback(async(x,k)=>{if(!x||!k)return[];try{const b=await e(x,"list_saved_sessions",{providerType:k,kind:"cli",limit:30}),S=(b==null?void 0:b.result)??b;return Array.isArray(S==null?void 0:S.sessions)?S.sessions:[]}catch(b){return console.error("List saved sessions failed",b),[]}},[e]),h=l.useCallback(async x=>{await Bp({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:w,setActiveCliViewMode:h}}function Aj(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 Mj(e,t,n=Date.now()){return!e||!Aj(t)?null:{tabKey:e,nonce:n}}function Tj({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,k;if(!e){if(c){const b=t.find(S=>S.tabKey===c);if(b)return b}return n[0]}const h=r[a];if(h){const b=t.find(S=>S.tabKey===h);if(b)return b}return((x=o[a])==null?void 0:x[0])||((k=o[0])==null?void 0:k[0])},[t,c,a,r,o,e,n]),f=l.useCallback(h=>{u(h)},[]),g=l.useCallback(h=>{u(h.tabKey),i(x=>{const k=new URLSearchParams(x),b=l0(h);return b?k.set("activeTab",b):k.delete("activeTab"),k},{replace:!0})},[i]),w=l.useCallback((h,x)=>{const k=Mj(h,x);k&&d(k)},[]);return{activeConv:m,openDesktopConversation:g,requestScrollToBottom:w,scrollToBottomRequest:p,setDesktopActiveTab:f}}function Pj(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 Ij(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 Dj({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=Is(e,n),m=Ij({tabKey:e.tabKey,historySessionId:Ma(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:Ks(e),liveState:d}),f=m.autoReadKey,g=Pj({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 w=()=>{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(w,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(w,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 Lj({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:n,ides:r,sendDaemonCommand:a,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:u}){var W;const{launchCli:p}=ka(),[d,m]=l.useState(!1),[f,g]=l.useState([]),[w,h]=l.useState(()=>Ft()),[x,k]=l.useState(!1),[b,S]=l.useState(null),j=l.useRef(null),y=l.useMemo(()=>n||t||e,[e,n,t]),v=!!y&&ct(y)&&!lt(y),N=l.useMemo(()=>{if(!y||!v)return null;const L=y.daemonId||y.routeId||"",P=bs(y),$=mo(y);return`${L}:${P}:${y.providerSessionId||""}:${$}`},[y,v]),C=l.useMemo(()=>!y||!v?"":mo(y),[y,v]),{isCreatingChat:A,isRefreshingHistory:M,handleSwitchSession:T,handleNewChat:R,handleRefreshHistory:E}=zp({sendDaemonCommand:a,activeConv:y,chats:(W=r.find(L=>L.id===(y==null?void 0:y.routeId)))==null?void 0:W.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),_=l.useCallback(()=>{m(!0)},[]),z=l.useCallback(()=>{m(!1)},[]),F=l.useCallback(async()=>{if(!(!y||!v||x)){k(!0);try{const L=y.daemonId||y.routeId,P=bs(y),$=mo(y),I=await a(L,"list_saved_sessions",{agentType:P,providerType:P,kind:"cli",limit:50,...y.providerSessionId?{providerSessionId:y.providerSessionId}:{},...$?{workspace:$}:{}}),U=(I==null?void 0:I.result)??I;g(Array.isArray(U==null?void 0:U.sessions)?U.sessions:[])}catch(L){console.error("Refresh saved sessions failed",L),g([])}finally{k(!1)}}},[y,x,v,a]);l.useEffect(()=>{if(!d){j.current=null;return}if(!v){j.current=null,g([]),k(!1);return}!N||x||j.current!==N&&(j.current=N,F())},[F,d,x,v,N]);const D=l.useCallback(async L=>{if(!y||!v||!L.providerSessionId||!L.workspace)return;const P=y.daemonId||y.routeId,$=bs(y);try{S(L.providerSessionId);const I=await p(P,{cliType:$,dir:L.workspace,resumeSessionId:L.providerSessionId,initialModel:Nu(L.summaryMetadata,"model",{preferShortValue:!0})||void 0}),U=(I==null?void 0:I.result)??I,J=typeof(U==null?void 0:U.sessionId)=="string"?U.sessionId:typeof(U==null?void 0:U.id)=="string"?U.id:"";J&&u(re=>{const Y=new URLSearchParams(re);return Y.set("activeTab",J),Y},{replace:!0}),z()}catch(I){console.error("Resume saved session failed",I)}finally{S(null)}},[z,y,v,a,u]);return{historyModalOpen:d,openHistoryModal:_,closeHistoryModal:z,historyTargetConv:y,isSavedSessionHistoryTarget:v,isHistoryCreatingChat:A,isHistoryRefreshingHistory:M,handleHistorySwitchSession:T,handleHistoryNewChat:R,handleHistoryRefresh:E,savedHistorySessions:f,savedHistoryFilters:w,setSavedHistoryFilters:h,missingWorkspaceResumePath:C,isSavedHistoryLoading:x,resumingSavedHistorySessionId:b,handleRefreshSavedHistory:F,handleResumeSavedHistorySession:D}}function Rj({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 k=c(r);return k&&!ct(k)&&!lt(k)?k:null},[e,r,c]),g=l.useMemo(()=>{const k=u==null?void 0:u.routeId;if(!k)return null;const b=u!=null&&u.tabKey?o.find(S=>S.tabKey===u.tabKey):a?o.find(S=>S.tabKey===a):null;return(b==null?void 0:b.routeId)===k?b:cs(o,k)},[o,u,a]),w=l.useMemo(()=>{if(g)return i.find(k=>k.id===g.routeId)},[i,g]);l.useEffect(()=>{f&&(p({routeId:f.routeId,tabKey:nc(f)}),m(f),n({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,n,f]);const h=l.useCallback(k=>{k&&(p({routeId:k.routeId,tabKey:nc(k)}),m(k))},[]),x=l.useCallback(()=>{p(null),m(null)},[]);return{remoteDialogConv:g,remoteDialogIdeEntry:w,remoteDialogActiveConv:d,setRemoteDialogActiveConv:m,openRemoteDialog:h,closeRemoteDialog:x}}function Ej({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:w,closeRemoteDialog:h}=Rj({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}),[x,k]=l.useState(!1),[b,S]=l.useState(null),j=l.useCallback(async N=>{const C=N||u;!C||!ct(C)&&!lt(C)||(S(C),k(!0))},[u]),y=l.useCallback(()=>{k(!1),S(null)},[]),v=l.useCallback(async N=>{const C=b||u;if(!C||!ct(C)&&!lt(C)){y();return}k(!1);try{const A=bs(C),M=C.routeId||C.daemonId||"";await p(M,"stop_cli",{cliType:A,targetSessionId:C.sessionId,mode:N,...Ia(C)})}catch(A){console.error("Stop CLI failed:",A)}finally{S(null)}},[u,y,b,p]);return{remoteDialogConv:d,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:g,openRemoteDialog:w,closeRemoteDialog:h,cliStopDialogOpen:x,cliStopTargetConv:b,requestCliStop:j,cancelCliStop:y,confirmCliStop:v}}function ho(e,t=!0){return(e??!0)&&t}const al=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:w,userName:h,scrollToBottomRequestNonce:x,isInputActive:k=!0,isVisible:b=!0}){const S=r,j=!r,y=ho(b,S),v=ho(b,j),N=ho(b),C=$p(t),A=C.status||C.modalMessage||C.modalButtons?{...t,...C.status?{status:C.status}:{},...C.modalMessage!==void 0?{modalMessage:C.modalMessage}:{},...C.modalButtons!==void 0?{modalButtons:C.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(gu,{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(Ys,{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:S?"visible":"hidden",pointerEvents:S?"auto":"none"},children:s.jsx(Bk,{activeConv:A,clearToken:n,terminalRef:o,handleSendChat:u,isSendingChat:d,sendFeedbackMessage:m,isVisible:y,isInputActive:k&&y})}),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(oi,{activeConv:A,ideEntry:a,handleSendChat:u,isSendingChat:d,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:w,userName:h,scrollToBottomRequestNonce:x,isInputActive:k&&v,isVisible:v})})]}):s.jsx(oi,{activeConv:A,ideEntry:a,handleSendChat:u,handleForceSendChat:p,isSendingChat:d,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:w,userName:h,scrollToBottomRequestNonce:x,isInputActive:k&&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 _j({conversation:e,className:t="",onOpenNativeConversation:n,onOpenMachine:r,interactive:a=!0,meshOnly:o=!1}){var j,y,v;const{t:i}=Ne("common"),c=mr(),u=Ds(e),p=o?null:Bu(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=vn(e),w=i0(e),h=(j=e.settings)==null?void 0:j.meshNodeFor,x=e.meshQueueStats,k=((y=e.coordinator)==null?void 0:y.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]),S=l.useCallback(()=>{if(n){n();return}const N=Qp(e);N&&c(dr(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:S,title:w,children:[s.jsx(us,{size:12}),s.jsx("span",{children:w})]}):s.jsxs("span",{className:"conversation-meta-chip",title:w,children:[s.jsx(us,{size:12}),s.jsx("span",{children:w})]})),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(or,{size:12}),s.jsx("span",{children:g})]}),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(or,{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(Ts,{size:12}),s.jsx("span",{children:p})]}):s.jsxs("span",{className:"conversation-meta-chip",title:p,children:[s.jsx(Ts,{size:12}),s.jsx("span",{children:p})]})),h&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(Ts,{size:12}),s.jsx("span",{children:i("dashboard.metaChips.meshNode")})]}),k&&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($f,{size:12}),s.jsxs("span",{children:[x.pending," Pending"]})]})]})}function $j({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:w,onStopCli:h,cliViewMode:x,onSetCliViewMode:k,handleSendChat:b,handleForceSendChat:S,handleFocusAgent:j,handleModalButton:y,handleRelaunch:v}){var R,E;const N=l.useRef(null),C=ct(e)&&!t,A=C&&x==="terminal",M=!!e.daemonId&&!!((R=e.coordinator)!=null&&R.meshId||(E=e.settings)!=null&&E.meshCoordinatorFor),T=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 ${T} 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(Ai,{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:xt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(_j,{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:[C&&x&&s.jsx(bp,{mode:x,onChange:k,compact:!0}),C&&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(At,{size:14})}),M&&w&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>w(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(es,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:s.jsx(Ti,{size:14})}),!t&&!C&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:s.jsx(us,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(al,{activeConv:e,clearToken:0,isCliTerminal:A,ideEntry:r,terminalRef:N,handleModalButton:y,handleRelaunch:v,handleSendChat:b,handleForceSendChat:S,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:j,isFocusingAgent:u,actionLogs:a,userName:o})})]})}const fo={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 Hj(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function em(){const[e,t]=l.useState("unix"),[n,r]=l.useState("powershell"),[a,o]=l.useState(!1),i=e==="unix"?"unix":n;l.useEffect(()=>{t(Hj())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(fo[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:fo[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:fo[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 tm({section:e,onSectionChange:t}){const n=[{key:"machines",label:"Machines",icon:us},{key:"chats",label:"Chats",icon:Zs}];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 Dr({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 nn({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 On({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 Fj({conversation:e,onCancel:t,onConfirm:n}){const{t:r}=Ne(),a=xt(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 Lr({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",w=t==="task_complete",{isReconnecting:h,isConnecting:x}=An(e.conversation),k=xt(e.conversation),b=yn(e.conversation),S=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",y=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",C=g?"text-text-secondary opacity-80":"text-text-muted",A=g?"text-text-muted opacity-80":"text-text-muted",M=!f&&!w,T=dp(e.conversation),R="text-[color:var(--status-warning)]",E=_=>{if(!c)return;_.preventDefault(),_.stopPropagation();const z=c==null?void 0:c(e.conversation);Promise.resolve(z).catch(F=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",F)})};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 ${y}`,style:m?{color:"var(--accent-on-primary)"}:void 0,children:n(k)}),T&&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:k}),title:d("mobileInbox.openLiveMeshGraph"),children:s.jsx(es,{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:E,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:k})}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${N}`,children:[s.jsx("span",{className:"truncate",children:b}),s.jsx(da,{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:`${R} 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")})]}):S==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:R,children:d("mobileInbox.actionNeeded")})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${C}`,children:e.preview})]}),s.jsxs("div",{className:"mobile-inbox-corner-actions absolute top-3 right-3 flex items-center gap-1.5",children:[M&&s.jsx("span",{className:`mr-0.5 text-[11px] font-medium shrink-0 ${A}`,children:fu(e.timestamp)}),w&&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:k}):d("mobileInbox.mute",{title:k}),title:d(u?"mobileInbox.mutedTitle":"mobileInbox.muteNotifications"),children:u?s.jsx(nu,{size:13}):s.jsx(Nn,{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:k}),title:d("mobileInbox.hideConversationTitle"),children:s.jsx(Pi,{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:k}),title:d("mobileInbox.stopSessionTitle"),children:s.jsx(At,{size:13})})]})]})},e.conversation.tabKey)}function Wc({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 Bj({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:w,onOpenNewSession:h,onOpenMachine:x,onOpenSettings:k,onSectionChange:b,wsStatus:S="connected",isStandalone:j=!1,onCollectChatDebugBundle:y,isConversationMuted:v,onToggleMuteConversation:N}){const{t:C}=Ne(),[A,M]=l.useState(null),T=S==="disconnected"||S==="reconnecting"||S==="offline"||S==="auth_failed",R=i.length>0,E=t.length>0||n.length>0||r.length>0||a.length>0,_=C(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),z=j?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",F=j?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",D=l.useCallback(async P=>{const $=Us(P);if(!$)return;const I=Array.isArray(P.messages)?P.messages:[],U=zu({activeConv:P,visibleMessages:I,actionLogs:u,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:I.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),J=await p($,"get_chat_debug_bundle",{...Ws(P),delivery:"daemon_file",frontendSnapshot:U}),re=er(J),Y=Yu(re),X=await Vu(Y);X==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),mt.showToast(Ku(re,{locatorCopyStatus:X}),X==="failed"?"warning":"success")},[u,p]),W=y||D,L=l.useCallback(()=>{A&&(f==null||f(A),M(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 ${z}`,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(Nn,{size:13}),s.jsx("span",{children:t.length+n.length})]}),s.jsx("button",{onClick:k,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(Sa,{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] ${F}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:T?s.jsx(On,{icon:s.jsx(Wc,{}),title:C(S==="offline"?"mobileInbox.networkOffline":S==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:C(S==="offline"?"mobileInbox.waitingForNetwork":S==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):i.length===0?s.jsx(On,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:C(j?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:C(j?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!j&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(em,{})})}):s.jsx(nn,{children:i.map((P,$)=>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] ${$>0?"border-t border-border-subtle/70":""}`,onClick:()=>x(P.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(P.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:P.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:P.unread>0?s.jsx("span",{className:"text-accent-primary",children:C("mobileInbox.newCount",{count:P.unread})}):P.total>0?C("mobileInbox.chatCount",{count:P.total}):C("mobileInbox.idle")})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:P.subtitle}),P.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[C("mobileInbox.chatCount",{count:P.total}),P.unread>0?C("mobileInbox.unreadSuffix",{count:P.unread}):""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:C("mobileInbox.noActiveChats")})]})]},P.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(Dr,{title:C("mobileInbox.needsAttention"),className:"mb-0"}),s.jsx(nn,{children:t.map((P,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Lr,{item:P,type:"needs_attention",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>M(P.conversation):void 0,onRequestStopCli:w?()=>w(P.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:W,isMuted:v==null?void 0:v(P.conversation),onToggleMute:N?()=>N(P.conversation):void 0})},P.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(Dr,{title:C("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),s.jsx(nn,{children:n.map((P,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Lr,{item:P,type:"task_complete",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>M(P.conversation):void 0,onRequestStopCli:w?()=>w(P.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:W,isMuted:v==null?void 0:v(P.conversation),onToggleMute:N?()=>N(P.conversation):void 0})},P.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(Dr,{title:C("mobileInbox.workingNow"),className:"mb-0 mt-2"}),s.jsx(nn,{children:r.map((P,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Lr,{item:P,type:"working",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>M(P.conversation):void 0,onRequestStopCli:w?()=>w(P.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:W,isMuted:v==null?void 0:v(P.conversation),onToggleMute:N?()=>N(P.conversation):void 0})},P.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(Dr,{title:C("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(nn,{children:a.map((P,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Lr,{item:P,type:"earlier",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>M(P.conversation):void 0,onRequestStopCli:w?()=>w(P.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:W,isMuted:v==null?void 0:v(P.conversation),onToggleMute:N?()=>N(P.conversation):void 0})},P.conversation.tabKey))}):E?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:C("mobileInbox.allCaughtUp")}):T?s.jsx(On,{icon:s.jsx(Wc,{size:28}),title:C("mobileInbox.connecting"),subtitle:C("mobileInbox.connectingSubtitle")}):R?s.jsx(On,{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(Zs,{size:20})}),title:C("mobileInbox.noConversations"),subtitle:C("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":C("paneGroup.newSession"),title:C("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:C("paneGroup.newSession")})]})}):s.jsx(On,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:C("mobileInbox.noMachinesConnected"),subtitle:C("mobileInbox.noMachinesSubtitle")})]}),e==="chats"&&o.length>0&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(nn,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:C("mobileInbox.hiddenTabs")}),s.jsx("div",{className:"mt-0.5 text-[13px] text-text-muted",children:C("mobileInbox.collapsedCount",{count:o.length})})]}),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:C("mobileInbox.restoreAll")})]})})})]}),e==="chats"&&h&&E&&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":C("paneGroup.newSession"),title:C("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(Fj,{conversation:A,onCancel:()=>M(null),onConfirm:L}),s.jsx(tm,{section:e,onSectionChange:b})]})}function Oj(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=Js(e.summaryMetadata);n&&t.push(n),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const r=Oj(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:r?`Updated ${r}`:"",preview:(e.preview||"").trim()}}function ol({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),w=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(At,{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(Ai,{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"||!w||a||(h.preventDefault(),u(w))},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:()=>{!w||a||u(w)},disabled:!w||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(xn,{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(w||n),disabled:!w&&!n||a,children:i})]})]})})}function nm({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:w,historyProviderNode:h,onConfirm:x,onCancel:k}){const{t:b}=Ne("common"),S=i??b("machine.launchConfirm.launch"),j=c??b("machine.launchConfirm.launching"),y=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:k,"aria-label":b("machine.launchConfirm.closeAria"),children:s.jsx(At,{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))}),(y==null?void 0:y.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:y.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&&w&&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=>w(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:k,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(su,{size:14}),u?j:S]})]})]})})}function Uc(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function rm(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?"⭐ ":""}${Uc(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:Uc(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 Wj(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Uj(e){return[Wj(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Gj(e){return e.lastLaunchedAt?ja(e.lastLaunchedAt):""}function am(e){return{metaText:Uj(e),updatedLabel:Gj(e)}}function bo(e,t,n){return e?"ide":t>0?"cli":n>0?"acp":null}function qj({selectedMachineEntry:e,cliProviders:t,acpProviders:n,machineAction:r,onBrowseDirectory:a,onListSavedSessions:o}){var he,$e,Be,Pe;const i=Tn(),[c,u]=l.useState(!1),p=(((he=e.detectedIdes)==null?void 0:he.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||(($e=d[0])==null?void 0:$e.id)||""),[w,h]=l.useState(""),[x,k]=l.useState(""),[b,S]=l.useState([]),[j,y]=l.useState(!1),[v,N]=l.useState(""),[C,A]=l.useState(!1),[M,T]=l.useState(bo(p,t.length,n.length)),R=l.useRef(null),[E,_]=l.useState(null),z=l.useRef("__home__"),[F,D]=l.useState("__home__"),[W,L]=l.useState(""),[P,$]=l.useState(""),[I,U]=l.useState(""),[J,re]=l.useState([]),[Y,X]=l.useState(()=>Ft().textQuery),[de,ne]=l.useState(()=>Ft().workspaceQuery),[O,ie]=l.useState(()=>Ft().modelQuery),[K,ae]=l.useState(()=>Ft().resumableOnly),[Ce,ye]=l.useState(()=>Ft().sortMode),[ke,me]=l.useState(!1),[q,G]=l.useState(!1),Z=l.useRef(null),V=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const fe=f==="__custom__"?w.trim():((Be=d.find(ve=>ve.id===f))==null?void 0:Be.path)||"",Te=f==="__custom__"&&!!fe&&r.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(r.message),ce=f!=="__custom__"&&((Pe=d.find(ve=>ve.id===f))==null?void 0:Pe.path)||"",H=l.useMemo(()=>(e.recentLaunches||[]).map(ve=>ve.workspace),[e]),pe=l.useCallback(async ve=>{y(!0),N("");try{const Ue=await a(ve);k(Ue.path),h(Ue.path),S(Ue.directories)}catch(Ue){N(Ue instanceof Error?Ue.message:"Could not load folder")}finally{y(!1)}},[a]),le=l.useCallback(()=>{var Ue;g("__custom__"),A(!0);const ve=nl(e.platform,sl(w.trim(),ce,H,e.defaultWorkspacePath,(Ue=d.find(ut=>ut.id===m))==null?void 0:Ue.path,d.map(ut=>ut.path)));pe(ve)},[w,m,pe,H,ce,e.platform,d]),B=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("")},[]),be=l.useCallback(ve=>{if(g(ve),ve==="__custom__"){le();return}h("")},[le]),je=l.useCallback(ve=>{g("__custom__"),h(ve)},[]),Se=l.useCallback((ve,Ue)=>{R.current=Ue,z.current=ve.selectedWorkspaceKey||"__home__",D(ve.selectedWorkspaceKey||"__home__"),L(ve.initialArgs||""),$(ve.initialModel||""),U(""),re([]);const ut=ve.providerType?`${e.id}:${ve.providerType}`:null;if(Jk(V.current,ut)){const ot=Ft();X(ot.textQuery),ne(ot.workspaceQuery),ie(ot.modelQuery),ae(ot.resumableOnly),ye(ot.sortMode)}V.current=ut,_(ve),ve.providerType&&o&&(me(!0),o(ve.providerType).then(ot=>re(ot||[])).catch(ot=>console.warn("Failed to load saved sessions",ot)).finally(()=>me(!1)))},[o,e.id]),He=l.useMemo(()=>gp(J,{textQuery:Y,workspaceQuery:de,modelQuery:O,resumableOnly:K,sortMode:Ce}),[O,K,J,Ce,Y,de]);l.useEffect(()=>{I&&(He.some(ve=>ve.providerSessionId===I)||U(""))},[He,I]);const Xe=l.useCallback(()=>{R.current&&(G(!0),R.current().finally(()=>{R.current=null,G(!1),_(null)}))},[]),dt=l.useCallback(()=>{R.current=null,_(null)},[]),it=l.useCallback(ve=>{z.current=ve,D(ve)},[]);return l.useEffect(()=>{var ve;Z.current!==e.id&&(Z.current=e.id,g(m||((ve=d[0])==null?void 0:ve.id)||"__custom__"),h(""),k(""),S([]),N(""),A(!1),X(Ft().textQuery),ne(Ft().workspaceQuery),ie(Ft().modelQuery),ae(Ft().resumableOnly),ye(Ft().sortMode),V.current=null,T(bo(p,t.length,n.length)))},[n.length,t.length,m,p,e.id,d]),l.useEffect(()=>{var ve;f!=="__custom__"&&(f&&d.some(Ue=>Ue.id===f)||g(m||((ve=d[0])==null?void 0:ve.id)||"__custom__"))},[m,f,d]),l.useEffect(()=>{M==="ide"&&p||M==="cli"&&t.length>0||M==="acp"&&n.length>0||T(bo(p,t.length,n.length))},[M,n.length,t.length,p]),{showAllRecent:c,setShowAllRecent:u,hasIdeOptions:p,workspaceRows:d,defaultWorkspaceId:m,workspaceChoice:f,customWorkspacePath:w,browseCurrentPath:x,browseDirectories:b,browseBusy:j,browseError:v,browseDialogOpen:C,activeLauncherKind:M,launchConfirm:E,launchConfirmWorkspaceKeyRef:z,launchConfirmWorkspaceKey:F,launchConfirmArgs:W,launchConfirmModel:P,launchConfirmResumeId:I,launchConfirmSavedSessions:J,launchConfirmTextFilter:Y,launchConfirmWorkspaceFilter:de,launchConfirmModelFilter:O,launchConfirmResumableOnly:K,launchConfirmSortMode:Ce,filteredLaunchConfirmSavedSessions:He,launchConfirmSessionsLoading:ke,launchConfirmBusy:q,resolvedWorkspacePath:fe,canCreateMissingWorkspace:Te,openBrowseDialog:le,loadBrowsePath:pe,handleWorkspaceChoiceChange:be,chooseCustomWorkspacePath:je,setCustomWorkspacePath:h,setBrowseDialogOpen:A,setActiveLauncherKind:T,openLaunchConfirm:Se,handleConfirmLaunch:Xe,closeLaunchConfirm:dt,setWorkspaceSelectionFromOption:B,setLaunchConfirmWorkspaceKeyAndSync:it,setLaunchConfirmArgs:L,setLaunchConfirmModel:$,setLaunchConfirmResumeId:U,setLaunchConfirmTextFilter:X,setLaunchConfirmWorkspaceFilter:ne,setLaunchConfirmModelFilter:ie,setLaunchConfirmResumableOnly:ae,setLaunchConfirmSortMode:ye}}function zj({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:w,onOpenMachineDetails:h,onMachineUpgrade:x,onLaunchDetectedIde:k,onAddWorkspace:b,onBrowseDirectory:S,onLaunchWorkspaceProvider:j,onListSavedSessions:y}){const{t:v}=Ne("common"),N=D=>D==="ide"?"IDE":D==="cli"?"CLI":"ACP",C=n.slice(0,4),A=t.slice(0,3),M=qj({selectedMachineEntry:e,cliProviders:r,acpProviders:a,machineAction:c,onBrowseDirectory:S,onListSavedSessions:y}),T=l.useMemo(()=>C.map(D=>{const{metaText:W,updatedLabel:L}=am(D);return{key:`recent-launch:${D.id}`,primary:D.label,secondary:W,updatedLabel:L,onClick:()=>{const{options:P,selectedKey:$}=rm({machine:{workspaces:M.workspaceRows,defaultWorkspaceId:M.defaultWorkspaceId},currentWorkspacePath:D.workspace,homeLabel:v("newSession.homeDirectory"),homeDescription:v("newSession.launchWithoutWorkspace")});M.openLaunchConfirm({title:D.kind==="ide"?ua(v,"restart-ide",D.label):D.providerSessionId?vp(v,D.label):ua(v,"start-fresh",D.label),description:D.kind==="ide"?pa(v,"restart-ide"):D.providerSessionId?yp(v):pa(v,"start-fresh"),confirmLabel:D.kind==="ide"?ma(v,"restart-ide"):D.providerSessionId?ii(v,!0):ma(v,"start-fresh"),busyLabel:D.kind==="ide"?ha(v,"restart-ide"):D.providerSessionId?xp(v,!0):ha(v,"start-fresh"),workspaceOptions:P,selectedWorkspaceKey:$,details:[{label:"Mode",value:N(D.kind)},...D.providerType?[{label:"Provider",value:D.providerType}]:[]]},async()=>{const I=P.find(U=>U.key===M.launchConfirmWorkspaceKeyRef.current);M.setWorkspaceSelectionFromOption(I),await w({...D,workspace:(I==null?void 0:I.workspacePath)??null})})}}}),[M,w,C,v]),R=l.useMemo(()=>A.map(D=>({key:`recent-chat:${D.conversation.tabKey}`,primary:xt(D.conversation),secondary:Nk(D.conversation,{timestampLabel:D.timestamp?fu(D.timestamp):null}),unread:D.unread,onClick:()=>g(D.conversation)})),[g,A]),E=M.showAllRecent?T:T.slice(0,4),_=T.length>0,z=R.length>0,F=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 ${F} 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(Ai,{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:ts(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:[z&&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:R.map(D=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${D.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:D.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:D.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:D.secondary})]},D.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:E.map(D=>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:D.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:D.primary}),D.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:D.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:D.secondary})]},D.key))}),T.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:()=>M.setShowAllRecent(D=>!D),children:M.showAllRecent?"Show fewer":`Show ${T.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"})]})]})]})]}),M.browseDialogOpen&&s.jsx(ol,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:M.browseCurrentPath,directories:M.browseDirectories,busy:M.browseBusy,error:M.browseError,confirmLabel:"Use this folder",onClose:()=>M.setBrowseDialogOpen(!1),onNavigate:D=>{M.loadBrowsePath(D)},onConfirm:D=>{M.chooseCustomWorkspacePath(D),M.setBrowseDialogOpen(!1)}}),M.launchConfirm&&s.jsx(nm,{title:M.launchConfirm.title,description:M.launchConfirm.description,details:M.launchConfirm.details,workspaceOptions:M.launchConfirm.workspaceOptions,selectedWorkspaceKey:M.launchConfirmWorkspaceKey,onWorkspaceChange:M.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:M.launchConfirm.providerType?ii(v,!!M.launchConfirmResumeId):M.launchConfirm.confirmLabel,busyLabel:M.launchConfirm.providerType?void 0:M.launchConfirm.busyLabel,busy:M.launchConfirmBusy,showArgsInput:M.launchConfirm.showArgsInput,argsValue:M.launchConfirmArgs,onArgsChange:M.setLaunchConfirmArgs,showModelInput:M.launchConfirm.showModelInput,modelValue:M.launchConfirmModel,onModelChange:M.setLaunchConfirmModel,historyProviderNode:M.launchConfirm.providerType&&(M.launchConfirmSessionsLoading||M.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"}),M.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:Vi(v)}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:M.launchConfirmTextFilter,onChange:D=>M.setLaunchConfirmTextFilter(D.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:M.launchConfirmBusy||M.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:M.launchConfirmWorkspaceFilter,onChange:D=>M.setLaunchConfirmWorkspaceFilter(D.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:M.launchConfirmBusy||M.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:M.launchConfirmModelFilter,onChange:D=>M.setLaunchConfirmModelFilter(D.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:M.launchConfirmBusy||M.launchConfirmSessionsLoading}),s.jsxs("select",{value:M.launchConfirmSortMode,onChange:D=>M.setLaunchConfirmSortMode(D.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:M.launchConfirmBusy||M.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:M.launchConfirmResumableOnly,onChange:D=>M.setLaunchConfirmResumableOnly(D.target.checked),disabled:M.launchConfirmBusy||M.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:M.launchConfirmResumeId,onChange:D=>M.setLaunchConfirmResumeId(D.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:M.launchConfirmBusy||M.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:Zk(v)}),M.filteredLaunchConfirmSavedSessions.map(D=>s.jsxs("option",{value:D.providerSessionId,disabled:!D.canResume,children:[D.title||D.providerSessionId," ",D.canResume?"":"(workspace missing)"]},D.providerSessionId))]}),!M.launchConfirmSessionsLoading&&M.launchConfirmSavedSessions.length>0&&M.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),M.launchConfirmResumeId&&(()=>{const D=M.filteredLaunchConfirmSavedSessions.find(L=>L.providerSessionId===M.launchConfirmResumeId);if(!D)return null;const W=sm(D);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:W.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:W.providerSessionId}),s.jsx("div",{className:"mt-1",children:W.metaLine}),W.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:W.updatedLabel}),W.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:W.preview})]})})()]}),onConfirm:M.handleConfirmLaunch,onCancel:M.closeLaunchConfirm}),d&&s.jsx(tm,{section:p,onSectionChange:f})]})}const Gc=8e3;function Kj(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 om(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 w=Date.now();let h=!1;for(const[x,k]of g){const b=e.get(x),S=k.muted===void 0||(b?b.muted===k.muted:!1),j=k.hidden===void 0||(b?b.surfaceHidden===k.hidden:!1),y=w-k.at>Gc;(S&&j||y)&&(g.delete(x),h=!0)}h&&o()},[e,o]),l.useEffect(()=>{if(r.current.size===0)return;const g=setInterval(()=>{const w=r.current,h=Date.now();let x=!1;for(const[k,b]of w)h-b.at>Gc&&(w.delete(k),x=!0);x&&o(),w.size===0&&clearInterval(g)},1e3);return()=>clearInterval(g)});const i=l.useCallback((g,w)=>{const h=r.current.get(g);r.current.set(g,{...h,...w,at:Date.now()}),o()},[o]),c=l.useCallback(g=>{const w=g.sessionId,h=w?r.current.get(w):void 0;return(h==null?void 0:h.muted)!==void 0?h.muted:Is(g,e).muted??!1},[e]),u=l.useCallback(g=>{const w=g.sessionId,h=w?r.current.get(w):void 0;return(h==null?void 0:h.hidden)!==void 0?h.hidden:Is(g,e).surfaceHidden??!1},[e]),p=l.useCallback((g,w)=>{const h=Ds(g),x=g.sessionId;!h||!x||(i(x,w),t(h,"set_conversation_prefs",{sessionId:x,...w,...Ia(g)}).then(k=>{const b=Kj(k);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(k=>{console.warn("[conversation-prefs] set_conversation_prefs failed",k),r.current.delete(x),o();const b=k instanceof Error?k.message:String(k??"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,w)=>{p(g,{hidden:w})},[p]),f=l.useCallback(g=>{p(g,{hidden:!u(g)})},[p,u]);return{isMuted:c,isHidden:u,toggleMute:d,setHidden:m,toggleHidden:f}}function Jr(e){return[...e].sort((t,n)=>{const r=n.timestamp-t.timestamp;return r!==0?r:t.conversation.tabKey.localeCompare(n.conversation.tabKey)})}function Vj(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:Jr(e)}function Yj(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 Jj(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:Js(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=ir(r)?"cli":mn(r)?"acp":"ide",o=Js(r.summaryMetadata);return{id:`${a}:${r.type}:${r.workspace||""}`,label:((i=r.activeChat)==null?void 0:i.title)||(ir(r)?r.cliName||r.type:mn(r)&&r.cliName||r.type),kind:a,providerType:r.type,providerSessionId:r.providerSessionId,subtitle:mn(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 Qj(e,t){const n=new Map;for(const r of t){const a=Ds(r.conversation),o=n.get(a);o?o.push(r):n.set(a,[r])}return e.map(r=>{const a=n.get(r.id)||[],o=[...a].sort((m,f)=>f.timestamp-m.timestamp)[0]||null,i=(o==null?void 0:o.conversation)||null,c=ei(r),u=a.filter(m=>m.unread||m.requiresAction).length,p=Yj(r),d=[r.platform||"machine",p].filter(Boolean);return{id:r.id,label:ts(r,{fallbackId:r.id}),subtitle:d.join(" · "),unread:u,total:a.length,latestConversation:i,latestTimestamp:(o==null?void 0:o.timestamp)||0,fallbackActivityAt:c,preview:i?Ak(i,rp(i)):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((r,a)=>{const o=r.latestTimestamp||r.fallbackActivityAt||0,i=a.latestTimestamp||a.fallbackActivityAt||0;return i!==o?i-o:r.label.localeCompare(a.label)})}function Xj(e){return e==="chat"}function Rr(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 Zj({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:w,setScreen:h,setSelectedMachineId:x,setSection:k,setMachineBackTarget:b,resetMachineAction:S}){const j=l.useRef(null),y=l.useCallback(v=>{if(!(v!=null&&v.sessionId))return;const N=Is(v,i),C=Math.max(Date.now(),Ks(v),N.lastUpdated||0);Rr("mark_read:start",{tabKey:v.tabKey,sessionId:v.sessionId,displayPrimary:xt(v),inboxBucket:N.inboxBucket,unread:N.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:Ks(v),readAt:C}),c(Ds(v)||v.routeId,"mark_session_seen",{sessionId:v.sessionId,providerSessionId:v.providerSessionId,seenAt:C,completionMarker:N.completionMarker}).then(A=>{Rr("mark_read:result",{tabKey:v.tabKey,sessionId:v.sessionId,result:A})}).catch(A=>{Rr("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){Xj(o)&&h("inbox"),w(((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,y(r))},[e,y,o,r,h,w]),l.useEffect(()=>{if(!u)return;const v=e.find(N=>N.tabKey===u);v&&(w(v.tabKey),h("chat"),p==null||p())},[e,p,u,h,w]),l.useEffect(()=>{if(!d)return;const v=t.find(N=>N.id===d);v&&(x(v.id),S(),k("machines"),b("inbox"),h("machine"),m==null||m())},[t,m,d,S,b,h,k,x]),l.useEffect(()=>{f&&(k(f),h("inbox"),g==null||g())},[g,f,h,k]),l.useEffect(()=>{const v=n.filter(N=>N.inboxBucket==="task_complete"||N.unread);v.length!==0&&Rr("inbox_state",{screen:o,selectedTabKey:a,items:v.map(N=>{const C=Is(N.conversation,i);return{liveState:C,tabKey:N.conversation.tabKey,sessionId:N.conversation.sessionId,displayPrimary:xt(N.conversation),serverBucket:C.inboxBucket,computedBucket:N.inboxBucket,serverUnread:C.unread,computedUnread:N.unread,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,activityAt:Ks(N.conversation)}})})},[n,i,o,a]),{markConversationRead:y}}function e1(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function qc(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function t1(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function s1({sendDaemonCommand:e,navigate:t,ides:n,conversations:r}){const{launchCli:a}=ka(),[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(S,j,y)=>{var v;try{i("loading"),u(`Launching ${j}…`);const N={ideType:j,enableCdp:!0};(v=y==null?void 0:y.workspacePath)!=null&&v.trim()&&(N.workspace=y.workspacePath.trim()),await e(S,"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(S,j,y)=>{if(j.trim())try{i("loading"),u(y!=null&&y.createIfMissing?"Creating folder…":"Saving workspace…");const v=await e(S,"workspace_add",{path:j.trim(),createIfMissing:(y==null?void 0:y.createIfMissing)===!0});if(v!=null&&v.success){i("done"),u(y!=null&&y.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]),w=l.useCallback(async S=>{var j,y,v,N,C,A;try{i("loading"),u("Starting daemon upgrade…");const M=await e(S,"daemon_upgrade",{});if((j=M==null?void 0:M.result)!=null&&j.alreadyLatest){i("done"),u(`Already on v${((y=M==null?void 0:M.result)==null?void 0:y.version)||"latest"}.`);return}if((v=M==null?void 0:M.result)!=null&&v.upgraded||(N=M==null?void 0:M.result)!=null&&N.success){i("done"),u(`Upgrade to v${((C=M==null?void 0:M.result)==null?void 0:C.version)||"latest"} started. Daemon is restarting…`);return}i("error"),u(((A=M==null?void 0:M.result)==null?void 0:A.error)||"Upgrade failed")}catch(M){i("error"),u(M instanceof Error?M.message:"Upgrade failed")}},[e]),h=l.useCallback(async(S,j,y,v)=>{var A,M,T;const N=Date.now(),C={machineId:S,kind:j,providerType:y,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 ${y}…`),d(C);const R={cliType:y};(A=v==null?void 0:v.workspacePath)!=null&&A.trim()?R.dir=v.workspacePath.trim():v!=null&&v.workspaceId?R.workspaceId=v.workspaceId:v!=null&&v.useHome&&(R.useHome=!0),v!=null&&v.resumeSessionId&&(R.resumeSessionId=v.resumeSessionId),(M=v==null?void 0:v.args)!=null&&M.trim()&&(R.cliArgs=v.args.trim().split(/\s+/).filter(Boolean)),(T=v==null?void 0:v.model)!=null&&T.trim()&&(R.initialModel=v.model.trim());const E=await a(S,R),_=(E==null?void 0:E.result)||E,z=(_==null?void 0:_.sessionId)||(_==null?void 0:_.id);if(E!=null&&E.success&&z){d(null),i("done"),u(`${y} launched`),t(dr(z));return}if(E!=null&&E.success){i("loading"),u(`${y} launch requested — waiting for session…`);return}d(null),i("error"),u((E==null?void 0:E.error)||(_==null?void 0:_.error)||`Could not launch ${j.toUpperCase()} workspace`)}catch(R){if(t1(R)){i("loading"),u(`${y} launch requested — waiting for session…`);return}d(null),i("error"),u(R instanceof Error?R.message:`Could not launch ${j.toUpperCase()} workspace`)}},[t,e]),x=l.useCallback(async(S,j)=>{try{const y=await e(S,"list_saved_sessions",{providerType:j,kind:"cli",limit:30}),v=(y==null?void 0:y.result)??y;return Array.isArray(v==null?void 0:v.sessions)?v.sessions:[]}catch(y){return console.error("Failed to list saved sessions on mobile:",y),[]}},[e]),k=l.useCallback(async(S,j)=>rl(e,S,j),[e]);l.useEffect(()=>{if(!p)return;const S=qc(p.workspacePath),j=n.find(v=>{var R,E,_,z;if(!v||v.type==="adhdev-daemon"||e1(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 M=String(v.providerSessionId||"");if(p.resumeSessionId&&M)return M===p.resumeSessionId;if(S){const F=qc(v.workspace||v.runtimeWorkspaceLabel);return F?F===S:!1}return Number(v.lastUpdated||v._lastUpdate||v.timestamp||((z=(_=(E=(R=v.activeChat)==null?void 0:R.messages)==null?void 0:E.at)==null?void 0:_.call(E,-1))==null?void 0:z.timestamp)||0)>=p.startedAt-5e3});if(!j)return;const y=Xp({entrySessionId:j.sessionId,entryInstanceId:j.instanceId,entryRouteId:j.id,conversations:r});y&&(d(null),i("done"),u(`${p.providerType} launched`),t(dr(y)))},[r,n,t,p]),l.useEffect(()=>{if(!p)return;const S=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(S)},[p]);const b=l.useCallback(async(S,j)=>{var y;if(j.kind==="ide"&&j.providerType){await f(S,j.providerType,{workspacePath:j.workspace||null});return}if((j.kind==="cli"||j.kind==="acp")&&j.providerType){const v=((y=j.workspace)==null?void 0:y.trim())||"";await h(S,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:w,handleLaunchWorkspaceProvider:h,handleListSavedSessions:x,handleBrowseDirectory:k,handleOpenRecent:b}}function n1({conversations:e,selectedConversation:t,machineBackTarget:n,markConversationRead:r,resetMachineAction:a,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:u,setMachineBackTarget:p}){const d=l.useCallback(k=>{o(k.tabKey),i("chat"),r(k)},[r,i,o]),m=l.useCallback(k=>{const b=e.find(S=>S.routeId===k.routeId&&S.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((k,b="inbox")=>{c(k),a(),u("machines"),p(b),i("machine")},[a,p,i,u,c]),w=l.useCallback(k=>{const b=Ds(k);b&&g(b,"chat")},[g]),h=l.useCallback(()=>{a(),i(n)},[n,a,i]),x=l.useCallback(k=>{u(k),i("inbox")},[i,u]);return{openConversation:d,openNativeConversation:m,backFromConversation:f,openMachine:g,openConversationMachine:w,backFromMachine:h,changeMachineSection:x}}function Sn(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function r1(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function a1({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:w,onOpenRemote:h,onStopCli:x,wsStatus:k,isConnected:b,onShowAllHiddenConversations:S,onHideConversation:j,onOpenMeshGraph:y,onOpenNewSession:v,liveSessionInboxState:N,setCliViewModeOverrides:C}){const[A,M]=l.useState(()=>{var B;return((B=e[0])==null?void 0:B.tabKey)||null}),[T,R]=l.useState(()=>e[0]?"chat":"inbox"),[E,_]=l.useState("chats"),[z,F]=l.useState(null),[D,W]=l.useState("inbox"),L=l.useRef([]),P=mr(),$="1.0.9",I=l.useMemo(()=>e.find(B=>B.tabKey===A)||e[0]||null,[e,A]),U=l.useMemo(()=>I?n.find(B=>B.id===I.routeId):void 0,[n,I]),J=l.useMemo(()=>!I||lt(I)||!ct(I)?null:Mn(I),[I]),re=l.useMemo(()=>n.filter(B=>B.type==="adhdev-daemon").sort($i),[n]),Y=l.useMemo(()=>re.find(B=>B.id===z)||null,[re,z]),X=Da({sendDaemonCommand:a,activeConv:I||void 0,setActionLogs:o,isStandalone:i}),de=s1({sendDaemonCommand:a,navigate:P,ides:n,conversations:e}),ne=sk(e),O=l.useMemo(()=>e.map(B=>{const be=T==="chat"&&(I==null?void 0:I.tabKey)===B.tabKey,je=Na(B,N,{hideOpenTaskCompleteUnread:!0,isOpenConversation:be}),Se=Ks(B),He=rp(B),Xe=up(B,He);return{conversation:B,timestamp:Se,preview:Xe,unread:je.unread,requiresAction:je.requiresAction,isWorking:je.isWorking,inboxBucket:je.inboxBucket}}),[e,N,T,I,ne]),{markConversationRead:ie}=Zj({conversations:e,machineEntries:re,items:O,selectedConversation:I,selectedTabKey:A,screen:T,liveSessionInboxState:N,sendDaemonCommand:a,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:M,setScreen:R,setSelectedMachineId:F,setSection:_,setMachineBackTarget:W,resetMachineAction:de.resetMachineAction}),K=n1({conversations:e,selectedConversation:I,machineBackTarget:D,markConversationRead:ie,resetMachineAction:de.resetMachineAction,setSelectedTabKey:M,setScreen:R,setSelectedMachineId:F,setSection:_,setMachineBackTarget:W}),{isMuted:ae,toggleMute:Ce}=om(N,a),ye=l.useMemo(()=>Jr(O.filter(B=>B.requiresAction&&!ae(B.conversation))),[O,ae]),ke=l.useMemo(()=>Jr(O.filter(B=>B.unread&&!B.requiresAction&&!ae(B.conversation))),[O,ae]),me=l.useMemo(()=>Vj(O.filter(B=>!B.unread&&!B.requiresAction&&B.isWorking),L.current),[O]);l.useEffect(()=>{L.current=me.map(B=>B.conversation.tabKey)},[me]);const q=l.useMemo(()=>Jr(O.filter(B=>!B.unread&&!B.requiresAction&&!B.isWorking)),[O]),G=l.useMemo(()=>Y?O.filter(B=>Ds(B.conversation)===Y.id):[],[O,Y]),Z=l.useMemo(()=>Jj(Y,n),[n,Y]),V=(Y==null?void 0:Y.version)||null,fe=!!Y&&!!V&&!0&&V!==$,Te=l.useMemo(()=>(Y==null?void 0:Y.availableProviders)||[],[Y]),ce=l.useMemo(()=>Te.filter(B=>Sn(B,"cli")).map(B=>({type:B.type,displayName:B.displayName||B.type,icon:B.icon})),[Te]),H=l.useMemo(()=>Te.filter(B=>Sn(B,"acp")).map(B=>({type:B.type,displayName:B.displayName||B.type,icon:B.icon})),[Te]),pe=l.useMemo(()=>Qj(re,O),[O,re]),le=l.useCallback(async B=>{Y&&await de.handleOpenRecent(Y.id,B)},[de,Y]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:T==="chat"&&I?s.jsx($j,{selectedConversation:I,isAcp:lt(I),isStandalone:i,selectedIdeEntry:U,actionLogs:r,userName:c,isSendingChat:X.isSendingChat,sendFeedbackMessage:X.sendFeedbackMessage,isFocusingAgent:X.isFocusingAgent,handleModalButton:X.handleModalButton,handleRelaunch:X.handleRelaunch,onBack:K.backFromConversation,onOpenNativeConversation:K.openNativeConversation,onOpenMachine:K.openConversationMachine,onOpenHistory:w,onOpenRemote:h,onOpenMeshGraph:y,onStopCli:x,cliViewMode:J,onSetCliViewMode:async B=>{await Bp({conversation:I,mode:B,ides:n,sendDaemonCommand:a,setCliViewModeOverrides:C})},handleSendChat:X.handleSendChat,handleForceSendChat:X.handleForceSendChat,handleFocusAgent:X.handleFocusAgent}):T==="machine"&&Y?s.jsx(zj,{selectedMachineEntry:Y,selectedMachineConversations:G,selectedMachineRecentLaunches:Z,cliProviders:ce,acpProviders:H,selectedMachineNeedsUpgrade:fe,appVersion:$,machineAction:de.machineAction,isStandalone:i,section:E,showBottomNav:D==="inbox",onBack:K.backFromMachine,onSectionChange:K.changeMachineSection,onOpenConversation:K.openConversation,onOpenRecent:le,onOpenMachineDetails:()=>P(`/machines/${Y.id}`),onMachineUpgrade:()=>de.handleMachineUpgrade(Y.id),onLaunchDetectedIde:(B,be)=>de.handleLaunchDetectedIde(Y.id,B,be),onAddWorkspace:(B,be)=>de.handleAddWorkspace(Y.id,B,be),onBrowseDirectory:B=>de.handleBrowseDirectory(Y.id,B),onLaunchWorkspaceProvider:(B,be,je)=>de.handleLaunchWorkspaceProvider(Y.id,B,be,je),onListSavedSessions:B=>de.handleListSavedSessions(Y.id,B)}):s.jsx(Bj,{section:E,attentionItems:ye,unreadItems:ke,workingItems:me,completedItems:q,hiddenConversations:t,machineCards:pe,getAvatarText:r1,actionLogs:r,sendDaemonCommand:a,onOpenConversation:K.openConversation,onShowAllHidden:S,onHideConversation:j,onOpenMeshGraph:y,onStopCli:x,onOpenNewSession:v,onOpenMachine:K.openMachine,onOpenSettings:()=>P("/settings"),onSectionChange:_,wsStatus:k,isConnected:b,isStandalone:i,isConversationMuted:ae,onToggleMuteConversation:Ce})})}function go(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function o1({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(),!go(t,n)){d("merge");return}const k=x.currentTarget.getBoundingClientRect(),b=x.clientX-k.left,S=k.width/3;b<S?d("split-left"):b>S*2?d("split-right"):d("merge")},[t,n]),w=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 k=x.dataTransfer.getData("text/tab-key"),b=k?e.some(j=>j.tabKey===k):!1,S=p;if(d(null),o(),!!k){if(x.preventDefault(),S==="split-left"&&go(t,n)){n==null||n(k,"split-left");return}if(S==="split-right"&&go(t,n)){n==null||n(k,"split-right");return}if(b){a(k);return}r==null||r(k)}},[e,p,t,n,r,a,o]);return{dragOver:c,dropAction:p,resetDragState:m,handleDragEnter:f,handleDragOver:g,handleDragLeave:w,handleDrop:h}}function i1(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 l1({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),w=l.useRef(a);l.useEffect(()=>{g.current=r},[r]),l.useEffect(()=>{w.current=a},[a]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{u(N=>{const C=i1(N,e);return C.length===N.length&&C.every((A,M)=>A===N[M])?N:C})},[e]);const h=l.useMemo(()=>{const N=p??c;if(N.length===0)return e;const C=new Map(N.map((A,M)=>[A,M]));return[...e].sort((A,M)=>{const T=C.get(A.tabKey)??999,R=C.get(M.tabKey)??999;return T-R})},[e,p,c]);l.useEffect(()=>{var C,A;if(h.length===0){o!==null&&(i(null),(C=g.current)==null||C.call(g,null));return}if(o&&h.some(M=>M.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]),k=l.useCallback(N=>{var C;i(N),(C=g.current)==null||C.call(g,N)},[]),b=l.useCallback((N,C,A)=>{u(M=>{var _;const T=M.filter(z=>z!==N),R=T.indexOf(C);if(R<0)return M;const E=A==="left"?R:R+1;return T.splice(E,0,N),(_=w.current)==null||_.call(w,T),T}),d(null)},[]),S=l.useCallback((N,C,A)=>{const T=(c.length>0?c:e.map(_=>_.tabKey)).filter(_=>_!==N),R=T.indexOf(C);if(R<0)return;const E=A==="left"?R:R+1;T.splice(E,0,N),m.current=T,d(T)},[c,e]),j=l.useCallback(()=>{var C;const N=m.current;N&&(u(N),(C=w.current)==null||C.call(w,N))},[]),y=l.useCallback(()=>{m.current=null,d(null)},[]),v=l.useCallback(N=>{u(C=>{var M;const A=C.filter(T=>T!==N);return A.push(N),(M=w.current)==null||M.call(w,A),A})},[]);return{activeTabId:o,activeConv:x,sortedConversations:h,previewOrderRef:m,draggingTabRef:f,selectTab:k,handleTabReorder:b,updatePreviewOrder:S,commitPreviewOrder:j,clearPreviewOrder:y,moveTabToEnd:v,setDraggingTabKey:N=>{f.current=N}}}function c1({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 il({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(Di,{size:14}),s.jsx("span",{children:i("paneGroup.newSession")})]})}),c&&s.jsx(em,{}),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 im="adhdev-tab-shortcuts";function lm(){try{return JSON.parse(localStorage.getItem(im)||"{}")}catch{return{}}}function cm({enabled:e=!0,sortedTabKeys:t,onFocus:n,onSelectTab:r}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>lm()),[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(im,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 w={...o};for(const[h,x]of Object.entries(w))x===g&&delete w[h];w[c]=g,d(w),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,w]of Object.entries(o))if(t.includes(g)&&p(f)===w){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 xo=e=>{e.preventDefault()},d1=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:w,onDragStateReset:h,onDragTabKeyChange:x,onReceiveTab:k,onOpenContextMenu:b,longPressTimer:S,isGroupActive:j}){const y=An(t),v=y.isGenerating?"agent-tab-generating":y.isWaiting?"agent-tab-waiting":"",N=y.isReconnecting,C=Ck(t),A=jk(t),M=dp(t),T=l.useCallback(P=>{c.current=t.tabKey,x(t.tabKey),P.dataTransfer.setData("text/tab-key",t.tabKey),P.dataTransfer.effectAllowed="move"},[t.tabKey,c,x]),R=l.useCallback(()=>{c.current=null,x(null),g(),w(),h()},[c,x,g,w,h]),E=l.useCallback(P=>{const $=c.current;if(!(!$||$===t.tabKey)&&P.dataTransfer.types.includes("text/tab-key")){P.preventDefault(),P.stopPropagation();const I=P.currentTarget.getBoundingClientRect(),U=P.clientX<I.left+I.width/2?"left":"right";m($,t.tabKey,U)}},[t.tabKey,c,m]),_=l.useCallback(P=>{P.preventDefault(),P.stopPropagation();const $=P.dataTransfer.getData("text/tab-key");if($&&$!==t.tabKey){const I=P.currentTarget.getBoundingClientRect(),U=P.clientX<I.left+I.width/2?"left":"right";i.includes($)?f($,t.tabKey,U):k&&k($)}w()},[t.tabKey,i,f,k,w]),z=l.useCallback(P=>{P.stopPropagation(),u(),p(t.tabKey),d(t)},[t,d,u,p]),F=l.useCallback(P=>{P.preventDefault(),b(P.clientX,P.clientY,t.tabKey)},[t.tabKey,b]),D=l.useCallback(P=>{const $=P.touches[0];S.current=setTimeout(()=>{b($.clientX,$.clientY,t.tabKey)},600)},[t.tabKey,S,b]),W=l.useCallback(()=>{S.current&&clearTimeout(S.current)},[S]),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:T,onDragEnd:R,onDragOver:E,onDrop:_,onClick:z,onContextMenu:F,onTouchStart:D,onTouchEnd:W,onTouchMove:W,style:{position:"relative",cursor:"pointer",opacity:r?.4:void 0},children:[M&&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(es,{size:11})}),a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:y.isGenerating?s.jsx("div",{className:"tab-spinner"}):y.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):N?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):y.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:"○"})}),C.length>0&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:A,"aria-label":A||C.join(" · "),children:C.join(" · ")}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:xt(t),children:xt(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:Gs(t)}):y.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[Gs(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:Gs(t)}),s.jsx(da,{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 u1({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:w,onHideTab:h,isGroupActive:x,allowTabShortcuts:k=!0}){const{t:b}=Ne("common"),[S,j]=l.useState(null),y=l.useRef(null),v=l.useRef(null),N=l.useMemo(()=>e.map(_=>_.tabKey),[e]);hr("PaneGroupTabBar",{groupIndex:n,activeTabId:t,tabCount:e.length,ctxMenuTab:(S==null?void 0:S.tabKey)||null});const{isMac:C,tabShortcuts:A,shortcutListening:M,setShortcutListening:T,saveShortcuts:R}=cm({enabled:k,sortedTabKeys:e.map(_=>_.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!S)return;const _=z=>{const F=document.querySelector("[data-pane-context-menu]");F&&F.contains(z.target)||j(null)};return window.addEventListener("mousedown",_,!0),()=>window.removeEventListener("mousedown",_,!0)},[S]),l.useEffect(()=>{const _=v.current;if(!_)return;const z=F=>{Math.abs(F.deltaY)<=Math.abs(F.deltaX)||(F.preventDefault(),_.scrollLeft+=F.deltaY)};return _.addEventListener("wheel",z,{passive:!1}),()=>_.removeEventListener("wheel",z)},[]);const E=l.useCallback((_,z,F)=>{j({x:_,y:z,tabKey:F})},[]);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(d1,{conv:_,isActive:t===_.tabKey,isDraggedTab:a.current===_.tabKey,isTaskCompleteUnread:r.has(_.tabKey),shortcut:k?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:w,onOpenContextMenu:E,longPressTimer:y,isGroupActive:x},_.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:b("paneGroup.noTabsInGroup")})]})}),S&&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:S.x,top:S.y},children:[k&&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:xo,onClick:_=>{_.stopPropagation(),T(S.tabKey),j(null)},children:["⌨ ",A[S.tabKey]?`Change shortcut (${A[S.tabKey]})`:"Set shortcut"]}),A[S.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:xo,onClick:()=>{const _={...A};delete _[S.tabKey],R(_),j(null)},children:"✕ Remove shortcut"})]}),h&&s.jsxs(s.Fragment,{children:[k&&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:xo,onClick:()=>{h(S.tabKey),j(null)},children:"🚫 Hide from Dashboard"})]})]}),k&&M&&s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>T(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. ",C?"⌘+1":"Ctrl+1",", ",C?"⌥+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 p1({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:w,style:h,onActiveTabChange:x,initialActiveTabId:k,initialTabOrder:b,onTabOrderChange:S,onHideTab:j,isFocused:y,allowTabShortcuts:v=!0,onOpenNewSession:N,liveSessionInboxState:C}){const{sendCommand:A}=vt(),M=l.useRef(null),{activeTabId:T,activeConv:R,sortedConversations:E,draggingTabRef:_,selectTab:z,handleTabReorder:F,updatePreviewOrder:D,commitPreviewOrder:W,clearPreviewOrder:L,moveTabToEnd:P,setDraggingTabKey:$}=l1({conversations:e,initialActiveTabId:k,initialTabOrder:b,onActiveTabChange:x,onTabOrderChange:S}),I=Da({sendDaemonCommand:a,activeConv:R,setActionLogs:o,isStandalone:i}),{dragOver:U,dropAction:J,resetDragState:re,handleDragEnter:Y,handleDragOver:X,handleDragLeave:de,handleDrop:ne}=o1({conversations:e,numGroups:f,onMoveTab:g,onReceiveTab:w,onOwnTabDrop:P,onClearPreviewOrder:L}),O=R&&!lt(R)&&Mn(R)==="terminal",ie=l.useMemo(()=>R?t.find(ye=>ye.id===R.routeId):void 0,[t,R]),K=l.useMemo(()=>R?r.filter(ye=>ye.routeId===R.tabKey):[],[r,R]),ae=l.useMemo(()=>new Set(E.filter(ye=>Eb(ye,C,{isOpenConversation:ye.tabKey===T})).map(ye=>ye.tabKey)),[T,C,E]);hr("PaneGroup",{groupIndex:p,conversationCount:e.length,activeTabId:T,dragOver:U});const Ce=l.useCallback(ye=>{ye.streamSource==="agent-stream"&&ye.agentType&&A(ye.routeId,qu(),{agentType:ye.agentType,...ye.sessionId&&{targetSessionId:ye.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:U?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(u1,{conversations:E,activeTabId:T,groupIndex:p,numGroups:f,unreadTabKeys:ae,draggingTabRef:_,onFocus:d,onSelectTab:z,onConversationActivated:Ce,onPreviewReorder:D,onReorderTab:F,onCommitPreviewOrder:W,onClearPreviewOrder:L,onDragStateReset:re,onDragTabKeyChange:$,onMoveTab:g,onReceiveTab:w,onHideTab:j,isGroupActive:y??!1,allowTabShortcuts:v}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:Y,onDragOver:X,onDragLeave:de,onDrop:ne,children:[U&&s.jsx(c1,{dropAction:J,canSplit:!!(f<4&&g)}),R?s.jsx(al,{activeConv:R,clearToken:n[R.tabKey]||0,isCliTerminal:!!O,ideEntry:ie,terminalRef:M,handleModalButton:I.handleModalButton,handleRelaunch:I.handleRelaunch,handleSendChat:I.handleSendChat,handleForceSendChat:I.handleForceSendChat,isSendingChat:I.isSendingChat,sendFeedbackMessage:I.sendFeedbackMessage,handleFocusAgent:I.handleFocusAgent,isFocusingAgent:I.isFocusingAgent,actionLogs:K,userName:u,isInputActive:!m||!!y}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(il,{conversationsCount:e.length,isSplitMode:m,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:N})})]})]})}function m1({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:w,moveTabToGroup:h,splitTabRelative:x,closeGroup:k,handleResizeStart:b,groupActiveTabIds:S,setGroupActiveTab:j,groupTabOrders:y,setGroupTabOrder:v,toggleHiddenTab:N,onOpenNewSession:C,allowTabShortcuts:A=!0,liveSessionInboxState:M}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((T,R)=>{const E=t&&r.length===n?`${r[R]}%`:void 0;return s.jsxs(Rt.Fragment,{children:[t&&R>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(R-1,_),onDoubleClick:()=>k(R),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(p1,{style:t?{flexBasis:E??`${100/n}%`,flexGrow:E?0:1,flexShrink:E?0:1}:void 0,conversations:T,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:u,setActionLogs:p,isStandalone:d,hasRegisteredMachines:m,userName:f,groupIndex:R,isFocused:t&&g===R,onFocus:()=>w(R),isSplitMode:t,numGroups:n,onMoveTab:(_,z)=>{z==="left"&&R>0?h(_,R-1):z==="right"&&R<n-1?h(_,R+1):z==="split-left"&&n<4?x(_,R,"left"):z==="split-right"&&n<4&&x(_,R,"right")},onReceiveTab:_=>h(_,R),onActiveTabChange:_=>j(R,_),initialActiveTabId:S[R],initialTabOrder:y[R],onTabOrderChange:_=>v(R,_),onHideTab:N,onOpenNewSession:C,allowTabShortcuts:A,liveSessionInboxState:M})]},R)})})}const dm="adhdev-dashboard-action-shortcuts",h1=1200,f1=[["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 b1(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function ht(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 um(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:ht("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:ht("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:ht("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:ht("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:ht("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:ht("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:ht("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:ht("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:ht("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:ht("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:ht("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:ht("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:ht("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:ht("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:ht("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:ht("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:ht("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:ht("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:ht("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:ht("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:ht("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:ht("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:ht("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:ht("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:ht("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:ht("toggleCliView",e)}]}function bi(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function va(e){const t=Object.fromEntries(um(e).map(n=>[n.id,n.defaultShortcut]));try{const n=JSON.parse(localStorage.getItem(dm)||"{}"),r={...t,...n};for(const[a,o]of f1)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 g1({enabled:e=!0,onTrigger:t}){const n=b1(),[r,a]=l.useState(()=>va(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=va(n),x=Object.entries(r),k=Object.entries(h);x.length===k.length&&x.every(([b,S])=>h[b]===S)||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}},h1))},[]);l.useEffect(()=>{if(!o)return;const h=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){i(null),u([]);return}const k=d(x);if(!k)return;const S=!(x.metaKey||x.ctrlKey||x.altKey)&&/^[A-Z0-9]$/.test(k);if(c.length===0&&S){u([k]);return}const y=[...c,k].slice(0,2).join(" "),v={...r};for(const[N,C]of Object.entries(v))C===y&&delete v[N];v[o]=y,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 k=d(x);if(!k)return;const b=x.metaKey||x.ctrlKey||x.altKey;if(bi(x.target))return;const S=p.current.parts,j=b?[k]:[...S.slice(-1),k].slice(-2),y=j.join(" "),v=j[j.length-1],N=Object.entries(r).filter(([,R])=>!!R),C=N.find(([,R])=>R===y);if(C){x.preventDefault(),f(),t(C[0]);return}if(N.some(([,R])=>R.startsWith(`${y} `))){x.preventDefault(),p.current.parts=j,g();return}const M=N.find(([,R])=>R===v);if(M){x.preventDefault(),f(),t(M[0]);return}if(N.some(([,R])=>R.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 w=l.useMemo(()=>um(n),[n]);return{isMac:n,actionDefinitions:w,actionShortcuts:r,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:u,saveShortcuts:m}}function x1({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 mm(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function zc({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:n,ides:r}){return!e||n>0?!1:t?!mm(r):!0}function v1({previousVisibleConversationCount:e,visibleConversationCount:t,ides:n}){return t>0||e<=0?!1:mm(n)}const hm=1e3,y1=4;function Kc(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function Vc(e,t,n){return Math.abs(t.clientX-e.clientX)>n||Math.abs(t.clientY-e.clientY)>n}function w1({detachDelayMs:e=hm,stillnessThresholdPx:t=y1,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},w=()=>{!o||!c||!u||d||p!=null||(p=r(()=>{p=null,!(!o||!c||!u||d)&&Kc(u,i)&&(Vc(c,u,t)||(d=!0,n({panelId:o,clientX:u.clientX,clientY:u.clientY})))},e))},h=k=>{if(!(!o||d)){if(!Kc(k,i)){u={clientX:k.clientX,clientY:k.clientY},f();return}(!c||Vc(c,k,t))&&(m(),c={clientX:k.clientX,clientY:k.clientY}),u={clientX:k.clientX,clientY:k.clientY},w()}},x=k=>{!o||d||(k&&(u={clientX:k.clientX,clientY:k.clientY}),f())};return{startDrag:k=>{m(),o=k.panelId,i=k.selfPanelBounds??null,c=null,u={clientX:k.clientX,clientY:k.clientY},d=!1},markSelfPanel:h,markNonSelfPanel:x,markNoDropTarget:x,markDockTarget:x,endDrag:g,isDragging:()=>o!=null,hasDetached:()=>d,dispose:g}}function k1(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Qr(e){return xt(e)||e.tabKey}function S1(e){return`remote:${e}`}function rs(e){return e.startsWith("remote:")}function Yc(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function vo(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 yo(e,t){e.classList.remove(Oo.className,Wo.className),e.classList.add(t==="light"?Oo.className:Wo.className)}function Jc(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 C1(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:Qr(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 Qc(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])rs(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!==Qr(a)&&o.api.setTitle(Qr(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:Qr(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 Xc(e,t,n){var u,p;const r=n?S1(n):null;for(const d of[...e.panels])rs(d.id)&&(!r||d.id!==r)&&e.removePanel(d);if(!n||!r)return;const a=cs(t,n);if(!a&&e.totalPanels===0)return;const o=e.getPanel(r),i=hp(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=>!rs(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 fm({doId:e,targetSessionId:t,connState:n,viewMode:r}){const[a,o]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?kt.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=kt.onStatus)==null?void 0:d.call(kt,(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?kt.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?kt.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 bm=l.createContext(null);function Ea(){const e=l.useContext(bm);if(!e)throw new Error("DashboardDockviewContext missing");return e}function j1(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 N1({params:e}){var u;const t=Ea(),n=l.useMemo(()=>cs([...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}=fm({doId:a,targetSessionId:n?Gu(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(pu,{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 A1(){const e=Ea();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(il,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function M1(e){var b,S;j1(e);const t=Ea(),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=>ok(j),[]),i=l.useCallback(()=>ak(a),[a]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const j=cs([...t.conversationsByTabKey.values()],e.params.routeId),y=((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${y?" 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=((S=e.api.group.activePanel)==null?void 0:S.id)===e.api.id,d=e.api.isGroupActive,m=Na(u,t.liveSessionInboxState,{isOpenConversation:p}),f=m.isReconnecting,g=m.isConnecting,w=m.isGenerating||c,h=m.isWaiting,x=m.unread,k=t.tabShortcuts[u.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${p?" is-active":""}${d?" is-group-active":""}${f?" is-reconnecting":""}`,title:xt(u),"data-tab-key":e.params.tabKey,onMouseDown:n,onTouchStart:n,onContextMenu:j=>{var y;j.preventDefault(),n(j),t.openTabContextMenu({x:j.clientX,y:j.clientY,tabKey:u.tabKey,sourceDocument:((y=j.target)==null?void 0:y.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:w?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:xt(u)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:f?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Gs(u)}):g?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Gs(u)}):s.jsx("span",{children:Gs(u)})})]}),k&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:k,children:k})]})}function Er(e){return e.isActive}function Zc(e){return e.isVisible}function T1(e){e.preventDefault()}function P1({params:e,api:t}){var g;const n=Ea(),r=l.useRef(null),[a,o]=l.useState(()=>Er(t)),[i,c]=l.useState(()=>Zc(t)),u=n.conversationsByTabKey.get(e.tabKey),p=Da({sendDaemonCommand:n.sendDaemonCommand,activeConv:u,setActionLogs:n.setActionLogs,isStandalone:n.isStandalone});l.useEffect(()=>{o(Er(t)),c(Zc(t));const w=[t.onDidActiveChange(h=>o(h.isActive)),t.onDidActiveGroupChange(h=>{if(!Er(t)&&!h.isActive){o(!1);return}o(Er(t))}),t.onDidVisibilityChange(h=>c(h.isVisible))];return()=>{for(const h of w)h.dispose()}},[t]);const d=l.useMemo(()=>u?n.ides.find(w=>w.id===u.routeId):void 0,[n.ides,u]),m=l.useMemo(()=>u?n.actionLogs.filter(w=>w.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(il,{conversationsCount:0,isSplitMode:!1,isStandalone:n.isStandalone,hasRegisteredMachines:n.hasRegisteredMachines,onOpenNewSession:n.onOpenNewSession,suppressGuide:n.hasDetachedConversationPanels})});const f=!lt(u)&&Mn(u)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(al,{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 I1({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:w,onRequestScrollToBottom:h,requestedActiveTabKey:x,requestedRemoteIdeId:k,onRequestedActiveTabConsumed:b,scrollToBottomRequest:S,liveSessionInboxState:j,layoutProfile:y}){var ut,ot,pt;const{theme:v}=Ls(),{sendCommand:N}=vt(),C=l.useRef(null),A=l.useRef(null),M=l.useRef(null),T=l.useRef(!1),R=l.useRef(!1),E=l.useRef(!1),_=l.useRef(null),z=l.useRef([]),[F,D]=l.useState(null),[W,L]=l.useState(0),P=l.useRef(typeof window>"u"?{}:JC(y)),$=l.useMemo(()=>new Map(e.map(Q=>[Q.tabKey,Q])),[e]),I=l.useMemo(()=>{const Q=C.current;return Q?Q.groups.some(ee=>{try{const oe=ee.model.location.type;return oe!=="floating"&&oe!=="popout"?!1:ee.panels.some(ue=>$.has(ue.id))}catch{return!1}}):!1},[$,W,e]),U=l.useCallback(()=>{var Q;(Q=C.current)==null||Q.focus()},[]),J=l.useCallback((Q,ee)=>{h==null||h(Q,ee)},[h]),re=l.useCallback(Q=>{const ee=document,oe=Q.document;for(const Ae of ee.querySelectorAll('link[rel="stylesheet"]')){const Oe=oe.createElement("link");Oe.rel="stylesheet",Oe.href=Ae.href,Ae.crossOrigin&&(Oe.crossOrigin=Ae.crossOrigin),oe.head.appendChild(Oe)}for(const Ae of ee.querySelectorAll("style")){const Oe=oe.createElement("style");Oe.textContent=Ae.textContent,oe.head.appendChild(Oe)}const ue=[];for(const Ae of ee.styleSheets)try{for(const Oe of Ae.cssRules)Oe instanceof CSSStyleRule&&(Oe.selectorText===":root"||Oe.selectorText==="html")&&ue.push(Oe.cssText)}catch{}if(ue.length>0){const Ae=oe.createElement("style");Ae.textContent=ue.join(`
69
+ Use this if you want to permanently remove a machine.`,confirmLabel:o("machine.connectedMachines.remove"),confirmColor:"red",onConfirm:M,onCancel:()=>m(null)})]})}const JS=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli","gemini-cli"];function QS({daemonId:e,knownCliTypes:t=JS}){const{t:n}=Ne("common"),{sendCommand:r}=vt(),[a,o]=l.useState({}),[i,c]=l.useState({}),[u,p]=l.useState(!0),[d,m]=l.useState(null),[f,g]=l.useState(null),[w,h]=l.useState(""),x=l.useCallback(async()=>{if(e){p(!0),g(null);try{const S=await r(e,"list_coordinator_prompts",{}),j=S!=null&&S.result&&typeof S.result=="object"?S.result:S;if(!(j!=null&&j.success)){g((j==null?void 0:j.error)||"Failed to load");return}const y=j.entries||{};h(j.dir||"");const v={};for(const N of t)v[N]=y[N]||{override:"",append:""};for(const N of Object.keys(y))v[N]||(v[N]=y[N]);o(v),c(JSON.parse(JSON.stringify(v)))}catch(S){g((S==null?void 0:S.message)||String(S))}finally{p(!1)}}},[r,e,t]);l.useEffect(()=>{x()},[x]);const k=l.useCallback(async(S,j)=>{var y;if(e){m(`${S}:${j}`),g(null);try{const v=((y=a[S])==null?void 0:y[j])||"",N=await r(e,"write_coordinator_prompt",{key:S,kind:j,content:v}),C=N!=null&&N.result&&typeof N.result=="object"?N.result:N;if(!(C!=null&&C.success)){g((C==null?void 0:C.error)||"Save failed");return}c(A=>({...A,[S]:{...A[S]||{override:"",append:""},[j]:v}}))}catch(v){g((v==null?void 0:v.message)||String(v))}finally{m(null)}}},[r,e,a]),b=l.useMemo(()=>(S,j)=>{var y,v;return(((y=a[S])==null?void 0:y[j])||"")!==(((v=i[S])==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:w||"~/.adhdev/coordinator-prompts/"})]}),s.jsxs("p",{className:"mt-1",children:[s.jsx(Bo,{i18nKey:"settings.coordinatorPrompts.overrideDesc",ns:"common",components:{strong:s.jsx("strong",{})}})," ",s.jsx(Bo,{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(([S,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:S}),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:y=>o(v=>({...v,[S]:{...v[S],override:y.target.value}})),placeholder:"(empty — use daemon default base prompt)",disabled:d===`${S}: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 k(S,"override"),disabled:d===`${S}:override`||!b(S,"override"),children:d===`${S}:override`?"Saving…":b(S,"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:y=>o(v=>({...v,[S]:{...v[S],append:y.target.value}})),placeholder:"(empty — nothing appended at this layer)",disabled:d===`${S}:append`}),s.jsx("div",{className:"mt-1 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void k(S,"append"),disabled:d===`${S}:append`||!b(S,"append"),children:d===`${S}:append`?"Saving…":b(S,"append")?"Save append":"Saved"})})]},S))})]}):s.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const XS=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function ZS(){const{preference:e,setPreference:t}=Ls();return s.jsx("div",{className:"flex gap-2",children:XS.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 eC(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 tC(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function io(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Pc(e){const{r:t,g:n,b:r}=tC(e);return .2126*io(t)+.7152*io(n)+.0722*io(r)}function Ic(e,t){const n=Pc(e),r=Pc(t),a=Math.max(n,r),o=Math.min(n,r);return(a+.05)/(o+.05)}function Lp(e){const t=eC(e);if(!t)return"#111827";const n="#111827",r="#ffffff";return Ic(t,n)>=Ic(t,r)?n:r}const ui={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},pi={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},sC=[{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"}}}],Rp="adhdev-chat-theme",Ep="adhdev-chat-theme-custom";function Vr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Rp)||"ember"}catch{return"ember"}}function os(e){try{const t=localStorage.getItem(Ep);if(t){const n=JSON.parse(t);return{...e==="dark"?ui:pi,...n[e]}}}catch{}return e==="dark"?ui:pi}function Tr(e,t){try{localStorage.setItem(Ep,JSON.stringify({dark:e,light:t}))}catch{}}function Qt(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 ga(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 nC={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function sr(e,t){var a;const n=(a=nC[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",ga(n,24)),r.style.setProperty("--accent-on-primary",Lp(n)),r.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${n}, ${ga(n,18)})`),r.style.setProperty("--border-accent",Qt(n,.35)),r.style.setProperty("--nav-active-bg",Qt(n,.1)),r.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${n}, 0 0 12px ${Qt(n,.06)}`)}function qs(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Qt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Qt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Qt(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",Qt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Qt(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",ga(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Lp(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${ga(e.accentColor,40)})`),t.style.setProperty("--border-accent",Qt(e.accentColor,.35)),t.style.setProperty("--nav-active-bg",Qt(e.accentColor,.1)),t.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${e.accentColor}, 0 0 12px ${Qt(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 ${Qt(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 Qi(){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(Rp,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=zs()?"dark":"light";qs(os(t))}else Qi(),sr(e,zs()?"dark":"light")}function aC(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Vr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=zs()?"dark":"light";qs(os(t))}else Qi(),sr(e,zs()?"dark":"light")}function zs(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Ht({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 Fn({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 oC({dark:e,onColorsChange:t}){const{t:n}=Ne("common"),r=e?"dark":"light",[a,o]=l.useState(()=>os(r));l.useEffect(()=>{o(os(r))},[r]);const i=l.useCallback((c,u)=>{o(p=>{const d={...p,[c]:u},f=os(r==="dark"?"light":"dark");return r==="dark"?Tr(d,f):Tr(f,d),qs(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(Fn,{title:n("settings.theme.sectionAppBackground"),children:[s.jsx(Ht,{label:n("settings.theme.colorBackground"),value:a.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(Ht,{label:n("settings.theme.colorSurface"),value:a.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(Ht,{label:n("settings.theme.colorCard"),value:a.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(Fn,{title:n("settings.theme.sectionAppText"),children:[s.jsx(Ht,{label:n("settings.theme.colorPrimary"),value:a.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(Ht,{label:n("settings.theme.colorSecondary"),value:a.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(Ht,{label:n("settings.theme.colorMuted"),value:a.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(Fn,{title:n("settings.theme.sectionBordersAccent"),children:[s.jsx(Ht,{label:n("settings.theme.colorBorderSubtle"),value:a.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(Ht,{label:n("settings.theme.colorBorderDefault"),value:a.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(Ht,{label:n("settings.theme.colorAccent"),value:a.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Fn,{title:n("settings.theme.sectionChatBubbles"),children:[s.jsx(Ht,{label:n("settings.theme.colorUserBubble"),value:a.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(Ht,{label:n("settings.theme.colorUserText"),value:a.userText,onChange:c=>i("userText",c)}),s.jsx(Ht,{label:n("settings.theme.colorAgentBubble"),value:a.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(Ht,{label:n("settings.theme.colorAgentText"),value:a.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(Fn,{title:n("settings.theme.sectionChatLayout"),children:[s.jsx(Ht,{label:n("settings.theme.colorChatBg"),value:a.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(Ht,{label:n("settings.theme.colorSendButton"),value:a.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(Ht,{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?ui:pi,p=os(e?"light":"dark");e?Tr(c,p):Tr(p,c),o(c),qs(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 iC(){const{t:e}=Ne("common"),[t,n]=l.useState(Vr),[r,a]=l.useState(!0),[o,i]=l.useState(()=>os("dark"));l.useEffect(()=>{a(zs());const p=new MutationObserver(()=>{const f=zs();a(f);const g=Vr();g==="custom"?qs(os(f?"dark":"light")):sr(g,f?"dark":"light")});p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const d=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const f=zs();a(f);const g=Vr();g==="custom"?qs(os(f?"dark":"light")):sr(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"?qs(os(r?"dark":"light")):(Qi(),sr(t,r?"dark":"light"))},[t,r]),l.useEffect(()=>{i(os(r?"dark":"light"))},[r]);const c=p=>{n(p),rC(p)},u=[...sC,{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(oC,{dark:r,onColorsChange:p=>i(p)})]})}const Xi="adhdev_mobileDashboardMode_v1",mi="adhdev:mobile-dashboard-mode-change";function Zi(){try{return localStorage.getItem(Xi)==="workspace"?"workspace":"chat"}catch{return"chat"}}function lC(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??Zi())},n=a=>{const o=a.detail;t(o)},r=a=>{a.key&&a.key!==Xi||t()};return window.addEventListener(mi,n),window.addEventListener("storage",r),()=>{window.removeEventListener(mi,n),window.removeEventListener("storage",r)}}function cC(e){try{localStorage.setItem(Xi,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(mi,{detail:e}))}function dC(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(Zi()==="chat")},[]),s.jsx(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Zs,{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),cC(n?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const uC="Choose a preset or create a fully custom theme. Custom themes control the entire app — backgrounds, text, borders, and chat bubbles.",pC="Choose whether the dashboard opens like a chat app on phones or keeps the full workspace layout.";function mC({themeDescription:e=uC,mobileDescription:t=pC,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(ZS,{})]}),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(iC,{})]}),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(dC,{})]})]})}const lo=new Map,Dc=new Map;function hC(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 fC(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 _p(){const{sendCommand:e}=vt(),{injectEntries:t,getIdes:n}=ar();return l.useCallback(async(r,a)=>{if(!r)return;const o=(a==null?void 0:a.minFreshMs)??N0,i=Dc.get(r)||0;if(!(a!=null&&a.force)&&i>0&&Date.now()-i<o)return;const c=lo.get(r);if(c)return c;const u=(async()=>{const p=await e(r,"get_machine_runtime_stats"),d=hC(p);if(!d)return;const m=n().find(g=>g.id===r),f=fC(m,r,d.machine,d.timestamp||Date.now());t([f]),Dc.set(r,Date.now())})().finally(()=>{lo.delete(r)});return lo.set(r,u),u},[n,t,e])}function bC(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 gC(e,t){const{sendData:n}=vt(),{injectEntries:r,getIdes:a}=ar(),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=>ls.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=bC(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 xC(e,t){const{sendData:n}=vt(),[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=ls.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)},T0):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 vC(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function $p(e){const{sendData:t}=vt(),[n,r]=l.useState({});return l.useEffect(()=>{const a=vC(e);if(!a||!e.sessionId||!t){r({});return}const o=ls.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}),bn.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 yC(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function wC(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 kC(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 SC({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(!yC(o))throw new Error(wC(o));return}await kC(e.sessionId,t,a)}function Hp(e){const{ides:t,isP2PActive:n,p2pStates:r}=gs(),{sendCommand:a}=vt(),[o,i]=l.useState(null),[c,u]=l.useState(!1),[p,d]=l.useState(null),m=l.useRef(!1),f=l.useMemo(()=>Ib(t,e),[t,e]),g=!!f,w=l.useMemo(()=>f?f.prompt.promptId===o?null:f:null,[o,f]),h=l.useCallback(async b=>{if(!w||m.current)return;m.current=!0;const S=mu(w.prompt,b);u(!0),d(null);try{const j=(r==null?void 0:r[w.daemonId])==="connected"||n===!0;await SC({promptSession:w,response:S,useP2PCommand:j,sendCommand:a}),i(w.prompt.promptId)}catch(j){throw d(j instanceof Error?j.message:String(j)),j}finally{u(!1),m.current=!1}},[n,r,w,a]),x=l.useCallback(()=>{w&&i(w.prompt.promptId)},[w]),k=l.useCallback(()=>{i(null),d(null)},[]);return{promptSession:w,hasActivePrompt:g,responseError:p,isSubmitting:c,submit:h,cancel:x,reopen:k}}function Fp(e){return e instanceof Error?e.message:String(e||"")}function CC(e){const t=Fp(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 jC(e){const t=Fp(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Bp({conversation:e,mode:t,ides:n,sendDaemonCommand:r,setCliViewModeOverrides:a}){if(!e||!ct(e)||lt(e))return;const o=Mn(e);if(o===t)return;const i=e.sessionId;i&&a(c=>({...c,[i]:t}));try{await r(Ds(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:bs(e),mode:t})}catch(c){const u=jC(c);i&&!u&&a(p=>{const d={...p};return o===AC(n,i)?delete d[i]:d[i]=o,d}),CC(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 Lc(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 NC(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=Lc(a,t),i=Array.isArray(a.childSessions)?a.childSessions.map(u=>Lc(u,t)):a.childSessions,c=i!==a.childSessions;return o!==a||c?(n=!0,{...o,...c?{childSessions:i}:{}}):a});return n?r:e}function AC(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 MC({visibleConversations:e,clearedTabs:t,setClearedTabs:n,setActionLogs:r,isConversationMuted:a}){l.useEffect(()=>{Mu()},[]);const o=l.useMemo(()=>e.map(i=>({id:i.tabKey,name:mp(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 Zy(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 Rc(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 Ks(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=Rc(t==null?void 0:t.receivedAt)||Rc(t==null?void 0:t.timestamp)||0;return Math.max(n,r)}function hi(e,t=0){return Ks(e)||e.lastUpdated||t||0}function Op(e){return Ks(e)||e.lastUpdated||0}function Wp(e,t,n=Op){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 fi(e){var n;const t=Zt(e.status,{activeModal:(n=e.modalButtons)!=null&&n.length?{buttons:e.modalButtons}:null});return t==="generating"||t==="waiting_approval"}function TC(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!fi(e)&&!e.title.trim()}function PC(e){return e.length===0?null:[...e].sort((t,n)=>{const r=Number(fi(n))-Number(fi(t));if(r!==0)return r;const a=n.messages.length-t.messages.length;return a!==0?a:Wp(t,n)})[0]||null}function cs(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=PC(a);return r?o&&TC(r)?o:r:o||n[0]||null}function IC(e){const t=e.filter(a=>a.type!=="adhdev-daemon"),n=new Set;for(const a of t){if(!Zo(a))continue;const o=ku(a);o&&n.add(o)}const r=new Map;for(const a of t){const o=Py(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,DC(d,d===a?i:a))}return Array.from(r.values())}function DC(e,t){const n=Zo(t),r=Zo(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 co(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 LC(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 Ec(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],n=t[t.length-1],r=n?LC(gn(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 RC(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||""),Ec(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||""),Ec(n.activeChat)].join(":"))].join("|")}function EC(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 _C(e,t){const n=new Map;for(const r of e){const a=t.get(r.routeId)||r;for(const o of Xn({routeId:r.routeId}))n.set(o,a);for(const o of Xn({providerSessionId:r.providerSessionId,sessionId:r.sessionId}))n.set(o,r.streamSource==="native"?a:r);for(const o of Xn({tabKey:r.tabKey}))n.set(o,r)}return n}function $C(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function HC(e){const t=$C(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=gn(t.content).slice(0,240);return`${e.messages.length}:${n}:${r}`}function FC({ides:e,connectionStates:t,clearedTabs:n}){const r=l.useMemo(()=>IC(e),[e]),a=l.useMemo(()=>bu(e),[e]),o=l.useMemo(()=>Cp(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,y=[];for(const A of r){const{connectionState:M="new",machineName:T}=jp(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),R=RC(A),E=p.current.get(A.id);if(E&&E.ide===A&&E.sourceSignature===R&&E.connectionState===M&&E.machineName===T){j.set(A.id,E),y.push(...E.conversations);continue}const _=Yi(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),z={ide:A,sourceSignature:R,connectionState:M,machineName:T,conversations:_};j.set(A.id,z),y.push(..._)}p.current=j;const v=new Map,N=A=>{const M=HC(A),T=d.current.get(A.tabKey);if(T&&T.signature===M)return v.set(A.tabKey,T),T.timestamp;const R={signature:M,timestamp:Op(A)||(T==null?void 0:T.timestamp)||0};return v.set(A.tabKey,R),R.timestamp},C=[...y].sort((A,M)=>Wp(A,M,N));return d.current=v,C},[r,t,o]),f=l.useMemo(()=>{const j=EC(m,n);return co(i.current,j)?i.current:(i.current=j,j)},[m,n]),g=l.useMemo(()=>{const j=new Map,y=Array.from(new Set(f.map(v=>v.routeId)));for(const v of y){const N=cs(f,v);N&&j.set(v,N)}return j},[f]),w=l.useMemo(()=>{const j=new Map;for(const y of f){const v=g.get(y.routeId),N=y.streamSource==="native"&&v?v:y;for(const C of Xn({providerSessionId:y.providerSessionId,sessionId:y.sessionId,tabKey:y.tabKey}))j.set(C,N)}return j},[f,g]),h=l.useMemo(()=>_C(f,g),[f,g]),x=l.useCallback(j=>{if(j)return w.get(j)},[w]),k=l.useCallback(j=>{if(j)return h.get(j)},[h]),b=l.useMemo(()=>{const j=f.filter(y=>!Is(y,a).surfaceHidden);return co(c.current,j)?c.current:(c.current=j,j)},[f,a]),S=l.useMemo(()=>{const j=b.map(y=>y.tabKey);return co(u.current,j)?u.current:(u.current=j,j)},[b]);return{chatIdes:r,conversations:f,visibleConversations:b,visibleTabKeys:S,resolveConversationBySessionId:x,resolveConversationByTarget:k}}function BC({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 OC({ides:e,sendDaemonCommand:t,setToasts:n,resolveConversationByTarget:r}){l.useEffect(()=>{mt.setIdes(e)},[e]),l.useEffect(()=>{mt.setResolveAction((a,o,i)=>{t(a,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const a=mt.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=cp.on("status_event",o=>{mt.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(),w=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(g);t(d,"resolve_action",{action:w?"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 WC="adhdev_dashboardLayout_v1",UC="adhdev_dashboardDockview_v1",GC="adhdev_dashboardDockviewHiddenRestore_v1",Bn={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function el(e,t){try{const n=localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}}function qC(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Up(e){return`${WC}:${e}`}function zC(e){const t=Up(e);return el(t,null)}function KC(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=Up(e);if(n){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Gp(e){return`${UC}:${e}`}function VC(e){const t=Gp(e);return el(t,null)}function YC(e,t){try{const n=Gp(e);if(!t){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function qp(e){return`${GC}:${e}`}function JC(e){const t=qp(e);return el(t,{})}function QC(e,t){try{const n=qp(e);if(Object.keys(t).length===0){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function XC(){return{groupAssignments:[...Bn.groupAssignments],focusedGroup:Bn.focusedGroup,groupActiveTabIds:{...Bn.groupActiveTabIds},groupTabOrders:{...Bn.groupTabOrders},groupSizes:[...Bn.groupSizes]}}function ZC(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):t.length===0}function ej(){const[e]=l.useState(()=>qC(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,w]=l.useState(!1),h=l.useCallback(()=>{if(g)return;const A=zC(e)??XC();n(new Map(A.groupAssignments)),a(A.focusedGroup),i(A.groupActiveTabIds),u(A.groupTabOrders),d(A.groupSizes),w(!0)},[g,e]);l.useEffect(()=>{g&&KC(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)"),M=T=>f(T.matches);return A.addEventListener("change",M),()=>A.removeEventListener("change",M)},[]);const x=l.useCallback(A=>{n(A)},[]),k=l.useCallback(A=>{a(A)},[]),b=l.useCallback(A=>{i(A)},[]),S=l.useCallback(A=>{u(A)},[]),j=l.useCallback(A=>{d(A)},[]),y=l.useCallback(A=>{k(A)},[k]),v=l.useCallback((A,M)=>{i(T=>(T[A]??null)===(M??null)?T:{...T,[A]:M})},[]),N=l.useCallback((A,M)=>{u(T=>{const R=T[A];return ZC(R,M)?T:{...T,[A]:M}})},[]),C=l.useCallback((A,M)=>{const T=M.get(A)??0;return v(T,A),y(T),T},[y,v]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:x,focusedGroup:r,updateFocusedGroup:k,focusGroup:y,groupActiveTabIds:o,updateGroupActiveTabIds:b,setGroupActiveTab:v,groupTabOrders:c,updateGroupTabOrders:S,setGroupTabOrder:N,groupSizes:p,updateGroupSizes:j,isMobile:m,hasHydratedStoredLayout:g,hydrateStoredLayout:h,focusConversationTab:C}}function tj(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0],r=Aa(t);return typeof(n==null?void 0:n.id)=="string"&&r.includes(n.id)}function sj({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),w=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 k=n(e);k&&(i(k.tabKey,r),g.current=!0,w.current=!0,h.current!=null&&(window.clearTimeout(h.current),h.current=null),c(b=>{const S=new URLSearchParams(b);return S.delete("activeTab"),S},{replace:!0}))},[e,t,n,r,a,o,i,c]),l.useEffect(()=>{if(!(w.current||a)&&t.length!==0){if(!e){o(),w.current=!0;return}if(g.current){w.current=!0;return}if(h.current==null)return h.current=window.setTimeout(()=>{h.current=null,!(w.current||a)&&(o(),w.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 k=m.find(b=>b.id===p.routeId);k&&(!k.chats||k.chats.length===0||tj(k.chats,p))&&(x.current=!0,f())},[u,p,d,m,f])}function uo(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=Aa(t);return typeof(n==null?void 0:n.id)=="string"&&r.includes(n.id)}function zp({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 w=>{try{await e("standalone","launch_ide",{ideType:w,enableCdp:!0})}catch(h){console.error("Launch failed",h)}},[e]),m=l.useCallback(async(w,h)=>{try{const x=w||(t==null?void 0:t.daemonId)||"",k=await e(x,"switch_chat",{id:h,sessionId:h,...Ws(t)}),b=k==null?void 0:k.result;if((k==null?void 0:k.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?on(a,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?on(a,`⚠️ Switch error: ${b}`):on(a,"⚠️ Session switch failed")}catch(x){console.error("Switch failed",x),on(a,`❌ Switch failed: ${x.message||"connection error"}`)}},[t,e,a]),f=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const w=Us(t);await e(w,"new_chat",{...Ws(t)}),V0(w,t.sessionId,Aa(t)[0]),o(h=>({...h,[t.tabKey]:Date.now()}))}catch(w){console.error("New chat failed",w)}finally{c(!1)}}},[t,i,e,o]),g=l.useCallback(async()=>{var w,h;if(!(!t||u)){p(!0);try{const x=Us(t),k=async()=>e(x,"list_chats",{forceExpand:!0,...Ws(t)});let b=await k(),S=(b==null?void 0:b.chats)||((w=b==null?void 0:b.result)==null?void 0:w.chats);uo(S,t)&&(await new Promise(j=>setTimeout(j,450)),b=await k(),S=(b==null?void 0:b.chats)||((h=b==null?void 0:b.result)==null?void 0:h.chats)),b!=null&&b.success&&Array.isArray(S)&&(r(t.routeId,S),uo(S,t)&&!uo(n,t)&&on(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 nj(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 _c(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 Pr(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 $c(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 aj(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 oj(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 Hc(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 Fc(e){return Array(e).fill(100/e)}function ij({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(()=>Pr(e,p),[e,p]),f=m.assignments,g=l.useMemo(()=>c?1:m.groupCount,[m.groupCount,c]),w=g>1,h=l.useCallback((y,v)=>{t(N=>{const C=new Map(Pr(N,p).assignments);return v===0?C.delete(y):C.set(y,v),C}),r(N=>({...N,[v]:y})),n(v)},[t,p,r,n]),x=l.useCallback(y=>{t(v=>{const N=Pr(v,p).assignments,C=new Map;for(const[A,M]of N)M!==y&&(M>y?C.set(A,M-1):C.set(A,M));return C}),i(v=>{if(v.length<=1)return[];const N=[...v];N.splice(y,1);const C=N.reduce((A,M)=>A+M,0);return C>0?N.map(A=>A/C*100):[]}),n(0)},[t,p,i,n]),k=l.useCallback((y,v)=>{v.preventDefault();const N=d.current;if(!N)return;const C=v.clientX,A=N.offsetWidth,M=o.length===g?[...o]:Fc(g),T=E=>{const z=(E.clientX-C)/A*100,F=[...M];F[y]=Math.max(15,M[y]+z),F[y+1]=Math.max(15,M[y+1]-z),i(F)},R=()=>{document.removeEventListener("mousemove",T),document.removeEventListener("mouseup",R),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",T),document.addEventListener("mouseup",R)},[o,g,i]),b=l.useCallback((y,v,N)=>{if(g>=4)return;const C=N==="left"?v:v+1;t(A=>{const M=Pr(A,p).assignments,T=new Map;for(const R of u){const E=M.get(R.tabKey)??0,_=E>=C?E+1:E;_>0&&T.set(R.tabKey,_)}return C>0&&T.set(y,C),T}),i(A=>{const M=A.length===g?[...A]:Fc(g),T=M[v]??100/g,R=Math.max(15,T/2),E=Math.max(15,T/2),_=[...M];_[v]=R,_.splice(C,0,E);const z=_.reduce((F,D)=>F+D,0);return _.map(F=>F/z*100)}),r(A=>{const M=Hc(A,C);return M[C]=y,M}),a(A=>{const M=Hc(A,C);return M[C]=[y],M}),n(C)},[g,t,p,u,i,r,a,n]);l.useEffect(()=>{nj(e,f)||t(f)},[e,f,t]),l.useEffect(()=>{const{mapping:y,usedGroups:v}=m;r(N=>{const C=$c(N,y);return _c(N,C)?N:C}),a(N=>{const C=$c(N,y);return _c(N,C)?N:C}),n(N=>{const C=c?0:aj(N,v,y);return N===C?N:C}),i(N=>{const C=c?[]:oj(N,v,m.groupCount);return rj(N,C)?N:C})},[m,c,r,a,n,i]);const S=l.useMemo(()=>{const y=Array.from({length:g},()=>[]);for(const v of u){const N=f.get(v.tabKey)??0,C=Math.min(N,g-1);y[C].push(v)}return y},[u,f,g]),j=l.useCallback(()=>{t(new Map),n(0)},[t,n]);return{containerRef:d,normalizedGroupAssignments:f,numGroups:g,isSplitMode:w,groupedConvs:S,moveTabToGroup:h,closeGroup:x,handleResizeStart:k,splitTabRelative:b,clearAllSplits:j}}function po(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 lj(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 Ir(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function tl(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},n=po(t.channel)||po(e.updateChannel)||po(e.releaseChannel)||void 0,r=lj(t.npmTag)||(n==="preview"?"next":n==="stable"?"latest":void 0),a=Ir(t.targetVersion)||Ir(e.serverVersion)||void 0,o=Ir(t.minVersion)||void 0,i=Ir(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 dn(e,t=null){return tl(e).targetVersion||t}function Kp(e){return tl(e).channel||null}function Vp(e){const t=tl(e);return{...t.channel?{channel:t.channel}:{},...t.npmTag?{npmTag:t.npmTag}:{},...t.targetVersion?{targetVersion:t.targetVersion}:{},...Object.keys(t).length>0?{updatePolicy:t}:{}}}function cj({ides:e,sendDaemonCommand:t}){const n="1.0.12",r=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:Ji(m,dn(m,n))).sort((m,f)=>Number(tr(f,dn(f,n)))-Number(tr(m,dn(m,n)))),[n,e]),a=l.useMemo(()=>r.some(m=>tr(m,dn(m,n))),[n,r]),o=l.useMemo(()=>r.map(m=>dn(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 g,w;const f=e.find(h=>h.id===m);if(f){p(h=>({...h,[m]:"upgrading"}));try{const h=await t(m,"daemon_upgrade",Vp(f));(g=h==null?void 0:h.result)!=null&&g.upgraded||(w=h==null?void 0:h.result)!=null&&w.success?p(x=>({...x,[m]:"done"})):p(x=>({...x,[m]:"error"}))}catch{p(h=>({...h,[m]:"error"}))}}},[e,t]);return{versionMismatchDaemons:r,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:u,handleBannerUpgrade:d}}const Yp=80;function Yr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function dj(e){return{...e,createdAt:Yr(e.createdAt),updatedAt:Yr(e.updatedAt,e.createdAt),lastEventAt:Yr(e.lastEventAt,e.updatedAt||e.createdAt)}}function uj(e){const t=wu(e);return t==="unknown:"?e.id:t}function pj(e){return[e.type,yu(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function mj(e,t=Yp){const n=new Map;for(const r of e){if(r.deletedAt)continue;const a=uj(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 hj(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=Na(a,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const u=Yr(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,n),p=pj({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(dj({id:p,dedupKey:p,type:c,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:Ou(a),preview:o0(a),createdAt:u,updatedAt:u,lastEventAt:u}))}return mj(r)}function fj(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function bj(e){const{conversations:t,liveSessionInboxState:n,maxItems:r=Yp}=e,a=l.useMemo(()=>hj(t,n).slice(0,Math.max(0,r)),[t,n,r]),o=l.useMemo(()=>fj(a),[a]);return{notifications:a,unreadCount:o}}function gj({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 sl(...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 xj(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 nl(e,t=[]){if(e==="win32"){for(const n of t){if(typeof n!="string")continue;const r=xj(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 rl(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 Bc(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 Jp(e,t={}){const n=e==null?void 0:e.mcpConfig;if((n==null?void 0:n.mode)!=="manual")return null;const a=Bc(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:Bc(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"})}}function wj(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 dr(e){return`/dashboard?activeTab=${encodeURIComponent(e)}`}function Qp(e){return Ma(e)||e.tabKey||e.routeId||null}function Xp(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=cs(e.conversations,r)||e.conversations.find(i=>i.routeId===r);if(o!=null&&o.tabKey)return o.tabKey}return t||n||r||null}function Ns(e){return String(e||"").trim()}function Zp(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function xa(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function kj(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function Sj(e,t){const n=Ns(e.providerSessionId),r=Ns(e.targetSessionId),a=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(Ns).filter(Boolean);return!!(n&&i.includes(n)||r&&i.includes(r))});return a?a.tabKey:r||n||null}function Cj(e,t,n){if(t.event!=="agent:generating_completed")return null;const r=Zp(t.daemonId);if(r&&r!==e.machineId)return null;const a=Ns(t.providerType);if(e.providerType&&a!==e.providerType)return null;const o=Ns(e.resumeSessionId),i=Ns(e.launchedSessionId),c=Ns(t.providerSessionId),u=Ns(t.targetSessionId);if(o&&o!==c&&o!==u||i&&i!==c&&i!==u)return null;const p=xa(e.workspacePath);if(p){const d=xa(t.workspaceName);if(d&&!kj(d,p))return null}return Sj(t,n)}function Oc(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function jj({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=xa(r.workspacePath),p=e.find(m=>{var x,k,b,S;if(!m||m.type==="adhdev-daemon"||Zp(m.daemonId||m.id)!==r.machineId||(ir(m)?"cli":mn(m)?"acp":"ide")!==r.kind)return!1;const w=String(m.agentType||m.type||"");if(r.providerType&&w!==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=xa(m.workspace||m.runtimeWorkspaceLabel);return j?j===u:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((S=(b=(k=(x=m.activeChat)==null?void 0:x.messages)==null?void 0:k.at)==null?void 0:b.call(k,-1))==null?void 0:S.timestamp)||0)>=r.startedAt-5e3});if(!p)return;const d=Xp({entrySessionId:p.sessionId,entryInstanceId:p.instanceId,entryRouteId:p.id,conversations:t});d&&(i(),n(d))},[i,t,e,n,r]),l.useEffect(()=>mt.onStatusEvent(u=>{const p=o.current;if(!p)return;const d=Cj(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 Nj({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:n,activeConv:r,ides:a,setCliViewModeOverrides:o}){const i=Bi(),{launchCli:c}=ka(),u=l.useCallback(async(x,k)=>rl(e,x,k),[e]),p=l.useCallback(async(x,k)=>{if(!k.trim())return{ok:!1,error:"Choose a workspace path first."};try{const b=await e(x,"workspace_add",{path:k.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,k,b)=>{var S;try{const j={ideType:k,enableCdp:!0};(S=b==null?void 0:b.workspacePath)!=null&&S.trim()&&(j.workspace=b.workspacePath.trim());const y=await e(x,"launch_ide",j);return!(y!=null&&y.success)&&(y==null?void 0:y.success)!==void 0?{ok:!1,error:(y==null?void 0:y.error)||"Could not launch IDE"}:(t({machineId:x,kind:"ide",providerType:k,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,k,b,S)=>{var y,v,N,C;const j=Date.now();try{const A={cliType:b};(y=S==null?void 0:S.workspacePath)!=null&&y.trim()?A.dir=S.workspacePath.trim():S!=null&&S.workspaceId?A.workspaceId=S.workspaceId:S!=null&&S.useHome&&(A.useHome=!0),(v=S==null?void 0:S.resumeSessionId)!=null&&v.trim()&&(A.resumeSessionId=S.resumeSessionId.trim()),Array.isArray(S==null?void 0:S.cliArgs)&&S.cliArgs.length>0&&(A.cliArgs=S.cliArgs),(N=S==null?void 0:S.initialModel)!=null&&N.trim()&&(A.initialModel=S.initialModel.trim()),(C=S==null?void 0:S.initialThinkingLevel)!=null&&C.trim()&&(A.initialThinkingLevel=S.initialThinkingLevel.trim());const M=await c(x,A),T=(M==null?void 0:M.result)||M,R=(T==null?void 0:T.sessionId)||(T==null?void 0:T.id);return M!=null&&M.success&&R?(t({machineId:x,kind:k,providerType:b,workspacePath:(S==null?void 0:S.workspacePath)||null,resumeSessionId:(S==null?void 0:S.resumeSessionId)||null,launchedSessionId:R,startedAt:j}),{ok:!0}):M!=null&&M.success?(t({machineId:x,kind:k,providerType:b,workspacePath:(S==null?void 0:S.workspacePath)||null,resumeSessionId:(S==null?void 0:S.resumeSessionId)||null,startedAt:j}),{ok:!0}):{ok:!1,error:(M==null?void 0:M.error)||(T==null?void 0:T.error)||`Could not launch ${k.toUpperCase()} session`,code:(M==null?void 0:M.code)||(T==null?void 0:T.code)||void 0}}catch(A){return Oc(A)?(t({machineId:x,kind:k,providerType:b,workspacePath:(S==null?void 0:S.workspacePath)||null,resumeSessionId:(S==null?void 0:S.resumeSessionId)||null,startedAt:j}),{ok:!0}):{ok:!1,error:A instanceof Error?A.message:`Could not launch ${k.toUpperCase()} session`}}},[c,e,t]),f=l.useCallback(async x=>{var k;if(i!=null&&i.listMeshes)return i.listMeshes(x);if(!x)return[];try{const b=await e(x,"list_meshes",{}),S=(b==null?void 0:b.result)??b;if((S==null?void 0:S.success)===!1)throw new Error((S==null?void 0:S.error)||"Could not load meshes");return(Array.isArray(S==null?void 0:S.meshes)?S.meshes:Array.isArray((k=S==null?void 0:S.result)==null?void 0:k.meshes)?S.result.meshes:[]).map(y=>{var v;return{id:String((y==null?void 0:y.id)||""),name:String((y==null?void 0:y.name)||(y==null?void 0:y.id)||"Untitled mesh"),repoIdentity:(y==null?void 0:y.repoIdentity)||(y==null?void 0:y.repo_identity)||null,workspace:Array.isArray(y==null?void 0:y.nodes)&&y.nodes.length>0?String(((v=y.nodes[0])==null?void 0:v.workspace)||""):null,nodesCount:Array.isArray(y==null?void 0:y.nodes)?y.nodes.length:void 0,status:(y==null?void 0:y.status)||null}}).filter(y=>y.id)}catch(b){throw console.error("List meshes failed",b),b}},[i,e]),g=l.useCallback(async(x,k,b,S)=>{var y,v;if(!k.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(x,k,b,S);const j=Date.now();try{const N={meshId:k.trim()};b.trim()&&(N.cliType=b.trim());const C=(y=S==null?void 0:S.initialModel)==null?void 0:y.trim(),A=(v=S==null?void 0:S.initialThinkingLevel)==null?void 0:v.trim();C&&(N.initialModel=C),A&&(N.initialThinkingLevel=A);const M=await e(x,"launch_mesh_coordinator",N),T=(M==null?void 0:M.result)??M;if((T==null?void 0:T.success)===!1||(M==null?void 0:M.success)===!1){const E=String((T==null?void 0:T.code)||(M==null?void 0:M.code)||""),_=wj((T==null?void 0:T.meshCoordinatorSetup)||(T==null?void 0:T.manualSetup)||(M==null?void 0:M.meshCoordinatorSetup)||(M==null?void 0:M.manualSetup));return{ok:!1,error:(T==null?void 0:T.error)||(M==null?void 0:M.error)||"Could not launch mesh coordinator",code:E||void 0,manualSetup:_}}const R=(T==null?void 0:T.sessionId)||(T==null?void 0:T.id);return R?n(R):t({machineId:x,kind:"cli",providerType:(T==null?void 0:T.cliType)||b.trim()||void 0,workspacePath:(T==null?void 0:T.workspace)||null,startedAt:j}),{ok:!0}}catch(N){return Oc(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]),w=l.useCallback(async(x,k)=>{if(!x||!k)return[];try{const b=await e(x,"list_saved_sessions",{providerType:k,kind:"cli",limit:30}),S=(b==null?void 0:b.result)??b;return Array.isArray(S==null?void 0:S.sessions)?S.sessions:[]}catch(b){return console.error("List saved sessions failed",b),[]}},[e]),h=l.useCallback(async x=>{await Bp({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:w,setActiveCliViewMode:h}}function Aj(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 Mj(e,t,n=Date.now()){return!e||!Aj(t)?null:{tabKey:e,nonce:n}}function Tj({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,k;if(!e){if(c){const b=t.find(S=>S.tabKey===c);if(b)return b}return n[0]}const h=r[a];if(h){const b=t.find(S=>S.tabKey===h);if(b)return b}return((x=o[a])==null?void 0:x[0])||((k=o[0])==null?void 0:k[0])},[t,c,a,r,o,e,n]),f=l.useCallback(h=>{u(h)},[]),g=l.useCallback(h=>{u(h.tabKey),i(x=>{const k=new URLSearchParams(x),b=l0(h);return b?k.set("activeTab",b):k.delete("activeTab"),k},{replace:!0})},[i]),w=l.useCallback((h,x)=>{const k=Mj(h,x);k&&d(k)},[]);return{activeConv:m,openDesktopConversation:g,requestScrollToBottom:w,scrollToBottomRequest:p,setDesktopActiveTab:f}}function Pj(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 Ij(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 Dj({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=Is(e,n),m=Ij({tabKey:e.tabKey,historySessionId:Ma(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:Ks(e),liveState:d}),f=m.autoReadKey,g=Pj({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 w=()=>{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(w,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(w,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 Lj({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:n,ides:r,sendDaemonCommand:a,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:u}){var W;const{launchCli:p}=ka(),[d,m]=l.useState(!1),[f,g]=l.useState([]),[w,h]=l.useState(()=>Ft()),[x,k]=l.useState(!1),[b,S]=l.useState(null),j=l.useRef(null),y=l.useMemo(()=>n||t||e,[e,n,t]),v=!!y&&ct(y)&&!lt(y),N=l.useMemo(()=>{if(!y||!v)return null;const L=y.daemonId||y.routeId||"",P=bs(y),$=mo(y);return`${L}:${P}:${y.providerSessionId||""}:${$}`},[y,v]),C=l.useMemo(()=>!y||!v?"":mo(y),[y,v]),{isCreatingChat:A,isRefreshingHistory:M,handleSwitchSession:T,handleNewChat:R,handleRefreshHistory:E}=zp({sendDaemonCommand:a,activeConv:y,chats:(W=r.find(L=>L.id===(y==null?void 0:y.routeId)))==null?void 0:W.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),_=l.useCallback(()=>{m(!0)},[]),z=l.useCallback(()=>{m(!1)},[]),F=l.useCallback(async()=>{if(!(!y||!v||x)){k(!0);try{const L=y.daemonId||y.routeId,P=bs(y),$=mo(y),I=await a(L,"list_saved_sessions",{agentType:P,providerType:P,kind:"cli",limit:50,...y.providerSessionId?{providerSessionId:y.providerSessionId}:{},...$?{workspace:$}:{}}),U=(I==null?void 0:I.result)??I;g(Array.isArray(U==null?void 0:U.sessions)?U.sessions:[])}catch(L){console.error("Refresh saved sessions failed",L),g([])}finally{k(!1)}}},[y,x,v,a]);l.useEffect(()=>{if(!d){j.current=null;return}if(!v){j.current=null,g([]),k(!1);return}!N||x||j.current!==N&&(j.current=N,F())},[F,d,x,v,N]);const D=l.useCallback(async L=>{if(!y||!v||!L.providerSessionId||!L.workspace)return;const P=y.daemonId||y.routeId,$=bs(y);try{S(L.providerSessionId);const I=await p(P,{cliType:$,dir:L.workspace,resumeSessionId:L.providerSessionId,initialModel:Nu(L.summaryMetadata,"model",{preferShortValue:!0})||void 0}),U=(I==null?void 0:I.result)??I,J=typeof(U==null?void 0:U.sessionId)=="string"?U.sessionId:typeof(U==null?void 0:U.id)=="string"?U.id:"";J&&u(re=>{const Y=new URLSearchParams(re);return Y.set("activeTab",J),Y},{replace:!0}),z()}catch(I){console.error("Resume saved session failed",I)}finally{S(null)}},[z,y,v,a,u]);return{historyModalOpen:d,openHistoryModal:_,closeHistoryModal:z,historyTargetConv:y,isSavedSessionHistoryTarget:v,isHistoryCreatingChat:A,isHistoryRefreshingHistory:M,handleHistorySwitchSession:T,handleHistoryNewChat:R,handleHistoryRefresh:E,savedHistorySessions:f,savedHistoryFilters:w,setSavedHistoryFilters:h,missingWorkspaceResumePath:C,isSavedHistoryLoading:x,resumingSavedHistorySessionId:b,handleRefreshSavedHistory:F,handleResumeSavedHistorySession:D}}function Rj({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 k=c(r);return k&&!ct(k)&&!lt(k)?k:null},[e,r,c]),g=l.useMemo(()=>{const k=u==null?void 0:u.routeId;if(!k)return null;const b=u!=null&&u.tabKey?o.find(S=>S.tabKey===u.tabKey):a?o.find(S=>S.tabKey===a):null;return(b==null?void 0:b.routeId)===k?b:cs(o,k)},[o,u,a]),w=l.useMemo(()=>{if(g)return i.find(k=>k.id===g.routeId)},[i,g]);l.useEffect(()=>{f&&(p({routeId:f.routeId,tabKey:nc(f)}),m(f),n({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,n,f]);const h=l.useCallback(k=>{k&&(p({routeId:k.routeId,tabKey:nc(k)}),m(k))},[]),x=l.useCallback(()=>{p(null),m(null)},[]);return{remoteDialogConv:g,remoteDialogIdeEntry:w,remoteDialogActiveConv:d,setRemoteDialogActiveConv:m,openRemoteDialog:h,closeRemoteDialog:x}}function Ej({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:w,closeRemoteDialog:h}=Rj({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}),[x,k]=l.useState(!1),[b,S]=l.useState(null),j=l.useCallback(async N=>{const C=N||u;!C||!ct(C)&&!lt(C)||(S(C),k(!0))},[u]),y=l.useCallback(()=>{k(!1),S(null)},[]),v=l.useCallback(async N=>{const C=b||u;if(!C||!ct(C)&&!lt(C)){y();return}k(!1);try{const A=bs(C),M=C.routeId||C.daemonId||"";await p(M,"stop_cli",{cliType:A,targetSessionId:C.sessionId,mode:N,...Ia(C)})}catch(A){console.error("Stop CLI failed:",A)}finally{S(null)}},[u,y,b,p]);return{remoteDialogConv:d,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:g,openRemoteDialog:w,closeRemoteDialog:h,cliStopDialogOpen:x,cliStopTargetConv:b,requestCliStop:j,cancelCliStop:y,confirmCliStop:v}}function ho(e,t=!0){return(e??!0)&&t}const al=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:w,userName:h,scrollToBottomRequestNonce:x,isInputActive:k=!0,isVisible:b=!0}){const S=r,j=!r,y=ho(b,S),v=ho(b,j),N=ho(b),C=$p(t),A=C.status||C.modalMessage||C.modalButtons?{...t,...C.status?{status:C.status}:{},...C.modalMessage!==void 0?{modalMessage:C.modalMessage}:{},...C.modalButtons!==void 0?{modalButtons:C.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(gu,{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(Ys,{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:S?"visible":"hidden",pointerEvents:S?"auto":"none"},children:s.jsx(Bk,{activeConv:A,clearToken:n,terminalRef:o,handleSendChat:u,isSendingChat:d,sendFeedbackMessage:m,isVisible:y,isInputActive:k&&y})}),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(oi,{activeConv:A,ideEntry:a,handleSendChat:u,isSendingChat:d,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:w,userName:h,scrollToBottomRequestNonce:x,isInputActive:k&&v,isVisible:v})})]}):s.jsx(oi,{activeConv:A,ideEntry:a,handleSendChat:u,handleForceSendChat:p,isSendingChat:d,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:w,userName:h,scrollToBottomRequestNonce:x,isInputActive:k&&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 _j({conversation:e,className:t="",onOpenNativeConversation:n,onOpenMachine:r,interactive:a=!0,meshOnly:o=!1}){var j,y,v;const{t:i}=Ne("common"),c=mr(),u=Ds(e),p=o?null:Bu(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=vn(e),w=i0(e),h=(j=e.settings)==null?void 0:j.meshNodeFor,x=e.meshQueueStats,k=((y=e.coordinator)==null?void 0:y.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]),S=l.useCallback(()=>{if(n){n();return}const N=Qp(e);N&&c(dr(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:S,title:w,children:[s.jsx(us,{size:12}),s.jsx("span",{children:w})]}):s.jsxs("span",{className:"conversation-meta-chip",title:w,children:[s.jsx(us,{size:12}),s.jsx("span",{children:w})]})),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(or,{size:12}),s.jsx("span",{children:g})]}),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(or,{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(Ts,{size:12}),s.jsx("span",{children:p})]}):s.jsxs("span",{className:"conversation-meta-chip",title:p,children:[s.jsx(Ts,{size:12}),s.jsx("span",{children:p})]})),h&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(Ts,{size:12}),s.jsx("span",{children:i("dashboard.metaChips.meshNode")})]}),k&&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($f,{size:12}),s.jsxs("span",{children:[x.pending," Pending"]})]})]})}function $j({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:w,onStopCli:h,cliViewMode:x,onSetCliViewMode:k,handleSendChat:b,handleForceSendChat:S,handleFocusAgent:j,handleModalButton:y,handleRelaunch:v}){var R,E;const N=l.useRef(null),C=ct(e)&&!t,A=C&&x==="terminal",M=!!e.daemonId&&!!((R=e.coordinator)!=null&&R.meshId||(E=e.settings)!=null&&E.meshCoordinatorFor),T=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 ${T} 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(Ai,{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:xt(e)}),s.jsx("div",{className:"min-w-0 max-w-full text-xs text-text-secondary",children:s.jsx(_j,{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:[C&&x&&s.jsx(bp,{mode:x,onChange:k,compact:!0}),C&&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(At,{size:14})}),M&&w&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>w(e),type:"button",title:"Open live repo mesh graph","aria-label":"Open live repo mesh graph",children:s.jsx(es,{size:14})}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>f(e),type:"button",children:s.jsx(Ti,{size:14})}),!t&&!C&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:s.jsx(us,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(al,{activeConv:e,clearToken:0,isCliTerminal:A,ideEntry:r,terminalRef:N,handleModalButton:y,handleRelaunch:v,handleSendChat:b,handleForceSendChat:S,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:j,isFocusingAgent:u,actionLogs:a,userName:o})})]})}const fo={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 Hj(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function em(){const[e,t]=l.useState("unix"),[n,r]=l.useState("powershell"),[a,o]=l.useState(!1),i=e==="unix"?"unix":n;l.useEffect(()=>{t(Hj())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(fo[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:fo[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:fo[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 tm({section:e,onSectionChange:t}){const n=[{key:"machines",label:"Machines",icon:us},{key:"chats",label:"Chats",icon:Zs}];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 Dr({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 nn({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 On({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 Fj({conversation:e,onCancel:t,onConfirm:n}){const{t:r}=Ne(),a=xt(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 Lr({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",w=t==="task_complete",{isReconnecting:h,isConnecting:x}=An(e.conversation),k=xt(e.conversation),b=yn(e.conversation),S=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",y=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",C=g?"text-text-secondary opacity-80":"text-text-muted",A=g?"text-text-muted opacity-80":"text-text-muted",M=!f&&!w,T=dp(e.conversation),R="text-[color:var(--status-warning)]",E=_=>{if(!c)return;_.preventDefault(),_.stopPropagation();const z=c==null?void 0:c(e.conversation);Promise.resolve(z).catch(F=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",F)})};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 ${y}`,style:m?{color:"var(--accent-on-primary)"}:void 0,children:n(k)}),T&&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:k}),title:d("mobileInbox.openLiveMeshGraph"),children:s.jsx(es,{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:E,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:k})}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${N}`,children:[s.jsx("span",{className:"truncate",children:b}),s.jsx(da,{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:`${R} 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")})]}):S==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:R,children:d("mobileInbox.actionNeeded")})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${C}`,children:e.preview})]}),s.jsxs("div",{className:"mobile-inbox-corner-actions absolute top-3 right-3 flex items-center gap-1.5",children:[M&&s.jsx("span",{className:`mr-0.5 text-[11px] font-medium shrink-0 ${A}`,children:fu(e.timestamp)}),w&&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:k}):d("mobileInbox.mute",{title:k}),title:d(u?"mobileInbox.mutedTitle":"mobileInbox.muteNotifications"),children:u?s.jsx(nu,{size:13}):s.jsx(Nn,{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:k}),title:d("mobileInbox.hideConversationTitle"),children:s.jsx(Pi,{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:k}),title:d("mobileInbox.stopSessionTitle"),children:s.jsx(At,{size:13})})]})]})},e.conversation.tabKey)}function Wc({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 Bj({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:w,onOpenNewSession:h,onOpenMachine:x,onOpenSettings:k,onSectionChange:b,wsStatus:S="connected",isStandalone:j=!1,onCollectChatDebugBundle:y,isConversationMuted:v,onToggleMuteConversation:N}){const{t:C}=Ne(),[A,M]=l.useState(null),T=S==="disconnected"||S==="reconnecting"||S==="offline"||S==="auth_failed",R=i.length>0,E=t.length>0||n.length>0||r.length>0||a.length>0,_=C(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),z=j?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",F=j?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",D=l.useCallback(async P=>{const $=Us(P);if(!$)return;const I=Array.isArray(P.messages)?P.messages:[],U=zu({activeConv:P,visibleMessages:I,actionLogs:u,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:I.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),J=await p($,"get_chat_debug_bundle",{...Ws(P),delivery:"daemon_file",frontendSnapshot:U}),re=er(J),Y=Yu(re),X=await Vu(Y);X==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),mt.showToast(Ku(re,{locatorCopyStatus:X}),X==="failed"?"warning":"success")},[u,p]),W=y||D,L=l.useCallback(()=>{A&&(f==null||f(A),M(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 ${z}`,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(Nn,{size:13}),s.jsx("span",{children:t.length+n.length})]}),s.jsx("button",{onClick:k,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(Sa,{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] ${F}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:T?s.jsx(On,{icon:s.jsx(Wc,{}),title:C(S==="offline"?"mobileInbox.networkOffline":S==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:C(S==="offline"?"mobileInbox.waitingForNetwork":S==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):i.length===0?s.jsx(On,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:C(j?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:C(j?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!j&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(em,{})})}):s.jsx(nn,{children:i.map((P,$)=>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] ${$>0?"border-t border-border-subtle/70":""}`,onClick:()=>x(P.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(P.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:P.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:P.unread>0?s.jsx("span",{className:"text-accent-primary",children:C("mobileInbox.newCount",{count:P.unread})}):P.total>0?C("mobileInbox.chatCount",{count:P.total}):C("mobileInbox.idle")})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:P.subtitle}),P.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[C("mobileInbox.chatCount",{count:P.total}),P.unread>0?C("mobileInbox.unreadSuffix",{count:P.unread}):""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:C("mobileInbox.noActiveChats")})]})]},P.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(Dr,{title:C("mobileInbox.needsAttention"),className:"mb-0"}),s.jsx(nn,{children:t.map((P,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Lr,{item:P,type:"needs_attention",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>M(P.conversation):void 0,onRequestStopCli:w?()=>w(P.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:W,isMuted:v==null?void 0:v(P.conversation),onToggleMute:N?()=>N(P.conversation):void 0})},P.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(Dr,{title:C("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),s.jsx(nn,{children:n.map((P,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Lr,{item:P,type:"task_complete",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>M(P.conversation):void 0,onRequestStopCli:w?()=>w(P.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:W,isMuted:v==null?void 0:v(P.conversation),onToggleMute:N?()=>N(P.conversation):void 0})},P.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(Dr,{title:C("mobileInbox.workingNow"),className:"mb-0 mt-2"}),s.jsx(nn,{children:r.map((P,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Lr,{item:P,type:"working",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>M(P.conversation):void 0,onRequestStopCli:w?()=>w(P.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:W,isMuted:v==null?void 0:v(P.conversation),onToggleMute:N?()=>N(P.conversation):void 0})},P.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(Dr,{title:C("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(nn,{children:a.map((P,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Lr,{item:P,type:"earlier",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>M(P.conversation):void 0,onRequestStopCli:w?()=>w(P.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:W,isMuted:v==null?void 0:v(P.conversation),onToggleMute:N?()=>N(P.conversation):void 0})},P.conversation.tabKey))}):E?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:C("mobileInbox.allCaughtUp")}):T?s.jsx(On,{icon:s.jsx(Wc,{size:28}),title:C("mobileInbox.connecting"),subtitle:C("mobileInbox.connectingSubtitle")}):R?s.jsx(On,{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(Zs,{size:20})}),title:C("mobileInbox.noConversations"),subtitle:C("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":C("paneGroup.newSession"),title:C("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:C("paneGroup.newSession")})]})}):s.jsx(On,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:C("mobileInbox.noMachinesConnected"),subtitle:C("mobileInbox.noMachinesSubtitle")})]}),e==="chats"&&o.length>0&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(nn,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:C("mobileInbox.hiddenTabs")}),s.jsx("div",{className:"mt-0.5 text-[13px] text-text-muted",children:C("mobileInbox.collapsedCount",{count:o.length})})]}),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:C("mobileInbox.restoreAll")})]})})})]}),e==="chats"&&h&&E&&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":C("paneGroup.newSession"),title:C("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(Fj,{conversation:A,onCancel:()=>M(null),onConfirm:L}),s.jsx(tm,{section:e,onSectionChange:b})]})}function Oj(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=Js(e.summaryMetadata);n&&t.push(n),(e.messageCount||0)>0&&t.push(`${e.messageCount} msgs`);const r=Oj(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:r?`Updated ${r}`:"",preview:(e.preview||"").trim()}}function ol({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),w=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(At,{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(Ai,{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"||!w||a||(h.preventDefault(),u(w))},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:()=>{!w||a||u(w)},disabled:!w||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(xn,{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(w||n),disabled:!w&&!n||a,children:i})]})]})})}function nm({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:w,historyProviderNode:h,onConfirm:x,onCancel:k}){const{t:b}=Ne("common"),S=i??b("machine.launchConfirm.launch"),j=c??b("machine.launchConfirm.launching"),y=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:k,"aria-label":b("machine.launchConfirm.closeAria"),children:s.jsx(At,{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))}),(y==null?void 0:y.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:y.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&&w&&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=>w(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:k,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(su,{size:14}),u?j:S]})]})]})})}function Uc(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function rm(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?"⭐ ":""}${Uc(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:Uc(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 Wj(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Uj(e){return[Wj(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Gj(e){return e.lastLaunchedAt?ja(e.lastLaunchedAt):""}function am(e){return{metaText:Uj(e),updatedLabel:Gj(e)}}function bo(e,t,n){return e?"ide":t>0?"cli":n>0?"acp":null}function qj({selectedMachineEntry:e,cliProviders:t,acpProviders:n,machineAction:r,onBrowseDirectory:a,onListSavedSessions:o}){var he,$e,Be,Pe;const i=Tn(),[c,u]=l.useState(!1),p=(((he=e.detectedIdes)==null?void 0:he.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||(($e=d[0])==null?void 0:$e.id)||""),[w,h]=l.useState(""),[x,k]=l.useState(""),[b,S]=l.useState([]),[j,y]=l.useState(!1),[v,N]=l.useState(""),[C,A]=l.useState(!1),[M,T]=l.useState(bo(p,t.length,n.length)),R=l.useRef(null),[E,_]=l.useState(null),z=l.useRef("__home__"),[F,D]=l.useState("__home__"),[W,L]=l.useState(""),[P,$]=l.useState(""),[I,U]=l.useState(""),[J,re]=l.useState([]),[Y,X]=l.useState(()=>Ft().textQuery),[de,ne]=l.useState(()=>Ft().workspaceQuery),[O,ie]=l.useState(()=>Ft().modelQuery),[K,ae]=l.useState(()=>Ft().resumableOnly),[Ce,ye]=l.useState(()=>Ft().sortMode),[ke,me]=l.useState(!1),[q,G]=l.useState(!1),Z=l.useRef(null),V=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const fe=f==="__custom__"?w.trim():((Be=d.find(ve=>ve.id===f))==null?void 0:Be.path)||"",Te=f==="__custom__"&&!!fe&&r.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(r.message),ce=f!=="__custom__"&&((Pe=d.find(ve=>ve.id===f))==null?void 0:Pe.path)||"",H=l.useMemo(()=>(e.recentLaunches||[]).map(ve=>ve.workspace),[e]),pe=l.useCallback(async ve=>{y(!0),N("");try{const Ue=await a(ve);k(Ue.path),h(Ue.path),S(Ue.directories)}catch(Ue){N(Ue instanceof Error?Ue.message:"Could not load folder")}finally{y(!1)}},[a]),le=l.useCallback(()=>{var Ue;g("__custom__"),A(!0);const ve=nl(e.platform,sl(w.trim(),ce,H,e.defaultWorkspacePath,(Ue=d.find(ut=>ut.id===m))==null?void 0:Ue.path,d.map(ut=>ut.path)));pe(ve)},[w,m,pe,H,ce,e.platform,d]),B=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("")},[]),be=l.useCallback(ve=>{if(g(ve),ve==="__custom__"){le();return}h("")},[le]),je=l.useCallback(ve=>{g("__custom__"),h(ve)},[]),Se=l.useCallback((ve,Ue)=>{R.current=Ue,z.current=ve.selectedWorkspaceKey||"__home__",D(ve.selectedWorkspaceKey||"__home__"),L(ve.initialArgs||""),$(ve.initialModel||""),U(""),re([]);const ut=ve.providerType?`${e.id}:${ve.providerType}`:null;if(Jk(V.current,ut)){const ot=Ft();X(ot.textQuery),ne(ot.workspaceQuery),ie(ot.modelQuery),ae(ot.resumableOnly),ye(ot.sortMode)}V.current=ut,_(ve),ve.providerType&&o&&(me(!0),o(ve.providerType).then(ot=>re(ot||[])).catch(ot=>console.warn("Failed to load saved sessions",ot)).finally(()=>me(!1)))},[o,e.id]),He=l.useMemo(()=>gp(J,{textQuery:Y,workspaceQuery:de,modelQuery:O,resumableOnly:K,sortMode:Ce}),[O,K,J,Ce,Y,de]);l.useEffect(()=>{I&&(He.some(ve=>ve.providerSessionId===I)||U(""))},[He,I]);const Xe=l.useCallback(()=>{R.current&&(G(!0),R.current().finally(()=>{R.current=null,G(!1),_(null)}))},[]),dt=l.useCallback(()=>{R.current=null,_(null)},[]),it=l.useCallback(ve=>{z.current=ve,D(ve)},[]);return l.useEffect(()=>{var ve;Z.current!==e.id&&(Z.current=e.id,g(m||((ve=d[0])==null?void 0:ve.id)||"__custom__"),h(""),k(""),S([]),N(""),A(!1),X(Ft().textQuery),ne(Ft().workspaceQuery),ie(Ft().modelQuery),ae(Ft().resumableOnly),ye(Ft().sortMode),V.current=null,T(bo(p,t.length,n.length)))},[n.length,t.length,m,p,e.id,d]),l.useEffect(()=>{var ve;f!=="__custom__"&&(f&&d.some(Ue=>Ue.id===f)||g(m||((ve=d[0])==null?void 0:ve.id)||"__custom__"))},[m,f,d]),l.useEffect(()=>{M==="ide"&&p||M==="cli"&&t.length>0||M==="acp"&&n.length>0||T(bo(p,t.length,n.length))},[M,n.length,t.length,p]),{showAllRecent:c,setShowAllRecent:u,hasIdeOptions:p,workspaceRows:d,defaultWorkspaceId:m,workspaceChoice:f,customWorkspacePath:w,browseCurrentPath:x,browseDirectories:b,browseBusy:j,browseError:v,browseDialogOpen:C,activeLauncherKind:M,launchConfirm:E,launchConfirmWorkspaceKeyRef:z,launchConfirmWorkspaceKey:F,launchConfirmArgs:W,launchConfirmModel:P,launchConfirmResumeId:I,launchConfirmSavedSessions:J,launchConfirmTextFilter:Y,launchConfirmWorkspaceFilter:de,launchConfirmModelFilter:O,launchConfirmResumableOnly:K,launchConfirmSortMode:Ce,filteredLaunchConfirmSavedSessions:He,launchConfirmSessionsLoading:ke,launchConfirmBusy:q,resolvedWorkspacePath:fe,canCreateMissingWorkspace:Te,openBrowseDialog:le,loadBrowsePath:pe,handleWorkspaceChoiceChange:be,chooseCustomWorkspacePath:je,setCustomWorkspacePath:h,setBrowseDialogOpen:A,setActiveLauncherKind:T,openLaunchConfirm:Se,handleConfirmLaunch:Xe,closeLaunchConfirm:dt,setWorkspaceSelectionFromOption:B,setLaunchConfirmWorkspaceKeyAndSync:it,setLaunchConfirmArgs:L,setLaunchConfirmModel:$,setLaunchConfirmResumeId:U,setLaunchConfirmTextFilter:X,setLaunchConfirmWorkspaceFilter:ne,setLaunchConfirmModelFilter:ie,setLaunchConfirmResumableOnly:ae,setLaunchConfirmSortMode:ye}}function zj({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:w,onOpenMachineDetails:h,onMachineUpgrade:x,onLaunchDetectedIde:k,onAddWorkspace:b,onBrowseDirectory:S,onLaunchWorkspaceProvider:j,onListSavedSessions:y}){const{t:v}=Ne("common"),N=D=>D==="ide"?"IDE":D==="cli"?"CLI":"ACP",C=n.slice(0,4),A=t.slice(0,3),M=qj({selectedMachineEntry:e,cliProviders:r,acpProviders:a,machineAction:c,onBrowseDirectory:S,onListSavedSessions:y}),T=l.useMemo(()=>C.map(D=>{const{metaText:W,updatedLabel:L}=am(D);return{key:`recent-launch:${D.id}`,primary:D.label,secondary:W,updatedLabel:L,onClick:()=>{const{options:P,selectedKey:$}=rm({machine:{workspaces:M.workspaceRows,defaultWorkspaceId:M.defaultWorkspaceId},currentWorkspacePath:D.workspace,homeLabel:v("newSession.homeDirectory"),homeDescription:v("newSession.launchWithoutWorkspace")});M.openLaunchConfirm({title:D.kind==="ide"?ua(v,"restart-ide",D.label):D.providerSessionId?vp(v,D.label):ua(v,"start-fresh",D.label),description:D.kind==="ide"?pa(v,"restart-ide"):D.providerSessionId?yp(v):pa(v,"start-fresh"),confirmLabel:D.kind==="ide"?ma(v,"restart-ide"):D.providerSessionId?ii(v,!0):ma(v,"start-fresh"),busyLabel:D.kind==="ide"?ha(v,"restart-ide"):D.providerSessionId?xp(v,!0):ha(v,"start-fresh"),workspaceOptions:P,selectedWorkspaceKey:$,details:[{label:"Mode",value:N(D.kind)},...D.providerType?[{label:"Provider",value:D.providerType}]:[]]},async()=>{const I=P.find(U=>U.key===M.launchConfirmWorkspaceKeyRef.current);M.setWorkspaceSelectionFromOption(I),await w({...D,workspace:(I==null?void 0:I.workspacePath)??null})})}}}),[M,w,C,v]),R=l.useMemo(()=>A.map(D=>({key:`recent-chat:${D.conversation.tabKey}`,primary:xt(D.conversation),secondary:Nk(D.conversation,{timestampLabel:D.timestamp?fu(D.timestamp):null}),unread:D.unread,onClick:()=>g(D.conversation)})),[g,A]),E=M.showAllRecent?T:T.slice(0,4),_=T.length>0,z=R.length>0,F=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 ${F} 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(Ai,{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:ts(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:[z&&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:R.map(D=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${D.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:D.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:D.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:D.secondary})]},D.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:E.map(D=>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:D.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:D.primary}),D.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:D.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:D.secondary})]},D.key))}),T.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:()=>M.setShowAllRecent(D=>!D),children:M.showAllRecent?"Show fewer":`Show ${T.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"})]})]})]})]}),M.browseDialogOpen&&s.jsx(ol,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:M.browseCurrentPath,directories:M.browseDirectories,busy:M.browseBusy,error:M.browseError,confirmLabel:"Use this folder",onClose:()=>M.setBrowseDialogOpen(!1),onNavigate:D=>{M.loadBrowsePath(D)},onConfirm:D=>{M.chooseCustomWorkspacePath(D),M.setBrowseDialogOpen(!1)}}),M.launchConfirm&&s.jsx(nm,{title:M.launchConfirm.title,description:M.launchConfirm.description,details:M.launchConfirm.details,workspaceOptions:M.launchConfirm.workspaceOptions,selectedWorkspaceKey:M.launchConfirmWorkspaceKey,onWorkspaceChange:M.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:M.launchConfirm.providerType?ii(v,!!M.launchConfirmResumeId):M.launchConfirm.confirmLabel,busyLabel:M.launchConfirm.providerType?void 0:M.launchConfirm.busyLabel,busy:M.launchConfirmBusy,showArgsInput:M.launchConfirm.showArgsInput,argsValue:M.launchConfirmArgs,onArgsChange:M.setLaunchConfirmArgs,showModelInput:M.launchConfirm.showModelInput,modelValue:M.launchConfirmModel,onModelChange:M.setLaunchConfirmModel,historyProviderNode:M.launchConfirm.providerType&&(M.launchConfirmSessionsLoading||M.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"}),M.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:Vi(v)}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:M.launchConfirmTextFilter,onChange:D=>M.setLaunchConfirmTextFilter(D.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:M.launchConfirmBusy||M.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:M.launchConfirmWorkspaceFilter,onChange:D=>M.setLaunchConfirmWorkspaceFilter(D.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:M.launchConfirmBusy||M.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:M.launchConfirmModelFilter,onChange:D=>M.setLaunchConfirmModelFilter(D.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:M.launchConfirmBusy||M.launchConfirmSessionsLoading}),s.jsxs("select",{value:M.launchConfirmSortMode,onChange:D=>M.setLaunchConfirmSortMode(D.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:M.launchConfirmBusy||M.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:M.launchConfirmResumableOnly,onChange:D=>M.setLaunchConfirmResumableOnly(D.target.checked),disabled:M.launchConfirmBusy||M.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:M.launchConfirmResumeId,onChange:D=>M.setLaunchConfirmResumeId(D.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:M.launchConfirmBusy||M.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:Zk(v)}),M.filteredLaunchConfirmSavedSessions.map(D=>s.jsxs("option",{value:D.providerSessionId,disabled:!D.canResume,children:[D.title||D.providerSessionId," ",D.canResume?"":"(workspace missing)"]},D.providerSessionId))]}),!M.launchConfirmSessionsLoading&&M.launchConfirmSavedSessions.length>0&&M.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),M.launchConfirmResumeId&&(()=>{const D=M.filteredLaunchConfirmSavedSessions.find(L=>L.providerSessionId===M.launchConfirmResumeId);if(!D)return null;const W=sm(D);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:W.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:W.providerSessionId}),s.jsx("div",{className:"mt-1",children:W.metaLine}),W.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:W.updatedLabel}),W.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:W.preview})]})})()]}),onConfirm:M.handleConfirmLaunch,onCancel:M.closeLaunchConfirm}),d&&s.jsx(tm,{section:p,onSectionChange:f})]})}const Gc=8e3;function Kj(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 om(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 w=Date.now();let h=!1;for(const[x,k]of g){const b=e.get(x),S=k.muted===void 0||(b?b.muted===k.muted:!1),j=k.hidden===void 0||(b?b.surfaceHidden===k.hidden:!1),y=w-k.at>Gc;(S&&j||y)&&(g.delete(x),h=!0)}h&&o()},[e,o]),l.useEffect(()=>{if(r.current.size===0)return;const g=setInterval(()=>{const w=r.current,h=Date.now();let x=!1;for(const[k,b]of w)h-b.at>Gc&&(w.delete(k),x=!0);x&&o(),w.size===0&&clearInterval(g)},1e3);return()=>clearInterval(g)});const i=l.useCallback((g,w)=>{const h=r.current.get(g);r.current.set(g,{...h,...w,at:Date.now()}),o()},[o]),c=l.useCallback(g=>{const w=g.sessionId,h=w?r.current.get(w):void 0;return(h==null?void 0:h.muted)!==void 0?h.muted:Is(g,e).muted??!1},[e]),u=l.useCallback(g=>{const w=g.sessionId,h=w?r.current.get(w):void 0;return(h==null?void 0:h.hidden)!==void 0?h.hidden:Is(g,e).surfaceHidden??!1},[e]),p=l.useCallback((g,w)=>{const h=Ds(g),x=g.sessionId;!h||!x||(i(x,w),t(h,"set_conversation_prefs",{sessionId:x,...w,...Ia(g)}).then(k=>{const b=Kj(k);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(k=>{console.warn("[conversation-prefs] set_conversation_prefs failed",k),r.current.delete(x),o();const b=k instanceof Error?k.message:String(k??"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,w)=>{p(g,{hidden:w})},[p]),f=l.useCallback(g=>{p(g,{hidden:!u(g)})},[p,u]);return{isMuted:c,isHidden:u,toggleMute:d,setHidden:m,toggleHidden:f}}function Jr(e){return[...e].sort((t,n)=>{const r=n.timestamp-t.timestamp;return r!==0?r:t.conversation.tabKey.localeCompare(n.conversation.tabKey)})}function Vj(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:Jr(e)}function Yj(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 Jj(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:Js(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=ir(r)?"cli":mn(r)?"acp":"ide",o=Js(r.summaryMetadata);return{id:`${a}:${r.type}:${r.workspace||""}`,label:((i=r.activeChat)==null?void 0:i.title)||(ir(r)?r.cliName||r.type:mn(r)&&r.cliName||r.type),kind:a,providerType:r.type,providerSessionId:r.providerSessionId,subtitle:mn(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 Qj(e,t){const n=new Map;for(const r of t){const a=Ds(r.conversation),o=n.get(a);o?o.push(r):n.set(a,[r])}return e.map(r=>{const a=n.get(r.id)||[],o=[...a].sort((m,f)=>f.timestamp-m.timestamp)[0]||null,i=(o==null?void 0:o.conversation)||null,c=ei(r),u=a.filter(m=>m.unread||m.requiresAction).length,p=Yj(r),d=[r.platform||"machine",p].filter(Boolean);return{id:r.id,label:ts(r,{fallbackId:r.id}),subtitle:d.join(" · "),unread:u,total:a.length,latestConversation:i,latestTimestamp:(o==null?void 0:o.timestamp)||0,fallbackActivityAt:c,preview:i?Ak(i,rp(i)):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((r,a)=>{const o=r.latestTimestamp||r.fallbackActivityAt||0,i=a.latestTimestamp||a.fallbackActivityAt||0;return i!==o?i-o:r.label.localeCompare(a.label)})}function Xj(e){return e==="chat"}function Rr(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 Zj({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:w,setScreen:h,setSelectedMachineId:x,setSection:k,setMachineBackTarget:b,resetMachineAction:S}){const j=l.useRef(null),y=l.useCallback(v=>{if(!(v!=null&&v.sessionId))return;const N=Is(v,i),C=Math.max(Date.now(),Ks(v),N.lastUpdated||0);Rr("mark_read:start",{tabKey:v.tabKey,sessionId:v.sessionId,displayPrimary:xt(v),inboxBucket:N.inboxBucket,unread:N.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:Ks(v),readAt:C}),c(Ds(v)||v.routeId,"mark_session_seen",{sessionId:v.sessionId,providerSessionId:v.providerSessionId,seenAt:C,completionMarker:N.completionMarker}).then(A=>{Rr("mark_read:result",{tabKey:v.tabKey,sessionId:v.sessionId,result:A})}).catch(A=>{Rr("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){Xj(o)&&h("inbox"),w(((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,y(r))},[e,y,o,r,h,w]),l.useEffect(()=>{if(!u)return;const v=e.find(N=>N.tabKey===u);v&&(w(v.tabKey),h("chat"),p==null||p())},[e,p,u,h,w]),l.useEffect(()=>{if(!d)return;const v=t.find(N=>N.id===d);v&&(x(v.id),S(),k("machines"),b("inbox"),h("machine"),m==null||m())},[t,m,d,S,b,h,k,x]),l.useEffect(()=>{f&&(k(f),h("inbox"),g==null||g())},[g,f,h,k]),l.useEffect(()=>{const v=n.filter(N=>N.inboxBucket==="task_complete"||N.unread);v.length!==0&&Rr("inbox_state",{screen:o,selectedTabKey:a,items:v.map(N=>{const C=Is(N.conversation,i);return{liveState:C,tabKey:N.conversation.tabKey,sessionId:N.conversation.sessionId,displayPrimary:xt(N.conversation),serverBucket:C.inboxBucket,computedBucket:N.inboxBucket,serverUnread:C.unread,computedUnread:N.unread,lastSeenAt:C.lastSeenAt,lastUpdated:C.lastUpdated,activityAt:Ks(N.conversation)}})})},[n,i,o,a]),{markConversationRead:y}}function e1(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function qc(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function t1(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function s1({sendDaemonCommand:e,navigate:t,ides:n,conversations:r}){const{launchCli:a}=ka(),[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(S,j,y)=>{var v;try{i("loading"),u(`Launching ${j}…`);const N={ideType:j,enableCdp:!0};(v=y==null?void 0:y.workspacePath)!=null&&v.trim()&&(N.workspace=y.workspacePath.trim()),await e(S,"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(S,j,y)=>{if(j.trim())try{i("loading"),u(y!=null&&y.createIfMissing?"Creating folder…":"Saving workspace…");const v=await e(S,"workspace_add",{path:j.trim(),createIfMissing:(y==null?void 0:y.createIfMissing)===!0});if(v!=null&&v.success){i("done"),u(y!=null&&y.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]),w=l.useCallback(async S=>{var j,y,v,N,C,A;try{i("loading"),u("Starting daemon upgrade…");const M=await e(S,"daemon_upgrade",{});if((j=M==null?void 0:M.result)!=null&&j.alreadyLatest){i("done"),u(`Already on v${((y=M==null?void 0:M.result)==null?void 0:y.version)||"latest"}.`);return}if((v=M==null?void 0:M.result)!=null&&v.upgraded||(N=M==null?void 0:M.result)!=null&&N.success){i("done"),u(`Upgrade to v${((C=M==null?void 0:M.result)==null?void 0:C.version)||"latest"} started. Daemon is restarting…`);return}i("error"),u(((A=M==null?void 0:M.result)==null?void 0:A.error)||"Upgrade failed")}catch(M){i("error"),u(M instanceof Error?M.message:"Upgrade failed")}},[e]),h=l.useCallback(async(S,j,y,v)=>{var A,M,T;const N=Date.now(),C={machineId:S,kind:j,providerType:y,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 ${y}…`),d(C);const R={cliType:y};(A=v==null?void 0:v.workspacePath)!=null&&A.trim()?R.dir=v.workspacePath.trim():v!=null&&v.workspaceId?R.workspaceId=v.workspaceId:v!=null&&v.useHome&&(R.useHome=!0),v!=null&&v.resumeSessionId&&(R.resumeSessionId=v.resumeSessionId),(M=v==null?void 0:v.args)!=null&&M.trim()&&(R.cliArgs=v.args.trim().split(/\s+/).filter(Boolean)),(T=v==null?void 0:v.model)!=null&&T.trim()&&(R.initialModel=v.model.trim());const E=await a(S,R),_=(E==null?void 0:E.result)||E,z=(_==null?void 0:_.sessionId)||(_==null?void 0:_.id);if(E!=null&&E.success&&z){d(null),i("done"),u(`${y} launched`),t(dr(z));return}if(E!=null&&E.success){i("loading"),u(`${y} launch requested — waiting for session…`);return}d(null),i("error"),u((E==null?void 0:E.error)||(_==null?void 0:_.error)||`Could not launch ${j.toUpperCase()} workspace`)}catch(R){if(t1(R)){i("loading"),u(`${y} launch requested — waiting for session…`);return}d(null),i("error"),u(R instanceof Error?R.message:`Could not launch ${j.toUpperCase()} workspace`)}},[t,e]),x=l.useCallback(async(S,j)=>{try{const y=await e(S,"list_saved_sessions",{providerType:j,kind:"cli",limit:30}),v=(y==null?void 0:y.result)??y;return Array.isArray(v==null?void 0:v.sessions)?v.sessions:[]}catch(y){return console.error("Failed to list saved sessions on mobile:",y),[]}},[e]),k=l.useCallback(async(S,j)=>rl(e,S,j),[e]);l.useEffect(()=>{if(!p)return;const S=qc(p.workspacePath),j=n.find(v=>{var R,E,_,z;if(!v||v.type==="adhdev-daemon"||e1(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 M=String(v.providerSessionId||"");if(p.resumeSessionId&&M)return M===p.resumeSessionId;if(S){const F=qc(v.workspace||v.runtimeWorkspaceLabel);return F?F===S:!1}return Number(v.lastUpdated||v._lastUpdate||v.timestamp||((z=(_=(E=(R=v.activeChat)==null?void 0:R.messages)==null?void 0:E.at)==null?void 0:_.call(E,-1))==null?void 0:z.timestamp)||0)>=p.startedAt-5e3});if(!j)return;const y=Xp({entrySessionId:j.sessionId,entryInstanceId:j.instanceId,entryRouteId:j.id,conversations:r});y&&(d(null),i("done"),u(`${p.providerType} launched`),t(dr(y)))},[r,n,t,p]),l.useEffect(()=>{if(!p)return;const S=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(S)},[p]);const b=l.useCallback(async(S,j)=>{var y;if(j.kind==="ide"&&j.providerType){await f(S,j.providerType,{workspacePath:j.workspace||null});return}if((j.kind==="cli"||j.kind==="acp")&&j.providerType){const v=((y=j.workspace)==null?void 0:y.trim())||"";await h(S,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:w,handleLaunchWorkspaceProvider:h,handleListSavedSessions:x,handleBrowseDirectory:k,handleOpenRecent:b}}function n1({conversations:e,selectedConversation:t,machineBackTarget:n,markConversationRead:r,resetMachineAction:a,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:u,setMachineBackTarget:p}){const d=l.useCallback(k=>{o(k.tabKey),i("chat"),r(k)},[r,i,o]),m=l.useCallback(k=>{const b=e.find(S=>S.routeId===k.routeId&&S.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((k,b="inbox")=>{c(k),a(),u("machines"),p(b),i("machine")},[a,p,i,u,c]),w=l.useCallback(k=>{const b=Ds(k);b&&g(b,"chat")},[g]),h=l.useCallback(()=>{a(),i(n)},[n,a,i]),x=l.useCallback(k=>{u(k),i("inbox")},[i,u]);return{openConversation:d,openNativeConversation:m,backFromConversation:f,openMachine:g,openConversationMachine:w,backFromMachine:h,changeMachineSection:x}}function Sn(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function r1(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function a1({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:w,onOpenRemote:h,onStopCli:x,wsStatus:k,isConnected:b,onShowAllHiddenConversations:S,onHideConversation:j,onOpenMeshGraph:y,onOpenNewSession:v,liveSessionInboxState:N,setCliViewModeOverrides:C}){const[A,M]=l.useState(()=>{var B;return((B=e[0])==null?void 0:B.tabKey)||null}),[T,R]=l.useState(()=>e[0]?"chat":"inbox"),[E,_]=l.useState("chats"),[z,F]=l.useState(null),[D,W]=l.useState("inbox"),L=l.useRef([]),P=mr(),$="1.0.12",I=l.useMemo(()=>e.find(B=>B.tabKey===A)||e[0]||null,[e,A]),U=l.useMemo(()=>I?n.find(B=>B.id===I.routeId):void 0,[n,I]),J=l.useMemo(()=>!I||lt(I)||!ct(I)?null:Mn(I),[I]),re=l.useMemo(()=>n.filter(B=>B.type==="adhdev-daemon").sort($i),[n]),Y=l.useMemo(()=>re.find(B=>B.id===z)||null,[re,z]),X=Da({sendDaemonCommand:a,activeConv:I||void 0,setActionLogs:o,isStandalone:i}),de=s1({sendDaemonCommand:a,navigate:P,ides:n,conversations:e}),ne=sk(e),O=l.useMemo(()=>e.map(B=>{const be=T==="chat"&&(I==null?void 0:I.tabKey)===B.tabKey,je=Na(B,N,{hideOpenTaskCompleteUnread:!0,isOpenConversation:be}),Se=Ks(B),He=rp(B),Xe=up(B,He);return{conversation:B,timestamp:Se,preview:Xe,unread:je.unread,requiresAction:je.requiresAction,isWorking:je.isWorking,inboxBucket:je.inboxBucket}}),[e,N,T,I,ne]),{markConversationRead:ie}=Zj({conversations:e,machineEntries:re,items:O,selectedConversation:I,selectedTabKey:A,screen:T,liveSessionInboxState:N,sendDaemonCommand:a,requestedActiveTabKey:u,onRequestedActiveTabConsumed:p,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:M,setScreen:R,setSelectedMachineId:F,setSection:_,setMachineBackTarget:W,resetMachineAction:de.resetMachineAction}),K=n1({conversations:e,selectedConversation:I,machineBackTarget:D,markConversationRead:ie,resetMachineAction:de.resetMachineAction,setSelectedTabKey:M,setScreen:R,setSelectedMachineId:F,setSection:_,setMachineBackTarget:W}),{isMuted:ae,toggleMute:Ce}=om(N,a),ye=l.useMemo(()=>Jr(O.filter(B=>B.requiresAction&&!ae(B.conversation))),[O,ae]),ke=l.useMemo(()=>Jr(O.filter(B=>B.unread&&!B.requiresAction&&!ae(B.conversation))),[O,ae]),me=l.useMemo(()=>Vj(O.filter(B=>!B.unread&&!B.requiresAction&&B.isWorking),L.current),[O]);l.useEffect(()=>{L.current=me.map(B=>B.conversation.tabKey)},[me]);const q=l.useMemo(()=>Jr(O.filter(B=>!B.unread&&!B.requiresAction&&!B.isWorking)),[O]),G=l.useMemo(()=>Y?O.filter(B=>Ds(B.conversation)===Y.id):[],[O,Y]),Z=l.useMemo(()=>Jj(Y,n),[n,Y]),V=(Y==null?void 0:Y.version)||null,fe=!!Y&&!!V&&!0&&V!==$,Te=l.useMemo(()=>(Y==null?void 0:Y.availableProviders)||[],[Y]),ce=l.useMemo(()=>Te.filter(B=>Sn(B,"cli")).map(B=>({type:B.type,displayName:B.displayName||B.type,icon:B.icon})),[Te]),H=l.useMemo(()=>Te.filter(B=>Sn(B,"acp")).map(B=>({type:B.type,displayName:B.displayName||B.type,icon:B.icon})),[Te]),pe=l.useMemo(()=>Qj(re,O),[O,re]),le=l.useCallback(async B=>{Y&&await de.handleOpenRecent(Y.id,B)},[de,Y]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:T==="chat"&&I?s.jsx($j,{selectedConversation:I,isAcp:lt(I),isStandalone:i,selectedIdeEntry:U,actionLogs:r,userName:c,isSendingChat:X.isSendingChat,sendFeedbackMessage:X.sendFeedbackMessage,isFocusingAgent:X.isFocusingAgent,handleModalButton:X.handleModalButton,handleRelaunch:X.handleRelaunch,onBack:K.backFromConversation,onOpenNativeConversation:K.openNativeConversation,onOpenMachine:K.openConversationMachine,onOpenHistory:w,onOpenRemote:h,onOpenMeshGraph:y,onStopCli:x,cliViewMode:J,onSetCliViewMode:async B=>{await Bp({conversation:I,mode:B,ides:n,sendDaemonCommand:a,setCliViewModeOverrides:C})},handleSendChat:X.handleSendChat,handleForceSendChat:X.handleForceSendChat,handleFocusAgent:X.handleFocusAgent}):T==="machine"&&Y?s.jsx(zj,{selectedMachineEntry:Y,selectedMachineConversations:G,selectedMachineRecentLaunches:Z,cliProviders:ce,acpProviders:H,selectedMachineNeedsUpgrade:fe,appVersion:$,machineAction:de.machineAction,isStandalone:i,section:E,showBottomNav:D==="inbox",onBack:K.backFromMachine,onSectionChange:K.changeMachineSection,onOpenConversation:K.openConversation,onOpenRecent:le,onOpenMachineDetails:()=>P(`/machines/${Y.id}`),onMachineUpgrade:()=>de.handleMachineUpgrade(Y.id),onLaunchDetectedIde:(B,be)=>de.handleLaunchDetectedIde(Y.id,B,be),onAddWorkspace:(B,be)=>de.handleAddWorkspace(Y.id,B,be),onBrowseDirectory:B=>de.handleBrowseDirectory(Y.id,B),onLaunchWorkspaceProvider:(B,be,je)=>de.handleLaunchWorkspaceProvider(Y.id,B,be,je),onListSavedSessions:B=>de.handleListSavedSessions(Y.id,B)}):s.jsx(Bj,{section:E,attentionItems:ye,unreadItems:ke,workingItems:me,completedItems:q,hiddenConversations:t,machineCards:pe,getAvatarText:r1,actionLogs:r,sendDaemonCommand:a,onOpenConversation:K.openConversation,onShowAllHidden:S,onHideConversation:j,onOpenMeshGraph:y,onStopCli:x,onOpenNewSession:v,onOpenMachine:K.openMachine,onOpenSettings:()=>P("/settings"),onSectionChange:_,wsStatus:k,isConnected:b,isStandalone:i,isConversationMuted:ae,onToggleMuteConversation:Ce})})}function go(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function o1({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(),!go(t,n)){d("merge");return}const k=x.currentTarget.getBoundingClientRect(),b=x.clientX-k.left,S=k.width/3;b<S?d("split-left"):b>S*2?d("split-right"):d("merge")},[t,n]),w=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 k=x.dataTransfer.getData("text/tab-key"),b=k?e.some(j=>j.tabKey===k):!1,S=p;if(d(null),o(),!!k){if(x.preventDefault(),S==="split-left"&&go(t,n)){n==null||n(k,"split-left");return}if(S==="split-right"&&go(t,n)){n==null||n(k,"split-right");return}if(b){a(k);return}r==null||r(k)}},[e,p,t,n,r,a,o]);return{dragOver:c,dropAction:p,resetDragState:m,handleDragEnter:f,handleDragOver:g,handleDragLeave:w,handleDrop:h}}function i1(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 l1({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),w=l.useRef(a);l.useEffect(()=>{g.current=r},[r]),l.useEffect(()=>{w.current=a},[a]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{u(N=>{const C=i1(N,e);return C.length===N.length&&C.every((A,M)=>A===N[M])?N:C})},[e]);const h=l.useMemo(()=>{const N=p??c;if(N.length===0)return e;const C=new Map(N.map((A,M)=>[A,M]));return[...e].sort((A,M)=>{const T=C.get(A.tabKey)??999,R=C.get(M.tabKey)??999;return T-R})},[e,p,c]);l.useEffect(()=>{var C,A;if(h.length===0){o!==null&&(i(null),(C=g.current)==null||C.call(g,null));return}if(o&&h.some(M=>M.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]),k=l.useCallback(N=>{var C;i(N),(C=g.current)==null||C.call(g,N)},[]),b=l.useCallback((N,C,A)=>{u(M=>{var _;const T=M.filter(z=>z!==N),R=T.indexOf(C);if(R<0)return M;const E=A==="left"?R:R+1;return T.splice(E,0,N),(_=w.current)==null||_.call(w,T),T}),d(null)},[]),S=l.useCallback((N,C,A)=>{const T=(c.length>0?c:e.map(_=>_.tabKey)).filter(_=>_!==N),R=T.indexOf(C);if(R<0)return;const E=A==="left"?R:R+1;T.splice(E,0,N),m.current=T,d(T)},[c,e]),j=l.useCallback(()=>{var C;const N=m.current;N&&(u(N),(C=w.current)==null||C.call(w,N))},[]),y=l.useCallback(()=>{m.current=null,d(null)},[]),v=l.useCallback(N=>{u(C=>{var M;const A=C.filter(T=>T!==N);return A.push(N),(M=w.current)==null||M.call(w,A),A})},[]);return{activeTabId:o,activeConv:x,sortedConversations:h,previewOrderRef:m,draggingTabRef:f,selectTab:k,handleTabReorder:b,updatePreviewOrder:S,commitPreviewOrder:j,clearPreviewOrder:y,moveTabToEnd:v,setDraggingTabKey:N=>{f.current=N}}}function c1({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 il({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(Di,{size:14}),s.jsx("span",{children:i("paneGroup.newSession")})]})}),c&&s.jsx(em,{}),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 im="adhdev-tab-shortcuts";function lm(){try{return JSON.parse(localStorage.getItem(im)||"{}")}catch{return{}}}function cm({enabled:e=!0,sortedTabKeys:t,onFocus:n,onSelectTab:r}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>lm()),[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(im,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 w={...o};for(const[h,x]of Object.entries(w))x===g&&delete w[h];w[c]=g,d(w),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,w]of Object.entries(o))if(t.includes(g)&&p(f)===w){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 xo=e=>{e.preventDefault()},d1=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:w,onDragStateReset:h,onDragTabKeyChange:x,onReceiveTab:k,onOpenContextMenu:b,longPressTimer:S,isGroupActive:j}){const y=An(t),v=y.isGenerating?"agent-tab-generating":y.isWaiting?"agent-tab-waiting":"",N=y.isReconnecting,C=Ck(t),A=jk(t),M=dp(t),T=l.useCallback(P=>{c.current=t.tabKey,x(t.tabKey),P.dataTransfer.setData("text/tab-key",t.tabKey),P.dataTransfer.effectAllowed="move"},[t.tabKey,c,x]),R=l.useCallback(()=>{c.current=null,x(null),g(),w(),h()},[c,x,g,w,h]),E=l.useCallback(P=>{const $=c.current;if(!(!$||$===t.tabKey)&&P.dataTransfer.types.includes("text/tab-key")){P.preventDefault(),P.stopPropagation();const I=P.currentTarget.getBoundingClientRect(),U=P.clientX<I.left+I.width/2?"left":"right";m($,t.tabKey,U)}},[t.tabKey,c,m]),_=l.useCallback(P=>{P.preventDefault(),P.stopPropagation();const $=P.dataTransfer.getData("text/tab-key");if($&&$!==t.tabKey){const I=P.currentTarget.getBoundingClientRect(),U=P.clientX<I.left+I.width/2?"left":"right";i.includes($)?f($,t.tabKey,U):k&&k($)}w()},[t.tabKey,i,f,k,w]),z=l.useCallback(P=>{P.stopPropagation(),u(),p(t.tabKey),d(t)},[t,d,u,p]),F=l.useCallback(P=>{P.preventDefault(),b(P.clientX,P.clientY,t.tabKey)},[t.tabKey,b]),D=l.useCallback(P=>{const $=P.touches[0];S.current=setTimeout(()=>{b($.clientX,$.clientY,t.tabKey)},600)},[t.tabKey,S,b]),W=l.useCallback(()=>{S.current&&clearTimeout(S.current)},[S]),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:T,onDragEnd:R,onDragOver:E,onDrop:_,onClick:z,onContextMenu:F,onTouchStart:D,onTouchEnd:W,onTouchMove:W,style:{position:"relative",cursor:"pointer",opacity:r?.4:void 0},children:[M&&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(es,{size:11})}),a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:y.isGenerating?s.jsx("div",{className:"tab-spinner"}):y.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):N?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):y.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:"○"})}),C.length>0&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:A,"aria-label":A||C.join(" · "),children:C.join(" · ")}),s.jsxs("div",{className:"adhdev-dockview-tab-copy",children:[s.jsx("span",{className:"adhdev-dockview-tab-primary",title:xt(t),children:xt(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:Gs(t)}):y.isConnecting?s.jsxs("span",{className:"adhdev-dockview-tab-connecting truncate",children:[Gs(t),s.jsx("span",{className:"connecting-dots"})]}):s.jsx("span",{className:"truncate",children:Gs(t)}),s.jsx(da,{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 u1({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:w,onHideTab:h,isGroupActive:x,allowTabShortcuts:k=!0}){const{t:b}=Ne("common"),[S,j]=l.useState(null),y=l.useRef(null),v=l.useRef(null),N=l.useMemo(()=>e.map(_=>_.tabKey),[e]);hr("PaneGroupTabBar",{groupIndex:n,activeTabId:t,tabCount:e.length,ctxMenuTab:(S==null?void 0:S.tabKey)||null});const{isMac:C,tabShortcuts:A,shortcutListening:M,setShortcutListening:T,saveShortcuts:R}=cm({enabled:k,sortedTabKeys:e.map(_=>_.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!S)return;const _=z=>{const F=document.querySelector("[data-pane-context-menu]");F&&F.contains(z.target)||j(null)};return window.addEventListener("mousedown",_,!0),()=>window.removeEventListener("mousedown",_,!0)},[S]),l.useEffect(()=>{const _=v.current;if(!_)return;const z=F=>{Math.abs(F.deltaY)<=Math.abs(F.deltaX)||(F.preventDefault(),_.scrollLeft+=F.deltaY)};return _.addEventListener("wheel",z,{passive:!1}),()=>_.removeEventListener("wheel",z)},[]);const E=l.useCallback((_,z,F)=>{j({x:_,y:z,tabKey:F})},[]);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(d1,{conv:_,isActive:t===_.tabKey,isDraggedTab:a.current===_.tabKey,isTaskCompleteUnread:r.has(_.tabKey),shortcut:k?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:w,onOpenContextMenu:E,longPressTimer:y,isGroupActive:x},_.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:b("paneGroup.noTabsInGroup")})]})}),S&&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:S.x,top:S.y},children:[k&&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:xo,onClick:_=>{_.stopPropagation(),T(S.tabKey),j(null)},children:["⌨ ",A[S.tabKey]?`Change shortcut (${A[S.tabKey]})`:"Set shortcut"]}),A[S.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:xo,onClick:()=>{const _={...A};delete _[S.tabKey],R(_),j(null)},children:"✕ Remove shortcut"})]}),h&&s.jsxs(s.Fragment,{children:[k&&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:xo,onClick:()=>{h(S.tabKey),j(null)},children:"🚫 Hide from Dashboard"})]})]}),k&&M&&s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>T(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. ",C?"⌘+1":"Ctrl+1",", ",C?"⌥+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 p1({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:w,style:h,onActiveTabChange:x,initialActiveTabId:k,initialTabOrder:b,onTabOrderChange:S,onHideTab:j,isFocused:y,allowTabShortcuts:v=!0,onOpenNewSession:N,liveSessionInboxState:C}){const{sendCommand:A}=vt(),M=l.useRef(null),{activeTabId:T,activeConv:R,sortedConversations:E,draggingTabRef:_,selectTab:z,handleTabReorder:F,updatePreviewOrder:D,commitPreviewOrder:W,clearPreviewOrder:L,moveTabToEnd:P,setDraggingTabKey:$}=l1({conversations:e,initialActiveTabId:k,initialTabOrder:b,onActiveTabChange:x,onTabOrderChange:S}),I=Da({sendDaemonCommand:a,activeConv:R,setActionLogs:o,isStandalone:i}),{dragOver:U,dropAction:J,resetDragState:re,handleDragEnter:Y,handleDragOver:X,handleDragLeave:de,handleDrop:ne}=o1({conversations:e,numGroups:f,onMoveTab:g,onReceiveTab:w,onOwnTabDrop:P,onClearPreviewOrder:L}),O=R&&!lt(R)&&Mn(R)==="terminal",ie=l.useMemo(()=>R?t.find(ye=>ye.id===R.routeId):void 0,[t,R]),K=l.useMemo(()=>R?r.filter(ye=>ye.routeId===R.tabKey):[],[r,R]),ae=l.useMemo(()=>new Set(E.filter(ye=>Eb(ye,C,{isOpenConversation:ye.tabKey===T})).map(ye=>ye.tabKey)),[T,C,E]);hr("PaneGroup",{groupIndex:p,conversationCount:e.length,activeTabId:T,dragOver:U});const Ce=l.useCallback(ye=>{ye.streamSource==="agent-stream"&&ye.agentType&&A(ye.routeId,qu(),{agentType:ye.agentType,...ye.sessionId&&{targetSessionId:ye.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:U?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(u1,{conversations:E,activeTabId:T,groupIndex:p,numGroups:f,unreadTabKeys:ae,draggingTabRef:_,onFocus:d,onSelectTab:z,onConversationActivated:Ce,onPreviewReorder:D,onReorderTab:F,onCommitPreviewOrder:W,onClearPreviewOrder:L,onDragStateReset:re,onDragTabKeyChange:$,onMoveTab:g,onReceiveTab:w,onHideTab:j,isGroupActive:y??!1,allowTabShortcuts:v}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:Y,onDragOver:X,onDragLeave:de,onDrop:ne,children:[U&&s.jsx(c1,{dropAction:J,canSplit:!!(f<4&&g)}),R?s.jsx(al,{activeConv:R,clearToken:n[R.tabKey]||0,isCliTerminal:!!O,ideEntry:ie,terminalRef:M,handleModalButton:I.handleModalButton,handleRelaunch:I.handleRelaunch,handleSendChat:I.handleSendChat,handleForceSendChat:I.handleForceSendChat,isSendingChat:I.isSendingChat,sendFeedbackMessage:I.sendFeedbackMessage,handleFocusAgent:I.handleFocusAgent,isFocusingAgent:I.isFocusingAgent,actionLogs:K,userName:u,isInputActive:!m||!!y}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(il,{conversationsCount:e.length,isSplitMode:m,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:N})})]})]})}function m1({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:w,moveTabToGroup:h,splitTabRelative:x,closeGroup:k,handleResizeStart:b,groupActiveTabIds:S,setGroupActiveTab:j,groupTabOrders:y,setGroupTabOrder:v,toggleHiddenTab:N,onOpenNewSession:C,allowTabShortcuts:A=!0,liveSessionInboxState:M}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((T,R)=>{const E=t&&r.length===n?`${r[R]}%`:void 0;return s.jsxs(Rt.Fragment,{children:[t&&R>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(R-1,_),onDoubleClick:()=>k(R),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(p1,{style:t?{flexBasis:E??`${100/n}%`,flexGrow:E?0:1,flexShrink:E?0:1}:void 0,conversations:T,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:u,setActionLogs:p,isStandalone:d,hasRegisteredMachines:m,userName:f,groupIndex:R,isFocused:t&&g===R,onFocus:()=>w(R),isSplitMode:t,numGroups:n,onMoveTab:(_,z)=>{z==="left"&&R>0?h(_,R-1):z==="right"&&R<n-1?h(_,R+1):z==="split-left"&&n<4?x(_,R,"left"):z==="split-right"&&n<4&&x(_,R,"right")},onReceiveTab:_=>h(_,R),onActiveTabChange:_=>j(R,_),initialActiveTabId:S[R],initialTabOrder:y[R],onTabOrderChange:_=>v(R,_),onHideTab:N,onOpenNewSession:C,allowTabShortcuts:A,liveSessionInboxState:M})]},R)})})}const dm="adhdev-dashboard-action-shortcuts",h1=1200,f1=[["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 b1(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function ht(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 um(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:ht("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:ht("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:ht("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:ht("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:ht("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:ht("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:ht("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:ht("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:ht("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:ht("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:ht("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:ht("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:ht("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:ht("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:ht("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:ht("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:ht("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:ht("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:ht("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:ht("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:ht("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:ht("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:ht("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:ht("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:ht("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:ht("toggleCliView",e)}]}function bi(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function va(e){const t=Object.fromEntries(um(e).map(n=>[n.id,n.defaultShortcut]));try{const n=JSON.parse(localStorage.getItem(dm)||"{}"),r={...t,...n};for(const[a,o]of f1)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 g1({enabled:e=!0,onTrigger:t}){const n=b1(),[r,a]=l.useState(()=>va(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=va(n),x=Object.entries(r),k=Object.entries(h);x.length===k.length&&x.every(([b,S])=>h[b]===S)||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}},h1))},[]);l.useEffect(()=>{if(!o)return;const h=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){i(null),u([]);return}const k=d(x);if(!k)return;const S=!(x.metaKey||x.ctrlKey||x.altKey)&&/^[A-Z0-9]$/.test(k);if(c.length===0&&S){u([k]);return}const y=[...c,k].slice(0,2).join(" "),v={...r};for(const[N,C]of Object.entries(v))C===y&&delete v[N];v[o]=y,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 k=d(x);if(!k)return;const b=x.metaKey||x.ctrlKey||x.altKey;if(bi(x.target))return;const S=p.current.parts,j=b?[k]:[...S.slice(-1),k].slice(-2),y=j.join(" "),v=j[j.length-1],N=Object.entries(r).filter(([,R])=>!!R),C=N.find(([,R])=>R===y);if(C){x.preventDefault(),f(),t(C[0]);return}if(N.some(([,R])=>R.startsWith(`${y} `))){x.preventDefault(),p.current.parts=j,g();return}const M=N.find(([,R])=>R===v);if(M){x.preventDefault(),f(),t(M[0]);return}if(N.some(([,R])=>R.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 w=l.useMemo(()=>um(n),[n]);return{isMac:n,actionDefinitions:w,actionShortcuts:r,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:u,saveShortcuts:m}}function x1({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 mm(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function zc({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:n,ides:r}){return!e||n>0?!1:t?!mm(r):!0}function v1({previousVisibleConversationCount:e,visibleConversationCount:t,ides:n}){return t>0||e<=0?!1:mm(n)}const hm=1e3,y1=4;function Kc(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function Vc(e,t,n){return Math.abs(t.clientX-e.clientX)>n||Math.abs(t.clientY-e.clientY)>n}function w1({detachDelayMs:e=hm,stillnessThresholdPx:t=y1,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},w=()=>{!o||!c||!u||d||p!=null||(p=r(()=>{p=null,!(!o||!c||!u||d)&&Kc(u,i)&&(Vc(c,u,t)||(d=!0,n({panelId:o,clientX:u.clientX,clientY:u.clientY})))},e))},h=k=>{if(!(!o||d)){if(!Kc(k,i)){u={clientX:k.clientX,clientY:k.clientY},f();return}(!c||Vc(c,k,t))&&(m(),c={clientX:k.clientX,clientY:k.clientY}),u={clientX:k.clientX,clientY:k.clientY},w()}},x=k=>{!o||d||(k&&(u={clientX:k.clientX,clientY:k.clientY}),f())};return{startDrag:k=>{m(),o=k.panelId,i=k.selfPanelBounds??null,c=null,u={clientX:k.clientX,clientY:k.clientY},d=!1},markSelfPanel:h,markNonSelfPanel:x,markNoDropTarget:x,markDockTarget:x,endDrag:g,isDragging:()=>o!=null,hasDetached:()=>d,dispose:g}}function k1(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Qr(e){return xt(e)||e.tabKey}function S1(e){return`remote:${e}`}function rs(e){return e.startsWith("remote:")}function Yc(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function vo(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 yo(e,t){e.classList.remove(Oo.className,Wo.className),e.classList.add(t==="light"?Oo.className:Wo.className)}function Jc(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 C1(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:Qr(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 Qc(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])rs(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!==Qr(a)&&o.api.setTitle(Qr(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:Qr(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 Xc(e,t,n){var u,p;const r=n?S1(n):null;for(const d of[...e.panels])rs(d.id)&&(!r||d.id!==r)&&e.removePanel(d);if(!n||!r)return;const a=cs(t,n);if(!a&&e.totalPanels===0)return;const o=e.getPanel(r),i=hp(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=>!rs(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 fm({doId:e,targetSessionId:t,connState:n,viewMode:r}){const[a,o]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?kt.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=kt.onStatus)==null?void 0:d.call(kt,(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?kt.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?kt.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 bm=l.createContext(null);function Ea(){const e=l.useContext(bm);if(!e)throw new Error("DashboardDockviewContext missing");return e}function j1(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 N1({params:e}){var u;const t=Ea(),n=l.useMemo(()=>cs([...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}=fm({doId:a,targetSessionId:n?Gu(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(pu,{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 A1(){const e=Ea();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(il,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function M1(e){var b,S;j1(e);const t=Ea(),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=>ok(j),[]),i=l.useCallback(()=>ak(a),[a]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const j=cs([...t.conversationsByTabKey.values()],e.params.routeId),y=((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${y?" 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=((S=e.api.group.activePanel)==null?void 0:S.id)===e.api.id,d=e.api.isGroupActive,m=Na(u,t.liveSessionInboxState,{isOpenConversation:p}),f=m.isReconnecting,g=m.isConnecting,w=m.isGenerating||c,h=m.isWaiting,x=m.unread,k=t.tabShortcuts[u.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${p?" is-active":""}${d?" is-group-active":""}${f?" is-reconnecting":""}`,title:xt(u),"data-tab-key":e.params.tabKey,onMouseDown:n,onTouchStart:n,onContextMenu:j=>{var y;j.preventDefault(),n(j),t.openTabContextMenu({x:j.clientX,y:j.clientY,tabKey:u.tabKey,sourceDocument:((y=j.target)==null?void 0:y.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:w?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:xt(u)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:f?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Gs(u)}):g?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Gs(u)}):s.jsx("span",{children:Gs(u)})})]}),k&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:k,children:k})]})}function Er(e){return e.isActive}function Zc(e){return e.isVisible}function T1(e){e.preventDefault()}function P1({params:e,api:t}){var g;const n=Ea(),r=l.useRef(null),[a,o]=l.useState(()=>Er(t)),[i,c]=l.useState(()=>Zc(t)),u=n.conversationsByTabKey.get(e.tabKey),p=Da({sendDaemonCommand:n.sendDaemonCommand,activeConv:u,setActionLogs:n.setActionLogs,isStandalone:n.isStandalone});l.useEffect(()=>{o(Er(t)),c(Zc(t));const w=[t.onDidActiveChange(h=>o(h.isActive)),t.onDidActiveGroupChange(h=>{if(!Er(t)&&!h.isActive){o(!1);return}o(Er(t))}),t.onDidVisibilityChange(h=>c(h.isVisible))];return()=>{for(const h of w)h.dispose()}},[t]);const d=l.useMemo(()=>u?n.ides.find(w=>w.id===u.routeId):void 0,[n.ides,u]),m=l.useMemo(()=>u?n.actionLogs.filter(w=>w.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(il,{conversationsCount:0,isSplitMode:!1,isStandalone:n.isStandalone,hasRegisteredMachines:n.hasRegisteredMachines,onOpenNewSession:n.onOpenNewSession,suppressGuide:n.hasDetachedConversationPanels})});const f=!lt(u)&&Mn(u)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(al,{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 I1({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:w,onRequestScrollToBottom:h,requestedActiveTabKey:x,requestedRemoteIdeId:k,onRequestedActiveTabConsumed:b,scrollToBottomRequest:S,liveSessionInboxState:j,layoutProfile:y}){var ut,ot,pt;const{theme:v}=Ls(),{sendCommand:N}=vt(),C=l.useRef(null),A=l.useRef(null),M=l.useRef(null),T=l.useRef(!1),R=l.useRef(!1),E=l.useRef(!1),_=l.useRef(null),z=l.useRef([]),[F,D]=l.useState(null),[W,L]=l.useState(0),P=l.useRef(typeof window>"u"?{}:JC(y)),$=l.useMemo(()=>new Map(e.map(Q=>[Q.tabKey,Q])),[e]),I=l.useMemo(()=>{const Q=C.current;return Q?Q.groups.some(ee=>{try{const oe=ee.model.location.type;return oe!=="floating"&&oe!=="popout"?!1:ee.panels.some(ue=>$.has(ue.id))}catch{return!1}}):!1},[$,W,e]),U=l.useCallback(()=>{var Q;(Q=C.current)==null||Q.focus()},[]),J=l.useCallback((Q,ee)=>{h==null||h(Q,ee)},[h]),re=l.useCallback(Q=>{const ee=document,oe=Q.document;for(const Ae of ee.querySelectorAll('link[rel="stylesheet"]')){const Oe=oe.createElement("link");Oe.rel="stylesheet",Oe.href=Ae.href,Ae.crossOrigin&&(Oe.crossOrigin=Ae.crossOrigin),oe.head.appendChild(Oe)}for(const Ae of ee.querySelectorAll("style")){const Oe=oe.createElement("style");Oe.textContent=Ae.textContent,oe.head.appendChild(Oe)}const ue=[];for(const Ae of ee.styleSheets)try{for(const Oe of Ae.cssRules)Oe instanceof CSSStyleRule&&(Oe.selectorText===":root"||Oe.selectorText==="html")&&ue.push(Oe.cssText)}catch{}if(ue.length>0){const Ae=oe.createElement("style");Ae.textContent=ue.join(`
71
71
  `),oe.head.appendChild(Ae)}const xe=ee.documentElement.getAttribute("data-theme");xe&&oe.documentElement.setAttribute("data-theme",xe),oe.documentElement.style.colorScheme=xe==="light"?"light":"dark",oe.body.className=ee.body.className;const Me=ee.documentElement.getAttribute("style");Me&&oe.documentElement.setAttribute("style",Me);const Le=oe.getElementById("dv-popout-window");Le instanceof HTMLElement&&(Le.classList.add("adhdev-dockview"),yo(Le,v))},[v]),Y=l.useCallback(()=>{var ee;const Q=C.current;if(Q)for(const oe of Q.groups)try{const ue=(ee=oe.element)==null?void 0:ee.ownerDocument;if(!ue||ue===document)continue;const xe=ue.getElementById("dv-popout-window");xe instanceof HTMLElement&&(xe.classList.add("adhdev-dockview"),yo(xe,v));const Me=document.documentElement.getAttribute("data-theme");Me&&ue.documentElement.setAttribute("data-theme",Me),ue.documentElement.style.colorScheme=Me==="light"?"light":"dark",ue.body.className=document.body.className;const Le=document.documentElement.getAttribute("style");Le?ue.documentElement.setAttribute("style",Le):ue.documentElement.removeAttribute("style")}catch{}},[v]),X=l.useCallback(Q=>{const ee=C.current;if(!ee)return;const oe=ee.getPanel(Q);oe&&ee.addPopoutGroup(oe,{popoutUrl:"/popout.html",onDidOpen:({window:ue})=>{re(ue),ke();const xe=$.get(Q);ue.document.title=xe?`${xt(xe)} — ADHDev`:"ADHDev — Popout"}})},[$,re]),de=l.useCallback(Q=>{const ee=C.current,oe=ee==null?void 0:ee.getPanel(Q);if(!ee||!oe)return;const ue=ee.groups.filter(xe=>{var Me;try{return((Me=xe.element)==null?void 0:Me.ownerDocument)===document}catch{return!0}});ue.length>0?oe.api.moveTo({group:ue[0],position:"center"}):oe.api.moveTo({position:"center"}),oe.api.setActive()},[]),ne=l.useCallback(Q=>{var ue;const ee=C.current;if(!ee)return!1;const oe=ee.getPanel(Q);if(!oe)return!1;try{return((ue=oe.group.element)==null?void 0:ue.ownerDocument)!==document}catch{return!1}},[]),O=l.useCallback(Q=>{ne(Q)&&de(Q),d(Q)},[ne,de,d]),ie=l.useCallback(Q=>{const ee=C.current,oe=ee==null?void 0:ee.getPanel(Q);!ee||!oe||ee.addFloatingGroup(oe,{width:600,height:500})},[]),K=l.useCallback(Q=>{var oe;const ee=(oe=C.current)==null?void 0:oe.getPanel(Q);if(!ee)return!1;try{return ee.group.model.location.type==="floating"}catch{return!1}},[]),ae=l.useCallback(()=>{var ee,oe;const Q=(oe=(ee=C.current)==null?void 0:ee.activePanel)==null?void 0:oe.id;return!Q||rs(Q)?null:$.has(Q)?Q:null},[$]),Ce=l.useCallback(Q=>{const ee=C.current,oe=ee==null?void 0:ee.getPanel(Q);if(!ee||!oe)return;const ue=ee.groups.filter(xe=>{try{return xe.model.location.type==="grid"}catch{return!0}});ue.length>0?oe.api.moveTo({group:ue[0],position:"center"}):oe.api.moveTo({position:"center"}),oe.api.setActive()},[]),ye=l.useCallback(()=>{var Me;const Q=C.current;if(!Q)return;const oe=Q.groups.filter(Le=>{var Ae;try{return((Ae=Le.element)==null?void 0:Ae.ownerDocument)===document&&Le.model.location.type==="grid"}catch{return!1}})[0]||null,ue=[...Q.panels];for(const Le of ue){const Ae=(Me=Le.group.element)==null?void 0:Me.ownerDocument,Oe=Le.group.model.location.type;Ae===document&&Oe==="grid"||(oe&&oe.id!==Le.group.id?Le.api.moveTo({group:oe,position:"center"}):Le.api.moveTo({position:"center"}))}const xe=Q.activePanel;xe&&(xe.group.model.openPanel(xe),xe.api.setActive()),vo(document)},[]),ke=l.useCallback(()=>{var ee,oe;const Q=C.current;if(Q)for(const ue of Q.groups){const xe=(ee=ue.element)==null?void 0:ee.ownerDocument;if(!xe||xe===document)continue;const Me=xe.getElementById("dv-popout-window");if(!(Me instanceof HTMLElement))continue;let Le=null,Ae=xe.title||"ADHDev",Oe="Popout workspace";const qe=ue.activePanel;if(qe)if(Le=qe.id,rs(qe.id)){const te=((oe=qe.params)==null?void 0:oe.routeId)||qe.id.slice(7),ge=cs([...$.values()],te);Ae=hp(ge),Oe=ge!=null&&ge.machineName?`Remote view · ${ge.machineName}`:"Remote view"}else{const te=$.get(qe.id);Ae=te?xt(te):qe.title||qe.id,Oe=te?Gs(te):"Dockview panel"}xe.title=`${Ae} — ADHDev`;const Ze=Array.from(xe.querySelectorAll("#adhdev-popout-header"));for(const te of Ze)te.remove();const _e=xe.createElement("div");_e.id="adhdev-popout-header",xe.body.appendChild(_e),_e.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(";")),_e.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 $=await n(
111
111
 
112
112
  `)}function WT(e,t){return t==="issues"?e.filter(n=>n.level==="warn"||n.level==="error"):t==="info"?e.filter(n=>n.level!=="debug"):e}function UT(e,t){return t==="issues"?e.filter(n=>n.level==="warn"||n.level==="error"):t==="info"?e.filter(n=>n.level!=="debug"):e}function GT({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=yT(r,o),g=ST(e,c),w=NT(t,c),h=AT(f,c),x=MT(a,c),k=WT(g,i),b=i==="all"?w:[],S=UT(h,i),j=i==="issues"?[]:x,y=TT({daemonLogs:g,daemonRawLines:w,trace:h,webEvents:x}),v=$T({daemonLogs:k,daemonRawLines:b,trace:S,webEvents:j}),N=FT(v),C=DT({daemonLoading:u,traceLoading:p,daemonFetchError:d,traceFetchError:m,daemonLogKind:n,daemonLogsCount:g.length,daemonRawLineCount:w.length,traceCount:h.length,webEventCount:x.length});return{filteredDaemonLogs:g,filteredDaemonRawLines:w,filteredTraceEntries:h,filteredWebEvents:x,visibleDaemonLogs:k,visibleDaemonRawLines:b,visibleTraceEntries:S,visibleWebEvents:j,quickFilterCounts:y,diagnosticEvents:v,diagnosticsSummary:N,sourceStates:C}}function qT(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function th(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function vi(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 Io(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 gl(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function zT({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${vi(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:th(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:gl(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 KT({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 VT({logLevel:e,traceCategory:t,onLogLevelChange:n,onTraceCategoryChange:r}){return s.jsx(Ss,{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:xT.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 YT({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 ${Io(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 ${Io(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:[gl(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:th(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 ${Io(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: ",qT(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 JT({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()," · ",gl(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function QT({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(zT,{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 ${vi(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 ${vi(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:jn(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:jn(d.payload,360)||"No payload"})]},d.id))]})]})]})}function XT({machineId:e,sendDaemonCommand:t}){const n=IT({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(()=>GT({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 w=d.current?"smooth":"instant";setTimeout(()=>{var h;(h=p.current)==null||h.scrollIntoView({behavior:w}),d.current=!0},50)}},[m.diagnosticEvents.length,n.autoRefresh]);const f=l.useCallback(async()=>{var h;const w=PT({daemonLogs:m.visibleDaemonLogs,daemonRawLines:m.visibleDaemonRawLines,trace:m.visibleTraceEntries,webEvents:m.visibleWebEvents});if(!w.trim()){mt.showToast("No visible logs to copy.","info");return}try{await((h=navigator.clipboard)==null?void 0:h.writeText(w)),mt.showToast("Copied visible logs to clipboard.","success")}catch(x){mt.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 w=OT({events:m.diagnosticEvents,summary:m.diagnosticsSummary,sources:m.sourceStates});try{await((h=navigator.clipboard)==null?void 0:h.writeText(w)),mt.showToast("Copied diagnostic bundle to clipboard.","success")}catch(x){mt.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(KT,{quickFilter:r,quickFilterCounts:m.quickFilterCounts,searchQuery:o,autoRefresh:n.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:i,onCopyDiagnostics:()=>{g()},onCopyVisible:()=>{f()},onToggleAutoRefresh:()=>n.setAutoRefresh(w=>!w),onRefresh:n.refresh,onClear:n.clear}),s.jsx(VT,{logLevel:n.logLevel,traceCategory:n.traceCategory,onLogLevelChange:n.setLogLevel,onTraceCategoryChange:n.setTraceCategory}),s.jsx(YT,{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(JT,{patterns:m.diagnosticsSummary.repeatedPatterns}),s.jsx(QT,{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 ZT(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 sh(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 eP(e){var a;const t=[],n=[],r=[];for(const o of e||[]){const i=String((o==null?void 0:o.lifecycle)||"").trim(),c=sh((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 tP(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Do(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 Lo(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Ro(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Ad(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 sP(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function nP(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 rP(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 aP({machineId:e,cliSessions:t,sendDaemonCommand:n}){const[r,a]=l.useState(""),[o,i]=l.useState(null),[c,u]=l.useState(!1),p=xC(e,{enabled:!!e,includeSessions:!0,limit:cc,intervalMs:M0}),d=p.diagnostics,m=p.loading,f=p.applyDiagnostics,g=l.useMemo(()=>ZT({diagnostics:d,loading:m,refreshing:c,error:r}),[d,m,c,r]),w=l.useMemo(()=>new Map(t.map(T=>[T.sessionId||T.id,T])),[t]),h=l.useCallback(async()=>{if(e){u(!0);try{const T=await n(e,"session_host_get_diagnostics",{includeSessions:!0,limit:cc}),R=Lo(T);if(!(R!=null&&R.success))throw new Error((R==null?void 0:R.error)||"Could not load hosted runtime diagnostics");f(R.diagnostics||R.result||null),a("")}catch(T){const R=T instanceof Error?T.message:"Could not load hosted runtime diagnostics";a(R)}finally{u(!1)}}},[f,e,n]);l.useEffect(()=>{!e||d||m||c||h()},[d,m,e,h,c]);const x=l.useCallback(async(T,R)=>{const E=`${T}:${R.sessionId}`;if(!(T==="session_host_stop_session"&&!window.confirm(`Stop ${R.displayName}?
113
113
  This will terminate the hosted runtime.`))){i(E);try{const _=await n(e,T,{sessionId:R.sessionId}),z=Lo(_);if(!(z!=null&&z.success))throw new Error((z==null?void 0:z.error)||"Session host action failed");const F=T==="session_host_resume_session"?"resumed":T==="session_host_restart_session"?"restarted":"stopped";mt.showToast(`Session host ${F}: ${R.displayName}`,"success"),await h()}catch(_){const z=_ instanceof Error?_.message:"Session host action failed";mt.showToast(z,"warning"),a(z)}finally{i(_=>_===E?null:_)}}},[e,h,n]),k=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 R=await n(e,"session_host_prune_duplicate_sessions",{}),E=Lo(R);if(!(E!=null&&E.success))throw new Error((E==null?void 0:E.error)||"Duplicate prune failed");const _=E.result||{},z=Array.isArray(_.prunedSessionIds)?_.prunedSessionIds.length:0,F=typeof _.duplicateGroupCount=="number"?_.duplicateGroupCount:0;mt.showToast(`Pruned ${z} duplicate runtime(s) across ${F} group(s)`,"success"),await h()}catch(R){const E=R instanceof Error?R.message:"Duplicate prune failed";mt.showToast(E,"warning"),a(E)}finally{i(R=>R==="session_host_prune_duplicate_sessions"?null:R)}}},[e,h,n]),b=l.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((T,R)=>(R.lastActivityAt||0)-(T.lastActivityAt||0)),[d==null?void 0:d.sessions]),S=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)||[]}:eP(b),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,b]),j=S.liveRuntimes,y=S.recoverySnapshots,v=S.inactiveRecords,N=l.useMemo(()=>rP(j),[j]),C=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(T=>T.level==="warn"||T.level==="error")||null,[d==null?void 0:d.recentLogs]),M=(T,R)=>{var $;const E=o===`session_host_resume_session:${T.sessionId}`,_=o===`session_host_restart_session:${T.sessionId}`,z=o===`session_host_stop_session:${T.sessionId}`,F=sh(T.meta),D=w.get(T.sessionId),W=T.attachedClients.length===1?"1 client":`${T.attachedClients.length} clients`,L=R==="recovery"?"Recover":"Resume",P=tP(R);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:T.displayName||(D==null?void 0:D.cliName)||T.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${nP(T.lifecycle)}`,children:T.lifecycle}),F&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:F})]}),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:T.workspaceLabel||(D==null?void 0:D.runtimeWorkspaceLabel)||T.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:T.runtimeKey}),T.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",T.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:(($=T.writeOwner)==null?void 0:$.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:sP(T.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(Jd,{size:11})," ",W]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",Ad(T.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",P]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[R==="recovery"&&(T.lifecycle==="interrupted"||T.lifecycle==="failed"||T.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{x("session_host_resume_session",T)},children:E?`${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",T)},children:_?"Restarting…":"Restart"}),R==="live"&&(T.lifecycle==="running"||T.lifecycle==="starting"||T.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",T)},children:z?"Stopping…":"Stop"})]})]})},T.sessionId)};return s.jsxs(Ss,{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(Ts,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:eS()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[N>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{k()},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(Ca,{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(Ys,{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:y.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:Ad(d.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Ro(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(Ys,{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:[Ro(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(Ii,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Do("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(T=>M(T,"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(Ts,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Do("recovery")}),y.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:y.map(T=>M(T,"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:Do("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:v.map(T=>M(T,"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"}),C.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:C.map(T=>{var E;const R=b.find(_=>_.sessionId===T.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:(R==null?void 0:R.displayName)||((E=w.get(T.sessionId))==null?void 0:E.cliName)||T.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[T.action,T.lifecycle?` · ${T.lifecycle}`:"",T.detail?` · ${T.detail}`:"",T.error?` · ${T.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${T.success===!1?"text-red-300":"text-text-secondary"}`,children:Ro(T.timestamp)})]},`${T.sessionId}:${T.timestamp}:${T.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 oP({machine:e,launchPick:t,actions:n}){const{t:r}=Ne("common"),{runLaunchCliCore:a,setLaunchPick:o}=n;return 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",children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(i=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{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 iP(e,t){const n=Kp(e),r=dn(e,t),a=Ji(e,r),o=tr(e,r),i=n==="preview"?"Update to preview":"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 Eo({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 _o({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 lP({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=iP(e,"1.0.9");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(Eo,{icon:s.jsx(Zs,{size:13}),children:c("machine.commandCenter.currentChats")}),s.jsx(_o,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(f=>{const g=hi(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:xt(f)}),g>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:ja(g)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:yn(f)})]},f.tabKey)})})})]}),p.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Eo,{icon:s.jsx(tu,{size:13}),children:c("machine.commandCenter.recentLaunches")}),s.jsx(_o,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:p.map(f=>{const{metaText:g,updatedLabel:w}=am(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}),w&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:w})]}),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(Eo,{icon:s.jsx(Ys,{size:13}),children:c("machine.commandCenter.daemonUpdate")}),s.jsx(_o,{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(Ca,{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 cP({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),[w,h]=l.useState(""),[x,k]=l.useState([]),[b,S]=l.useState(!1),[j,y]=l.useState(""),v=l.useCallback(async C=>{S(!0),y("");try{const A=await rl(i,e,C);h(A.path),k(A.directories)}catch(A){y(A instanceof Error?A.message:"Could not load folder")}finally{S(!1)}},[e,i]),N=l.useCallback(()=>{g(!0);const C=[...n.map(M=>M.workspace),...r.map(M=>M.workspace),...a.map(M=>M.workspace)],A=nl(t.platform,sl(C,t.defaultWorkspacePath,(t.workspaces||[]).map(M=>M.path)));v(A)},[a,r,n,v,t.defaultWorkspacePath,t.platform,t.workspaces]);return s.jsxs(s.Fragment,{children:[s.jsxs(Ss,{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(xn,{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(C=>{const A=C.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:C.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:Su(C.path,C.label)}),s.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:C.path,children:C.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void p(C.id),children:m("machine.managedWorkspaces.remove")})]},C.id)})})]}),f&&s.jsx(ol,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:w,directories:x,busy:b,error:j,confirmLabel:"Add workspace",onClose:()=>g(!1),onNavigate:C=>{v(C)},onConfirm:C=>{(async()=>{if(!C)return;await u(C)&&g(!1)})()}})]})}function dP({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(cP,{machineId:t,machine:e,ideSessions:n,cliSessions:r,acpSessions:a,actions:o,sendDaemonCommand:i})]})}function uP({onNicknameSynced:e}={}){var ye,ke,me,q,G,Z,V,fe,Te,ce;const{t}=Ne("common"),{id:n}=qh(),r=mr(),a=Ci(),{sendCommand:o}=vt(),i=Tn(),c=_p(),u=lp(),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?(ye=u.connectionRetryStatuses)==null?void 0:ye[n]:void 0,w=!!(g!=null&&g.blocked),[h,x]=l.useState("workspace"),[k,b]=l.useState(null);l.useCallback((H,pe)=>{b({daemonId:H,workspace:pe})},[]);const[,S]=l.useState("ide"),j=l.useRef(null),[y,v]=l.useState(null),N=l.useRef("__home__"),[C,A]=l.useState("__home__"),[M,T]=l.useState(!1),R=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]),gC(n&&h==="overview"?[n]:[],{enabled:h==="overview",intervalMs:j0});const E=()=>{if(f){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},_=rT({machineId:n,registeredMachineId:(m==null?void 0:m.machineId)||null,sendDaemonCommand:o,onNicknameSynced:e,logsEndRef:R});l.useEffect(()=>mt.onToast(pe=>{u.setToasts(B=>{if(B.some(Se=>Se.message===pe.message&&pe.timestamp-Se.timestamp<3e3))return B;const je={id:pe.id,message:pe.message,type:pe.type,timestamp:pe.timestamp,targetKey:pe.targetKey,actions:pe.actions};return[...B.slice(-4),je]});const le=pe.duration||5e3;setTimeout(()=>u.setToasts(B=>B.filter(be=>be.id!==pe.id)),le)}),[u]);const z=(m==null?void 0:m.availableProviders)||[],F={};for(const H of z)F[H.type]=H.icon;const D=m?{id:m.id,hostname:Cu(m,{fallbackId:m.id}),platform:((ke=m.machine)==null?void 0:ke.platform)||"unknown",arch:((me=m.machine)==null?void 0:me.arch)||"",cpus:((q=m.machine)==null?void 0:q.cpus)||0,totalMem:((G=m.machine)==null?void 0:G.totalMem)||0,freeMem:(Z=m.machine)==null?void 0:Z.freeMem,availableMem:(V=m.machine)==null?void 0:V.availableMem,loadavg:(fe=m.machine)==null?void 0:fe.loadavg,uptime:(Te=m.machine)==null?void 0:Te.uptime,release:((ce=m.machine)==null?void 0:ce.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,W=p.filter(H=>H.daemonId===n&&H.type!=="adhdev-daemon").filter(H=>!ir(H)&&!mn(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:By(H.aiAgents||(H.agents||[]).map(pe=>({id:pe.name,name:pe.name,status:pe.status,version:pe.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&&ir(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})),P=p.filter(H=>H.daemonId===n&&mn(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?ts(m,{fallbackId:n}):"",I="workspace",U=a.state,J=U==null?void 0:U.initialMachineTab,re=U==null?void 0:U.initialWorkspaceCategory;U==null||U.initialWorkspaceId,U==null||U.initialWorkspacePath;const Y=J==="ides"||J==="clis"||J==="acps"?"workspace":J||I,X=J==="ides"?"ide":J==="clis"?"cli":J==="acps"?"acp":re,de=[...W.map(H=>{var pe;return{id:`ide:${H.type}:${H.workspace||""}`,label:((pe=H.activeChat)==null?void 0:pe.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 pe;return{id:`cli:${H.type}:${H.workspace||""}`,label:((pe=H.activeChat)==null?void 0:pe.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}}),...P.map(H=>{var pe;return{id:`acp:${H.type}:${H.workspace||""}`,label:((pe=H.activeChat)==null?void 0:pe.title)||H.acpName,kind:"acp",providerType:H.type,providerSessionId:H.providerSessionId,subtitle:Js(H.summaryMetadata)||H.workspace||void 0,workspace:H.workspace||void 0,lastLaunchedAt:H.lastMessageAt||0}})].sort((H,pe)=>(pe.lastLaunchedAt||0)-(H.lastLaunchedAt||0)),ne=((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:Js(H.summaryMetadata)||H.workspace||void 0,workspace:H.workspace,summaryMetadata:H.summaryMetadata,lastLaunchedAt:H.lastLaunchedAt})):de,O=l.useMemo(()=>{var pe;const H=((pe=u.connectionStates)==null?void 0:pe[n||""])||void 0;return p.filter(le=>le.daemonId===n&&le.type!=="adhdev-daemon").flatMap(le=>Yi(le,{connectionStates:n&&H?{[n]:H}:void 0,defaultConnectionState:H})).filter(le=>!(le.transport==="pty"&&le.mode==="terminal")).sort((le,B)=>hi(B)-hi(le))},[p,u.connectionStates,n]),ie=l.useCallback(H=>{const pe=Qp(H);pe&&r(dr(pe))},[r]),K=l.useCallback(()=>{j.current&&(T(!0),j.current().finally(()=>{j.current=null,T(!1),v(null)}))},[]),ae=l.useCallback(H=>{if(!D)return;const{options:pe,selectedKey:le}=rm({machine:D,currentWorkspacePath:H.workspace,homeLabel:t("newSession.homeDirectory"),homeDescription:t("newSession.launchWithoutWorkspace")}),B=async()=>{S(H.kind),x("workspace")};j.current=async()=>{const be=pe.find(He=>He.key===N.current),je=(be==null?void 0:be.workspacePath)??null,Se=(be==null?void 0:be.workspaceId)??null;if(H.kind==="ide"&&H.providerType){await _.handleLaunchIde(H.providerType,je?{workspace:je}:void 0);return}if((H.kind==="cli"||H.kind==="acp")&&H.providerType){await _.runLaunchCliCore({cliType:H.providerType,dir:Se?void 0:je||"",workspaceId:Se||void 0,model:H.kind==="acp"&&Nu(H.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:H.providerSessionId});return}await B()},N.current=le,A(le),v({title:H.kind==="ide"?ua(t,"restart-ide",H.label):H.providerSessionId?vp(t,H.label):ua(t,"start-fresh",H.label),description:H.kind==="ide"?pa(t,"restart-ide"):H.providerSessionId?yp(t):pa(t,"start-fresh"),confirmLabel:H.kind==="ide"?ma(t,"restart-ide"):H.providerSessionId?ii(t,!0):ma(t,"start-fresh"),busyLabel:H.kind==="ide"?ha(t,"restart-ide"):H.providerSessionId?xp(t,!0):ha(t,"start-fresh"),workspaceOptions:pe,details:[{label:"Mode",value:H.kind.toUpperCase()},...H.providerType?[{label:"Provider",value:H.providerType}]:[]]})},[_,D]);if(l.useEffect(()=>{x(Y)},[I,Y,n]),l.useEffect(()=>{X&&S(X)},[X,n]),!D)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:E,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 Ce=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(us,{size:14})," ",t("machine.detail.tabWorkspace")]}),count:W.length+L.length+P.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ts,{size:14})," ",t("machine.detail.tabHostedRuntimes")]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Sa,{size:14})," ",t("machine.detail.tabProviders")]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Hf,{size:14})," ",t("machine.detail.tabSystem")]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Xd,{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:E,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(D.machineNickname||"")},title:t("machine.detail.clickToSetNickname"),children:$}),w?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:[D.platform," · ",D.arch]}),s.jsx("span",{children:t("machine.detail.coresCount",{count:D.cpus})}),(m==null?void 0:m.version)&&s.jsxs("span",{children:["v",m.version]}),D.p2p.available&&s.jsx("span",{children:t("machine.detail.p2pState",{state:D.p2p.state==="connected"?t("machine.detail.p2pConnected"):D.p2p.state})}),D.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:D.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:Ce.map(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(lP,{machineEntry:m,providers:z,recentLaunches:ne,currentConversations:O,onUpgradeDaemon:async()=>{try{await o(n,"daemon_upgrade",Vp(m))}catch{}},onOpenRecent:ae,onOpenConversation:ie}),s.jsx(dP,{machine:D,machineId:n,ideSessions:W,cliSessions:L,acpSessions:P,actions:_,sendDaemonCommand:o})]}),h==="providers"&&s.jsx(gT,{machineId:n,providers:z,sendDaemonCommand:o}),h==="overview"&&s.jsx(aT,{machine:D,ideSessions:W,cliSessions:L,acpSessions:P}),h==="session-host"&&s.jsx(aP,{machineId:n,cliSessions:L,sendDaemonCommand:o}),h==="logs"&&s.jsx(XT,{machineId:n,sendDaemonCommand:o})]})})}),_.launchPick&&D&&s.jsx(oP,{machine:D,launchPick:_.launchPick,actions:_}),y&&s.jsx(nm,{title:y.title,description:y.description,details:y.details,workspaceOptions:y.workspaceOptions,selectedWorkspaceKey:C,onWorkspaceChange:H=>{N.current=H,A(H)},confirmLabel:y.confirmLabel,busyLabel:y.busyLabel,busy:M,onConfirm:K,onCancel:()=>{j.current=null,v(null)}}),k&&s.jsx(eh,{daemonId:k.daemonId,workspace:k.workspace,onClose:()=>b(null)}),s.jsx(kp,{toasts:u.toasts||[],onDismiss:H=>u.setToasts(pe=>pe.filter(le=>le.id!==H)),onClickToast:H=>{H.targetKey&&r(dr(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 R=await n(e,"session_host_prune_duplicate_sessions",{}),E=Lo(R);if(!(E!=null&&E.success))throw new Error((E==null?void 0:E.error)||"Duplicate prune failed");const _=E.result||{},z=Array.isArray(_.prunedSessionIds)?_.prunedSessionIds.length:0,F=typeof _.duplicateGroupCount=="number"?_.duplicateGroupCount:0;mt.showToast(`Pruned ${z} duplicate runtime(s) across ${F} group(s)`,"success"),await h()}catch(R){const E=R instanceof Error?R.message:"Duplicate prune failed";mt.showToast(E,"warning"),a(E)}finally{i(R=>R==="session_host_prune_duplicate_sessions"?null:R)}}},[e,h,n]),b=l.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((T,R)=>(R.lastActivityAt||0)-(T.lastActivityAt||0)),[d==null?void 0:d.sessions]),S=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)||[]}:eP(b),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,b]),j=S.liveRuntimes,y=S.recoverySnapshots,v=S.inactiveRecords,N=l.useMemo(()=>rP(j),[j]),C=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(T=>T.level==="warn"||T.level==="error")||null,[d==null?void 0:d.recentLogs]),M=(T,R)=>{var $;const E=o===`session_host_resume_session:${T.sessionId}`,_=o===`session_host_restart_session:${T.sessionId}`,z=o===`session_host_stop_session:${T.sessionId}`,F=sh(T.meta),D=w.get(T.sessionId),W=T.attachedClients.length===1?"1 client":`${T.attachedClients.length} clients`,L=R==="recovery"?"Recover":"Resume",P=tP(R);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:T.displayName||(D==null?void 0:D.cliName)||T.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${nP(T.lifecycle)}`,children:T.lifecycle}),F&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:F})]}),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:T.workspaceLabel||(D==null?void 0:D.runtimeWorkspaceLabel)||T.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:T.runtimeKey}),T.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",T.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:(($=T.writeOwner)==null?void 0:$.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:sP(T.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(Jd,{size:11})," ",W]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",Ad(T.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",P]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[R==="recovery"&&(T.lifecycle==="interrupted"||T.lifecycle==="failed"||T.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{x("session_host_resume_session",T)},children:E?`${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",T)},children:_?"Restarting…":"Restart"}),R==="live"&&(T.lifecycle==="running"||T.lifecycle==="starting"||T.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",T)},children:z?"Stopping…":"Stop"})]})]})},T.sessionId)};return s.jsxs(Ss,{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(Ts,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:eS()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[N>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{k()},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(Ca,{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(Ys,{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:y.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:Ad(d.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Ro(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(Ys,{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:[Ro(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(Ii,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Do("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(T=>M(T,"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(Ts,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Do("recovery")}),y.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:y.map(T=>M(T,"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:Do("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:v.map(T=>M(T,"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"}),C.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:C.map(T=>{var E;const R=b.find(_=>_.sessionId===T.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:(R==null?void 0:R.displayName)||((E=w.get(T.sessionId))==null?void 0:E.cliName)||T.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[T.action,T.lifecycle?` · ${T.lifecycle}`:"",T.detail?` · ${T.detail}`:"",T.error?` · ${T.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${T.success===!1?"text-red-300":"text-text-secondary"}`,children:Ro(T.timestamp)})]},`${T.sessionId}:${T.timestamp}:${T.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 oP({machine:e,launchPick:t,actions:n}){const{t:r}=Ne("common"),{runLaunchCliCore:a,setLaunchPick:o}=n;return 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",children:s.jsxs("div",{className:"w-full max-w-md max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-xl border border-border-subtle bg-bg-secondary shadow-xl p-4 sm:p-5 overflow-y-auto",children:[s.jsx("h2",{id:"launch-pick-title",className:"text-sm font-semibold text-text-primary m-0 mb-1",children:"Where should this run?"}),s.jsx("p",{className:"text-[11px] text-text-muted m-0 mb-4",children:"Nothing is assumed. Pick a saved workspace, your default workspace, or home — or cancel and type a path."}),s.jsx("div",{className:"flex flex-col gap-2 mb-4 max-h-48 overflow-y-auto",children:(e.workspaces||[]).length===0?s.jsx("span",{className:"text-[11px] text-text-muted",children:"No saved workspaces yet. Add one in Overview or type a path above."}):(e.workspaces||[]).map(i=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{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 iP(e,t){const n=Kp(e),r=dn(e,t),a=Ji(e,r),o=tr(e,r),i=n==="preview"?"Update to preview":"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 Eo({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 _o({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 lP({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=iP(e,"1.0.12");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(Eo,{icon:s.jsx(Zs,{size:13}),children:c("machine.commandCenter.currentChats")}),s.jsx(_o,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(f=>{const g=hi(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:xt(f)}),g>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:ja(g)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:yn(f)})]},f.tabKey)})})})]}),p.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Eo,{icon:s.jsx(tu,{size:13}),children:c("machine.commandCenter.recentLaunches")}),s.jsx(_o,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:p.map(f=>{const{metaText:g,updatedLabel:w}=am(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}),w&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:w})]}),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(Eo,{icon:s.jsx(Ys,{size:13}),children:c("machine.commandCenter.daemonUpdate")}),s.jsx(_o,{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(Ca,{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 cP({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),[w,h]=l.useState(""),[x,k]=l.useState([]),[b,S]=l.useState(!1),[j,y]=l.useState(""),v=l.useCallback(async C=>{S(!0),y("");try{const A=await rl(i,e,C);h(A.path),k(A.directories)}catch(A){y(A instanceof Error?A.message:"Could not load folder")}finally{S(!1)}},[e,i]),N=l.useCallback(()=>{g(!0);const C=[...n.map(M=>M.workspace),...r.map(M=>M.workspace),...a.map(M=>M.workspace)],A=nl(t.platform,sl(C,t.defaultWorkspacePath,(t.workspaces||[]).map(M=>M.path)));v(A)},[a,r,n,v,t.defaultWorkspacePath,t.platform,t.workspaces]);return s.jsxs(s.Fragment,{children:[s.jsxs(Ss,{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(xn,{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(C=>{const A=C.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:C.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:Su(C.path,C.label)}),s.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:C.path,children:C.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void p(C.id),children:m("machine.managedWorkspaces.remove")})]},C.id)})})]}),f&&s.jsx(ol,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:w,directories:x,busy:b,error:j,confirmLabel:"Add workspace",onClose:()=>g(!1),onNavigate:C=>{v(C)},onConfirm:C=>{(async()=>{if(!C)return;await u(C)&&g(!1)})()}})]})}function dP({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(cP,{machineId:t,machine:e,ideSessions:n,cliSessions:r,acpSessions:a,actions:o,sendDaemonCommand:i})]})}function uP({onNicknameSynced:e}={}){var ye,ke,me,q,G,Z,V,fe,Te,ce;const{t}=Ne("common"),{id:n}=qh(),r=mr(),a=Ci(),{sendCommand:o}=vt(),i=Tn(),c=_p(),u=lp(),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?(ye=u.connectionRetryStatuses)==null?void 0:ye[n]:void 0,w=!!(g!=null&&g.blocked),[h,x]=l.useState("workspace"),[k,b]=l.useState(null);l.useCallback((H,pe)=>{b({daemonId:H,workspace:pe})},[]);const[,S]=l.useState("ide"),j=l.useRef(null),[y,v]=l.useState(null),N=l.useRef("__home__"),[C,A]=l.useState("__home__"),[M,T]=l.useState(!1),R=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]),gC(n&&h==="overview"?[n]:[],{enabled:h==="overview",intervalMs:j0});const E=()=>{if(f){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},_=rT({machineId:n,registeredMachineId:(m==null?void 0:m.machineId)||null,sendDaemonCommand:o,onNicknameSynced:e,logsEndRef:R});l.useEffect(()=>mt.onToast(pe=>{u.setToasts(B=>{if(B.some(Se=>Se.message===pe.message&&pe.timestamp-Se.timestamp<3e3))return B;const je={id:pe.id,message:pe.message,type:pe.type,timestamp:pe.timestamp,targetKey:pe.targetKey,actions:pe.actions};return[...B.slice(-4),je]});const le=pe.duration||5e3;setTimeout(()=>u.setToasts(B=>B.filter(be=>be.id!==pe.id)),le)}),[u]);const z=(m==null?void 0:m.availableProviders)||[],F={};for(const H of z)F[H.type]=H.icon;const D=m?{id:m.id,hostname:Cu(m,{fallbackId:m.id}),platform:((ke=m.machine)==null?void 0:ke.platform)||"unknown",arch:((me=m.machine)==null?void 0:me.arch)||"",cpus:((q=m.machine)==null?void 0:q.cpus)||0,totalMem:((G=m.machine)==null?void 0:G.totalMem)||0,freeMem:(Z=m.machine)==null?void 0:Z.freeMem,availableMem:(V=m.machine)==null?void 0:V.availableMem,loadavg:(fe=m.machine)==null?void 0:fe.loadavg,uptime:(Te=m.machine)==null?void 0:Te.uptime,release:((ce=m.machine)==null?void 0:ce.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,W=p.filter(H=>H.daemonId===n&&H.type!=="adhdev-daemon").filter(H=>!ir(H)&&!mn(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:By(H.aiAgents||(H.agents||[]).map(pe=>({id:pe.name,name:pe.name,status:pe.status,version:pe.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&&ir(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})),P=p.filter(H=>H.daemonId===n&&mn(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?ts(m,{fallbackId:n}):"",I="workspace",U=a.state,J=U==null?void 0:U.initialMachineTab,re=U==null?void 0:U.initialWorkspaceCategory;U==null||U.initialWorkspaceId,U==null||U.initialWorkspacePath;const Y=J==="ides"||J==="clis"||J==="acps"?"workspace":J||I,X=J==="ides"?"ide":J==="clis"?"cli":J==="acps"?"acp":re,de=[...W.map(H=>{var pe;return{id:`ide:${H.type}:${H.workspace||""}`,label:((pe=H.activeChat)==null?void 0:pe.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 pe;return{id:`cli:${H.type}:${H.workspace||""}`,label:((pe=H.activeChat)==null?void 0:pe.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}}),...P.map(H=>{var pe;return{id:`acp:${H.type}:${H.workspace||""}`,label:((pe=H.activeChat)==null?void 0:pe.title)||H.acpName,kind:"acp",providerType:H.type,providerSessionId:H.providerSessionId,subtitle:Js(H.summaryMetadata)||H.workspace||void 0,workspace:H.workspace||void 0,lastLaunchedAt:H.lastMessageAt||0}})].sort((H,pe)=>(pe.lastLaunchedAt||0)-(H.lastLaunchedAt||0)),ne=((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:Js(H.summaryMetadata)||H.workspace||void 0,workspace:H.workspace,summaryMetadata:H.summaryMetadata,lastLaunchedAt:H.lastLaunchedAt})):de,O=l.useMemo(()=>{var pe;const H=((pe=u.connectionStates)==null?void 0:pe[n||""])||void 0;return p.filter(le=>le.daemonId===n&&le.type!=="adhdev-daemon").flatMap(le=>Yi(le,{connectionStates:n&&H?{[n]:H}:void 0,defaultConnectionState:H})).filter(le=>!(le.transport==="pty"&&le.mode==="terminal")).sort((le,B)=>hi(B)-hi(le))},[p,u.connectionStates,n]),ie=l.useCallback(H=>{const pe=Qp(H);pe&&r(dr(pe))},[r]),K=l.useCallback(()=>{j.current&&(T(!0),j.current().finally(()=>{j.current=null,T(!1),v(null)}))},[]),ae=l.useCallback(H=>{if(!D)return;const{options:pe,selectedKey:le}=rm({machine:D,currentWorkspacePath:H.workspace,homeLabel:t("newSession.homeDirectory"),homeDescription:t("newSession.launchWithoutWorkspace")}),B=async()=>{S(H.kind),x("workspace")};j.current=async()=>{const be=pe.find(He=>He.key===N.current),je=(be==null?void 0:be.workspacePath)??null,Se=(be==null?void 0:be.workspaceId)??null;if(H.kind==="ide"&&H.providerType){await _.handleLaunchIde(H.providerType,je?{workspace:je}:void 0);return}if((H.kind==="cli"||H.kind==="acp")&&H.providerType){await _.runLaunchCliCore({cliType:H.providerType,dir:Se?void 0:je||"",workspaceId:Se||void 0,model:H.kind==="acp"&&Nu(H.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:H.providerSessionId});return}await B()},N.current=le,A(le),v({title:H.kind==="ide"?ua(t,"restart-ide",H.label):H.providerSessionId?vp(t,H.label):ua(t,"start-fresh",H.label),description:H.kind==="ide"?pa(t,"restart-ide"):H.providerSessionId?yp(t):pa(t,"start-fresh"),confirmLabel:H.kind==="ide"?ma(t,"restart-ide"):H.providerSessionId?ii(t,!0):ma(t,"start-fresh"),busyLabel:H.kind==="ide"?ha(t,"restart-ide"):H.providerSessionId?xp(t,!0):ha(t,"start-fresh"),workspaceOptions:pe,details:[{label:"Mode",value:H.kind.toUpperCase()},...H.providerType?[{label:"Provider",value:H.providerType}]:[]]})},[_,D]);if(l.useEffect(()=>{x(Y)},[I,Y,n]),l.useEffect(()=>{X&&S(X)},[X,n]),!D)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:E,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 Ce=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(us,{size:14})," ",t("machine.detail.tabWorkspace")]}),count:W.length+L.length+P.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ts,{size:14})," ",t("machine.detail.tabHostedRuntimes")]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Sa,{size:14})," ",t("machine.detail.tabProviders")]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Hf,{size:14})," ",t("machine.detail.tabSystem")]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Xd,{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:E,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(D.machineNickname||"")},title:t("machine.detail.clickToSetNickname"),children:$}),w?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:[D.platform," · ",D.arch]}),s.jsx("span",{children:t("machine.detail.coresCount",{count:D.cpus})}),(m==null?void 0:m.version)&&s.jsxs("span",{children:["v",m.version]}),D.p2p.available&&s.jsx("span",{children:t("machine.detail.p2pState",{state:D.p2p.state==="connected"?t("machine.detail.p2pConnected"):D.p2p.state})}),D.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:D.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:Ce.map(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(lP,{machineEntry:m,providers:z,recentLaunches:ne,currentConversations:O,onUpgradeDaemon:async()=>{try{await o(n,"daemon_upgrade",Vp(m))}catch{}},onOpenRecent:ae,onOpenConversation:ie}),s.jsx(dP,{machine:D,machineId:n,ideSessions:W,cliSessions:L,acpSessions:P,actions:_,sendDaemonCommand:o})]}),h==="providers"&&s.jsx(gT,{machineId:n,providers:z,sendDaemonCommand:o}),h==="overview"&&s.jsx(aT,{machine:D,ideSessions:W,cliSessions:L,acpSessions:P}),h==="session-host"&&s.jsx(aP,{machineId:n,cliSessions:L,sendDaemonCommand:o}),h==="logs"&&s.jsx(XT,{machineId:n,sendDaemonCommand:o})]})})}),_.launchPick&&D&&s.jsx(oP,{machine:D,launchPick:_.launchPick,actions:_}),y&&s.jsx(nm,{title:y.title,description:y.description,details:y.details,workspaceOptions:y.workspaceOptions,selectedWorkspaceKey:C,onWorkspaceChange:H=>{N.current=H,A(H)},confirmLabel:y.confirmLabel,busyLabel:y.busyLabel,busy:M,onConfirm:K,onCancel:()=>{j.current=null,v(null)}}),k&&s.jsx(eh,{daemonId:k.daemonId,workspace:k.workspace,onClose:()=>b(null)}),s.jsx(kp,{toasts:u.toasts||[],onDismiss:H=>u.setToasts(pe=>pe.filter(le=>le.id!==H)),onClickToast:H=>{H.targetKey&&r(dr(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 pP({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=>ls.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 mP={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,queueSection:!0,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},nh=l.createContext(null);function hP(){const e=l.useContext(nh);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}function fP({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 bP({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 gP({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 xP({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 vP({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 yP(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function wP({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:w,onNewMeshDaemonIdChange:h,newMeshWorkspace:x,onNewMeshWorkspaceChange:k,createPickerWorkspaces:b,onSelectMesh:S,onCreate:j,onCancelCreate:y}){const{t:v}=Ne("common"),N=o.maxMeshes!=null&&e.length>=o.maxMeshes,[C,A]=l.useState(!1),M=C||!!d.trim();return s.jsxs(gr,{icon:s.jsx(es,{}),title:v("repoMesh.list.title"),subtitle:v("repoMesh.list.count",{count:e.length}),widthClassName:"max-w-5xl",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:c,disabled:N,title:N?v("repoMesh.list.meshLimitReached",{max:o.maxMeshes}):void 0,children:v("repoMesh.list.createMesh")}),children:[N&&s.jsx(Ot,{variant:"info",className:"mb-4",children:v("repoMesh.list.meshLimitBanner",{max:o.maxMeshes})}),n&&s.jsx(Ot,{variant:"error",onDismiss:r,className:"mb-4",children:n}),i&&s.jsxs(bt,{className:"mb-5 border-accent/40 animate-[fadeIn_0.3s_ease-out]",children:[s.jsx("h3",{className:"text-base font-bold mb-4",children:v("repoMesh.list.createTitle")}),o.createDaemonPicker&&s.jsx(Ct,{label:v("repoMesh.list.createOnMachine"),hint:v("repoMesh.list.createOnMachineHint"),children:s.jsx("select",{className:"input w-full",value:w,onChange:T=>h(T.target.value),disabled:!a.length,children:a.length===0?s.jsx("option",{value:"",children:v("repoMesh.list.noConnectedDaemon")}):a.map(T=>s.jsx("option",{value:T.id,children:yP(T)},T.id))})}),o.createDaemonPicker&&s.jsx(Ct,{label:v("repoMesh.list.workspace"),hint:v("repoMesh.list.workspaceHint"),children:s.jsx("select",{className:"input w-full",value:x,onChange:T=>k(T.target.value),disabled:!w||!b.length,children:w?b.length===0?s.jsx("option",{value:"",children:v("repoMesh.list.noRegisteredWorkspaces")}):b.map(T=>s.jsx("option",{value:T.path,children:T.label?`${T.label} · ${T.path}`:T.path},T.id||T.path)):s.jsx("option",{value:"",children:v("repoMesh.list.selectMachineFirst")})})}),s.jsx(Ct,{label:v("repoMesh.list.name"),children:s.jsx(is,{value:u,onChange:T=>p(T.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(Ct,{label:v("repoMesh.list.remoteUrl"),hint:v("repoMesh.list.remoteUrlHint"),children:s.jsx(is,{value:f,onChange:T=>g(T.target.value),placeholder:"https://github.com/user/repo"})}),M?s.jsx(Ct,{label:v("repoMesh.list.repoIdentity"),hint:v("repoMesh.list.repoIdentityHint"),children:s.jsx(is,{value:d,onChange:T=>m(T.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:()=>A(!0),children:v("repoMesh.list.advancedIdentityToggle")}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:j,disabled:!u.trim()||!f.trim()&&!d.trim()||o.createDaemonPicker&&(!w||!x),children:v("repoMesh.list.create")}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:y,children:v("repoMesh.list.cancel")})]})]}),t?s.jsx("div",{className:"text-sm text-text-muted p-4",children:v("repoMesh.list.loading")}):e.length===0?s.jsx(Ra,{icon:s.jsx(es,{}),title:v("repoMesh.list.emptyTitle"),description:a.length>0?v("repoMesh.list.emptyWithDaemons"):v("repoMesh.list.emptyNoDaemons"),action:s.jsx("button",{className:"btn btn-primary btn-sm",disabled:!a.length,onClick:c,children:v("repoMesh.list.createFirst")})}):s.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(T=>{var R;return s.jsx("button",{type:"button",onClick:()=>S(T.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(es,{size:16}),s.jsx("span",{className:"font-bold text-sm",children:T.name})]}),s.jsxs("div",{className:"text-[12px] text-text-muted flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:T.repoIdentity||T.repo_identity||v("repoMesh.list.noRepoIdentity")}),(T.defaultBranch||T.default_branch)&&s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(bP,{size:11}),T.defaultBranch||T.default_branch]})]})]}),s.jsxs("div",{className:"text-right text-[11px] text-text-muted shrink-0 ml-4",children:[s.jsx("div",{children:new Date(T.createdAt||T.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("div",{className:"text-text-muted/60",children:[((R=T.nodes)==null?void 0:R.length)??T.nodeCount??0," ",v("repoMesh.list.nodesSuffix")]})]})]})},T.id)})})]})}const kP=["claude-cli","codex-cli","gemini-cli","hermes-cli","antigravity-cli"],SP=[{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 CP(){return{nodeId:"",provider:"",model:"",n:""}}function Md(e){var t;return(t=e.providers)!=null&&t.length?e.providers.filter(Boolean):(e.providerPriority??[]).filter(Boolean)}function jP(e){return{nodeId:e.nodeId??"",provider:e.provider??"",model:e.model??"",n:e.n!=null?String(e.n):""}}function NP(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 AP({status:e,daemonId:t,sendDaemonCommand:n,availableProviders:r}){const{t:a}=Ne(),{theme:o}=Ls(),i=l.useMemo(()=>Rs(o),[o]),c=l.useMemo(()=>Ap(r),[r]),[u,p]=l.useState({}),[d,m]=l.useState(!1),[f,g]=l.useState(null),[w,h]=l.useState({}),[x,k]=l.useState(null),b=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(P=>({nodeId:P.nodeId,machineLabel:P.machineLabel,providers:P.providers,providerPriority:P.providerPriority})),[e==null?void 0:e.nodes]),S=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(P=>P.nodeId),[e==null?void 0:e.nodes]),j=l.useMemo(()=>Object.fromEntries(((e==null?void 0:e.nodes)??[]).map(P=>[P.nodeId,P.machineLabel||P.nodeId])),[e==null?void 0:e.nodes]),y=l.useMemo(()=>{const P={};for(const $ of b)P[$.nodeId]=Md($);return P},[b]),v=l.useMemo(()=>{const P=[...new Set(b.flatMap(Md).filter(Boolean))];return[...new Set([...P,...kP])].sort()},[b]),N=!!t&&!!n,C=P=>P&&typeof P=="object"&&"result"in P?P.result:P,A=l.useCallback(async()=>{if(!(!t||!n)){m(!0),g(null);try{const P=await n(t,"magi_kind_panel_list",{}),$=C(P);if(($==null?void 0:$.success)===!1)throw new Error($.error||a("meshGraph.magiKind.errorLoad"));p($!=null&&$.kindPanels&&typeof $.kindPanels=="object"?$.kindPanels:{}),h({})}catch(P){g((P==null?void 0:P.message)||a("meshGraph.magiKind.errorLoad"))}finally{m(!1)}}},[t,n,a]);l.useEffect(()=>{A()},[A]);const M=l.useCallback(P=>{if(w[P])return w[P];const $=u[P];return $?$.map(jP):[]},[w,u]),T=(P,$)=>{h(I=>({...I,[P]:$}))},R=(P,$,I)=>{const U=M(P);T(P,U.map((J,re)=>re===$?{...J,...I}:J))},E=P=>{T(P,[...M(P),CP()])},_=(P,$)=>{T(P,M(P).filter((I,U)=>U!==$))},z=l.useCallback(async P=>{if(!t||!n)return;const $=NP(M(P));if("error"in $){const I=$.error,U=I.code==="provider_required"?a("meshGraph.magiKind.errorSlotProvider",{slot:I.slot}):I.code==="replica_min"?a("meshGraph.magiKind.errorSlotReplica",{slot:I.slot}):a("meshGraph.magiKind.errorNoSlot");g(`${P}: ${U}`);return}k(P),g(null);try{const I=await n(t,"magi_kind_panel_set",{kind:P,slots:$.slots}),U=C(I);if((U==null?void 0:U.success)===!1)throw new Error(U.error||a("meshGraph.magiKind.errorSave"));await A()}catch(I){g((I==null?void 0:I.message)||a("meshGraph.magiKind.errorSave"))}finally{k(null)}},[t,n,M,A,a]),F=l.useCallback(async P=>{if(!(!t||!n)&&confirm(a("meshGraph.magiKind.removeConfirm",{kind:P}))){k(P),g(null);try{const $=await n(t,"magi_kind_panel_remove",{kind:P}),I=C($);if((I==null?void 0:I.success)===!1)throw new Error(I.error||a("meshGraph.magiKind.errorRemove"));await A()}catch($){g(($==null?void 0:$.message)||a("meshGraph.magiKind.errorRemove"))}finally{k(null)}}},[t,n,A,a]),D=`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"}`,W="btn btn-primary btn-sm",L="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:L,onClick:()=>void A(),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:SP.map(({kind:P,labelKey:$,hint:I})=>{const U=M(P),J=!!u[P],re=x===P;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($)}),s.jsx("span",{className:`font-mono text-[10px] ${i.textMuted}`,children:I}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${J?"border-emerald-400/30 bg-emerald-500/10 text-emerald-300":"border-slate-400/20 bg-slate-500/10 text-slate-300"}`,children:J?a("meshGraph.magiKind.agentCount",{count:u[P].length}):a("meshGraph.magiKind.off")})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[U.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")}),U.map((Y,X)=>{const de=Y.nodeId?y[Y.nodeId]??[]:[],ne=Y.nodeId&&de.length?de: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:D,value:Y.nodeId,onChange:O=>R(P,X,{nodeId:O.target.value}),title:a("meshGraph.magiKind.machineTitle"),children:[s.jsx("option",{value:"",children:a("meshGraph.magiKind.anyMachine")}),S.map(O=>s.jsx("option",{value:O,children:j[O]??O},O)),Y.nodeId&&!S.includes(Y.nodeId)&&s.jsx("option",{value:Y.nodeId,children:a("meshGraph.magiKind.offlineSuffix",{label:j[Y.nodeId]??Y.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:D,value:Y.provider,onChange:O=>R(P,X,{provider:O.target.value}),title:a("meshGraph.magiKind.providerTitle"),children:[s.jsx("option",{value:"",children:a("meshGraph.magiKind.selectProvider")}),ne.map(O=>s.jsx("option",{value:O,children:O},O)),Y.provider&&!ne.includes(Y.provider)&&s.jsx("option",{value:Y.provider,children:Y.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 K;const O=(Y.provider?(K=c.get(Y.provider))==null?void 0:K.models:void 0)??[],ie=!!Y.model&&O.length>0&&!O.includes(Y.model);return O.length>0&&!ie?s.jsxs("select",{className:D,value:O.includes(Y.model)?Y.model:"",title:a("meshGraph.magiKind.modelTitle"),onChange:ae=>R(P,X,{model:ae.target.value==="__custom__"?" ":ae.target.value}),children:[s.jsx("option",{value:"",children:a("meshGraph.magiKind.modelDefault")}),O.map(ae=>s.jsx("option",{value:ae,children:ae},ae)),s.jsx("option",{value:"__custom__",children:a("meshGraph.magiKind.modelCustom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:D,value:Y.model.trim(),placeholder:a("meshGraph.magiKind.modelDefault"),title:a("meshGraph.magiKind.modelTitle"),onChange:ae=>R(P,X,{model:ae.target.value})}),O.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:()=>R(P,X,{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:`${D} sm:w-16`,value:Y.n,placeholder:"1",inputMode:"numeric",title:a("meshGraph.magiKind.copiesTitle"),onChange:O=>R(P,X,{n:O.target.value})})]}),s.jsx("button",{type:"button",className:`${L} sm:mt-[18px] inline-flex h-8 w-8 items-center justify-center p-0`,onClick:()=>_(P,X),"aria-label":a("meshGraph.magiKind.removeAgent"),title:a("meshGraph.magiKind.removeAgent"),children:"✕"})]},X)}),s.jsx("div",{children:s.jsx("button",{type:"button",className:L,onClick:()=>E(P),disabled:!N,children:a("meshGraph.magiKind.addAgent")})})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:W,onClick:()=>void z(P),disabled:re||!N,children:a(re?"meshGraph.magiKind.saving":"meshGraph.magiKind.save")}),s.jsx("button",{type:"button",className:L,onClick:()=>void F(P),disabled:re||!N||!J,title:a(J?"meshGraph.magiKind.removeBindingTitle":"meshGraph.magiKind.removeBindingDisabledTitle"),children:a("meshGraph.magiKind.removeBinding")})]})]},P)})})]})}function MP({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,w]=l.useState(null),h=l.useCallback(async()=>{if(!e||!t){d(a("repoMesh.promptPreview.connectPrompt"));return}u(!0),d(null);try{const k=await r(e,"coordinator_prompt_preview",{meshId:t,cliType:n}),b=k!=null&&k.result&&typeof k.result=="object"?k.result:k;if(!(b!=null&&b.success)){d((b==null?void 0:b.error)||a("repoMesh.promptPreview.errorRender"));return}f(typeof b.prompt=="string"?b.prompt:""),w(typeof b.bytes=="number"?b.bytes:null)}catch(k){d((k==null?void 0:k.message)||String(k))}finally{u(!1)}},[e,t,n,r,a]),x=l.useCallback(()=>{const k=!o;i(k),k&&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:k=>k.currentTarget.select()})]})]})]})}const TP=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function PP(e){const t=TP(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function IP(e){const t=e==null?void 0:e.missions;return Array.isArray(t)?t:[]}function DP(e){return typeof e.goal=="string"&&e.goal?{text:e.goal,truncated:!1}:{text:e.goalPreview??"",truncated:e.goalTruncated===!0}}const LP=["active","paused","completed","abandoned"];function Td(e){return(e.status||"active").toLowerCase()}const RP=8;function EP({status:e,daemonId:t,meshId:n,sendCommand:r}){const{t:a}=Ne("common"),o=l.useMemo(()=>IP(e),[e]),[i,c]=l.useState({}),[u,p]=l.useState({}),[d,m]=l.useState(!1),[f,g]=l.useState(null),[w,h]=l.useState("active"),[x,k]=l.useState(!1),b=l.useMemo(()=>{const A={};for(const M of o){const T=Td(M);A[T]=(A[T]||0)+1}return A},[o]),S=l.useMemo(()=>w==="all"?o:o.filter(A=>Td(A)===w),[o,w]),j=x?S:S.slice(0,RP),y=S.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}),M=PP(A),T=Array.isArray(M==null?void 0:M.missions)?M.missions:[],R={};for(const E of T)E.id&&typeof E.goal=="string"&&E.goal&&(R[E.id]=E.goal);c(E=>({...E,...R}))}catch(A){g(A instanceof Error?A.message:a("repoMesh.missions.errorFetch"))}finally{m(!1)}}},[t,n,r,a]),C=l.useCallback(A=>{p(M=>({...M,[A]:!M[A]})),!u[A]&&!i[A]&&N()},[u,i,N]);return o.length===0?null:s.jsxs(bt,{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:[LP.filter(A=>(b[A]||0)>0).map(A=>s.jsxs("button",{type:"button",onClick:()=>{h(A),k(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] capitalize transition-colors ${w===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"),k(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] transition-colors ${w==="all"?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:["All ",o.length]})]}),S.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:a("repoMesh.missions.empty",{status:w})}),s.jsx("div",{className:"flex flex-col gap-2",children:j.map(A=>{var F;const M=u[A.id]===!0,T=i[A.id],R=DP(A),E=M&&T?T:R.text,_=M&&!T&&R.truncated,z=((F=A.tasks)==null?void 0:F.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}),z>0&&s.jsx("span",{className:"shrink-0 text-[11px] text-text-muted",children:a("repoMesh.missions.taskCount",{count:z})})]}),E&&s.jsxs("div",{className:`mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-text-secondary ${M?"max-h-72 overflow-y-auto":"line-clamp-2"}`,children:[E,_&&s.jsx("span",{className:"text-text-muted",children:a("repoMesh.missions.goalUnavailable")})]}),(R.truncated||T)&&v&&s.jsx("button",{type:"button",className:"mt-1.5 text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:()=>C(A.id),disabled:d,children:a(M?"repoMesh.missions.showLess":d&&!T?"repoMesh.missions.loading":"repoMesh.missions.showFullGoal")})]},A.id)})}),y>0&&s.jsx("button",{type:"button",className:"mt-2 text-[12px] text-accent-primary hover:underline",onClick:()=>k(!0),children:a("repoMesh.missions.showMore",{count:y})})]})}const _P=["","low","medium","high"],$P={easy:"Easy",medium:"Medium",difficult:"Difficult",freeform:"Freeform"};function Pd(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 Id(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 HP(){return{provider:"",model:"",thinkingLevel:"",difficulty:[],capability:[],maxParallel:""}}const $s="w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-2.5 py-1.5 text-xs";function FP({slots:e,availableProviders:t,saving:n,onSave:r}){const{t:a}=Ne("common"),[o,i]=l.useState(()=>e.map(Pd)),c=l.useMemo(()=>JSON.stringify(e),[e]);l.useEffect(()=>{i(e.map(Pd))},[c]);const u=l.useMemo(()=>[...new Set(t.map(b=>b.type).filter(Boolean))],[t]),p=l.useMemo(()=>Ap(t),[t]),d=l.useMemo(()=>{const b=o.map(Id).filter(Boolean);return JSON.stringify(b)!==JSON.stringify(e)},[o,e]),m=(b,S)=>i(j=>j.map((y,v)=>v===b?{...y,...S}:y)),f=(b,S)=>i(j=>j.map((y,v)=>{var A;if(v!==b)return y;const N=((A=p.get(S))==null?void 0:A.models)??[],C=!y.model||N.length===0||N.includes(y.model);return{...y,provider:S,...C?{}:{model:""}}})),g=b=>i(S=>S.filter((j,y)=>y!==b)),w=()=>i(b=>[...b,HP()]),h=(b,S)=>i(j=>{const y=b+S;if(y<0||y>=j.length)return j;const v=[...j];return[v[b],v[y]]=[v[y],v[b]],v}),x=(b,S)=>i(j=>j.map((y,v)=>{if(v!==b)return y;const N=y.difficulty.includes(S);return{...y,difficulty:N?y.difficulty.filter(C=>C!==S):[...y.difficulty,S]}})),k=()=>r(o.map(Id).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,S)=>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:["#",S+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:S===0,onClick:()=>h(S,-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:S===o.length-1,onClick:()=>h(S,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(S),"aria-label":a("repoMesh.slotEditor.removeSlot"),children:s.jsx(At,{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:$s,value:b.provider,onChange:j=>f(S,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:$s,value:b.provider,placeholder:"claude-cli",onChange:j=>m(S,{provider:j.target.value})})]}),(()=>{var C;const j=p.get(b.provider),y=(j==null?void 0:j.models)??[],v=(C=j==null?void 0:j.thinking)!=null&&C.length?["",...j.thinking]:_P,N=!!b.model&&y.length>0&&!y.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")}),y.length>0&&!N?s.jsxs("select",{className:$s,value:y.includes(b.model)?b.model:"",onChange:A=>m(S,{model:A.target.value==="__custom__"?" ":A.target.value}),children:[s.jsx("option",{value:"",children:a("repoMesh.slotEditor.providerDefault")}),y.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:$s,value:b.model.trim(),placeholder:b.provider?`${b.provider} model`:a("repoMesh.slotEditor.modelPlaceholder"),onChange:A=>m(S,{model:A.target.value})}),y.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(S,{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:$s,value:b.thinkingLevel,onChange:A=>m(S,{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:Ay.map(j=>{const y=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 ${y?"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(S,j),children:$P[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:$s,value:b.capability.join(", "),placeholder:"worktree, os=darwin",onChange:j=>m(S,{capability:j.target.value.split(",").map(y=>y.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:$s,value:b.maxParallel,placeholder:a("repoMesh.slotEditor.maxParallelPlaceholder"),onChange:j=>m(S,{maxParallel:j.target.value})})]})]})]},S)),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:w,children:[s.jsx(Di,{size:13})," ",a("repoMesh.slotEditor.addSlot")]}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:k,disabled:!!n||!d,children:a(n?"repoMesh.slotEditor.saving":"repoMesh.slotEditor.saveSlots")})]})]})}function BP(e){const t=new Map;for(const n of e)n!=null&&n.id&&t.set(n.id,wn(n.availableProviders||[]));return t}function OP(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 WP(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 UP(e){const t=e.capabilities;return Array.isArray(t)?t.map(n=>typeof n=="string"?n.trim():"").filter(Boolean):[]}const GP=["os=","arch=","provider=","worktree=","converge="];function qP({node:e,saving:t,onSave:n}){const{t:r}=Ne("common"),a=l.useMemo(()=>WP(e).filter(h=>!h.custom),[e]),o=l.useMemo(()=>UP(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"):GP.some(k=>x.toLowerCase().startsWith(k))?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 w(h){c(x=>x.filter(k=>k!==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:()=>w(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 zP(e,t){return t.filter(n=>n.status!=="assigned"?!1:(n.assignedNodeId||n.nodeId)===e.id)}function KP(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 VP(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 YP(e){const t=VP(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 JP(e){return e.isLocalWorktree===!0}function QP(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 Dd(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function XP(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 ZP({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:w,savingNodeSystemPromptId:h,onSaveNodeSystemPrompt:x,selectedNodeId:k,onSelectNode:b,showAddNode:S,onShowAddNode:j,onCancelAddNode:y,nodeWorkspace:v,onNodeWorkspaceChange:N,nodeProviderPriority:C,onNodeProviderPriorityChange:A,nodeDaemonId:M,onNodeDaemonIdChange:T,nodeCustomPath:R,onNodeCustomPathChange:E,nodePickerWorkspaces:_,nodePickerProviders:z,attachableDaemons:F,onAddNode:D,onRemoveNode:W}){const{t:L}=Ne("common"),P=l.useMemo(()=>BP(r),[r]),$=l.useMemo(()=>e.filter(I=>!JP(I)),[e]);return s.jsxs(bt,{title:i.addNodeDaemonPicker?L("repoMesh.nodeList.title",{count:$.length}):L("repoMesh.nodeList.titleNoCount"),description:i.addNodeDaemonPicker?L("repoMesh.nodeList.descriptionCloud"):L("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:L("repoMesh.nodeList.daemonCandidates")}),s.jsx("div",{className:"text-[12px] text-text-muted",children:L("repoMesh.nodeList.daemonCandidatesHint")})]}),s.jsx("span",{className:"text-[11px] text-text-muted",children:L("repoMesh.nodeList.available",{count:F.length})})]}),r.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:L("repoMesh.nodeList.noDaemonsAvailable")}):F.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:L("repoMesh.nodeList.allDaemonsAttached")}):s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:F.map(I=>s.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors ${I.id===c?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{T(I.id),N(""),E(!1),A(cr(wn(I.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:Dd(I)}),I.id===c&&s.jsx("span",{className:"text-[10px] text-accent-primary",children:L("repoMesh.nodeList.selectedHost")})]}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted font-mono truncate",children:I.id}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:L("repoMesh.nodeList.workspacesDetected",{count:(I.workspaces||[]).length})})]},I.id))})]}),!S&&s.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:j,children:[s.jsx(xP,{size:13})," ",i.addNodeDaemonPicker?L("repoMesh.nodeList.attachMachine"):L("repoMesh.nodeList.addNode")]}),S&&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?L("repoMesh.nodeList.attachMachineTitle"):L("repoMesh.nodeList.addNodeTitle")}),s.jsx("button",{onClick:()=>{y(),T(""),E(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(At,{size:16})})]}),i.addNodeDaemonPicker&&s.jsx(Ct,{label:L("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:M,onChange:I=>{var U;T(I.target.value),N(""),E(!1),A(cr(wn(((U=r.find(J=>J.id===I.target.value))==null?void 0:U.availableProviders)||[])))},children:[s.jsx("option",{value:"",children:L("repoMesh.nodeList.selectMachine")}),r.map(I=>s.jsx("option",{value:I.id,children:Dd(I)},I.id))]})}),(i.addNodeDaemonPicker?M:!0)&&s.jsx(Ct,{label:L("repoMesh.nodeList.workspacePath"),children:i.addNodeDaemonPicker&&!R&&_.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:_.map(I=>s.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${v===I.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(I.path),children:[s.jsx("span",{className:"font-medium block truncate",children:I.label||I.path.split("/").pop()}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:I.path})]},I.id||I.path))}),s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{E(!0),N("")},children:L("repoMesh.nodeList.enterCustomPath")})]}):s.jsx(s.Fragment,{children:i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[s.jsx(is,{value:v,onChange:I=>N(I.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:I=>{I.key==="Enter"&&D()}}),_.length>0&&s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0 mt-1",onClick:()=>{E(!1),N("")},children:L("repoMesh.nodeList.pickFromSaved")})]}):(()=>{var J;const I=Array.isArray(n==null?void 0:n.workspaces)?n.workspaces:[],U=`mesh-add-node-workspaces-${a||"new"}`;return s.jsxs(s.Fragment,{children:[s.jsx(is,{value:v,onChange:re=>N(re.target.value),placeholder:((J=I[0])==null?void 0:J.path)||"/Users/dev/projects/myapp",list:I.length>0?U:void 0,autoFocus:!0}),I.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:U,children:I.map(re=>s.jsx("option",{value:re.path,children:re.label||re.path},re.id||re.path))}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:I.slice(0,6).map(re=>s.jsx("button",{type:"button",onClick:()=>N(re.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:re.path,children:re.label||re.path.split("/").filter(Boolean).pop()||re.path},re.id||re.path))})]})]})})()})}),s.jsx(Ct,{label:L("repoMesh.nodeList.preferredTools"),hint:L("repoMesh.nodeList.preferredToolsHint"),children:s.jsx(xS,{value:C,availableProviders:i.addNodeDaemonPicker?z:u,onChange:A})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:D,disabled:!v.trim()||i.addNodeDaemonPicker&&!M,className:"btn btn-primary btn-sm",children:L("repoMesh.nodeList.add")}),s.jsx("button",{onClick:()=>{y(),T(""),E(!1)},className:"btn btn-secondary btn-sm",children:L("repoMesh.nodeList.cancel")})]})]}),i.addNodeDaemonPicker&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-300 bg-amber-500/10 border border-amber-500/20 rounded-lg px-3 py-2",children:L("repoMesh.nodeList.setupInventoryWarning")}),$.length===0?s.jsx(Ra,{icon:s.jsx(xn,{}),title:L("repoMesh.nodeList.emptyTitle"),description:L("repoMesh.nodeList.emptyDescription")}):s.jsx("div",{className:"flex flex-col gap-2",children:$.map(I=>{var de;const U=YP(I),J=zP(I,t),re=QP(I,n),Y=k===I.id,X=I.status||I.machine_status||(J.length>0||re.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 ${Y?"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(Y?null:I.id),onKeyDown:i.addNodeDaemonPicker?void 0:ne=>{(ne.key==="Enter"||ne.key===" ")&&(ne.preventDefault(),b(Y?null:I.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:I.machine_label||I.machine_nickname||I.hostname||I.workspace}):s.jsx("span",{className:"text-sm font-medium",children:I.workspace.split("/").pop()}),i.addNodeDaemonPicker&&s.jsx(vP,{status:X}),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:L("repoMesh.nodeList.setupInventory")})]}),i.addNodeDaemonPicker&&s.jsx("div",{className:"text-[11px] text-text-muted",children:L("repoMesh.nodeList.ownerMachine",{owner:XP(r.find(ne=>ne.id===String(I.daemon_id||"")),o),machine:I.machine_label||I.daemon_id||I.workspace})}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:I.workspace}),s.jsx(qP,{node:I,saving:m===I.id,onSave:ne=>f(I,ne)}),i.addNodeDaemonPicker&&s.jsx("div",{className:"mt-2 text-[11px] text-amber-300",children:L("repoMesh.nodeList.liveDetailGraphOwned")}),s.jsxs("div",{className:"mt-3 max-w-2xl",onClick:ne=>ne.stopPropagation(),children:[s.jsx(Ct,{label:L("repoMesh.nodeList.slotsLabel"),hint:L("repoMesh.nodeList.slotsHint"),children:s.jsx(FP,{slots:Array.isArray((de=I.policy)==null?void 0:de.slots)?I.policy.slots:[],availableProviders:OP(I,P),saving:p===I.id,onSave:ne=>d(I,ne)})}),i.nodeInstruction&&s.jsxs(Ct,{label:L("repoMesh.nodeList.nodeInstruction"),hint:L("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[I.id]??"",onChange:ne=>{const O=ne.target.value;w(I.id,O)},onClick:ne=>ne.stopPropagation(),disabled:h===I.id,placeholder:L("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:ne=>{ne.stopPropagation(),x(I)},disabled:h===I.id,children:h===I.id?L("repoMesh.nodeList.saving"):L("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:ne=>{ne.stopPropagation(),W(I.id)},title:L("repoMesh.nodeList.removeNode"),children:s.jsx(gP,{size:14})})]}),s.jsxs("details",{className:"mt-3 group",onClick:ne=>ne.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:"▸"})," ",L("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:L("repoMesh.nodeList.nodeId")})," ",s.jsx("span",{className:"font-mono break-all",children:I.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:L("repoMesh.nodeList.launchReady")})," ",s.jsx("span",{className:U.configured?"text-green-400":"text-amber-400",children:U.configured?L("repoMesh.nodeList.launchReadyYes"):L("repoMesh.nodeList.launchReadyNo")})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:L("repoMesh.nodeList.repoRoot")})," ",s.jsx("span",{className:"font-mono break-all",children:I.repoRoot||I.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:L("repoMesh.nodeList.activeSessionsLabel")})," ",re.length]}),i.addNodeDaemonPicker&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:L("repoMesh.nodeList.added")})," ",new Date(I.created_at||I.createdAt||Date.now()).toLocaleDateString()]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:L("repoMesh.nodeList.activeQueueAssignments")}),J.length===0?s.jsx("div",{children:L("repoMesh.nodeList.noActiveAssignment")}):s.jsx("ul",{className:"m-0 pl-4",children:J.map(ne=>s.jsx("li",{className:"font-mono",children:KP(ne)},ne.id))})]}),re.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:L("repoMesh.nodeList.activeSessions")}),s.jsx("ul",{className:"m-0 pl-4",children:re.map(ne=>s.jsxs("li",{className:"font-mono",children:[ne.provider," / ",ne.status," / ",ne.id]},ne.id))})]})]})]})]},I.id)})})]})}function Or(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function eI({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:w}){const{t:h}=Ne("common"),x=s.jsx(Ct,{label:h("repoMesh.host.coordinatorProvider"),hint:h("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:S=>a(S.target.value),children:[s.jsx("option",{value:"",children:h("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"})]})}),k=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(bt,{title:h("repoMesh.host.title"),description:h("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:h("repoMesh.host.hostLabel")}),s.jsx("span",{className:"font-medium",children:d||h("repoMesh.host.unknown")}),s.jsxs("span",{className:m?"text-text-muted":"text-amber-400",children:["· ",h(m?"repoMesh.host.online":"repoMesh.host.offline")]})]}),(u==null?void 0:u.workspace)&&s.jsxs("span",{className:"text-[12px] text-text-muted",children:[h("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(Ot,{variant:"warning",className:"mb-3",children:[s.jsx("strong",{children:h("repoMesh.host.hostOffline")})," ",h("repoMesh.host.hostOfflineText")]}),e.length>0?s.jsx(Ct,{label:h("repoMesh.host.reconnectToCommand"),hint:h("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:S=>g(S.target.value),children:[s.jsx("option",{value:"",children:h("repoMesh.host.waitForHost")}),e.map(S=>s.jsx("option",{value:S.id,children:Or(S)},S.id))]})}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:h("repoMesh.host.noDaemonsToRoute")})]}),s.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-[180px_auto] items-end",children:[x,s.jsx("button",{className:"btn btn-primary btn-sm",onClick:w,disabled:o||!t,title:t?void 0:h("repoMesh.host.noCommandTarget"),children:h(o?"repoMesh.host.launching":"repoMesh.host.launchHost")})]}),k]});const b=e.find(S=>S.id===t);return s.jsxs(bt,{title:h("repoMesh.host.title"),description:h("repoMesh.host.descriptionUnset"),children:[s.jsxs(Ot,{variant:"info",className:"mb-4",children:[s.jsx("strong",{children:h("repoMesh.host.setHostBanner")})," ",h("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:Or(b)}),u!=null&&u.workspace?s.jsxs(s.Fragment,{children:[" · setup node ",s.jsx("span",{className:"font-mono text-text-secondary",children:u.workspace})]}):null,". Launching sets this daemon as the mesh host."]}):s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:Or(b)}),". Attach one of its workspaces as a node first, then launch to set the host."]})}):s.jsx(Ct,{label:h("repoMesh.host.hostDaemon"),hint:h("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:S=>n(S.target.value),children:[s.jsx("option",{value:"",children:h("repoMesh.host.resolvingHost")}),e.map(S=>s.jsx("option",{value:S.id,children:Or(S)},S.id))]})}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-[180px_auto] items-end mt-3",children:[x,s.jsx("button",{className:"btn btn-primary btn-sm",onClick:w,disabled:!t||!c||o,title:t?c?void 0:h("repoMesh.host.attachNodeFirst"):h("repoMesh.host.pickHostFirst"),children:h(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:h("repoMesh.host.noDaemonsToHost")}),k]})}function tI({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=Jp(r==null?void 0:r.meshCoordinator,{meshId:e});return a?s.jsx(bt,{title:n("repoMesh.hermesMcp.title"),description:n("repoMesh.hermesMcp.description"),children:s.jsx(ym,{setup:a,providerName:(r==null?void 0:r.name)||n("repoMesh.hermesMcp.fallbackProvider")})}):null}const $o=[{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."}],sI=[{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 nI(e){return e==="smart"?"fitness":e==="spread"?"least_loaded":"first_eligible"}function rI(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 aI={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,schedulingStrategy:"first_eligible",sessionCleanupOnNodeRemove:"preserve"};function yi(e){return{...aI,...(e==null?void 0:e.policy)||{}}}function oI(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 iI({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:w,daemons:h,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:k,coordinatorCliType:b,onCoordinatorCliTypeChange:S,launchingCoordinator:j,launchResult:y,isHostNodeAttached:v,selectedHostNode:N,hostPinned:C,hostLabel:A,hostOnline:M,hostRebindDaemonId:T,onHostRebindDaemonIdChange:R,onLaunchCoordinator:E,activeDaemon:_,activeDaemonId:z,meshQueue:F,userName:D,availableCliProviders:W,savingNodeSlotsId:L,onUpdateNodeSlots:P,savingNodeCapabilitiesId:$,onUpdateNodeCapabilities:I,nodeSystemPromptDrafts:U,onNodeSystemPromptDraftChange:J,savingNodeSystemPromptId:re,onSaveNodeSystemPrompt:Y,selectedNodeId:X,onSelectNode:de,showAddNode:ne,onShowAddNode:O,onCancelAddNode:ie,nodeWorkspace:K,onNodeWorkspaceChange:ae,nodeProviderPriority:Ce,onNodeProviderPriorityChange:ye,nodeDaemonId:ke,onNodeDaemonIdChange:me,nodeCustomPath:q,onNodeCustomPathChange:G,nodePickerWorkspaces:Z,nodePickerProviders:V,attachableDaemons:fe,onAddNode:Te,onRemoveNode:ce,availableCliAgents:H,features:pe,sendCommand:le}){var Be;const{t:B}=Ne("common"),be=yi(e),je=e.nodes||[],Se=je.some(Pe=>{var Ue;const ve=Number((Ue=Pe.policy)==null?void 0:Ue.schedulingPriority);return Number.isFinite(ve)&&ve!==0}),He=!be.schedulingStrategy,Xe=l.useMemo(()=>je.some(Pe=>{var ve;return Array.isArray((ve=Pe.policy)==null?void 0:ve.slots)&&Pe.policy.slots.length>0}),[je]),dt=He?Xe?"smart":je.length>=2?"spread":null:null,[it,he]=l.useState(!1),$e=!!z&&!!e.id;return s.jsxs(gr,{icon:s.jsx(es,{}),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:B("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(fP,{size:13}),B(i?"repoMesh.detail.probing":"repoMesh.detail.refresh")]}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>a(e.id),children:B("repoMesh.detail.delete")})]}),children:[t&&s.jsx(Ot,{variant:"error",onDismiss:n,className:"mb-4",children:t}),pe.meshHostDaemonSection&&s.jsx(eI,{daemons:h,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:k,coordinatorCliType:b,onCoordinatorCliTypeChange:S,launchingCoordinator:j,launchResult:y,isHostNodeAttached:v,selectedHostNode:N,hostPinned:C,hostLabel:A,hostOnline:M,hostRebindDaemonId:T,onHostRebindDaemonIdChange:Pe=>{R(Pe),u()},onLaunchCoordinator:E}),s.jsxs(bt,{title:B("repoMesh.detail.observabilityTitle"),description:B("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:()=>he(!0),disabled:!$e,title:B($e?"repoMesh.detail.observabilityOpenTitle":"repoMesh.detail.observabilityDisabledTitle"),children:[s.jsx(es,{size:14}),B("repoMesh.detail.observabilityOpen")]}),s.jsx("span",{className:"text-[12px] text-text-muted",children:B("repoMesh.detail.observabilityHint")})]})]}),s.jsx(ZP,{nodes:je,meshQueue:F,activeDaemon:_,daemons:h,selectedMeshId:e.id,userName:D,features:{addNodeDaemonPicker:pe.addNodeDaemonPicker,nodeInstruction:pe.nodeInstruction},coordinatorDaemonId:x,availableCliProviders:W,savingNodeSlotsId:L,onUpdateNodeSlots:P,savingNodeCapabilitiesId:$,onUpdateNodeCapabilities:I,nodeSystemPromptDrafts:U,onNodeSystemPromptDraftChange:J,savingNodeSystemPromptId:re,onSaveNodeSystemPrompt:Y,selectedNodeId:X,onSelectNode:de,showAddNode:ne,onShowAddNode:O,onCancelAddNode:ie,nodeWorkspace:K,onNodeWorkspaceChange:ae,nodeProviderPriority:Ce,onNodeProviderPriorityChange:ye,nodeDaemonId:ke,onNodeDaemonIdChange:me,nodeCustomPath:q,onNodeCustomPathChange:G,nodePickerWorkspaces:Z,nodePickerProviders:V,attachableDaemons:fe,onAddNode:Te,onRemoveNode:ce}),s.jsxs(bt,{title:B("repoMesh.detail.schedulingTitle"),description:B("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:B("repoMesh.detail.distribution")}),s.jsx("div",{className:"flex flex-col gap-2",children:sI.map(Pe=>{const Ue=rI(be.schedulingStrategy,{priorityConfigured:Se})===Pe.value;return s.jsxs("label",{className:`flex items-start gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${Ue?"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:Pe.value,checked:Ue,disabled:p,onChange:()=>d({schedulingStrategy:nI(Pe.value)})}),s.jsxs("span",{className:"min-w-0",children:[s.jsxs("span",{className:"flex items-center gap-2 text-sm text-text-primary",children:[Pe.label,dt===Pe.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:B("repoMesh.detail.recommended")})]}),s.jsx("span",{className:"block text-[12px] text-text-muted",children:Pe.description})]})]},Pe.value)})})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:B("repoMesh.detail.saving")})]}),s.jsx(bt,{title:B("repoMesh.detail.visibilityTitle"),description:B("repoMesh.detail.visibilityDescription"),children:s.jsx(Ct,{label:B("repoMesh.detail.visibilityLabel"),hint:B("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:be.spawnedSessionVisibility==="visible"?"visible":"hidden",onChange:Pe=>d({spawnedSessionVisibility:Pe.target.value==="visible"?"visible":"hidden"}),disabled:p,children:[s.jsx("option",{value:"hidden",children:B("repoMesh.detail.visibilityHidden")}),s.jsx("option",{value:"visible",children:B("repoMesh.detail.visibilityVisible")})]})})}),o&&s.jsx(bt,{title:B("repoMesh.detail.magiTitle"),description:B("repoMesh.detail.magiDescription"),children:s.jsx(AP,{status:o,daemonId:z,sendDaemonCommand:le,availableProviders:W})}),s.jsx(EP,{status:o,daemonId:z,meshId:e.id,sendCommand:le}),pe.coordinatorPrompt&&s.jsxs(bt,{title:B("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:B("repoMesh.detail.advanced")}),description:B("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:B("repoMesh.detail.thisMesh")}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:B("repoMesh.detail.thisMeshHint",{name:e.name})}),s.jsxs(Ct,{label:B("repoMesh.detail.overrideLabel"),hint:B("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:Pe=>f({...m,override:Pe.target.value}),disabled:g,placeholder:B("repoMesh.detail.overridePlaceholder")}),s.jsx(MP,{daemonId:z,meshId:e.id,cliType:b,sendCommand:le})]}),s.jsx(Ct,{label:B("repoMesh.detail.appendLabel"),hint:B("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:Pe=>f({...m,append:Pe.target.value}),disabled:g,placeholder:B("repoMesh.detail.appendPlaceholder")})}),s.jsxs("details",{className:"mt-2 text-[12px] text-text-muted",children:[s.jsx("summary",{className:"cursor-pointer select-none",children:B("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:w,disabled:g,children:B(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:B("repoMesh.detail.clearTitle"),children:B("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:B("repoMesh.detail.userLevel")}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:B("repoMesh.detail.userLevelDescription")}),s.jsx(QS,{daemonId:z||void 0})]})]}),s.jsxs(bt,{title:B("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:B("repoMesh.detail.advanced")}),description:B("repoMesh.detail.safetyDescription"),children:[s.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:[{label:B("repoMesh.detail.checkpointBefore"),key:"requirePreTaskCheckpoint",opts:[["no","No"],["yes","Yes"]],val:Pe=>Pe?"yes":"no",parse:Pe=>Pe==="yes"},{label:B("repoMesh.detail.checkpointAfter"),key:"requirePostTaskCheckpoint",opts:[["yes","Yes"],["no","No"]],val:Pe=>Pe?"yes":"no",parse:Pe=>Pe==="yes"},{label:B("repoMesh.detail.pushApproval"),key:"requireApprovalForPush",opts:[["required",B("repoMesh.detail.requireApprovalBeforePush")],["not_required",B("repoMesh.detail.doNotRequireApproval")]],val:Pe=>Pe?"required":"not_required",parse:Pe=>Pe==="required"},{label:B("repoMesh.detail.destructiveGitApproval"),key:"requireApprovalForDestructiveGit",opts:[["required",B("repoMesh.detail.requireApproval")],["not_required",B("repoMesh.detail.doNotRequireApproval")]],val:Pe=>Pe?"required":"not_required",parse:Pe=>Pe==="required"},{label:B("repoMesh.detail.uncommittedChanges"),key:"dirtyWorkspaceBehavior",opts:[["warn",B("repoMesh.detail.warnAndContinue")],["block",B("repoMesh.detail.blockTask")],["checkpoint_then_continue",B("repoMesh.detail.checkpointThenContinue")]],val:Pe=>Pe||"warn",parse:Pe=>Pe},{label:B("repoMesh.detail.autoPublishSubmodule"),key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled",B("repoMesh.detail.requireExplicitApproval")],["enabled",B("repoMesh.detail.allowRefineryPublish")]],val:Pe=>Pe?"enabled":"disabled",parse:Pe=>Pe==="enabled"}].map(({label:Pe,key:ve,opts:Ue,val:ut,parse:ot})=>s.jsx(Ct,{label:Pe,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:ut(be[ve]),onChange:pt=>d({[ve]:ot(pt.target.value)}),disabled:p,children:Ue.map(([pt,Q])=>s.jsx("option",{value:pt,children:Q},pt))})},ve))}),(()=>{const Pe=be.autoFastForward&&typeof be.autoFastForward=="object"?be.autoFastForward:{},ve=Pe.enabled!==!1,Ue=Pe.remoteNodes===!0,ut=Pe.mode==="continuous"?"continuous":"idle",ot=pt=>d({autoFastForward:{...Pe,...pt}});return s.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[s.jsx(Ct,{label:B("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:ve?"enabled":"disabled",onChange:pt=>ot({enabled:pt.target.value==="enabled"}),disabled:p,children:[s.jsx("option",{value:"enabled",children:B("repoMesh.detail.ffEnabled")}),s.jsx("option",{value:"disabled",children:B("repoMesh.detail.ffDisabled")})]})}),s.jsx(Ct,{label:B("repoMesh.detail.includeRemoteNodes"),hint:B("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:Ue?"yes":"no",onChange:pt=>ot({remoteNodes:pt.target.value==="yes"}),disabled:p||!ve,children:[s.jsx("option",{value:"no",children:B("repoMesh.detail.remoteNo")}),s.jsx("option",{value:"yes",children:B("repoMesh.detail.remoteYes")})]})}),s.jsx(Ct,{label:B("repoMesh.detail.detectionMode"),hint:B("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:ut,onChange:pt=>ot({mode:pt.target.value==="continuous"?"continuous":"idle"}),disabled:p||!ve||!Ue,children:[s.jsx("option",{value:"idle",children:B("repoMesh.detail.idleEdgeOnly")}),s.jsx("option",{value:"continuous",children:B("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(Ct,{label:B("repoMesh.detail.sessionCleanupLabel"),hint:B("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:be.sessionCleanupOnNodeRemove||"preserve",onChange:Pe=>d({sessionCleanupOnNodeRemove:Pe.target.value}),disabled:p,children:$o.map(Pe=>s.jsx("option",{value:Pe.value,children:Pe.label},Pe.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((Be=$o.find(Pe=>Pe.value===be.sessionCleanupOnNodeRemove))==null?void 0:Be.description)||$o[0].description})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:B("repoMesh.detail.saving")})]}),pe.hermesMcpConfig&&s.jsx(tI,{meshId:e.id,availableCliAgents:H}),pe.meshHostDaemonSection&&s.jsxs(Ot,{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."]}),it&&$e&&s.jsx(Xm,{activeConv:oI({meshId:e.id,daemonId:z,meshName:e.name}),sendDaemonCommand:le,onClose:()=>he(!1)})]})}const Un=new Map;function lI({daemons:e,primaryDaemonId:t,sendCommand:n,unwrapResult:r,normalizeMesh:a,features:o,loadDaemonMetadata:i}){const c=e.map(P=>P.id).filter(Boolean).sort().join(","),[u,p]=l.useState(()=>Un.get(c)??[]),[d,m]=l.useState(null),[f,g]=l.useState(()=>!Un.has(c)),[w,h]=l.useState(null),[x,k]=l.useState(!1),[b,S]=l.useState(""),[j,y]=l.useState(""),[v,N]=l.useState(""),[C,A]=l.useState(""),[M,T]=l.useState(""),R=l.useMemo(()=>e.find(P=>P.id===C),[e,C]),E=(R==null?void 0:R.workspaces)||[],_=l.useMemo(()=>wn((R==null?void 0:R.availableProviders)||[]),[R]);l.useEffect(()=>{!o.createDaemonPicker||!i||!C||!R||!(!R.workspaces||!R.availableProviders)||Promise.resolve(i(C,{minFreshMs:3e4})).catch(()=>{})},[o.createDaemonPicker,i,C,R]);const z=l.useMemo(()=>e.map(P=>P.id).filter(Boolean).sort().join(","),[e]),F=l.useCallback(async(P=!1)=>{const $=P||Un.has(z);g(I=>$?I:!0);try{if(o.createDaemonPicker){const I=await Promise.allSettled(e.map(async re=>{if(!re.id)return[];const Y=await n(re.id,"list_meshes",{}),X=r(Y);if((X==null?void 0:X.success)===!1)throw new Error(X.error||"Failed to load meshes");return(Array.isArray(X==null?void 0:X.meshes)?X.meshes:[]).map(de=>a(de,re.id)).filter(de=>de.id)})),U=new Map;for(const re of I)if(re.status==="fulfilled")for(const Y of re.value)U.has(Y.id)||U.set(Y.id,Y);const J=Array.from(U.values());p(J),Un.set(z,J),h(null)}else{if(!t)return;const I=await n(t,"list_meshes");if(I!=null&&I.success){const U=(I.meshes||[]).map(J=>a(J,t));p(U),Un.set(z,U),h(null)}else h((I==null?void 0:I.error)||"Failed to load meshes")}}catch(I){h((I==null?void 0:I.message)||"Failed to load meshes")}finally{g(!1)}},[z,t,n,r,a,o.createDaemonPicker]);async function D(){var U,J;const P=o.createDaemonPicker?C:t;if(!P||!b.trim())return;const $=v.trim(),I=j.trim();if(!(!$&&!I))try{const re={name:b.trim()};$&&(re.repoRemoteUrl=$),I&&(re.repoIdentity=I);const Y=await n(P,"create_mesh",re),X=r(Y);if((X==null?void 0:X.success)===!1)throw new Error(X.error||"Create failed");const de=typeof((U=X==null?void 0:X.mesh)==null?void 0:U.id)=="string"?X.mesh.id:"";if(de&&o.createDaemonPicker&&M){const ne=await n(P,"add_mesh_node",{meshId:de,daemonId:P,machineId:R==null?void 0:R.machineId,workspace:M,role:"host",providerPriority:cr(_)}),O=r(ne);if((O==null?void 0:O.success)===!1)throw new Error(O.error||"Mesh created but failed to attach workspace")}k(!1),S(""),y(""),N(""),T(""),await F(),(J=X==null?void 0:X.mesh)!=null&&J.id&&m(X.mesh.id)}catch(re){h((re==null?void 0:re.message)||"Create failed")}}async function W(P){var I;if(!confirm("Delete this mesh? This cannot be undone."))return;const $=((I=u.find(U=>U.id===P))==null?void 0:I.__sourceDaemonId)||t;try{const U=await n($,"delete_mesh",{meshId:P}),J=r(U);if((J==null?void 0:J.success)===!1)throw new Error(J.error||"Failed to delete");d===P&&m(null),await F()}catch(U){h((U==null?void 0:U.message)||"Delete failed")}}function L(){k(!1),S(""),y(""),N("")}return{meshes:u,setMeshes:p,selectedMeshId:d,setSelectedMeshId:m,loading:f,error:w,setError:h,showCreate:x,setShowCreate:k,createName:b,setCreateName:S,createRepoIdentity:j,setCreateRepoIdentity:y,createRepoRemoteUrl:v,setCreateRepoRemoteUrl:N,newMeshDaemonId:C,setNewMeshDaemonId:A,newMeshWorkspace:M,setNewMeshWorkspace:T,createPickerWorkspaces:E,createPickerProviders:_,loadMeshes:F,handleCreate:D,handleDelete:W,cancelCreate:L}}function cI({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:w}){const[h,x]=l.useState({}),[k,b]=l.useState(null),[S,j]=l.useState(null),[y,v]=l.useState(!1),[N,C]=l.useState(""),[A,M]=l.useState([]),[T,R]=l.useState(""),[E,_]=l.useState(!1),[z,F]=l.useState(""),[D,W]=l.useState(!1),[L,P]=l.useState(null),[$,I]=l.useState(!1),[U,J]=l.useState({override:"",append:""}),[re,Y]=l.useState(!1),[X,de]=l.useState({}),[ne,O]=l.useState(null),ie=l.useMemo(()=>a.find(le=>le.id===T),[a,T]),K=(ie==null?void 0:ie.workspaces)||[],ae=l.useMemo(()=>wn((ie==null?void 0:ie.availableProviders)||[]),[ie]);async function Ce(){const le=(e==null?void 0:e.__sourceDaemonId)||n;if(!t||!le)return;const B=N.trim();if(B)try{const be={meshId:t,workspace:B};d.addNodeDaemonPicker&&T&&(be.daemonId=T,be.machineId=ie==null?void 0:ie.machineId),be.providerPriority=kn(A);const je=await o(le,"add_mesh_node",be),Se=i(je);if((Se==null?void 0:Se.success)===!1)throw new Error(Se.error||"Add node failed");v(!1),C(""),M([]),R(""),_(!1),await m(),g||await f(t)}catch(be){w((be==null?void 0:be.message)||"Add node failed")}}async function ye(le){var Se;if(!e)return;const B=yi(e),be=((Se=[{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(He=>He.value===B.sessionCleanupOnNodeRemove))==null?void 0:Se.label)||"Preserve history and runtimes";if(!confirm(`Remove this node?
120
120
 
121
- Node removal cleanup policy: ${be}`))return;const je=e.__sourceDaemonId||n;try{const He=await o(je,"remove_mesh_node",{meshId:e.id,nodeId:le}),Xe=i(He);if((Xe==null?void 0:Xe.success)===!1)throw new Error(Xe.error||"Remove failed");S===le&&j(null),await m(),g||await f(t)}catch(He){w((He==null?void 0:He.message)||"Remove node failed")}}async function ke(le){if(!e)return;const B={...yi(e),...le},be=e.__sourceDaemonId||n;try{I(!0),w(null);const je=await o(be,"update_mesh",{meshId:e.id,policy:B}),Se=i(je);if((Se==null?void 0:Se.success)===!1)throw new Error(Se.error||"Policy update failed");await m()}catch(je){w((je==null?void 0:je.message)||"Policy update failed")}finally{I(!1)}}async function me(le){if(!t)return;const B=(e==null?void 0:e.__sourceDaemonId)||n,be=h[le.id]||dI(le),je=kn(be),Se={...le.policy||{}};delete Se.provider_priority,je.length?Se.providerPriority=je:delete Se.providerPriority;try{b(le.id),w(null);const He=await o(B,"update_mesh_node",{meshId:t,nodeId:le.id,policy:Se,providerPriority:je}),Xe=i(He);if((Xe==null?void 0:Xe.success)===!1){w(Xe.error||"Node policy update failed");return}await m()}catch(He){w((He==null?void 0:He.message)||"Node policy update failed")}finally{b(null)}}const[q,G]=l.useState(null);async function Z(le,B){if(!t)return;const be=(e==null?void 0:e.__sourceDaemonId)||n;try{G(le.id),w(null);const je=await o(be,"update_mesh_node",{meshId:t,nodeId:le.id,policy:{slots:B}}),Se=i(je);if((Se==null?void 0:Se.success)===!1){w(Se.error||"Node slots update failed");return}await m()}catch(je){w((je==null?void 0:je.message)||"Node slots update failed")}finally{G(null)}}const[V,fe]=l.useState(null);async function Te(le,B){if(!t)return;const be=(e==null?void 0:e.__sourceDaemonId)||n,je=B.map(Se=>Se.trim()).filter(Boolean);try{fe(le.id),w(null);const Se=await o(be,"update_mesh_node",{meshId:t,nodeId:le.id,capabilities:je}),He=i(Se);if((He==null?void 0:He.success)===!1){w(He.error||"Node tag update failed");return}await m()}catch(Se){w((Se==null?void 0:Se.message)||"Node tag update failed")}finally{fe(null)}}async function ce(){if(!n||!t)return;const B={...(e==null?void 0:e.coordinator)||{}};U.override.trim()?B.systemPromptOverride=U.override:delete B.systemPromptOverride,U.append.trim()?B.systemPromptAppend=U.append:delete B.systemPromptAppend,delete B.systemPromptSuffix;try{Y(!0),w(null);const be=await o(n,"update_mesh",{meshId:t,coordinator:B}),je=i(be);if((je==null?void 0:je.success)===!1){w(je.error||"Coordinator prompt save failed");return}await m()}catch(be){w((be==null?void 0:be.message)||"Coordinator prompt save failed")}finally{Y(!1)}}async function H(le){if(!n||!t)return;const B=(X[le.id]||"").trim();try{O(le.id),w(null);const be=await o(n,"update_mesh_node",{meshId:t,nodeId:le.id,systemPrompt:B}),je=i(be);if((je==null?void 0:je.success)===!1){w(je.error||"Node instruction save failed");return}await m()}catch(be){w((be==null?void 0:be.message)||"Node instruction save failed")}finally{O(null)}}async function pe(){if(e){w(null),P(null);try{W(!0);const le=c?await c(r,e.id,e):null,B=u(r,e.id,e,e.nodes||[],le);if("error"in B)throw new Error(B.error);const be=await p(B.targetDaemonId,{meshId:e.id,inlineMesh:B.inlineMesh,coordinatorNodeId:B.coordinatorNodeId,cliType:z.trim()||void 0});P(be.message)}catch(le){w((le==null?void 0:le.message)||"Coordinator launch failed")}finally{W(!1)}}}return{nodeProviderPriorityDrafts:h,setNodeProviderPriorityDrafts:x,savingNodePolicyId:k,selectedNodeId:S,setSelectedNodeId:j,showAddNode:y,setShowAddNode:v,nodeWorkspace:N,setNodeWorkspace:C,nodeProviderPriority:A,setNodeProviderPriority:M,nodeDaemonId:T,setNodeDaemonId:R,nodeCustomPath:E,setNodeCustomPath:_,nodePickerWorkspaces:K,nodePickerProviders:ae,coordinatorCliType:z,setCoordinatorCliType:F,launchingCoordinator:D,launchResult:L,savingPolicy:$,coordinatorPromptDraft:U,setCoordinatorPromptDraft:J,savingCoordinatorPrompt:re,nodeSystemPromptDrafts:X,setNodeSystemPromptDrafts:de,savingNodeSystemPromptId:ne,savingNodeSlotsId:q,savingNodeCapabilitiesId:V,handleAddNode:Ce,handleRemoveNode:ye,handleUpdatePolicy:ke,handleUpdateNodeProviderPriority:me,handleUpdateNodeSlots:Z,handleUpdateNodeCapabilities:Te,handleSaveCoordinatorPrompt:ce,handleSaveNodeSystemPrompt:H,handleLaunchCoordinator:pe}}function dI(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 uI(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 pI({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),w=l.useCallback(async x=>{if(!e||!x){c([]);return}try{const k=await n(e,"get_mesh_queue",{meshId:x});c(k!=null&&k.success?Array.isArray(k.queue)?k.queue:[]:[])}catch{c([])}},[e,n]);async function h(x){var k,b;if(x){m(!0),g(null);try{const S=a?await a(t,x.id,x):null,j=o(t,x.id,x,x.nodes||[],S);if("error"in j)throw new Error(j.error);const y=await n(j.targetDaemonId,"get_mesh_queue",{meshId:x.id}),v=r(y);if((v==null?void 0:v.success)===!1)throw new Error(v.error||"Queue load failed");const N=Array.isArray(((k=v==null?void 0:v.result)==null?void 0:k.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(uI(N))}catch(S){g((S==null?void 0:S.message)||"Queue load failed")}finally{m(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:u,queueLoading:d,queueError:f,loadQueue:w,handleLoadQueue:h}}function mI(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}const rh=new Map;function ah(e){return e?rh.get(e)??null:null}function hI(e,t){!e||!t||rh.set(e,t)}function fI({selectedMeshId:e,loadMeshStatus:t,extractStatus:n,normalizeNode:r,gateIncompleteGraph:a}){const[o,i]=l.useState(()=>ah(e)),[c,u]=l.useState(!1),[p,d]=l.useState(null),[m,f]=l.useState("idle"),[g,w]=l.useState(!1),h=l.useRef(!1);async function x(k,b=e,S=!1){if(!(!k||!b))try{u(!S&&o===null),f(S?"settling":"first_paint"),d(null);const j=await t(k,b,{refresh:S,retryProfile:S?"settled":"interactive"});w(mI(j));const y=n(j),v=r&&y?{...y,nodes:(y.nodes??[]).map(N=>r(N,y.meshId??b,""))}:y;if(v){if(a&&!S&&o!==null&&!DN(Em(v))){f("settling"),h.current||(h.current=!0,Promise.resolve().then(()=>x(k,b,!0)).finally(()=>{h.current=!1}));return}i(v),hI(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 bI(e,t,n,r,a){if(!e.length)return"";const o=String(a||"");if(o){const u=e.find(p=>Os(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=>Os(p.id,c));if(u)return u.id}return""}const gI=7e3,xI=45e3;function vI(){const e=hP(),{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:w}=e,h=Tn(),x=r[0],k=(x==null?void 0:x.id)||"",b=l.useMemo(()=>((x==null?void 0:x.availableProviders)||[]).filter(rt=>rt.category==="cli").map(rt=>({id:rt.type||rt.id,name:rt.displayName||rt.name||rt.type,meshCoordinator:rt.meshCoordinator})),[x]),S=l.useMemo(()=>wn((x==null?void 0:x.availableProviders)||[]),[x]),{meshes:j,selectedMeshId:y,setSelectedMeshId:v,loading:N,error:C,setError:A,showCreate:M,setShowCreate:T,createName:R,setCreateName:E,createRepoIdentity:_,setCreateRepoIdentity:z,createRepoRemoteUrl:F,setCreateRepoRemoteUrl:D,newMeshDaemonId:W,setNewMeshDaemonId:L,newMeshWorkspace:P,setNewMeshWorkspace:$,createPickerWorkspaces:I,loadMeshes:U,handleCreate:J,handleDelete:re,cancelCreate:Y}=lI({daemons:r,primaryDaemonId:k,sendCommand:t,unwrapResult:p,normalizeMesh:d,features:g,loadDaemonMetadata:h}),X=j.find(Re=>Re.id===y)||null,{meshGraphStatus:de,setMeshGraphStatus:ne,graphLoading:O,graphError:ie,setGraphError:K,loadGraph:ae}=fI({selectedMeshId:y,loadMeshStatus:o,extractStatus:u,normalizeNode:m,gateIncompleteGraph:w}),[Ce,ye]=l.useState(""),[ke,me]=l.useState(""),q=g.meshHostDaemonSection&&Ce||k,{meshQueue:G,loadQueue:Z}=pI({primaryDaemonId:k,activeDaemonId:q,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f}),{setNodeProviderPriorityDrafts:V,selectedNodeId:fe,setSelectedNodeId:Te,showAddNode:ce,setShowAddNode:H,nodeWorkspace:pe,setNodeWorkspace:le,nodeProviderPriority:B,setNodeProviderPriority:be,nodeDaemonId:je,setNodeDaemonId:Se,nodeCustomPath:He,setNodeCustomPath:Xe,nodePickerWorkspaces:dt,nodePickerProviders:it,coordinatorCliType:he,setCoordinatorCliType:$e,launchingCoordinator:Be,launchResult:Pe,savingPolicy:ve,coordinatorPromptDraft:Ue,setCoordinatorPromptDraft:ut,savingCoordinatorPrompt:ot,nodeSystemPromptDrafts:pt,setNodeSystemPromptDrafts:Q,savingNodeSystemPromptId:ee,savingNodeSlotsId:oe,savingNodeCapabilitiesId:ue,handleAddNode:xe,handleRemoveNode:Me,handleUpdatePolicy:Le,handleUpdateNodeSlots:Ae,handleUpdateNodeCapabilities:Oe,handleSaveCoordinatorPrompt:qe,handleSaveNodeSystemPrompt:Ze,handleLaunchCoordinator:_e}=cI({selectedMesh:X,selectedMeshId:y,primaryDaemonId:k,activeDaemonId:q,daemons:r,availableCliProviders:S,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f,launchCoordinator:i,features:{addNodeDaemonPicker:g.addNodeDaemonPicker},loadMeshes:U,loadQueue:Z,queueSection:g.queueSection,setError:A}),Ge=l.useMemo(()=>r.find(Re=>Re.id===q)||x,[r,q,x]),et=l.useMemo(()=>new Set(((X==null?void 0:X.nodes)||[]).map(Re=>String(Re.daemon_id||Re.daemonId||""))),[X]),te=l.useMemo(()=>r.filter(Re=>Re.id&&!et.has(Re.id)),[r,et]),ge=(X==null?void 0:X.nodes)||[],we=l.useMemo(()=>ge.find(Re=>Os(String(Re.daemon_id||Re.daemonId||""),Ce)),[ge,Ce]),ze=g.meshHostDaemonSection?!!we:!0,We=l.useMemo(()=>{if(!g.meshHostDaemonSection||!X)return{pinned:!1,daemonId:"",label:"",online:!1};const Re=X.meshHost,rt=de!=null&&de.meshId&&String(de.meshId)===String(X.id??"")?de.meshHost:void 0,jt=rt!=null&&rt.hostDaemonId?rt:Re??rt,Ut=String((jt==null?void 0:jt.hostDaemonId)||""),se=ge.find(vs=>vs.role==="host"),Fe=String((jt==null?void 0:jt.hostNodeId)||(se==null?void 0:se.id)||""),Ee=Fe?ge.find(vs=>String(vs.id)===Fe):void 0,yt=String((Ee==null?void 0:Ee.daemon_id)||(Ee==null?void 0:Ee.daemonId)||""),Jt=Ut||yt;if(!Jt)return{pinned:!1,daemonId:"",label:"",online:!1};const Pn=r.find(vs=>Ut&&Os(vs.id,Ut))||(yt?r.find(vs=>Os(vs.id,yt)):void 0);if(Pn)return{pinned:!0,daemonId:Pn.id,label:yI(Pn),online:!0};const Wa=String((Ee==null?void 0:Ee.machineLabel)||"")||String((Ee==null?void 0:Ee.workspace)||"")||Jt;return{pinned:!0,daemonId:Jt,label:Wa,online:!1}},[X,ge,r,de,g.meshHostDaemonSection]),tt=We.daemonId,Ke=We.online,Ye=l.useMemo(()=>!g.meshHostDaemonSection||!We.pinned?"":!Ke&&ke&&r.some(Re=>Re.id===ke)?ke:tt,[g.meshHostDaemonSection,We.pinned,Ke,ke,r,tt]),Mt=l.useMemo(()=>de?[...new Set((de.nodes??[]).map(Re=>String(Re.daemonId||Re.daemon_id||"")).filter(Boolean))]:[],[de]),Wt=Qm({status:de,daemonId:q||null,extraDaemonIds:Mt,meshId:y,sendData:n});l.useEffect(()=>{V(Object.fromEntries(((X==null?void 0:X.nodes)||[]).map(Re=>[Re.id,wI(Re)])))},[X]),l.useEffect(()=>{const Re=(X==null?void 0:X.coordinator)||{};ut({override:typeof Re.systemPromptOverride=="string"?Re.systemPromptOverride:"",append:typeof Re.systemPromptAppend=="string"?Re.systemPromptAppend:typeof Re.systemPromptSuffix=="string"?Re.systemPromptSuffix:""}),Q(Object.fromEntries(((X==null?void 0:X.nodes)||[]).map(rt=>[rt.id,typeof rt.systemPrompt=="string"?rt.systemPrompt:""])))},[X]),l.useEffect(()=>{const Re=g.addNodeDaemonPicker?cr(it):cr(S);ce&&B.length===0&&Re.length>0&&be(Re)},[ce,S,it,B.length,g.addNodeDaemonPicker]),l.useEffect(()=>{const Re=new Set(((X==null?void 0:X.nodes)||[]).map(rt=>rt.id));fe&&!Re.has(fe)&&Te(null)},[X,fe]);const ss=l.useMemo(()=>{var Re;if(!(!(de!=null&&de.meshId)||String(de.meshId)!==String((X==null?void 0:X.id)??"")))return(Re=de.meshHost)==null?void 0:Re.hostDaemonId},[de,X]),Ie=l.useMemo(()=>bI(r,ge,q,k,ss),[r,ge,q,k,ss]);l.useEffect(()=>{if(!g.meshHostDaemonSection)return;if(!r.length&&!We.pinned){ye("");return}const Re=We.pinned?Ye:Ie;Re&&!Os(Re,Ce)&&ye(Re)},[r,Ce,We.pinned,Ye,Ie,g.meshHostDaemonSection]),l.useEffect(()=>{ke&&(Ke||!r.some(Re=>Re.id===ke))&&me("")},[Ke,ke,r]),l.useEffect(()=>{if(g.createDaemonPicker){if(!r.length){L("");return}(!W||!r.some(Re=>Re.id===W))&&L(r[0].id)}},[r,W,g.createDaemonPicker]),l.useEffect(()=>{var Re;if(!g.createDaemonPicker||!W){$("");return}if(!I.length){$("");return}I.some(rt=>rt.path===P)||$(((Re=I[0])==null?void 0:Re.path)||"")},[W,P,I,g.createDaemonPicker]);const Qe=l.useRef(null);l.useEffect(()=>{if(!y)return;const Re=Qe.current!==y;if(Qe.current=y,Re){const rt=ah(y);ne(rt),K(null),ae(q,y,rt!==null)}else K(null),ae(q,y,!0)},[y,q]);const It=l.useRef(ae);It.current=ae;const Tt=l.useRef(!1),Kt=l.useRef(()=>{});Kt.current=()=>{Tt.current||!y||!q||(Tt.current=!0,Promise.resolve(It.current(q,y,!0)).finally(()=>{Tt.current=!1}))};const Vt=g.meshStatePushRefresh?xI:gI;pP({daemonIds:l.useMemo(()=>[q,...Mt].filter(Boolean),[q,Mt]),meshId:y,sendData:n,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||Kt.current()}}),l.useEffect(()=>{if(!y||!q||typeof document>"u")return;let Re=null;const rt=()=>{document.visibilityState==="visible"&&Kt.current()},jt=()=>{Re===null&&(Re=setInterval(rt,Vt))},Ut=()=>{Re!==null&&(clearInterval(Re),Re=null)},se=()=>{document.visibilityState==="visible"?jt():Ut()};return document.visibilityState==="visible"&&jt(),document.addEventListener("visibilitychange",se),()=>{Ut(),document.removeEventListener("visibilitychange",se)}},[y,q,Vt]),l.useEffect(()=>{g.queueSection||Z(y)},[y,g.queueSection]);const Yt=l.useMemo(()=>r.map(Re=>Re.id).filter(Boolean).sort().join(","),[r]),xs=l.useRef(!1);return l.useEffect(()=>{U(xs.current),xs.current=!0},[Yt]),k?X?s.jsx(iI,{selectedMesh:X,error:C,onDismissError:()=>A(null),onBack:()=>{v(null),ne(null)},onDelete:re,displayedMeshStatus:Wt,graphLoading:O,graphError:ie,onRefreshGraph:()=>ae(q,y,!0),savingPolicy:ve,onUpdatePolicy:Le,coordinatorPromptDraft:Ue,onCoordinatorPromptDraftChange:ut,savingCoordinatorPrompt:ot,onSaveCoordinatorPrompt:qe,daemons:r,coordinatorDaemonId:Ce,onCoordinatorDaemonIdChange:ye,coordinatorCliType:he,onCoordinatorCliTypeChange:$e,launchingCoordinator:Be,launchResult:Pe,isHostNodeAttached:ze,selectedHostNode:we,hostPinned:We.pinned,hostLabel:We.label,hostOnline:Ke,hostRebindDaemonId:ke,onHostRebindDaemonIdChange:Re=>me(Re),onLaunchCoordinator:_e,activeDaemon:Ge,activeDaemonId:q,meshQueue:G,userName:a,availableCliProviders:S,savingNodeSlotsId:oe,onUpdateNodeSlots:Ae,savingNodeCapabilitiesId:ue,onUpdateNodeCapabilities:Oe,nodeSystemPromptDrafts:pt,onNodeSystemPromptDraftChange:(Re,rt)=>Q(jt=>({...jt,[Re]:rt})),savingNodeSystemPromptId:ee,onSaveNodeSystemPrompt:Ze,selectedNodeId:fe,onSelectNode:Te,showAddNode:ce,onShowAddNode:()=>H(!0),onCancelAddNode:()=>H(!1),nodeWorkspace:pe,onNodeWorkspaceChange:le,nodeProviderPriority:B,onNodeProviderPriorityChange:be,nodeDaemonId:je,onNodeDaemonIdChange:Se,nodeCustomPath:He,onNodeCustomPathChange:Xe,nodePickerWorkspaces:dt,nodePickerProviders:it,attachableDaemons:te,onAddNode:xe,onRemoveNode:Me,availableCliAgents:b,features:{coordinatorPrompt:g.coordinatorPrompt,meshHostDaemonSection:g.meshHostDaemonSection,hermesMcpConfig:g.hermesMcpConfig,addNodeDaemonPicker:g.addNodeDaemonPicker,nodeInstruction:g.nodeInstruction},sendCommand:t}):s.jsx(wP,{meshes:j,loading:N,error:C,onDismissError:()=>A(null),daemons:r,features:{createDaemonPicker:g.createDaemonPicker,maxMeshes:g.maxMeshes},showCreate:M,onToggleCreate:()=>T(!M),createName:R,onCreateNameChange:E,createRepoIdentity:_,onCreateRepoIdentityChange:z,createRepoRemoteUrl:F,onCreateRepoRemoteUrlChange:D,newMeshDaemonId:W,onNewMeshDaemonIdChange:L,newMeshWorkspace:P,onNewMeshWorkspaceChange:$,createPickerWorkspaces:I,onSelectMesh:v,onCreate:J,onCancelCreate:Y}):s.jsx(gr,{icon:s.jsx(es,{}),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 yI(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}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 kI({children:e}){const{sendCommand:t,sendData:n}=vt(),{ides:r}=gs(),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:Wi,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,u)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:mP}),[t,n,a]);return s.jsx(nh.Provider,{value:o,children:e})}function xl(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function SI(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=xl();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 hs(e,t){return await fetch(SI(e),{credentials:"same-origin",...t})}function oh(){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 CI{constructor(){st(this,"adapters",new Map);st(this,"states",new Map);st(this,"runtimeListeners",new Map);st(this,"screenshotCallbacks",new Map);st(this,"statusCallbacks",new Set);st(this,"stateChangeCallbacks",new Set);st(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 hs(`${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 ms=new CI;function jI(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=xl();return n?`${t}?token=${encodeURIComponent(n)}`:t}const Wr=jI(),Ld=3e3,NI=3e4;let as=null,AI=0;const wa=new Map;let Hs=null,nr=null;function Rd(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Gn(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function MI(e){return e==="connected"?"connected":e}async function rr(e,t,n){const r=Mp(e,n||{}),a=as;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++AI}_${Date.now()}`;return new Promise((i,c)=>{const u=setTimeout(()=>{wa.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);wa.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 wi(e,t){const n=as;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 ih(e,t,n){const r=as;if(!r||r.readyState!==WebSocket.OPEN)return!1;const a=Mp(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}}ms.registerPtyInputSender(ih);class TI{constructor(t){st(this,"daemonId");st(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(as==null?void 0:as.readyState)===WebSocket.OPEN}get connectionState(){return(as==null?void 0:as.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,n){return rr(this.daemonId,t,n)}async sendInput(t,n){return rr(this.daemonId,"cdp_remote_action",{action:t,params:n,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,Hs&&(clearInterval(Hs),Hs=null);const n=async()=>{if(this.hasCommandChannel)try{const r=await rr(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());ms.emitScreenshot(this.daemonId,a)}}catch{}};n(),Hs=setInterval(n,2e3)}stopScreenshots(t){Hs&&(clearInterval(Hs),Hs=null)}}let Xt=null;function PI(e){return(!Xt||Xt.daemonId!==e)&&(Xt=new TI(e)),Xt}function II({children:e}){const t=l.useRef(ar()),n=ar();t.current=n;const{setUserName:r}=gs(),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),nr==null||nr(h,x)},[]),p=l.useRef(null),d=l.useRef(),m=l.useRef(Ld),f=l.useRef(!0),g=l.useRef(!1),w=l.useRef("initial_connect");return l.useEffect(()=>{f.current=!0,g.current=!1;function h(){var b,S;if(!f.current||((b=p.current)==null?void 0:b.readyState)===WebSocket.OPEN||((S=p.current)==null?void 0:S.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${Wr}...`),Gn("connect_attempt",{url:Wr,reason:w.current,delayMs:m.current});let k;try{k=new WebSocket(Wr)}catch(j){console.error("[Standalone WS] Failed to create WebSocket:",j),x();return}p.current=k,k.onopen=()=>{if(!f.current){k.close();return}u("connected"),m.current=Ld,Gn("open",{url:Wr,reason:w.current}),ls.resubscribeAll({sendData:wi}),console.log("[Standalone WS] Connected")},as=k,k.onmessage=j=>{var y,v;try{const N=JSON.parse(j.data);if((N.type==="command_result"||N.type==="error")&&N.requestId){const C=wa.get(N.requestId);C&&(wa.delete(N.requestId),N.type==="error"?C.reject(new Error(((y=N.data)==null?void 0:y.message)||"Command failed")):C.resolve(N.data));return}if(N.type==="session_output"){const C=N.sessionId||N.cliId||N.cliType;C&&ms.emitSessionOutput(C,typeof N.data=="string"?N.data:"",typeof N.seq=="number"?N.seq:void 0);return}if(N.type==="runtime_snapshot"){ms.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 C=N.update;C&&ls.publish(C);return}if(N.type==="status"||N.type==="initial_state"){const C=N.data;if(!C)return;const{injectEntries:A,markLoaded:M,getIdes:T}=t.current,R=C.instanceId||"standalone",E=T().find(F=>F.id===R),_=PI(R);ms.register(R,_),ms.setState(R,"connected"),u("connected",R),ms.emitStatus(R,C);const z=ia(C,{daemonId:R,existingDaemon:E,existingEntries:T()});Rd("ws_status",{type:N.type,daemonId:R,sessions:(C.sessions||[]).map(F=>({id:F.id,parentId:F.parentId,providerType:F.providerType,kind:F.kind,transport:F.transport,unread:F.unread,inboxBucket:F.inboxBucket,lastSeenAt:F.lastSeenAt,lastUpdated:F.lastUpdated,title:F.title})),recentLaunches:(C.recentLaunches||[]).map(F=>({id:F.id,providerType:F.providerType,kind:F.kind,workspace:F.workspace,lastLaunchedAt:F.lastLaunchedAt}))}),Rd("entries",{daemonId:R,entries:z.filter(F=>F.type!=="adhdev-daemon").map(F=>({id:F.id,type:F.type,unread:F.unread,inboxBucket:F.inboxBucket,lastSeenAt:F.lastSeenAt,lastUpdated:F.lastUpdated,sessionId:F.sessionId}))}),z.length>0&&A(z,{authoritativeDaemonIds:[R]}),M(),i.current!==R&&((v=o.current)==null||v.call(o),i.current=R,o.current=ls.subscribe({sendData:wi},R,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${R}`,params:{includeSessions:!0}},F=>{if(F.topic!=="daemon.metadata")return;const D=t.current.getIdes(),W=D.find(P=>P.id===R),L=ia(F.status,{daemonId:R,existingDaemon:W,existingEntries:D,timestamp:F.timestamp});L.length>0&&t.current.injectEntries(L,{authoritativeDaemonIds:[R]}),F.userName&&a.current&&a.current(F.userName)}))}}catch(N){console.error("[Standalone WS] Parse error:",N)}},k.onclose=j=>{f.current&&(Xt==null||Xt.stopScreenshots(),Xt&&ms.setState(Xt.daemonId,"disconnected"),u("disconnected"),p.current=null,w.current=`close:${j.code}${j.wasClean?":clean":":unclean"}`,Gn("close",{code:j.code,reason:j.reason||"",wasClean:j.wasClean}),x())},k.onerror=j=>{g.current||!f.current||(w.current="error",Gn("error",{message:j instanceof Event?"event":String(j),readyState:k.readyState}),console.warn("[Standalone WS] Error, will reconnect:",j))}}function x(){if(!f.current)return;clearTimeout(d.current);const k=m.current;console.log(`[Standalone WS] Reconnecting in ${k}ms...`),Gn("schedule_reconnect",{reason:w.current,delayMs:k}),d.current=setTimeout(()=>{m.current=Math.min(m.current*1.5,NI),h()},k)}return h(),()=>{var k;f.current=!1,g.current=!0,(k=o.current)==null||k.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,as=null),Xt&&(Xt.stopScreenshots(),ms.unregister(Xt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function DI({children:e}){const[t,n]=l.useState("disconnected"),[r,a]=l.useState(null);l.useEffect(()=>(nr=(i,c)=>{n(i),c&&a(c)},()=>{nr=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=MI(t),u={};return r&&(u[r]=c),u.standalone=c,{wsStatus:t,isConnected:i,connectionStates:u}},[t,r]);return s.jsx(df,{connectionOverrides:o,children:s.jsx(II,{children:e})})}const lh="adhdev_standalone_font_preferences",Vs={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Oa=[{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"}],pr=[{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"}],LI=new Set(Oa.map(e=>e.id)),RI=new Set(pr.map(e=>e.id));function fs(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:ea("chat",t.chat),code:ea("code",t.code),terminal:ea("terminal",t.terminal)}}function ea(e,t){const n=Vs[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"?LI:RI).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:n:{preset:a}:n}function ta(e,t){var a;const n=ea(e,t);if(n.preset==="custom"&&n.customFamily)return n.customFamily;const r=e==="chat"?Oa:pr;return((a=r.find(o=>o.id===n.preset))==null?void 0:a.family)||r[0].family}function EI(e){const t=fs(e),n=ta("chat",t.chat),r=ta("code",t.code),a=ta("terminal",t.terminal);return{"--chat-font-family":n,"--chat-code-font-family":r,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Bs(e,t=document.documentElement){const n=fs(e),r=EI(n);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(r))t.style.setProperty(a,o);return n}function ki(e){const t=fs(e);try{localStorage.setItem(lh,JSON.stringify(t))}catch{}return t}function _I(){try{const e=localStorage.getItem(lh);if(e)return fs(JSON.parse(e))}catch{}return Vs}function $I(){return Bs(_I())}function qn(e,t){var r;const n=e==="chat"?Oa:pr;return((r=n.find(a=>a.id===t))==null?void 0:r.label)||n[0].label}function HI({children:e}){const t=mr(),n=Ci(),{t:r}=Ne("common"),a=l.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:s.jsx(Yd,{}),label:r("standalone.nav.dashboard"),active:n.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:s.jsx(Ts,{}),label:"Burrow",active:n.pathname.startsWith("/machines"),onSelect:()=>t("/machines")},{id:"mesh",path:"/mesh",icon:s.jsx(es,{}),label:"Mesh",active:n.pathname.startsWith("/mesh"),onSelect:()=>t("/mesh")},{id:"settings",path:"/settings",icon:s.jsx(Sa,{}),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(Qd,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:r("standalone.nav.docs")},{id:"about",label:r("standalone.nav.about"),icon:s.jsx(Mi,{}),active:n.pathname==="/about",onSelect:()=>t("/about"),title:r("standalone.nav.about")}],[n.pathname,t,r]);return s.jsx(ES,{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.9"]}),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 FI=[{icon:s.jsx(Ts,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Zs,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(eu,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(us,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(or,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Qd,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],BI=[{icon:s.jsx(Bf,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Yd,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Nn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Rf,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Jd,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(_f,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],OI=[{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 WI(){const{t:e}=Ne("common");return s.jsxs(gr,{icon:s.jsx(Mi,{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.9"]}),children:[s.jsx(bt,{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(bt,{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:FI.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(bt,{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:Tp.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:Ip.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:Pp.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(bt,{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:BI.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(bt,{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:OI.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(Ra,{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(Yf,{size:14,className:"mr-1"}),e("standalone.about.discord")]})]})})]})}function Ho(e,t,n){return{...e,[t]:n}}function Fo({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(FS,{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(is,{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:ta(e,r)})]})]})]})}function UI({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(Ot,{variant:"error",children:r}),a&&s.jsx(Ot,{variant:"success",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(Fo,{surface:"chat",title:p("standalone.fonts.chat"),description:p("standalone.fonts.chatDescription"),value:e.chat,options:Oa,onChange:m=>o(Ho(e,"chat",m))}),s.jsx(Fo,{surface:"code",title:p("standalone.fonts.code"),description:p("standalone.fonts.codeDescription"),value:e.code,options:pr,onChange:m=>o(Ho(e,"code",m))}),s.jsx(Fo,{surface:"terminal",title:p("standalone.fonts.terminal"),description:p("standalone.fonts.terminalDescription"),value:e.terminal,options:pr,onChange:m=>o(Ho(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: ",qn("chat",e.chat.preset)," · Code: ",qn("code",e.code.preset)," · Terminal: ",qn("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[p("standalone.fonts.defaults")," ",qn("chat",Vs.chat.preset)," / ",qn("code",Vs.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(ks,{type:"button",variant:"primary",size:"sm",onClick:i,disabled:n||!d,children:p(n?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),s.jsx(ks,{type:"button",variant:"secondary",size:"sm",onClick:c,disabled:n||!d,children:p("standalone.fonts.revertToSaved")}),s.jsx(ks,{type:"button",variant:"secondary",size:"sm",onClick:u,disabled:n,children:p("standalone.fonts.resetToDefaults")})]})]})}function GI(){const{t:e}=Ne("common"),{ides:t}=gs(),n=t.find(O=>O.type==="adhdev-daemon"),r=(n==null?void 0:n.detectedIdes)||[],{sendCommand:a}=vt(),{userName:o}=gs(),[i,c]=l.useState(o||""),[u,p]=l.useState(null),[d,m]=l.useState(null),[f,g]=l.useState(Vs),[w,h]=l.useState(!1),[x,k]=l.useState(""),[b,S]=l.useState(""),[j,y]=l.useState("127.0.0.1"),[v,N]=l.useState(""),[C,A]=l.useState(""),[M,T]=l.useState(""),[R,E]=l.useState(""),[_,z]=l.useState(""),[F,D]=l.useState(!1),W=async()=>{const ie=await(await hs("/auth/session")).json();p(ie)},L=async()=>{const ie=await(await hs("/api/v1/standalone/preferences")).json();m(ie),y(ie.standaloneBindHost);const K=fs(ie.standaloneFontPreferences);g(K),Bs(K),ki(K)};l.useEffect(()=>{o!==void 0&&c(o)},[o]),l.useEffect(()=>{Promise.all([W(),L()]).catch(O=>{E(O instanceof Error?O.message:String(O))})},[]),l.useEffect(()=>{Bs(f)},[f]);const P=O=>{const ie=O.target.value.trim();n!=null&&n.id&&ie!==o&&a(n.id,"set_user_name",{userName:ie}).catch(console.error)},[$,I]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),U=O=>{I(O);try{localStorage.setItem("adhdev_sound",O?"1":"0")}catch{}},J=async()=>{k(""),S(""),h(!0);try{const O=fs(f),ie=await hs("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:O})}),K=await ie.json();if(!ie.ok)throw new Error((K==null?void 0:K.error)||"Failed to save standalone font preferences");const ae=fs(K.standaloneFontPreferences);m(K),g(ae),Bs(ae),ki(ae),S(e("standalone.settings.fontsSaved"))}catch(O){k(O instanceof Error?O.message:String(O))}finally{h(!1)}},re=()=>{const O=fs(d==null?void 0:d.standaloneFontPreferences);k(""),S(""),g(O),Bs(O)},Y=()=>{k(""),S(""),g(Vs),Bs(Vs)},X=async()=>{E(""),z(""),D(!0);try{const O=await hs("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:j})}),ie=await O.json();if(!O.ok)throw new Error((ie==null?void 0:ie.error)||"Failed to save standalone network preference");m(ie),y(ie.standaloneBindHost),z(ie.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(O){E(O instanceof Error?O.message:String(O))}finally{D(!1)}},de=async()=>{if(E(""),z(""),C.trim().length<4){E(e("standalone.settings.passwordTooShort"));return}if(C!==M){E(e("standalone.settings.passwordMismatch"));return}D(!0);try{const O=await hs("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,newPassword:C})}),ie=await O.json();if(!O.ok)throw new Error((ie==null?void 0:ie.error)||"Failed to save password");p(ie),await L(),N(""),A(""),T(""),z(u!=null&&u.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),oh()}catch(O){E(O instanceof Error?O.message:String(O))}finally{D(!1)}},ne=async()=>{E(""),z(""),D(!0);try{const O=await hs("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,clear:!0})}),ie=await O.json();if(!O.ok)throw new Error((ie==null?void 0:ie.error)||"Failed to clear password");p(ie),await L(),N(""),A(""),T(""),z(e("standalone.settings.passwordDisabled"))}catch(O){E(O instanceof Error?O.message:String(O))}finally{D(!1)}};return s.jsxs(gr,{icon:s.jsx(Sa,{className:"text-text-primary"}),title:e("standalone.settings.title"),subtitle:e("standalone.settings.subtitle"),widthClassName:"max-w-5xl",children:[s.jsx(Ot,{variant:"info",children:e("standalone.settings.infoNotice")}),(u==null?void 0:u.publicHostWarning)&&s.jsx(Ot,{variant:"warning",children:e("standalone.settings.publicHostWarning")}),s.jsx(bt,{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.9"]}),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(bt,{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:()=>y("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:()=>y("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(ks,{type:"button",variant:"primary",size:"sm",onClick:()=>{X()},disabled:F,children:e(F?"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(bt,{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")}),R&&s.jsx(Ot,{variant:"error",children:R}),_&&s.jsx(Ot,{variant:"success",children:_}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx(is,{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(is,{type:"password",placeholder:u!=null&&u.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:C,onChange:O=>A(O.target.value)}),s.jsx(is,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:M,onChange:O=>T(O.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(ks,{type:"button",variant:"primary",size:"sm",onClick:()=>{de()},disabled:F,children:F?e("standalone.settings.saving"):u!=null&&u.hasPasswordAuth?e("standalone.settings.updatePassword"):e("standalone.settings.enablePassword")}),(u==null?void 0:u.hasPasswordAuth)&&s.jsx(ks,{type:"button",variant:"danger",size:"sm",onClick:()=>{ne()},disabled:F,children:e("standalone.settings.disablePassword")})]})]})}),s.jsx(bt,{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(bt,{title:e("standalone.settings.machineSection"),description:e("standalone.settings.machineDescription"),children:s.jsx(KS,{ides:t,emptyMessage:e("standalone.settings.daemonNotConnected")})}),s.jsx(bt,{title:e("standalone.settings.appearanceSection"),description:e("standalone.settings.appearanceDescription"),children:s.jsx(mC,{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(UI,{value:f,savedValue:fs(d==null?void 0:d.standaloneFontPreferences),saving:w,error:x,notice:b,onChange:g,onSave:()=>{J()},onResetToSaved:re,onResetToDefaults:Y})]})})}),s.jsx(bt,{title:e("standalone.settings.notificationsSection"),description:e("standalone.settings.notificationsDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(US,{}),s.jsx(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Vf,{size:15})," ",e("standalone.settings.soundEffectsLabel")]}),description:e("standalone.settings.soundEffectsDescription"),checked:$,onChange:U})]})}),s.jsx(bt,{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(Lf,{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(is,{type:"text",className:"w-48 text-right",placeholder:e("standalone.settings.displayNamePlaceholder"),value:i,onChange:O=>c(O.target.value),onBlur:P,onKeyDown:O=>{O.key==="Enter"&&O.currentTarget.blur()}})]})})})]})}const qI=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],Yn="adhdev_onboarding_done",zI=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],KI={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function VI({onDone:e}){const{t}=Ne("common"),[n,r]=l.useState([]),[a,o]=l.useState(new Set(qI)),[i,c]=l.useState(!0),[u,p]=l.useState(null),[d,m]=l.useState(!1),[f,g]=l.useState(null),[w,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(C=>{if(!C.ok)throw new Error(`HTTP ${C.status}`);return C.json()}).then(C=>{v||r(C.providers??[])}).catch(C=>{v||p(C instanceof Error?C.message:String(C))}).finally(()=>{v||c(!1)}),()=>{v=!0}},[]);const x=n.filter(v=>w==="all"||v.category===w),k=["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 C=new Set(N);return C.has(v)?C.delete(v):C.add(v),C})},[]),S=l.useCallback(async()=>{if(a.size===0){localStorage.setItem(Yn,"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(C){v.push({type:N,ok:!1,error:C instanceof Error?C.message:String(C)})}g(v),m(!1),v.every(N=>N.ok)&&localStorage.setItem(Yn,"1")},[a,e]),j=l.useCallback(()=>{localStorage.setItem(Yn,"1"),e()},[e]),y=l.useCallback(()=>{f&&f.every(v=>v.ok)?e():d||j()},[f,d,e,j]);return s.jsx(_u,{open:!0,onClose:y,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(ks,{variant:"secondary",size:"sm",onClick:j,disabled:d,children:t("standalone.onboarding.skip")}),s.jsx(ks,{variant:"primary",size:"sm",onClick:()=>{f?(localStorage.setItem(Yn,"1"),e()):S()},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:zI.map(v=>{const N=v.key==="all"?n.length:n.filter(C=>C.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 ${w===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(Ot,{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:k.map(v=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:KI[v.category]??v.category}),s.jsx("div",{className:"grid gap-1.5",children:v.items.map(N=>{var R,E;const C=a.has(N.type),A=f==null?void 0:f.find(_=>_.type===N.type),M=((R=N.manifest)==null?void 0:R.icon)??"📦",T=((E=N.manifest)==null?void 0:E.details)??"";return s.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${C?"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:C,onChange:()=>b(N.type),disabled:d,className:"shrink-0"}),s.jsx("span",{className:"text-base shrink-0",children:M}),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}),T&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:T})]}),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 YI(){try{return localStorage.getItem(Yn)==="1"}catch{return!1}}jS();aC();fy();$I();const JI=Wd({baseUrl:"",getToken:xl});function QI({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 hs("/auth/session")).json();r(h)}catch(w){p(w instanceof Error?w.message:String(w))}finally{o(!1)}};l.useEffect(()=>{f()},[]),l.useEffect(()=>{if(!n||n.required&&!n.authenticated)return;let w=!1;return(async()=>{try{const h=await hs("/api/v1/standalone/preferences");if(!h.ok)return;const x=await h.json();if(w)return;const k=fs(x.standaloneFontPreferences);Bs(k),ki(k)}catch{}})(),()=>{w=!0}},[n==null?void 0:n.authenticated,n==null?void 0:n.required]);const g=async w=>{w.preventDefault(),m(!0),p("");try{const h=await hs("/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(""),oh()}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(is,{type:"password",value:i,onChange:w=>c(w.target.value),placeholder:t("standalone.auth.passwordPlaceholder"),autoFocus:!0}),s.jsx(ks,{type:"submit",variant:"primary",disabled:d||!i,className:"justify-center",children:t(d?"standalone.auth.signingIn":"standalone.auth.unlock")})]}):s.jsx(Ot,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),u&&s.jsx(Ot,{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 Ed(){const{t:e}=Ne("common"),{ides:t,initialLoaded:n}=gs();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(Uo,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Uo,{to:"/dashboard",replace:!0})}function XI(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let n=!1;if(!YI())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(VI,{onDone:()=>t(!1)}):null}function ZI(){const{t:e}=Ne("common"),{ides:t}=gs(),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}=Hp(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(hu,{promptSession:r,isSubmitting:i,error:o,onSubmit:c,onCancel:u})]}):null}function eD(){const e=l.useMemo(()=>({sendCommand:rr,sendData:wi,sendPtyInput:ih}),[]);return s.jsx(zh,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(mf,{client:JI,children:s.jsx(QI,{children:s.jsx(DI,{children:s.jsx(ff,{value:e,children:s.jsxs(vf,{sendDaemonCommand:rr,children:[s.jsx(ZI,{}),s.jsxs(HI,{children:[s.jsx(XI,{}),s.jsxs(Kh,{children:[s.jsx(js,{path:"/dashboard",element:s.jsx(nT,{})}),s.jsx(js,{path:"/machine",element:s.jsx(Ed,{})}),s.jsx(js,{path:"/machines/:id",element:s.jsx(uP,{})}),s.jsx(js,{path:"/machines",element:s.jsx(Ed,{})}),s.jsx(js,{path:"/about",element:s.jsx(WI,{})}),s.jsx(js,{path:"/settings",element:s.jsx(GI,{})}),s.jsx(js,{path:"/mesh",element:s.jsx(kI,{children:s.jsx(vI,{})})}),s.jsx(js,{path:"*",element:s.jsx(Uo,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}vk({connectionManager:ms});Vh(document.getElementById("root")).render(s.jsx(eD,{}));
121
+ Node removal cleanup policy: ${be}`))return;const je=e.__sourceDaemonId||n;try{const He=await o(je,"remove_mesh_node",{meshId:e.id,nodeId:le}),Xe=i(He);if((Xe==null?void 0:Xe.success)===!1)throw new Error(Xe.error||"Remove failed");S===le&&j(null),await m(),g||await f(t)}catch(He){w((He==null?void 0:He.message)||"Remove node failed")}}async function ke(le){if(!e)return;const B={...yi(e),...le},be=e.__sourceDaemonId||n;try{I(!0),w(null);const je=await o(be,"update_mesh",{meshId:e.id,policy:B}),Se=i(je);if((Se==null?void 0:Se.success)===!1)throw new Error(Se.error||"Policy update failed");await m()}catch(je){w((je==null?void 0:je.message)||"Policy update failed")}finally{I(!1)}}async function me(le){if(!t)return;const B=(e==null?void 0:e.__sourceDaemonId)||n,be=h[le.id]||dI(le),je=kn(be),Se={...le.policy||{}};delete Se.provider_priority,je.length?Se.providerPriority=je:delete Se.providerPriority;try{b(le.id),w(null);const He=await o(B,"update_mesh_node",{meshId:t,nodeId:le.id,policy:Se,providerPriority:je}),Xe=i(He);if((Xe==null?void 0:Xe.success)===!1){w(Xe.error||"Node policy update failed");return}await m()}catch(He){w((He==null?void 0:He.message)||"Node policy update failed")}finally{b(null)}}const[q,G]=l.useState(null);async function Z(le,B){if(!t)return;const be=(e==null?void 0:e.__sourceDaemonId)||n;try{G(le.id),w(null);const je=await o(be,"update_mesh_node",{meshId:t,nodeId:le.id,policy:{slots:B}}),Se=i(je);if((Se==null?void 0:Se.success)===!1){w(Se.error||"Node slots update failed");return}await m()}catch(je){w((je==null?void 0:je.message)||"Node slots update failed")}finally{G(null)}}const[V,fe]=l.useState(null);async function Te(le,B){if(!t)return;const be=(e==null?void 0:e.__sourceDaemonId)||n,je=B.map(Se=>Se.trim()).filter(Boolean);try{fe(le.id),w(null);const Se=await o(be,"update_mesh_node",{meshId:t,nodeId:le.id,capabilities:je}),He=i(Se);if((He==null?void 0:He.success)===!1){w(He.error||"Node tag update failed");return}await m()}catch(Se){w((Se==null?void 0:Se.message)||"Node tag update failed")}finally{fe(null)}}async function ce(){if(!n||!t)return;const B={...(e==null?void 0:e.coordinator)||{}};U.override.trim()?B.systemPromptOverride=U.override:delete B.systemPromptOverride,U.append.trim()?B.systemPromptAppend=U.append:delete B.systemPromptAppend,delete B.systemPromptSuffix;try{Y(!0),w(null);const be=await o(n,"update_mesh",{meshId:t,coordinator:B}),je=i(be);if((je==null?void 0:je.success)===!1){w(je.error||"Coordinator prompt save failed");return}await m()}catch(be){w((be==null?void 0:be.message)||"Coordinator prompt save failed")}finally{Y(!1)}}async function H(le){if(!n||!t)return;const B=(X[le.id]||"").trim();try{O(le.id),w(null);const be=await o(n,"update_mesh_node",{meshId:t,nodeId:le.id,systemPrompt:B}),je=i(be);if((je==null?void 0:je.success)===!1){w(je.error||"Node instruction save failed");return}await m()}catch(be){w((be==null?void 0:be.message)||"Node instruction save failed")}finally{O(null)}}async function pe(){if(e){w(null),P(null);try{W(!0);const le=c?await c(r,e.id,e):null,B=u(r,e.id,e,e.nodes||[],le);if("error"in B)throw new Error(B.error);const be=await p(B.targetDaemonId,{meshId:e.id,inlineMesh:B.inlineMesh,coordinatorNodeId:B.coordinatorNodeId,cliType:z.trim()||void 0});P(be.message)}catch(le){w((le==null?void 0:le.message)||"Coordinator launch failed")}finally{W(!1)}}}return{nodeProviderPriorityDrafts:h,setNodeProviderPriorityDrafts:x,savingNodePolicyId:k,selectedNodeId:S,setSelectedNodeId:j,showAddNode:y,setShowAddNode:v,nodeWorkspace:N,setNodeWorkspace:C,nodeProviderPriority:A,setNodeProviderPriority:M,nodeDaemonId:T,setNodeDaemonId:R,nodeCustomPath:E,setNodeCustomPath:_,nodePickerWorkspaces:K,nodePickerProviders:ae,coordinatorCliType:z,setCoordinatorCliType:F,launchingCoordinator:D,launchResult:L,savingPolicy:$,coordinatorPromptDraft:U,setCoordinatorPromptDraft:J,savingCoordinatorPrompt:re,nodeSystemPromptDrafts:X,setNodeSystemPromptDrafts:de,savingNodeSystemPromptId:ne,savingNodeSlotsId:q,savingNodeCapabilitiesId:V,handleAddNode:Ce,handleRemoveNode:ye,handleUpdatePolicy:ke,handleUpdateNodeProviderPriority:me,handleUpdateNodeSlots:Z,handleUpdateNodeCapabilities:Te,handleSaveCoordinatorPrompt:ce,handleSaveNodeSystemPrompt:H,handleLaunchCoordinator:pe}}function dI(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 uI(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 pI({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),w=l.useCallback(async x=>{if(!e||!x){c([]);return}try{const k=await n(e,"get_mesh_queue",{meshId:x});c(k!=null&&k.success?Array.isArray(k.queue)?k.queue:[]:[])}catch{c([])}},[e,n]);async function h(x){var k,b;if(x){m(!0),g(null);try{const S=a?await a(t,x.id,x):null,j=o(t,x.id,x,x.nodes||[],S);if("error"in j)throw new Error(j.error);const y=await n(j.targetDaemonId,"get_mesh_queue",{meshId:x.id}),v=r(y);if((v==null?void 0:v.success)===!1)throw new Error(v.error||"Queue load failed");const N=Array.isArray(((k=v==null?void 0:v.result)==null?void 0:k.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(uI(N))}catch(S){g((S==null?void 0:S.message)||"Queue load failed")}finally{m(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:u,queueLoading:d,queueError:f,loadQueue:w,handleLoadQueue:h}}function mI(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}const rh=new Map;function ah(e){return e?rh.get(e)??null:null}function hI(e,t){!e||!t||rh.set(e,t)}function fI({selectedMeshId:e,loadMeshStatus:t,extractStatus:n,normalizeNode:r,gateIncompleteGraph:a}){const[o,i]=l.useState(()=>ah(e)),[c,u]=l.useState(!1),[p,d]=l.useState(null),[m,f]=l.useState("idle"),[g,w]=l.useState(!1),h=l.useRef(!1);async function x(k,b=e,S=!1){if(!(!k||!b))try{u(!S&&o===null),f(S?"settling":"first_paint"),d(null);const j=await t(k,b,{refresh:S,retryProfile:S?"settled":"interactive"});w(mI(j));const y=n(j),v=r&&y?{...y,nodes:(y.nodes??[]).map(N=>r(N,y.meshId??b,""))}:y;if(v){if(a&&!S&&o!==null&&!DN(Em(v))){f("settling"),h.current||(h.current=!0,Promise.resolve().then(()=>x(k,b,!0)).finally(()=>{h.current=!1}));return}i(v),hI(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 bI(e,t,n,r,a){if(!e.length)return"";const o=String(a||"");if(o){const u=e.find(p=>Os(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=>Os(p.id,c));if(u)return u.id}return""}const gI=7e3,xI=45e3;function vI(){const e=hP(),{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:w}=e,h=Tn(),x=r[0],k=(x==null?void 0:x.id)||"",b=l.useMemo(()=>((x==null?void 0:x.availableProviders)||[]).filter(rt=>rt.category==="cli").map(rt=>({id:rt.type||rt.id,name:rt.displayName||rt.name||rt.type,meshCoordinator:rt.meshCoordinator})),[x]),S=l.useMemo(()=>wn((x==null?void 0:x.availableProviders)||[]),[x]),{meshes:j,selectedMeshId:y,setSelectedMeshId:v,loading:N,error:C,setError:A,showCreate:M,setShowCreate:T,createName:R,setCreateName:E,createRepoIdentity:_,setCreateRepoIdentity:z,createRepoRemoteUrl:F,setCreateRepoRemoteUrl:D,newMeshDaemonId:W,setNewMeshDaemonId:L,newMeshWorkspace:P,setNewMeshWorkspace:$,createPickerWorkspaces:I,loadMeshes:U,handleCreate:J,handleDelete:re,cancelCreate:Y}=lI({daemons:r,primaryDaemonId:k,sendCommand:t,unwrapResult:p,normalizeMesh:d,features:g,loadDaemonMetadata:h}),X=j.find(Re=>Re.id===y)||null,{meshGraphStatus:de,setMeshGraphStatus:ne,graphLoading:O,graphError:ie,setGraphError:K,loadGraph:ae}=fI({selectedMeshId:y,loadMeshStatus:o,extractStatus:u,normalizeNode:m,gateIncompleteGraph:w}),[Ce,ye]=l.useState(""),[ke,me]=l.useState(""),q=g.meshHostDaemonSection&&Ce||k,{meshQueue:G,loadQueue:Z}=pI({primaryDaemonId:k,activeDaemonId:q,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f}),{setNodeProviderPriorityDrafts:V,selectedNodeId:fe,setSelectedNodeId:Te,showAddNode:ce,setShowAddNode:H,nodeWorkspace:pe,setNodeWorkspace:le,nodeProviderPriority:B,setNodeProviderPriority:be,nodeDaemonId:je,setNodeDaemonId:Se,nodeCustomPath:He,setNodeCustomPath:Xe,nodePickerWorkspaces:dt,nodePickerProviders:it,coordinatorCliType:he,setCoordinatorCliType:$e,launchingCoordinator:Be,launchResult:Pe,savingPolicy:ve,coordinatorPromptDraft:Ue,setCoordinatorPromptDraft:ut,savingCoordinatorPrompt:ot,nodeSystemPromptDrafts:pt,setNodeSystemPromptDrafts:Q,savingNodeSystemPromptId:ee,savingNodeSlotsId:oe,savingNodeCapabilitiesId:ue,handleAddNode:xe,handleRemoveNode:Me,handleUpdatePolicy:Le,handleUpdateNodeSlots:Ae,handleUpdateNodeCapabilities:Oe,handleSaveCoordinatorPrompt:qe,handleSaveNodeSystemPrompt:Ze,handleLaunchCoordinator:_e}=cI({selectedMesh:X,selectedMeshId:y,primaryDaemonId:k,activeDaemonId:q,daemons:r,availableCliProviders:S,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f,launchCoordinator:i,features:{addNodeDaemonPicker:g.addNodeDaemonPicker},loadMeshes:U,loadQueue:Z,queueSection:g.queueSection,setError:A}),Ge=l.useMemo(()=>r.find(Re=>Re.id===q)||x,[r,q,x]),et=l.useMemo(()=>new Set(((X==null?void 0:X.nodes)||[]).map(Re=>String(Re.daemon_id||Re.daemonId||""))),[X]),te=l.useMemo(()=>r.filter(Re=>Re.id&&!et.has(Re.id)),[r,et]),ge=(X==null?void 0:X.nodes)||[],we=l.useMemo(()=>ge.find(Re=>Os(String(Re.daemon_id||Re.daemonId||""),Ce)),[ge,Ce]),ze=g.meshHostDaemonSection?!!we:!0,We=l.useMemo(()=>{if(!g.meshHostDaemonSection||!X)return{pinned:!1,daemonId:"",label:"",online:!1};const Re=X.meshHost,rt=de!=null&&de.meshId&&String(de.meshId)===String(X.id??"")?de.meshHost:void 0,jt=rt!=null&&rt.hostDaemonId?rt:Re??rt,Ut=String((jt==null?void 0:jt.hostDaemonId)||""),se=ge.find(vs=>vs.role==="host"),Fe=String((jt==null?void 0:jt.hostNodeId)||(se==null?void 0:se.id)||""),Ee=Fe?ge.find(vs=>String(vs.id)===Fe):void 0,yt=String((Ee==null?void 0:Ee.daemon_id)||(Ee==null?void 0:Ee.daemonId)||""),Jt=Ut||yt;if(!Jt)return{pinned:!1,daemonId:"",label:"",online:!1};const Pn=r.find(vs=>Ut&&Os(vs.id,Ut))||(yt?r.find(vs=>Os(vs.id,yt)):void 0);if(Pn)return{pinned:!0,daemonId:Pn.id,label:yI(Pn),online:!0};const Wa=String((Ee==null?void 0:Ee.machineLabel)||"")||String((Ee==null?void 0:Ee.workspace)||"")||Jt;return{pinned:!0,daemonId:Jt,label:Wa,online:!1}},[X,ge,r,de,g.meshHostDaemonSection]),tt=We.daemonId,Ke=We.online,Ye=l.useMemo(()=>!g.meshHostDaemonSection||!We.pinned?"":!Ke&&ke&&r.some(Re=>Re.id===ke)?ke:tt,[g.meshHostDaemonSection,We.pinned,Ke,ke,r,tt]),Mt=l.useMemo(()=>de?[...new Set((de.nodes??[]).map(Re=>String(Re.daemonId||Re.daemon_id||"")).filter(Boolean))]:[],[de]),Wt=Qm({status:de,daemonId:q||null,extraDaemonIds:Mt,meshId:y,sendData:n});l.useEffect(()=>{V(Object.fromEntries(((X==null?void 0:X.nodes)||[]).map(Re=>[Re.id,wI(Re)])))},[X]),l.useEffect(()=>{const Re=(X==null?void 0:X.coordinator)||{};ut({override:typeof Re.systemPromptOverride=="string"?Re.systemPromptOverride:"",append:typeof Re.systemPromptAppend=="string"?Re.systemPromptAppend:typeof Re.systemPromptSuffix=="string"?Re.systemPromptSuffix:""}),Q(Object.fromEntries(((X==null?void 0:X.nodes)||[]).map(rt=>[rt.id,typeof rt.systemPrompt=="string"?rt.systemPrompt:""])))},[X]),l.useEffect(()=>{const Re=g.addNodeDaemonPicker?cr(it):cr(S);ce&&B.length===0&&Re.length>0&&be(Re)},[ce,S,it,B.length,g.addNodeDaemonPicker]),l.useEffect(()=>{const Re=new Set(((X==null?void 0:X.nodes)||[]).map(rt=>rt.id));fe&&!Re.has(fe)&&Te(null)},[X,fe]);const ss=l.useMemo(()=>{var Re;if(!(!(de!=null&&de.meshId)||String(de.meshId)!==String((X==null?void 0:X.id)??"")))return(Re=de.meshHost)==null?void 0:Re.hostDaemonId},[de,X]),Ie=l.useMemo(()=>bI(r,ge,q,k,ss),[r,ge,q,k,ss]);l.useEffect(()=>{if(!g.meshHostDaemonSection)return;if(!r.length&&!We.pinned){ye("");return}const Re=We.pinned?Ye:Ie;Re&&!Os(Re,Ce)&&ye(Re)},[r,Ce,We.pinned,Ye,Ie,g.meshHostDaemonSection]),l.useEffect(()=>{ke&&(Ke||!r.some(Re=>Re.id===ke))&&me("")},[Ke,ke,r]),l.useEffect(()=>{if(g.createDaemonPicker){if(!r.length){L("");return}(!W||!r.some(Re=>Re.id===W))&&L(r[0].id)}},[r,W,g.createDaemonPicker]),l.useEffect(()=>{var Re;if(!g.createDaemonPicker||!W){$("");return}if(!I.length){$("");return}I.some(rt=>rt.path===P)||$(((Re=I[0])==null?void 0:Re.path)||"")},[W,P,I,g.createDaemonPicker]);const Qe=l.useRef(null);l.useEffect(()=>{if(!y)return;const Re=Qe.current!==y;if(Qe.current=y,Re){const rt=ah(y);ne(rt),K(null),ae(q,y,rt!==null)}else K(null),ae(q,y,!0)},[y,q]);const It=l.useRef(ae);It.current=ae;const Tt=l.useRef(!1),Kt=l.useRef(()=>{});Kt.current=()=>{Tt.current||!y||!q||(Tt.current=!0,Promise.resolve(It.current(q,y,!0)).finally(()=>{Tt.current=!1}))};const Vt=g.meshStatePushRefresh?xI:gI;pP({daemonIds:l.useMemo(()=>[q,...Mt].filter(Boolean),[q,Mt]),meshId:y,sendData:n,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||Kt.current()}}),l.useEffect(()=>{if(!y||!q||typeof document>"u")return;let Re=null;const rt=()=>{document.visibilityState==="visible"&&Kt.current()},jt=()=>{Re===null&&(Re=setInterval(rt,Vt))},Ut=()=>{Re!==null&&(clearInterval(Re),Re=null)},se=()=>{document.visibilityState==="visible"?jt():Ut()};return document.visibilityState==="visible"&&jt(),document.addEventListener("visibilitychange",se),()=>{Ut(),document.removeEventListener("visibilitychange",se)}},[y,q,Vt]),l.useEffect(()=>{g.queueSection||Z(y)},[y,g.queueSection]);const Yt=l.useMemo(()=>r.map(Re=>Re.id).filter(Boolean).sort().join(","),[r]),xs=l.useRef(!1);return l.useEffect(()=>{U(xs.current),xs.current=!0},[Yt]),k?X?s.jsx(iI,{selectedMesh:X,error:C,onDismissError:()=>A(null),onBack:()=>{v(null),ne(null)},onDelete:re,displayedMeshStatus:Wt,graphLoading:O,graphError:ie,onRefreshGraph:()=>ae(q,y,!0),savingPolicy:ve,onUpdatePolicy:Le,coordinatorPromptDraft:Ue,onCoordinatorPromptDraftChange:ut,savingCoordinatorPrompt:ot,onSaveCoordinatorPrompt:qe,daemons:r,coordinatorDaemonId:Ce,onCoordinatorDaemonIdChange:ye,coordinatorCliType:he,onCoordinatorCliTypeChange:$e,launchingCoordinator:Be,launchResult:Pe,isHostNodeAttached:ze,selectedHostNode:we,hostPinned:We.pinned,hostLabel:We.label,hostOnline:Ke,hostRebindDaemonId:ke,onHostRebindDaemonIdChange:Re=>me(Re),onLaunchCoordinator:_e,activeDaemon:Ge,activeDaemonId:q,meshQueue:G,userName:a,availableCliProviders:S,savingNodeSlotsId:oe,onUpdateNodeSlots:Ae,savingNodeCapabilitiesId:ue,onUpdateNodeCapabilities:Oe,nodeSystemPromptDrafts:pt,onNodeSystemPromptDraftChange:(Re,rt)=>Q(jt=>({...jt,[Re]:rt})),savingNodeSystemPromptId:ee,onSaveNodeSystemPrompt:Ze,selectedNodeId:fe,onSelectNode:Te,showAddNode:ce,onShowAddNode:()=>H(!0),onCancelAddNode:()=>H(!1),nodeWorkspace:pe,onNodeWorkspaceChange:le,nodeProviderPriority:B,onNodeProviderPriorityChange:be,nodeDaemonId:je,onNodeDaemonIdChange:Se,nodeCustomPath:He,onNodeCustomPathChange:Xe,nodePickerWorkspaces:dt,nodePickerProviders:it,attachableDaemons:te,onAddNode:xe,onRemoveNode:Me,availableCliAgents:b,features:{coordinatorPrompt:g.coordinatorPrompt,meshHostDaemonSection:g.meshHostDaemonSection,hermesMcpConfig:g.hermesMcpConfig,addNodeDaemonPicker:g.addNodeDaemonPicker,nodeInstruction:g.nodeInstruction},sendCommand:t}):s.jsx(wP,{meshes:j,loading:N,error:C,onDismissError:()=>A(null),daemons:r,features:{createDaemonPicker:g.createDaemonPicker,maxMeshes:g.maxMeshes},showCreate:M,onToggleCreate:()=>T(!M),createName:R,onCreateNameChange:E,createRepoIdentity:_,onCreateRepoIdentityChange:z,createRepoRemoteUrl:F,onCreateRepoRemoteUrlChange:D,newMeshDaemonId:W,onNewMeshDaemonIdChange:L,newMeshWorkspace:P,onNewMeshWorkspaceChange:$,createPickerWorkspaces:I,onSelectMesh:v,onCreate:J,onCancelCreate:Y}):s.jsx(gr,{icon:s.jsx(es,{}),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 yI(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}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 kI({children:e}){const{sendCommand:t,sendData:n}=vt(),{ides:r}=gs(),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:Wi,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,u)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:mP}),[t,n,a]);return s.jsx(nh.Provider,{value:o,children:e})}function xl(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function SI(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=xl();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 hs(e,t){return await fetch(SI(e),{credentials:"same-origin",...t})}function oh(){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 CI{constructor(){st(this,"adapters",new Map);st(this,"states",new Map);st(this,"runtimeListeners",new Map);st(this,"screenshotCallbacks",new Map);st(this,"statusCallbacks",new Set);st(this,"stateChangeCallbacks",new Set);st(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 hs(`${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 ms=new CI;function jI(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=xl();return n?`${t}?token=${encodeURIComponent(n)}`:t}const Wr=jI(),Ld=3e3,NI=3e4;let as=null,AI=0;const wa=new Map;let Hs=null,nr=null;function Rd(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-status] ${e}`,t)}catch{}}function Gn(e,t){if(!(typeof window>"u"))try{if(!(window.localStorage.getItem("adhdev_mobile_debug")==="1"))return;console.debug(`[standalone-ws] ${e}`,t)}catch{}}function MI(e){return e==="connected"?"connected":e}async function rr(e,t,n){const r=Mp(e,n||{}),a=as;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++AI}_${Date.now()}`;return new Promise((i,c)=>{const u=setTimeout(()=>{wa.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);wa.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 wi(e,t){const n=as;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 ih(e,t,n){const r=as;if(!r||r.readyState!==WebSocket.OPEN)return!1;const a=Mp(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}}ms.registerPtyInputSender(ih);class TI{constructor(t){st(this,"daemonId");st(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(as==null?void 0:as.readyState)===WebSocket.OPEN}get connectionState(){return(as==null?void 0:as.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,n){return rr(this.daemonId,t,n)}async sendInput(t,n){return rr(this.daemonId,"cdp_remote_action",{action:t,params:n,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,Hs&&(clearInterval(Hs),Hs=null);const n=async()=>{if(this.hasCommandChannel)try{const r=await rr(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());ms.emitScreenshot(this.daemonId,a)}}catch{}};n(),Hs=setInterval(n,2e3)}stopScreenshots(t){Hs&&(clearInterval(Hs),Hs=null)}}let Xt=null;function PI(e){return(!Xt||Xt.daemonId!==e)&&(Xt=new TI(e)),Xt}function II({children:e}){const t=l.useRef(ar()),n=ar();t.current=n;const{setUserName:r}=gs(),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),nr==null||nr(h,x)},[]),p=l.useRef(null),d=l.useRef(),m=l.useRef(Ld),f=l.useRef(!0),g=l.useRef(!1),w=l.useRef("initial_connect");return l.useEffect(()=>{f.current=!0,g.current=!1;function h(){var b,S;if(!f.current||((b=p.current)==null?void 0:b.readyState)===WebSocket.OPEN||((S=p.current)==null?void 0:S.readyState)===WebSocket.CONNECTING)return;u("connecting"),console.log(`[Standalone WS] Connecting to ${Wr}...`),Gn("connect_attempt",{url:Wr,reason:w.current,delayMs:m.current});let k;try{k=new WebSocket(Wr)}catch(j){console.error("[Standalone WS] Failed to create WebSocket:",j),x();return}p.current=k,k.onopen=()=>{if(!f.current){k.close();return}u("connected"),m.current=Ld,Gn("open",{url:Wr,reason:w.current}),ls.resubscribeAll({sendData:wi}),console.log("[Standalone WS] Connected")},as=k,k.onmessage=j=>{var y,v;try{const N=JSON.parse(j.data);if((N.type==="command_result"||N.type==="error")&&N.requestId){const C=wa.get(N.requestId);C&&(wa.delete(N.requestId),N.type==="error"?C.reject(new Error(((y=N.data)==null?void 0:y.message)||"Command failed")):C.resolve(N.data));return}if(N.type==="session_output"){const C=N.sessionId||N.cliId||N.cliType;C&&ms.emitSessionOutput(C,typeof N.data=="string"?N.data:"",typeof N.seq=="number"?N.seq:void 0);return}if(N.type==="runtime_snapshot"){ms.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 C=N.update;C&&ls.publish(C);return}if(N.type==="status"||N.type==="initial_state"){const C=N.data;if(!C)return;const{injectEntries:A,markLoaded:M,getIdes:T}=t.current,R=C.instanceId||"standalone",E=T().find(F=>F.id===R),_=PI(R);ms.register(R,_),ms.setState(R,"connected"),u("connected",R),ms.emitStatus(R,C);const z=ia(C,{daemonId:R,existingDaemon:E,existingEntries:T()});Rd("ws_status",{type:N.type,daemonId:R,sessions:(C.sessions||[]).map(F=>({id:F.id,parentId:F.parentId,providerType:F.providerType,kind:F.kind,transport:F.transport,unread:F.unread,inboxBucket:F.inboxBucket,lastSeenAt:F.lastSeenAt,lastUpdated:F.lastUpdated,title:F.title})),recentLaunches:(C.recentLaunches||[]).map(F=>({id:F.id,providerType:F.providerType,kind:F.kind,workspace:F.workspace,lastLaunchedAt:F.lastLaunchedAt}))}),Rd("entries",{daemonId:R,entries:z.filter(F=>F.type!=="adhdev-daemon").map(F=>({id:F.id,type:F.type,unread:F.unread,inboxBucket:F.inboxBucket,lastSeenAt:F.lastSeenAt,lastUpdated:F.lastUpdated,sessionId:F.sessionId}))}),z.length>0&&A(z,{authoritativeDaemonIds:[R]}),M(),i.current!==R&&((v=o.current)==null||v.call(o),i.current=R,o.current=ls.subscribe({sendData:wi},R,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${R}`,params:{includeSessions:!0}},F=>{if(F.topic!=="daemon.metadata")return;const D=t.current.getIdes(),W=D.find(P=>P.id===R),L=ia(F.status,{daemonId:R,existingDaemon:W,existingEntries:D,timestamp:F.timestamp});L.length>0&&t.current.injectEntries(L,{authoritativeDaemonIds:[R]}),F.userName&&a.current&&a.current(F.userName)}))}}catch(N){console.error("[Standalone WS] Parse error:",N)}},k.onclose=j=>{f.current&&(Xt==null||Xt.stopScreenshots(),Xt&&ms.setState(Xt.daemonId,"disconnected"),u("disconnected"),p.current=null,w.current=`close:${j.code}${j.wasClean?":clean":":unclean"}`,Gn("close",{code:j.code,reason:j.reason||"",wasClean:j.wasClean}),x())},k.onerror=j=>{g.current||!f.current||(w.current="error",Gn("error",{message:j instanceof Event?"event":String(j),readyState:k.readyState}),console.warn("[Standalone WS] Error, will reconnect:",j))}}function x(){if(!f.current)return;clearTimeout(d.current);const k=m.current;console.log(`[Standalone WS] Reconnecting in ${k}ms...`),Gn("schedule_reconnect",{reason:w.current,delayMs:k}),d.current=setTimeout(()=>{m.current=Math.min(m.current*1.5,NI),h()},k)}return h(),()=>{var k;f.current=!1,g.current=!0,(k=o.current)==null||k.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,as=null),Xt&&(Xt.stopScreenshots(),ms.unregister(Xt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function DI({children:e}){const[t,n]=l.useState("disconnected"),[r,a]=l.useState(null);l.useEffect(()=>(nr=(i,c)=>{n(i),c&&a(c)},()=>{nr=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=MI(t),u={};return r&&(u[r]=c),u.standalone=c,{wsStatus:t,isConnected:i,connectionStates:u}},[t,r]);return s.jsx(df,{connectionOverrides:o,children:s.jsx(II,{children:e})})}const lh="adhdev_standalone_font_preferences",Vs={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Oa=[{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"}],pr=[{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"}],LI=new Set(Oa.map(e=>e.id)),RI=new Set(pr.map(e=>e.id));function fs(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:ea("chat",t.chat),code:ea("code",t.code),terminal:ea("terminal",t.terminal)}}function ea(e,t){const n=Vs[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"?LI:RI).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:n:{preset:a}:n}function ta(e,t){var a;const n=ea(e,t);if(n.preset==="custom"&&n.customFamily)return n.customFamily;const r=e==="chat"?Oa:pr;return((a=r.find(o=>o.id===n.preset))==null?void 0:a.family)||r[0].family}function EI(e){const t=fs(e),n=ta("chat",t.chat),r=ta("code",t.code),a=ta("terminal",t.terminal);return{"--chat-font-family":n,"--chat-code-font-family":r,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Bs(e,t=document.documentElement){const n=fs(e),r=EI(n);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(r))t.style.setProperty(a,o);return n}function ki(e){const t=fs(e);try{localStorage.setItem(lh,JSON.stringify(t))}catch{}return t}function _I(){try{const e=localStorage.getItem(lh);if(e)return fs(JSON.parse(e))}catch{}return Vs}function $I(){return Bs(_I())}function qn(e,t){var r;const n=e==="chat"?Oa:pr;return((r=n.find(a=>a.id===t))==null?void 0:r.label)||n[0].label}function HI({children:e}){const t=mr(),n=Ci(),{t:r}=Ne("common"),a=l.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:s.jsx(Yd,{}),label:r("standalone.nav.dashboard"),active:n.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:s.jsx(Ts,{}),label:"Burrow",active:n.pathname.startsWith("/machines"),onSelect:()=>t("/machines")},{id:"mesh",path:"/mesh",icon:s.jsx(es,{}),label:"Mesh",active:n.pathname.startsWith("/mesh"),onSelect:()=>t("/mesh")},{id:"settings",path:"/settings",icon:s.jsx(Sa,{}),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(Qd,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:r("standalone.nav.docs")},{id:"about",label:r("standalone.nav.about"),icon:s.jsx(Mi,{}),active:n.pathname==="/about",onSelect:()=>t("/about"),title:r("standalone.nav.about")}],[n.pathname,t,r]);return s.jsx(ES,{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.12"]}),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 FI=[{icon:s.jsx(Ts,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Zs,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(eu,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(us,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(or,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Qd,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],BI=[{icon:s.jsx(Bf,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Yd,{size:16}),title:"Low-latency P2P stream",desc:"Cloud adds the WebRTC path for faster screenshots and remote control."},{icon:s.jsx(Nn,{size:16}),title:"Mobile notifications",desc:"Get approval prompts and activity updates when you are away from your desk."},{icon:s.jsx(Rf,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Jd,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(_f,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],OI=[{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 WI(){const{t:e}=Ne("common");return s.jsxs(gr,{icon:s.jsx(Mi,{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.12"]}),children:[s.jsx(bt,{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(bt,{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:FI.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(bt,{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:Tp.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:Ip.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:Pp.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(bt,{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:BI.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(bt,{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:OI.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(Ra,{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(Yf,{size:14,className:"mr-1"}),e("standalone.about.discord")]})]})})]})}function Ho(e,t,n){return{...e,[t]:n}}function Fo({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(FS,{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(is,{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:ta(e,r)})]})]})]})}function UI({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(Ot,{variant:"error",children:r}),a&&s.jsx(Ot,{variant:"success",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(Fo,{surface:"chat",title:p("standalone.fonts.chat"),description:p("standalone.fonts.chatDescription"),value:e.chat,options:Oa,onChange:m=>o(Ho(e,"chat",m))}),s.jsx(Fo,{surface:"code",title:p("standalone.fonts.code"),description:p("standalone.fonts.codeDescription"),value:e.code,options:pr,onChange:m=>o(Ho(e,"code",m))}),s.jsx(Fo,{surface:"terminal",title:p("standalone.fonts.terminal"),description:p("standalone.fonts.terminalDescription"),value:e.terminal,options:pr,onChange:m=>o(Ho(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: ",qn("chat",e.chat.preset)," · Code: ",qn("code",e.code.preset)," · Terminal: ",qn("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[p("standalone.fonts.defaults")," ",qn("chat",Vs.chat.preset)," / ",qn("code",Vs.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(ks,{type:"button",variant:"primary",size:"sm",onClick:i,disabled:n||!d,children:p(n?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),s.jsx(ks,{type:"button",variant:"secondary",size:"sm",onClick:c,disabled:n||!d,children:p("standalone.fonts.revertToSaved")}),s.jsx(ks,{type:"button",variant:"secondary",size:"sm",onClick:u,disabled:n,children:p("standalone.fonts.resetToDefaults")})]})]})}function GI(){const{t:e}=Ne("common"),{ides:t}=gs(),n=t.find(O=>O.type==="adhdev-daemon"),r=(n==null?void 0:n.detectedIdes)||[],{sendCommand:a}=vt(),{userName:o}=gs(),[i,c]=l.useState(o||""),[u,p]=l.useState(null),[d,m]=l.useState(null),[f,g]=l.useState(Vs),[w,h]=l.useState(!1),[x,k]=l.useState(""),[b,S]=l.useState(""),[j,y]=l.useState("127.0.0.1"),[v,N]=l.useState(""),[C,A]=l.useState(""),[M,T]=l.useState(""),[R,E]=l.useState(""),[_,z]=l.useState(""),[F,D]=l.useState(!1),W=async()=>{const ie=await(await hs("/auth/session")).json();p(ie)},L=async()=>{const ie=await(await hs("/api/v1/standalone/preferences")).json();m(ie),y(ie.standaloneBindHost);const K=fs(ie.standaloneFontPreferences);g(K),Bs(K),ki(K)};l.useEffect(()=>{o!==void 0&&c(o)},[o]),l.useEffect(()=>{Promise.all([W(),L()]).catch(O=>{E(O instanceof Error?O.message:String(O))})},[]),l.useEffect(()=>{Bs(f)},[f]);const P=O=>{const ie=O.target.value.trim();n!=null&&n.id&&ie!==o&&a(n.id,"set_user_name",{userName:ie}).catch(console.error)},[$,I]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),U=O=>{I(O);try{localStorage.setItem("adhdev_sound",O?"1":"0")}catch{}},J=async()=>{k(""),S(""),h(!0);try{const O=fs(f),ie=await hs("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:O})}),K=await ie.json();if(!ie.ok)throw new Error((K==null?void 0:K.error)||"Failed to save standalone font preferences");const ae=fs(K.standaloneFontPreferences);m(K),g(ae),Bs(ae),ki(ae),S(e("standalone.settings.fontsSaved"))}catch(O){k(O instanceof Error?O.message:String(O))}finally{h(!1)}},re=()=>{const O=fs(d==null?void 0:d.standaloneFontPreferences);k(""),S(""),g(O),Bs(O)},Y=()=>{k(""),S(""),g(Vs),Bs(Vs)},X=async()=>{E(""),z(""),D(!0);try{const O=await hs("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:j})}),ie=await O.json();if(!O.ok)throw new Error((ie==null?void 0:ie.error)||"Failed to save standalone network preference");m(ie),y(ie.standaloneBindHost),z(ie.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(O){E(O instanceof Error?O.message:String(O))}finally{D(!1)}},de=async()=>{if(E(""),z(""),C.trim().length<4){E(e("standalone.settings.passwordTooShort"));return}if(C!==M){E(e("standalone.settings.passwordMismatch"));return}D(!0);try{const O=await hs("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,newPassword:C})}),ie=await O.json();if(!O.ok)throw new Error((ie==null?void 0:ie.error)||"Failed to save password");p(ie),await L(),N(""),A(""),T(""),z(u!=null&&u.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),oh()}catch(O){E(O instanceof Error?O.message:String(O))}finally{D(!1)}},ne=async()=>{E(""),z(""),D(!0);try{const O=await hs("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,clear:!0})}),ie=await O.json();if(!O.ok)throw new Error((ie==null?void 0:ie.error)||"Failed to clear password");p(ie),await L(),N(""),A(""),T(""),z(e("standalone.settings.passwordDisabled"))}catch(O){E(O instanceof Error?O.message:String(O))}finally{D(!1)}};return s.jsxs(gr,{icon:s.jsx(Sa,{className:"text-text-primary"}),title:e("standalone.settings.title"),subtitle:e("standalone.settings.subtitle"),widthClassName:"max-w-5xl",children:[s.jsx(Ot,{variant:"info",children:e("standalone.settings.infoNotice")}),(u==null?void 0:u.publicHostWarning)&&s.jsx(Ot,{variant:"warning",children:e("standalone.settings.publicHostWarning")}),s.jsx(bt,{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.12"]}),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(bt,{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:()=>y("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:()=>y("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(ks,{type:"button",variant:"primary",size:"sm",onClick:()=>{X()},disabled:F,children:e(F?"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(bt,{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")}),R&&s.jsx(Ot,{variant:"error",children:R}),_&&s.jsx(Ot,{variant:"success",children:_}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx(is,{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(is,{type:"password",placeholder:u!=null&&u.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:C,onChange:O=>A(O.target.value)}),s.jsx(is,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:M,onChange:O=>T(O.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(ks,{type:"button",variant:"primary",size:"sm",onClick:()=>{de()},disabled:F,children:F?e("standalone.settings.saving"):u!=null&&u.hasPasswordAuth?e("standalone.settings.updatePassword"):e("standalone.settings.enablePassword")}),(u==null?void 0:u.hasPasswordAuth)&&s.jsx(ks,{type:"button",variant:"danger",size:"sm",onClick:()=>{ne()},disabled:F,children:e("standalone.settings.disablePassword")})]})]})}),s.jsx(bt,{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(bt,{title:e("standalone.settings.machineSection"),description:e("standalone.settings.machineDescription"),children:s.jsx(KS,{ides:t,emptyMessage:e("standalone.settings.daemonNotConnected")})}),s.jsx(bt,{title:e("standalone.settings.appearanceSection"),description:e("standalone.settings.appearanceDescription"),children:s.jsx(mC,{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(UI,{value:f,savedValue:fs(d==null?void 0:d.standaloneFontPreferences),saving:w,error:x,notice:b,onChange:g,onSave:()=>{J()},onResetToSaved:re,onResetToDefaults:Y})]})})}),s.jsx(bt,{title:e("standalone.settings.notificationsSection"),description:e("standalone.settings.notificationsDescription"),children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(US,{}),s.jsx(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Vf,{size:15})," ",e("standalone.settings.soundEffectsLabel")]}),description:e("standalone.settings.soundEffectsDescription"),checked:$,onChange:U})]})}),s.jsx(bt,{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(Lf,{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(is,{type:"text",className:"w-48 text-right",placeholder:e("standalone.settings.displayNamePlaceholder"),value:i,onChange:O=>c(O.target.value),onBlur:P,onKeyDown:O=>{O.key==="Enter"&&O.currentTarget.blur()}})]})})})]})}const qI=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],Yn="adhdev_onboarding_done",zI=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],KI={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function VI({onDone:e}){const{t}=Ne("common"),[n,r]=l.useState([]),[a,o]=l.useState(new Set(qI)),[i,c]=l.useState(!0),[u,p]=l.useState(null),[d,m]=l.useState(!1),[f,g]=l.useState(null),[w,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(C=>{if(!C.ok)throw new Error(`HTTP ${C.status}`);return C.json()}).then(C=>{v||r(C.providers??[])}).catch(C=>{v||p(C instanceof Error?C.message:String(C))}).finally(()=>{v||c(!1)}),()=>{v=!0}},[]);const x=n.filter(v=>w==="all"||v.category===w),k=["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 C=new Set(N);return C.has(v)?C.delete(v):C.add(v),C})},[]),S=l.useCallback(async()=>{if(a.size===0){localStorage.setItem(Yn,"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(C){v.push({type:N,ok:!1,error:C instanceof Error?C.message:String(C)})}g(v),m(!1),v.every(N=>N.ok)&&localStorage.setItem(Yn,"1")},[a,e]),j=l.useCallback(()=>{localStorage.setItem(Yn,"1"),e()},[e]),y=l.useCallback(()=>{f&&f.every(v=>v.ok)?e():d||j()},[f,d,e,j]);return s.jsx(_u,{open:!0,onClose:y,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(ks,{variant:"secondary",size:"sm",onClick:j,disabled:d,children:t("standalone.onboarding.skip")}),s.jsx(ks,{variant:"primary",size:"sm",onClick:()=>{f?(localStorage.setItem(Yn,"1"),e()):S()},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:zI.map(v=>{const N=v.key==="all"?n.length:n.filter(C=>C.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 ${w===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(Ot,{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:k.map(v=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:KI[v.category]??v.category}),s.jsx("div",{className:"grid gap-1.5",children:v.items.map(N=>{var R,E;const C=a.has(N.type),A=f==null?void 0:f.find(_=>_.type===N.type),M=((R=N.manifest)==null?void 0:R.icon)??"📦",T=((E=N.manifest)==null?void 0:E.details)??"";return s.jsxs("label",{className:`flex items-center gap-3 px-3 py-2 rounded-xl border cursor-pointer transition-colors ${C?"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:C,onChange:()=>b(N.type),disabled:d,className:"shrink-0"}),s.jsx("span",{className:"text-base shrink-0",children:M}),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}),T&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:T})]}),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 YI(){try{return localStorage.getItem(Yn)==="1"}catch{return!1}}jS();aC();fy();$I();const JI=Wd({baseUrl:"",getToken:xl});function QI({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 hs("/auth/session")).json();r(h)}catch(w){p(w instanceof Error?w.message:String(w))}finally{o(!1)}};l.useEffect(()=>{f()},[]),l.useEffect(()=>{if(!n||n.required&&!n.authenticated)return;let w=!1;return(async()=>{try{const h=await hs("/api/v1/standalone/preferences");if(!h.ok)return;const x=await h.json();if(w)return;const k=fs(x.standaloneFontPreferences);Bs(k),ki(k)}catch{}})(),()=>{w=!0}},[n==null?void 0:n.authenticated,n==null?void 0:n.required]);const g=async w=>{w.preventDefault(),m(!0),p("");try{const h=await hs("/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(""),oh()}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(is,{type:"password",value:i,onChange:w=>c(w.target.value),placeholder:t("standalone.auth.passwordPlaceholder"),autoFocus:!0}),s.jsx(ks,{type:"submit",variant:"primary",disabled:d||!i,className:"justify-center",children:t(d?"standalone.auth.signingIn":"standalone.auth.unlock")})]}):s.jsx(Ot,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),u&&s.jsx(Ot,{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 Ed(){const{t:e}=Ne("common"),{ides:t,initialLoaded:n}=gs();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(Uo,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Uo,{to:"/dashboard",replace:!0})}function XI(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let n=!1;if(!YI())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(VI,{onDone:()=>t(!1)}):null}function ZI(){const{t:e}=Ne("common"),{ides:t}=gs(),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}=Hp(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(hu,{promptSession:r,isSubmitting:i,error:o,onSubmit:c,onCancel:u})]}):null}function eD(){const e=l.useMemo(()=>({sendCommand:rr,sendData:wi,sendPtyInput:ih}),[]);return s.jsx(zh,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(mf,{client:JI,children:s.jsx(QI,{children:s.jsx(DI,{children:s.jsx(ff,{value:e,children:s.jsxs(vf,{sendDaemonCommand:rr,children:[s.jsx(ZI,{}),s.jsxs(HI,{children:[s.jsx(XI,{}),s.jsxs(Kh,{children:[s.jsx(js,{path:"/dashboard",element:s.jsx(nT,{})}),s.jsx(js,{path:"/machine",element:s.jsx(Ed,{})}),s.jsx(js,{path:"/machines/:id",element:s.jsx(uP,{})}),s.jsx(js,{path:"/machines",element:s.jsx(Ed,{})}),s.jsx(js,{path:"/about",element:s.jsx(WI,{})}),s.jsx(js,{path:"/settings",element:s.jsx(GI,{})}),s.jsx(js,{path:"/mesh",element:s.jsx(kI,{children:s.jsx(vI,{})})}),s.jsx(js,{path:"*",element:s.jsx(Uo,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}vk({connectionManager:ms});Vh(document.getElementById("root")).render(s.jsx(eD,{}));