@adhdev/daemon-standalone 0.9.82-rc.561 → 0.9.82-rc.563

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.
@@ -0,0 +1,121 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/terminal-BNQ0ACgR.js","assets/vendor-D2oK2clQ.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
2
+ var gm=Object.defineProperty;var xm=(e,t,n)=>t in e?gm(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var st=(e,t,n)=>xm(e,typeof t!="symbol"?t+"":t,n);import{r as l,j as s,u as Le,M as wi,a as ym,b as vm,c as wm,t as km,d as Sm,i as wt,e as Cm,f as fn,R as Rt,g as pr,h as Fa,k as Ha,D as jm,E as Nm,l as Am,C as Tm,m as Im,B as Mm,n as Dm,o as Pm,p as Lm,H as vr,P as Cs,q as Rm,s as Em,v as _m,w as $m,x as Bm,y as Fm,z as ki,A as Hm,F as Wm,G as Om,I as Um,J as js,N as Wa,K as Gm}from"./vendor-D2oK2clQ.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const a of o)if(a.type==="childList")for(const i of a.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(o){const a={};return o.integrity&&(a.integrity=o.integrity),o.referrerPolicy&&(a.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?a.credentials="include":o.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function r(o){if(o.ep)return;o.ep=!0;const a=n(o);fetch(o.href,a)}})();function Km(e={}){const t=Math.max(1,Math.floor(e.capacity||200)),n=[];return{record(r){const o={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(o),n.length>t&&n.splice(0,n.length-t),o},list(r={}){const o=Math.max(1,Math.floor(r.limit||100));return n.filter(a=>!r.interactionId||a.interactionId===r.interactionId).filter(a=>!r.topic||a.topic===r.topic).filter(a=>!r.kind||a.kind===r.kind).slice(-o).map(a=>({...a,payload:a.payload?{...a.payload}:{}}))},clear(){n.splice(0,n.length)}}}const bn=Km();function Sl(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 zm(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function Cl(e){return Array.isArray(e)?[...e]:[]}function Pd(e,t){if(!e)return t??null;const n=Object.prototype.hasOwnProperty.call(e,"messages"),r=Object.prototype.hasOwnProperty.call(e,"activeModal"),o=typeof e.id=="string"?e.id.trim():"",a=typeof(t==null?void 0:t.id)=="string"?t.id.trim():"",i=!!o&&!!a&&o!==a;return t?{...t,...e,messages:n?Cl(e.messages):i?[]:t.messages,activeModal:r?e.activeModal??null:t.activeModal,inputContent:e.inputContent??t.inputContent}:{...e,...n?{messages:Cl(e.messages)}:{},...r?{activeModal:e.activeModal??null}:{}}}function zn(e,t){const n=zm(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:Pd(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 Ld(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(o=>{const a=e.find(i=>i.id===o.id);return a?zn(o,a):o});if((n==null?void 0:n.preserveMissing)!==!1){const o=new Set(t.map(a=>a.id));for(const a of e)o.has(a.id)||r.push(a)}return r}function jl(e){return!!e&&typeof e=="object"&&"text"in e}function Si(e,t){const n=(t==null?void 0:t.joiner)??" ",r=(t==null?void 0:t.normalizeWhitespace)??!1;let o="";return typeof e=="string"?o=e:Array.isArray(e)?o=e.map(a=>typeof a=="string"?a:jl(a)?String(a.text||""):"").join(n):jl(e)?o=String(e.text||""):o=String(e||""),r?o.replace(/\s+/g," ").trim():o}function gn(e){return Si(e,{normalizeWhitespace:!0})}function qm(e){let t="";for(let n=0;n<e.length;n++){const r=e[n],o=e.charCodeAt(n);if(!(o<=31&&r!==`
3
+ `&&r!==" ")&&!(o>=127&&o<=159)&&!(o>=8203&&o<=8207||o>=8234&&o<=8238||o===8288||o===65279)&&o!==65533){if(o===65038||o===65039){const a=t.length>0?t[t.length-1]:"";if(!a||a===`
4
+ `||a===" "||a===" ")continue}t+=r}}return t}function Nl(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 Rd(e,t,n){if(n.type!=="adhdev-daemon")return n;const r={...n},o=t.version??n.version??e.version,a=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 o&&(r.version=o),a&&(r.serverVersion=a),u&&(r.versionUpdateReason=u),o&&a&&o===a?(delete r.versionMismatch,delete r.serverVersion,delete r.versionUpdateRequired,delete r.versionUpdateReason,r):((t.versionMismatch===!0||i&&o&&a&&o!==a)&&(r.versionMismatch=!0),c&&(r.versionUpdateRequired=!0),r)}function Vm(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 Uo(e){if(!e||typeof e!="object")return"";const t=e,n=Vm(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 Ym(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 o=Uo(r);for(let a=0;a<o.length;a+=1)n^=o.charCodeAt(a),n=Math.imul(n,16777619)>>>0}return{count:e.length,hash:n.toString(16).padStart(8,"0"),first:Uo(e[0]),last:Uo(e[e.length-1])}}function Oa(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function Ua(e,t,n){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(Oa(e)&&Oa(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)Ua(e[c],t[c],n);return}const r=e,o=t,a=new Set([...Object.keys(r),...Object.keys(o)]);for(const i of a)i!=="messages"&&Ua(r[i],o[i],n)}function Jn(e,t){return Array.isArray(e)?e.map(n=>Jn(n,t)):!e||typeof e!="object"?e:Oa(e)?Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[o])=>r.localeCompare(o)).map(([r,o])=>[r,r==="messages"?Ym(o,t):Jn(o,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 Jm(e,t){try{const n=new WeakSet;return Ua(e,t,n),JSON.stringify(Jn(e,n))===JSON.stringify(Jn(t,n))}catch{return!1}}function Ga(e,t,n){return Jm(e,t)?(e._lastUpdate=n,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function Ed(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function Qm(e,t,n){t[n]!==void 0&&(e[n]=t[n])}function Al(e,t,n,r){var u;const o=(u=t.chats)!=null&&u.length?t.chats:e.chats,a=Ld(e.childSessions,t.childSessions,{preserveMissing:r}),i=Pd(t.activeChat,e.activeChat),c=t.workspace||e.workspace;return Rd(e,t,{...e,...t,chats:o,childSessions:a,activeChat:i,workspace:c,_lastUpdate:n})}function Xm(e,t,n){var o,a;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=Ld(e.childSessions,t.childSessions,{preserveMissing:n})),(o=t.chats)!=null&&o.length&&!((a=e.chats)!=null&&a.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"])Qm(r,t,i);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(r.machineNickname=t.machineNickname),t.versionMismatch===!0&&(r.versionMismatch=!0),r}function Zm(e,t,n,r){const o=Xm(e,t,r),a=Object.keys(o).length>0?Rd(e,t,{...e,...o,_lastUpdate:n}):{...e,_lastUpdate:n};return Ga(e,a,n)}function ef(e){const t=new Set(e.map(a=>a.id)),n=new Set,r=new Set,o=new Set;for(const a of e){const i=Ed(a);i&&n.add(i),i&&a.type!=="adhdev-daemon"&&r.add(i),i&&a.type==="adhdev-daemon"&&a._sessionListAuthoritative&&o.add(i)}return{incomingIds:t,incomingDaemonIds:n,daemonIdsWithSessionEntries:r,daemonIdsWithAuthoritativeSessionList:o}}function tf(e,t,n,r,o,a){return!o.has(t)||!a.has(t)||r.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?n>1e4:e.transport==="cdp-page"?n>3e4:!1}function sf(e,t,n,r,o){return e.transport?n.has(t)&&!r.has(t)?!0:o.has(t):!1}function nf(e,t,n){var d,m;const r=Date.now(),o=new Set((n==null?void 0:n.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(f=>({...f,_lastUpdate:r}));const a=new Map;for(const f of t)a.set(f.id,f);const{incomingIds:i,incomingDaemonIds:c,daemonIdsWithSessionEntries:u,daemonIdsWithAuthoritativeSessionList:h}=ef(e);for(const f of e){const x=a.get(f.id);if(!x){a.set(f.id,{...f,_lastUpdate:r});continue}const w=Nl(f),p=Nl(x),y=Ed(f),k=!o.has(y);if(w>p){const S=Al(x,f,r,k);a.set(f.id,Ga(x,S,r));continue}if(w<p){a.set(f.id,Zm(x,f,r,k));continue}const b=f.timestamp||r,j=x._lastUpdate||x.timestamp||0;if(b>=j){const S=Al(x,f,r,k);a.set(f.id,Ga(x,S,r));continue}(d=f.chats)!=null&&d.length&&!((m=x.chats)!=null&&m.length)&&a.set(f.id,{...x,chats:f.chats})}for(const[f,x]of a){const w=x.daemonId||f.split(":")[0];if(!c.has(w))continue;if(o.has(w)&&h.has(w)&&!i.has(f)){a.delete(f);continue}const p=r-(x._lastUpdate||x.timestamp||0);tf(x,w,p,i,o,u)&&a.delete(f)}for(const[f,x]of a){const w=x.daemonId||f.split(":")[0];if(sf(x,w,c,u,a))continue;r-(x._lastUpdate||x.timestamp||0)>3e5&&x.status!=="online"&&a.delete(f)}return Array.from(a.values())}function rf(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 _d=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}),$d=l.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function of({children:e,connectionOverrides:t}){const[n,r]=l.useState([]),[o,a]=l.useState(!1),[i,c]=l.useState([]),[u,h]=l.useState(void 0),d=l.useRef(n);l.useEffect(()=>{d.current=n},[n]);const m=l.useCallback((k,b)=>{r(j=>{let S=!1;const v=j.map(g=>g.id!==k||g.chats===b?g:(S=!0,{...g,chats:b}));return S?v:j})},[]),f=l.useCallback((k,b)=>{r(j=>{const S=j.length===0?k:nf(k,j,b),v=!rf(j,S);return v&&bn.record({kind:"dashboard.entries_applied",payload:{incoming:Sl(k),next:Sl(S)}}),v?S:j})},[]),x=l.useCallback(()=>a(!0),[]),w=l.useMemo(()=>({injectEntries:f,markLoaded:x,getIdes:()=>d.current}),[f,x]),p=t,y=l.useMemo(()=>({ides:n,updateRouteChats:m,initialLoaded:o,toasts:i,setToasts:c,wsStatus:(p==null?void 0:p.wsStatus)??"connected",isConnected:(p==null?void 0:p.isConnected)??!0,connectionStates:(p==null?void 0:p.connectionStates)??{},connectionTransports:(p==null?void 0:p.connectionTransports)??{},showReconnected:(p==null?void 0:p.showReconnected)??!1,retryConnection:p==null?void 0:p.retryConnection,retryServerConnection:p==null?void 0:p.retryServerConnection,connectionLoginUrl:p==null?void 0:p.connectionLoginUrl,isP2PActive:(p==null?void 0:p.isP2PActive)??!1,p2pStates:(p==null?void 0:p.p2pStates)??{},userRole:p==null?void 0:p.userRole,connectionRetryStatuses:p==null?void 0:p.connectionRetryStatuses,userName:u,setUserName:h}),[n,m,o,i,p==null?void 0:p.wsStatus,p==null?void 0:p.isConnected,p==null?void 0:p.connectionStates,p==null?void 0:p.connectionTransports,p==null?void 0:p.showReconnected,p==null?void 0:p.retryConnection,p==null?void 0:p.retryServerConnection,p==null?void 0:p.connectionLoginUrl,p==null?void 0:p.isP2PActive,p==null?void 0:p.p2pStates,p==null?void 0:p.userRole,p==null?void 0:p.connectionRetryStatuses,u]);return s.jsx($d.Provider,{value:w,children:s.jsx(_d.Provider,{value:y,children:e})})}function gs(){return l.useContext(_d)}function or(){return l.useContext($d)}function Bd(e){const{baseUrl:t,getToken:n,onUnauthorized:r}=e;function o(c){return c.startsWith("http")?c:`${t}${c.startsWith("/")?"":"/"}${c}`}function a(c){const u=n==null?void 0:n(),h=o(c),d=c.startsWith("http")?new URL(h):new URL(h,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 h={"Content-Type":"application/json",...u.headers||{}},d=n==null?void 0:n();d&&(h.Authorization=`Bearer ${d}`);const m=o(c),f=new AbortController,x=setTimeout(()=>f.abort(),15e3);try{const w=await fetch(m,{...u,headers:h,signal:f.signal});if(w.status===401)throw r==null||r(),new Error("Unauthorized");if(!w.ok){const p=await w.json().catch(()=>({error:w.statusText}));throw new Error(p.error||`API Error: ${w.status}`)}return w.json()}finally{clearTimeout(x)}}return{getDaemons:()=>i("/api/v1/daemons"),getDaemonStatus:c=>i(`/api/v1/daemons/${c}/status`),sendCommand:(c,u,h={})=>i(`/api/v1/daemons/${c}/command`,{method:"POST",body:JSON.stringify({type:u,payload:h})}),execTerminal:(c,u,h)=>i(`/api/v1/daemons/${c}/terminal`,{method:"POST",body:JSON.stringify({command:u,name:h})}),sendAgentMessage:(c,u,h)=>i(`/api/v1/shortcuts/${c}/chat`,{method:"POST",body:JSON.stringify({agentType:u,message:h})}),getAgentStatus:c=>i(`/api/v1/shortcuts/${c}/status`),approveAgent:(c,u,h)=>i(`/api/v1/shortcuts/${c}/approve`,{method:"POST",body:JSON.stringify({agentType:u,action:h?"approve":"reject"})}),getMuxState:c=>i(`/api/v1/mux/${encodeURIComponent(c)}/state`),getMuxSocketInfo:c=>i(`/api/v1/mux/${encodeURIComponent(c)}/socket-info`),controlMux:(c,u,h={})=>i(`/api/v1/mux/${encodeURIComponent(c)}/control`,{method:"POST",body:JSON.stringify({type:u,payload:h})}),getMuxEventsUrl:c=>a(`/api/v1/mux/${encodeURIComponent(c)}/events`),getRuntimeEventsUrl:c=>a(`/api/v1/runtime/${encodeURIComponent(c)}/events`),request:i}}const af=Bd({baseUrl:"http://localhost:3847"}),lf=l.createContext(af);function cf({client:e,children:t}){return s.jsx(lf.Provider,{value:e,children:t})}const df={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Fd=l.createContext(df);function uf({value:e,children:t}){return s.jsx(Fd.Provider,{value:e,children:t})}function yt(){return l.useContext(Fd)}function Hd(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function hf(e){const t=Hd(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 pf(e){const[t,n]=l.useState(null),r=l.useCallback(async(i,c)=>{const u=m=>e(i,"launch_cli",{...c,...m}),h=await u({}),d=hf(h);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)}})}):h},[e]),o=l.useCallback(async()=>{const i=t;if(i){n(null);try{const c=await i.retry(),u=Hd(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]),a=l.useCallback(()=>{const i=t;i&&(n(null),i.resolve({ok:!1,cancelled:!0}))},[t]);return{launchCli:r,pending:t,confirm:o,cancel:a}}function mf({providerType:e,sourceName:t,description:n,onConfirm:r,onCancel:o}){const{t:a}=Le("common"),i=l.useRef(null);return l.useEffect(()=>{var c;(c=i.current)==null||c.focus()},[]),l.useEffect(()=>{const c=u=>{u.key==="Escape"&&o()};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[o]),s.jsx("div",{role:"dialog","aria-modal":"true","aria-label":a("machine.confirmExternal.dialogAria"),className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",onClick:o,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:a("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??a("machine.confirmExternal.description")}),s.jsx("p",{className:"text-text-secondary",children:a("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:o,className:"px-3 py-1 text-sm rounded border border-border-default hover:bg-surface-secondary",children:a("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:a("machine.confirmExternal.activate")})]})]})})}const Wd=l.createContext(null);function ff({sendDaemonCommand:e,children:t}){const n=pf(e),r=l.useMemo(()=>({launchCli:n.launchCli}),[n.launchCli]);return s.jsxs(Wd.Provider,{value:r,children:[t,n.pending&&s.jsx(mf,{providerType:n.pending.providerType,sourceName:n.pending.sourceName,description:n.pending.description,onConfirm:n.confirm,onCancel:n.cancel})]})}function ko(){const e=l.useContext(Wd);return e||{launchCli:async()=>{throw new Error("useLaunchCli must be used inside <LaunchCliProvider>")}}}function Od(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function bf(e,t,n){return Number(e.receivedAt||n[to(e)]||0)||0}function Ud(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function gf(e){return Array.isArray(e)&&e.some(t=>!!t&&typeof t=="object"&&"type"in t)}function Pn(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 Go(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 xf(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 to(e,t){const n=e,r=Si(e.content,{joiner:`
5
+ `}),o=[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(o.length>0)return o.join("|");const a=e.receivedAt||e.timestamp||0;return[e.role?`role:${e.role}`:"role:",`chash:${xf(r)}`,a?`ts:${a}`:""].filter(Boolean).join("|")}function yf(e){let t=2166136261;for(const n of e){const r=String(n||"");for(let o=0;o<r.length;o+=1)t^=r.charCodeAt(o),t=Math.imul(t,16777619)>>>0;t^=255,t=Math.imul(t,16777619)>>>0}return t.toString(16).padStart(8,"0")}function vf(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function Gd(e){return e?yf([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),vf(e.content)]):""}const Ci=200,wf=80,Tl=650,Ln=new Map;function so(e,t){if(!e)return!1;const n=String(e.messageFingerprint||"");return n?n===String(t||""):!0}function kf(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}:${Gd(r)}`}function Sf(e,t,n,r){return e||!t?!1:so(n,r)}function Cf({scrollTop:e,scrollHeight:t,clientHeight:n,topThresholdPx:r=wf,bottomThresholdPx:o=Ci}){const a=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:a>r,showBottom:Math.max(0,i-a-c)>o}}function jf(e){return Cf({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function qn(e,t=Ci){return!!e&&e.fromBottom>=t}function Nf(e,t){return so(e,t)?!qn(e):!0}function Af({hasSelection:e,userScrolledUp:t,hasChatContentChanged:n=!0}){return!(e||t||!n)}function Tf({hasSelection:e,userScrolledUp:t,contextAutoScrollActive:n}){return e?!1:n||!t}function Ko(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 Kd({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 ji({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 Is({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 zd({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 If({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 Mf({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 Vd({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 Df({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 So({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 Ni({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 Pf({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 Lf({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 Ai({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 Co({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 ar({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 Rf({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 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("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 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:"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 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("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("polyline",{points:"12 6 12 12 16 14"})]})}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("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 _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("rect",{x:"3",y:"5",width:"18",height:"14",rx:"2"}),s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"})]})}function Qd({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 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("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 $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("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 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("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 Ff({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 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("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 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:"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 Wf({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 Of({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 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:"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 Zd({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 Gf({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 Kf({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 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("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 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("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 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("polyline",{points:"9 14 4 9 9 4"}),s.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}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("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 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:"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 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("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 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("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 eu="adhdev_chat_activity_visible",Il=new Set(["hidden","debug","internal"]),Ml=new Set(["visible","user","chat"]),Zf=new Set(["debug","trace","internal"]),eb=new Set(["tool_call","terminal_command","runtime_activity"]),tb=new Set(["runtime_status","provider_chrome","control"]),sb=new Set(["thought","tool","terminal"]);function tu(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 zo(e,t,n){return e[n]??(t==null?void 0:t[n])}function Dl(e,t,n){const r=e;return n.some(o=>r[o]===!0||(t==null?void 0:t[o])===!0)}function nb(e,t){const n=rn(e.kind);return n||(t==="tool"?"tool":"standard")}function qo(e,t,n){const r=tu(e),o=typeof(r==null?void 0:r.label)=="string"?r.label.trim():"";return o||(t==="terminal"||n==="terminal_command"?"Terminal":t==="tool"||n==="tool_call"?"Tool":t==="thought"?"Thought":n==="runtime_activity"?"Runtime":"Activity")}function rb(e){const t=e.content;return Array.isArray(t)&&t.some(n=>!!n&&typeof n=="object"&&n.type!=="text")}function Di(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal"};const t=tu(e),n=rn(e.role),r=nb(e,n),o=rn(zo(e,t,"visibility")),a=rn(e.transcriptVisibility??(t==null?void 0:t.transcriptVisibility)??o),i=rn(zo(e,t,"audience")),c=rn(zo(e,t,"source")),u=Il.has(o)||Il.has(a)||Zf.has(i)||Dl(e,t,["internal","isInternal","debug","statusOnly","controlOnly"]),h=Ml.has(o)||Ml.has(a)||i==="chat"||Dl(e,t,["userFacing"]),d=sb.has(r)||eb.has(c);if(u)return{surface:d?"activity":"internal",isUserFacing:!1,isActivityFacing:d,isInternal:!d,role:n,kind:r,label:qo(e,r,c)};if(h)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:n,kind:r,label:qo(e,r,c)};if((n==="system"||r==="system")&&rb(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:n,kind:r,label:"Chat"};if(tb.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:qo(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 ob(e){return(Array.isArray(e)?e:[]).filter(t=>Di(t).isUserFacing)}function su(e){return(Array.isArray(e)?e:[]).filter(t=>Di(t).isActivityFacing)}function nu(e){const t=e.content;return typeof t=="string"?t:(()=>{try{return JSON.stringify(t??"")}catch{return String(t??"")}})()}function ab(e){return`${String(e.role||"")}::${nu(e)}`}function ib(e){if(e.length<2)return e;const t=[];let n="";for(const r of e){const o=ab(r);nu(r).trim().length>0&&o===n||(t.push(r),n=o)}return t}function lb(e,t,n){return!n||t.length===0?e:[...e,...t].sort((r,o)=>{const a=Number(r.receivedAt??r.timestamp??0)||0,i=Number(o.receivedAt??o.timestamp??0)||0;if(a!==i)return a-i;const c=Number(r.index??0)||0,u=Number(o.index??0)||0;return c-u})}function Pl(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(eu))==="1"}catch{return!1}}function cb({text:e}){const{t}=Le("common"),[n,r]=l.useState(!1),o=l.useCallback(()=>{navigator.clipboard.writeText(e).catch(()=>{}),r(!0),setTimeout(()=>r(!1),1500)},[e]);return s.jsx("button",{type:"button",onClick:o,"aria-label":t("chat.copyMessage"),className:"chat-copy-btn",children:n?s.jsx(Df,{size:11}):s.jsx(Vd,{size:11})})}const ru=[ym,{singleTilde:!1}],ou=[ru,vm,wm],db=[ru];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 Ll(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):Ud(e)?s.jsx(wi,{remarkPlugins:ou,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}const ub=l.memo(function({content:t,renderAsPreformatted:n,renderAsMarkdown:r}){return n?s.jsx("pre",{className:"chat-preformatted",children:t}):r?s.jsx(wi,{remarkPlugins:ou,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:Ll(String(n.text||""),t)},`text-${r}`);if(n.type==="image"){const o=Go(n),a=n.alt||n.description||Pn(n.uri,"image");return o?s.jsx("img",{src:o,alt:a,className:"max-w-full rounded-md border border-border-subtle"},`image-${r}`):s.jsx("div",{children:wr("Image",a,n.mimeType)},`image-fallback-${r}`)}if(n.type==="audio"){const o=Go(n);return o?s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx("audio",{controls:!0,src:o,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",Pn(n.uri,"audio"),n.transcript||n.mimeType)},`audio-fallback-${r}`)}if(n.type==="video"){const o=Go(n),a=n.title||n.name||n.alt||Pn(n.uri,"video"),i=[n.transcript,n.description,n.mimeType].filter(Boolean).join(`
6
+ `);return s.jsxs("div",{className:"flex flex-col gap-1",children:[o?s.jsx("video",{controls:!0,src:o,poster:n.posterUri,className:"max-w-full rounded-md border border-border-subtle"}):wr("Video",a,i),o&&i?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:i}):null]},`video-${r}`)}if(n.type==="resource_link"){const o=n.title||n.name||Pn(n.uri,"resource"),a=[n.description,n.mimeType].filter(Boolean).join(`
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:o}):wr("Resource",o,a),n.uri&&a?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:a}):null]},`resource-link-${r}`)}if(n.type==="resource"&&n.resource){const o=Pn(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:o}),Ll(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:o},`resource-uri-${r}`)}return null})})}const hb=l.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(wi,{remarkPlugins:db,children:t.text}),s.jsx("span",{className:"action-time",children:Od(t.timestamp)})]})},(e,t)=>e.log===t.log);function Rl(e){const t=e.meta;return[Gd(e),e.kind||"",e.senderName||"",e.bubbleId||"",e.bubbleState||"",e.visibility||"",e.transcriptVisibility||"",e.audience||"",e.source||"",e.userFacing===void 0?"":String(e.userFacing),e.internal===void 0?"":String(e.internal),e.isInternal===void 0?"":String(e.isInternal),e.debug===void 0?"":String(e.debug),t?String(t.label??""):"",t?String(t.isRunning??""):"",t?String(t.renderMode??""):""].join("")}const pb=l.memo(function({message:t,receivedAt:n,agentName:r,userName:o,isCliMode:a,isTextExpanded:i,onToggleTextExpanded:c}){var C,A,T;const u=(t.role||"").toLowerCase(),h=u==="user"||u==="human",d=t.kind||(u==="tool"?"tool":"standard"),m=Di(t),f=gf(t.content)?t.content:null,x=!!(f!=null&&f.some(M=>M.type!=="text")),w=Si(t.content,{joiner:`
8
+ `});if(m.isActivityFacing&&d!=="thought"&&d!=="tool"&&d!=="terminal"){const M=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:M})]}),x&&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 M=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(Ff,{size:13}),s.jsx("span",{children:M})]}),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"})]}),x&&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 M=(A=t.meta)!=null&&A.isRunning?"⏳":"✅",L=typeof((T=t.meta)==null?void 0:T.label)=="string"?t.meta.label:"Ran command";return s.jsxs("div",{className:"self-start chat-msg-terminal","data-chat-activity-row":m.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-header",children:[s.jsx("span",{children:M}),s.jsx("span",{children:L})]}),x&&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:x&&f?s.jsx(Rn,{parts:f,renderAsPreformatted:!1}):w.slice(0,100)});const p=t.meta,k=(typeof(p==null?void 0:p.renderMode)=="string"?p.renderMode.trim():"")==="preformatted",b=w,j=!1,S=b,v=k,g=!h&&!v&&Ud(S),N=["chat-message-row",h?"chat-message-row-user self-end":"chat-message-row-assistant self-start"].join(" ");return s.jsx("div",{className:N,children:(b||x||h)&&s.jsxs("div",{className:`chat-bubble ${h?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${b||x?"mb-1.5":"mb-0"}`,children:[s.jsx("span",{className:"chat-sender",children:h?o||"You":t.senderName||r}),s.jsxs("span",{className:"chat-bubble-header-end",children:[(b||x)&&s.jsx(cb,{text:w}),n!=null&&s.jsx("span",{className:"chat-time",children:Od(n)})]})]}),(b||x)&&s.jsx("div",{className:"chat-markdown",children:x&&f?s.jsx(Rn,{parts:f,renderAsPreformatted:v}):s.jsx(ub,{content:S,renderAsPreformatted:v,renderAsMarkdown:g})}),j]})})},(e,t)=>(e.message===t.message||Rl(e.message)===Rl(t.message))&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded),mb=l.forwardRef(function({messages:t,actionLogs:n,agentName:r="Agent",userName:o,isCliMode:a=!1,isWorking:i=!1,contextKey:c="",receivedAtMap:u={},lastMessageHash:h,showActivityMessages:d=!1,emptyState:m,onLoadMore:f,isLoadingMore:x,hasMoreHistory:w,hiddenLiveCount:p=0,loadError:y,scrollToBottomRequestNonce:k,isVisible:b=!0},j){const{t:S}=Le("common"),v=l.useRef(null),g=l.useRef(null),N=l.useRef(null),C=l.useRef(0),A=l.useRef(""),T=l.useRef(""),M=l.useRef(!1),L=l.useRef(null),P=l.useRef(!1),B=l.useRef(null),K=l.useRef(!1),[F,R]=l.useState(new Set),[Q,E]=l.useState({showTop:!1,showBottom:!1}),I=l.useRef(!1),$=l.useRef(!1),D=l.useRef(b),U=l.useRef(b),Y=l.useRef(null);U.current=b;const ae=()=>{const _=v.current;return _?_.scrollHeight-_.scrollTop-_.clientHeight<Ci:!0},z=l.useCallback(()=>{const _=v.current,te=_?jf(_):{showTop:!1,showBottom:!1};E(ve=>ve.showTop===te.showTop&&ve.showBottom===te.showBottom?ve:te)},[]),X=l.useCallback((_="auto")=>{var ve;const te=v.current;te&&(te.scrollTo({top:te.scrollHeight,behavior:_}),(ve=te.ownerDocument.defaultView)==null||ve.requestAnimationFrame(()=>z()))},[z]),de=l.useCallback((_="auto")=>{var ve;const te=v.current;te&&(te.scrollTo({top:0,behavior:_}),(ve=te.ownerDocument.defaultView)==null||ve.requestAnimationFrame(()=>z()))},[z]),re=l.useCallback(()=>{var H;const _=v.current,te=(H=window.getSelection)==null?void 0:H.call(window);if(!_||!te||te.rangeCount===0||te.isCollapsed){K.current=!1;return}const ve=te.anchorNode,ce=te.focusNode;K.current=!!(ve&&ce&&_.contains(ve)&&_.contains(ce))},[]),W=l.useMemo(()=>{const _=ob(t),te=su(t);return ib(lb(_,te,d))},[t,d]),oe=W.length===t.length?h:void 0,V=kf(W,oe),ie=l.useCallback(()=>{const _=v.current;if(!_||!c||!U.current)return;const te={top:_.scrollTop,fromBottom:Math.max(0,_.scrollHeight-_.scrollTop-_.clientHeight),messageFingerprint:V};Y.current={contextKey:c,snapshot:te},Ln.set(c,te)},[c,V]),ke=l.useCallback((_="auto")=>{L.current!=null&&cancelAnimationFrame(L.current),L.current=requestAnimationFrame(()=>{L.current=null,X(_)})},[X]),xe=l.useCallback(()=>{I.current=!1,P.current=!0,$.current=!0,B.current!=null&&window.clearTimeout(B.current),B.current=window.setTimeout(()=>{P.current=!1,B.current=null},Tl)},[]);l.useEffect(()=>{const _=!M.current,te=T.current!==c;if(T.current=c,_||te){M.current=!0;const ce=c?Ln.get(c):null,H=!!ce&&so(ce,V);I.current=H?qn(ce):!1,P.current=Nf(ce,V),K.current||(H?requestAnimationFrame(()=>{const fe=v.current;fe&&(Ko(fe,ce),I.current=qn(ce),z(),$.current=!0)}):ke("auto")),C.current=W.length,A.current=V;return}W.length>C.current;const ve=V!==A.current;Af({hasSelection:K.current,userScrolledUp:I.current,hasChatContentChanged:ve})&&ke("auto"),C.current=W.length,A.current=V},[V,c,W.length,ke,z]),l.useEffect(()=>{k&&(xe(),K.current||ke("auto"))},[xe,ke,k]),l.useEffect(()=>{const _=D.current;_&&!b&&ie(),U.current=b,D.current=b;const te=c?Ln.get(c):null;if(Sf(_,b,te,V)){if(!te)return;I.current=qn(te),P.current=!1,K.current||requestAnimationFrame(()=>{const ve=v.current;ve&&(Ko(ve,te),z())});return}},[b,c,V,xe,ie,ke,z]),l.useEffect(()=>()=>{const _=Y.current;_&&Ln.set(_.contextKey,_.snapshot),L.current!=null&&cancelAnimationFrame(L.current),B.current!=null&&window.clearTimeout(B.current)},[]),l.useEffect(()=>{const _=g.current,te=v.current;if(!_||!te)return;const ve=()=>{B.current!=null&&window.clearTimeout(B.current),B.current=window.setTimeout(()=>{P.current=!1,B.current=null},Tl)},ce=new ResizeObserver(()=>{z();const H=P.current;Tf({hasSelection:K.current,userScrolledUp:I.current,contextAutoScrollActive:H})&&(ke("auto"),H&&ve())});return ce.observe(_),te!==_&&ce.observe(te),()=>{ce.disconnect(),B.current!=null&&(window.clearTimeout(B.current),B.current=null)}},[ke,c,z]),l.useImperativeHandle(j,()=>({scrollToBottom:(_="smooth")=>{X(_)}}),[X]),l.useEffect(()=>{const _=v.current;if(!_)return;let te;const ve=()=>{ie(),clearTimeout(te),te=setTimeout(()=>{I.current=!ae(),z()},50)};return _.addEventListener("scroll",ve,{passive:!0}),()=>{_.removeEventListener("scroll",ve),clearTimeout(te)}},[ie,z]),l.useEffect(()=>(document.addEventListener("selectionchange",re),()=>document.removeEventListener("selectionchange",re)),[re]);const Se=l.useRef(0),pe=l.useRef(!1);l.useEffect(()=>{const _=v.current;if(!_||!pe.current||Se.current===0)return;const te=_.scrollHeight-Se.current;te>0&&(_.scrollTop=te),z(),ie(),Se.current=0,pe.current=!1},[W.length,ie,z]),l.useEffect(()=>{if($.current||!c)return;const _=Ln.get(c),te=v.current;if(!(!_||!te)){if(!so(_,V)){X("auto"),$.current=!0;return}Ko(te,_),I.current=qn(_),z(),$.current=!0}},[c,V,W.length,X,z]);const G=()=>{const _=v.current;_&&(Se.current=_.scrollHeight),pe.current=!0,f==null||f()},O=()=>{I.current=!0,de("smooth"),ie()},Z=()=>{xe(),X("smooth"),ie()},q=l.useMemo(()=>{const _=W.map((H,fe)=>({type:"message",data:H,index:fe,ts:bf(H,fe,u)}));if(!n||n.length===0)return _;const te=[...n].sort((H,fe)=>H.timestamp-fe.timestamp).map((H,fe)=>({type:"action",data:H,index:fe,ts:H.timestamp})),ve=[];let ce=0;for(const H of _){for(;ce<te.length&&H.ts>0&&te[ce].ts<H.ts;)ve.push(te[ce++]);ve.push(H)}for(;ce<te.length;)ve.push(te[ce++]);return ve},[W,n,u]),me=p>0||!!w,Te=p>0?p>80?S("chatList.showEarlierMessagesHidden",{count:Math.min(p,80),total:p}):S("chatList.showEarlierMessages",{count:Math.min(p,80)}):y?S("chatList.loadErrorRetry",{error:y}):S("chatList.loadOlderMessages");return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:v,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:g,className:"chat-container-content",children:[x&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:S("chatList.loadingOlderMessages")}),me&&!x&&s.jsx("div",{className:"text-center py-2",children:s.jsx("button",{type:"button",onClick:G,className:`text-[11px] rounded-xl px-4 py-1.5 cursor-pointer border transition-all ${y&&p===0?"bg-transparent border-yellow-500/30 text-yellow-400 opacity-80 hover:opacity-100":"bg-transparent border-border-subtle text-text-muted opacity-70 hover:opacity-100 hover:border-accent/40"}`,children:Te})}),q.length===0&&!me&&(m||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:S("chatList.waitingForMessages")})),q.map(_=>{if(_.type==="action"){const je=_.data;return s.jsx(hb,{log:je},`action-${_.index}`)}const te=_.data;_.index;const ve=to(te),ce=te.receivedAt||u[ve],H=`${c}-${ve}`,fe=F.has(H);return s.jsx(pb,{message:te,receivedAt:ce,agentName:r,userName:o,isCliMode:a,isTextExpanded:fe,onToggleTextExpanded:()=>R(je=>{const Ce=new Set(je);return fe?Ce.delete(H):Ce.add(H),Ce})},`msg-${ve}`)}),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:S("chatList.agentGenerating")})]})}),s.jsx("div",{className:"min-h-10",ref:N})]})}),(Q.showTop||Q.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":S("chatList.jumpToTop"),children:[Q.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:O,"aria-label":S("chatList.jumpToOldestMessages"),title:S("chatList.jumpToTop"),children:S("chatList.top")}),Q.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:Z,"aria-label":S("chatList.jumpToLatestMessages"),title:S("chatList.jumpToBottom"),children:S("chatList.latest")})]})]})}),fb=l.memo(mb,(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),bb="modulepreload",gb=function(e){return"/"+e},El={},xb=function(t,n,r){let o=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"));o=Promise.allSettled(n.map(u=>{if(u=gb(u),u in El)return;El[u]=!0;const h=u.endsWith(".css"),d=h?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const m=document.createElement("link");if(m.rel=h?"stylesheet":bb,h||(m.as="script"),m.crossOrigin="",m.href=u,c&&m.setAttribute("nonce",c),document.head.appendChild(m),h)return new Promise((f,x)=>{m.addEventListener("load",f),m.addEventListener("error",()=>x(new Error(`Unable to preload CSS for ${u}`)))})}))}function a(i){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=i,window.dispatchEvent(c),!c.defaultPrevented)throw i}return o.then(i=>{for(const c of i||[])c.status==="rejected"&&a(c.reason);return t().catch(a)})};let _l=!1;const au=l.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:n,fontSize:r=13,readOnly:o=!1,sizingMode:a="measured"},i)=>{const c=l.useRef(null),[u,h]=l.useState(null),d=l.useRef([]),m=l.useRef(!1),f=l.useRef(!1),x=l.useRef(!1),w=l.useRef(!1),p=()=>{const y=c.current;if(y){m.current&&(y.clear(),m.current=!1);for(const k of d.current)y.write(k.data,k.onProcessed);d.current=[],f.current&&(y.fit(),f.current=!1),x.current&&(y.bumpResize(),x.current=!1),w.current&&(y.scrollToTop(),w.current=!1)}};return l.useImperativeHandle(i,()=>({write:(y,k)=>{c.current?c.current.write(y,k):d.current.push({data:y,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:(y,k)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(y,k)},fit:()=>{c.current?c.current.fit():f.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():x.current=!0},scrollToTop:()=>{c.current?c.current.scrollToTop():w.current=!0},getSelection:()=>{var y,k;return((k=(y=c.current)==null?void 0:y.getSelection)==null?void 0:k.call(y))||""},getVisibleText:()=>{var y,k;return((k=(y=c.current)==null?void 0:y.getVisibleText)==null?void 0:k.call(y))||""}}),[]),l.useEffect(()=>{u&&p()},[u]),l.useEffect(()=>{let y=!1;return xb(()=>import("./terminal-BNQ0ACgR.js"),__vite__mapDeps([0,1,2])).then(k=>{_l||(_l=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),y||h(()=>k.GhosttyTerminalView)}).catch(k=>{console.error("[CliTerminal] failed to load terminal renderer",k)}),()=>{y=!0}},[]),u?s.jsx(u,{ref:c,onInput:e,onViewportMetrics:t,onScrollMetrics:n,fontSize:r,readOnly:o,sizingMode:a,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"}})});au.displayName="CliTerminal";function Ht(...e){return km(Sm(e))}const yb={lg:"rounded-lg",xl:"rounded-xl","2xl":"rounded-2xl"},vb={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,...o},a){return s.jsx("div",{ref:a,className:Ht("border border-border-subtle bg-bg-secondary",yb[t],vb[n],r),...o})});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 $l({value:e,max:t,label:n,color:r="#8b5cf6",detail:o,compact:a=!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 a?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)`}})}),o&&s.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:o})]})}function wb({cursorPos:e,viewportRef:t,imgRef:n}){var b;if(!e||!n.current)return null;const r=n.current,o=r.getBoundingClientRect(),a=(b=t.current)==null?void 0:b.getBoundingClientRect();if(!a)return null;const i=r.naturalWidth||o.width,c=r.naturalHeight||o.height,u=i/c,h=o.width/o.height;let d,m,f,x;u>h?(d=o.width,m=o.width/u,f=0,x=(o.height-m)/2):(m=o.height,d=o.height*u,f=(o.width-d)/2,x=0);const w=o.left-a.left+f+d*e.nx,p=o.top-a.top+x+m*e.ny,y=Math.max(8,Math.min(a.width-8,w)),k=Math.max(8,Math.min(a.height-8,p));return s.jsxs("div",{style:{position:"absolute",left:y-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 kb({inputMode:e,onToggleInputMode:t,isImeOpen:n,setIsImeOpen:r,isMenuOpen:o,setIsMenuOpen:a,imeText:i,setImeText:c,handleImeSubmit:u,isConnActive:h,zoom:d,isMobile:m,mobileFillZoom:f,onZoomOut:x,onZoomReset:w,onZoomIn:p,transportType:y,screenshotUsage:k,lastActionStatus:b}){const{t:j}=Le("common");return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:S=>S.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:j(e==="mouse"?"remote.mouse":"remote.touch")})]}),s.jsxs("div",{className:"relative",children:[s.jsx("div",{onClick:()=>{r(S=>!S),a(!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:j("remote.typeAndEnter"),value:i,autoFocus:!0,onTouchStart:S=>S.stopPropagation(),onChange:S=>c(S.target.value),onKeyDown:S=>{u(S)},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:()=>{a(S=>!S),r(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${o?"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:h?"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:h?"#22c55e":"#eab308",boxShadow:h?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),s.jsx("span",{className:"text-[8px] font-extrabold",style:{color:h?"#22c55e":"#eab308"},children:j(h?"remote.connected":"remote.ws")})]}),d>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(d*100),"%"]}),y==="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:j("remote.directP2PTitle"),children:j("remote.direct")}),y==="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:j("remote.turnRelayTitle"),children:j("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:j("remote.dailyTurnTitle"),children:k.budgetExhausted?j("remote.turnBlocked"):j("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})]})]}),o&&s.jsxs("div",{onTouchStart:S=>S.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:j("remote.settings")}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:[j("remote.zoom")," ",d<=(m?f:1)+.01?j(m?"remote.fill":"remote.fit"):`${Math.round(d*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:S=>{S.stopPropagation(),x()},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:S=>{S.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:j(m?"remote.fill":"remote.fit")}),s.jsx("button",{onClick:S=>{S.stopPropagation(),p()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function Sb({waitingLabel:e,waitingHint:t,transportType:n}){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:"TURN relay active"})]})}function Cb(){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 Bl(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 mr(e,t){const n=l.useRef(null),r=l.useRef(0);l.useEffect(()=>{if(!Cb())return;r.current+=1;const o=n.current;if(!o){console.debug(`[render-trace] ${e}#${r.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(t).map(([i,c])=>[i,Bl(c)]))}),n.current=t;return}const a=Object.keys({...o,...t}).filter(i=>!Object.is(o[i],t[i]));a.length>0&&console.debug(`[render-trace] ${e}#${r.current}`,{changed:a,snapshot:Object.fromEntries(a.map(i=>[i,Bl(t[i])]))}),n.current=t})}function jb({containerRef:e,viewportRef:t,imgRef:n,inputMode:r,setInputMode:o,minZoom:a,zoomRef:i,panXRef:c,panYRef:u,setPanX:h,setPanY:d,setZoom:m,lastWheelTimeRef:f,onAction:x,setLastActionStatus:w,spawnRippleFromNormalized:p,clampPan:y,isMobile:k,mobileFillZoom:b}){const[j,S]=l.useState(null),v=l.useRef(null),g=l.useRef(null),N=l.useRef(null),C=l.useRef(!1),A=l.useRef(null),T=l.useRef(0),M=l.useRef(null),L=l.useRef(1),P=l.useRef({x:0,y:0}),B=l.useRef(!1),K=l.useRef(r),F=l.useRef(x),R=30,Q=550,E=18,I=60,$=400,D=12,U=()=>{if(v.current)return;const z={nx:.5,ny:.5};v.current=z,S(z)};return l.useEffect(()=>{K.current=r,r==="mouse"&&U()},[r]),l.useEffect(()=>{F.current=x},[x]),l.useEffect(()=>{const z=e.current;if(!z)return;const X=ie=>{if(!n.current)return null;const ke=n.current.getBoundingClientRect();return!ke.width||!ke.height?null:{nx:Math.max(0,Math.min(1,(ie.clientX-ke.left)/ke.width)),ny:Math.max(0,Math.min(1,(ie.clientY-ke.top)/ke.height))}},de=(ie,ke)=>{if(!n.current)return{dnx:0,dny:0};const xe=n.current,Se=xe.getBoundingClientRect(),pe=xe.naturalWidth||Se.width,G=xe.naturalHeight||Se.height,O=pe/G,Z=Se.width/Se.height;let q,me;return O>Z?(q=Se.width,me=Se.width/O):(me=Se.height,q=Se.height*O),{dnx:ie/q,dny:ke/me}},re=(ie,ke,xe)=>{if(xe<=1.05)return;const Se=-(ie-.5)*100,pe=-(ke-.5)*100,G=y(Se,pe,xe);(Math.abs(G.x-c.current)>.1||Math.abs(G.y-u.current)>.1)&&(h(G.x),d(G.y),c.current=G.x,u.current=G.y)},W=ie=>{const ke=t.current;if(ke&&ie.target instanceof Node&&ke.contains(ie.target))ie.preventDefault();else return;if(ie.touches.length===1){const xe=ie.touches[0];g.current={x:xe.clientX,y:xe.clientY,time:Date.now()},N.current={x:xe.clientX,y:xe.clientY},B.current||(C.current=!1),A.current=setTimeout(()=>{if(!C.current&&!B.current)if(C.current=!0,K.current==="mouse"){const Se=v.current||{nx:.5,ny:.5};w("Right Click"),p(Se.nx,Se.ny,"right"),F.current("input_click",{...Se,button:"right"}).catch(()=>{})}else{const Se=X(xe);Se&&(w("Right Click"),p(Se.nx,Se.ny,"right"),F.current("input_click",{...Se,button:"right"}).catch(()=>{}))}},500);return}if(ie.touches.length===2){A.current&&clearTimeout(A.current),C.current=!0,B.current=!0;const xe=ie.touches[1].clientX-ie.touches[0].clientX,Se=ie.touches[1].clientY-ie.touches[0].clientY;M.current=Math.sqrt(xe*xe+Se*Se),L.current=i.current,P.current={x:(ie.touches[0].clientX+ie.touches[1].clientX)/2,y:(ie.touches[0].clientY+ie.touches[1].clientY)/2}}},oe=ie=>{const ke=t.current;if(ke&&ie.target instanceof Node&&ke.contains(ie.target)&&ie.preventDefault(),ie.touches.length===1&&N.current){const xe=ie.touches[0],Se=xe.clientX-N.current.x,pe=xe.clientY-N.current.y;if(!C.current&&g.current){const G=xe.clientX-g.current.x,O=xe.clientY-g.current.y;Math.sqrt(G*G+O*O)>8&&(C.current=!0,A.current&&clearTimeout(A.current))}if(C.current)if(K.current==="mouse"){const G=de(Se,pe),O=v.current||{nx:.5,ny:.5},Z=Math.max(0,Math.min(1,O.nx+G.dnx)),q=Math.max(0,Math.min(1,O.ny+G.dny));v.current={nx:Z,ny:q},S({nx:Z,ny:q}),w(`Cursor: ${Math.round(Z*100)}%, ${Math.round(q*100)}%`),re(Z,q,i.current);const me=Date.now();me-f.current>=30&&(f.current=me,F.current("input_mouseMoved",{nx:Z,ny:q}).catch(()=>{}))}else if(i.current>1){const G=t.current;if(G){const O=G.clientWidth,Z=G.clientHeight,q=c.current+Se/O*100,me=u.current+pe/Z*100,Te=y(q,me,i.current);h(Te.x),d(Te.y),c.current=Te.x,u.current=Te.y}}else{const G=X(xe);if(G){const O=Date.now();O-f.current>=40&&(f.current=O,w("Scroll"),F.current("input_wheel",{nx:G.nx,ny:G.ny,deltaX:Math.round(-Se*2.5),deltaY:Math.round(-pe*2.5)}).catch(()=>{}))}}N.current={x:xe.clientX,y:xe.clientY};return}if(ie.touches.length===2&&M.current!==null){const xe=ie.touches[1].clientX-ie.touches[0].clientX,Se=ie.touches[1].clientY-ie.touches[0].clientY,G=Math.sqrt(xe*xe+Se*Se)/M.current,O=(ie.touches[0].clientX+ie.touches[1].clientX)/2,Z=(ie.touches[0].clientY+ie.touches[1].clientY)/2,q=O-P.current.x,me=Z-P.current.y,Te=Math.abs(G-1)>.03;if(K.current==="mouse"){if(Te){const _=Math.max(a,Math.min(5,L.current*G));m(_),i.current=_}else if(Math.abs(q)>2||Math.abs(me)>2){const _=v.current||{nx:.5,ny:.5},te=Date.now();te-f.current>=30&&(f.current=te,w("Scroll"),F.current("input_wheel",{nx:_.nx,ny:_.ny,deltaX:Math.round(-q*3),deltaY:Math.round(-me*3)}).catch(()=>{}))}}else{const _=Math.max(a,Math.min(5,L.current*G));m(_),i.current=_;const te=t.current;if(te&&_>1){const ve=te.clientWidth,ce=te.clientHeight,H=c.current+q/ve*100,fe=u.current+me/ce*100,je=y(H,fe,_);h(je.x),d(je.y),c.current=je.x,u.current=je.y}}P.current={x:O,y:Z}}},V=ie=>{var ke;if(A.current&&clearTimeout(A.current),M.current=null,ie.touches.length===1&&B.current){const xe=ie.touches[0];g.current={x:xe.clientX,y:xe.clientY,time:Date.now()},N.current={x:xe.clientX,y:xe.clientY},C.current=!0;return}if(ie.touches.length===0){if(B.current){B.current=!1,C.current=!1;return}if(ie.changedTouches.length===1){const xe=ie.changedTouches[0],Se=Date.now(),pe=Se-(((ke=g.current)==null?void 0:ke.time)||0),G=g.current?xe.clientX-g.current.x:0,O=g.current?xe.clientY-g.current.y:0,Z=Math.sqrt(G*G+O*O);if(K.current==="mouse"){if(pe<R||pe>Q||Z>E){C.current=!1;return}const q=v.current||X(xe);q&&(w(`Click: ${Math.round(q.nx*100)}%, ${Math.round(q.ny*100)}%`),p(q.nx,q.ny,"left"),F.current("input_click",{...q}).catch(()=>{}))}else{if(C.current){C.current=!1;return}if(pe<I||pe>$||Z>D){C.current=!1;return}const q=X(xe);if(!q)return;Se-T.current<300?(w("Double tap"),p(q.nx,q.ny,"double"),F.current("input_click",{...q,clickCount:2}).catch(()=>{}),T.current=0):(w(`Tap: ${Math.round(q.nx*100)}%, ${Math.round(q.ny*100)}%`),p(q.nx,q.ny,"left"),F.current("input_click",{...q}).catch(()=>{}),T.current=Se)}}C.current=!1}};return z.addEventListener("touchstart",W,{passive:!1}),z.addEventListener("touchmove",oe,{passive:!1}),z.addEventListener("touchend",V,{passive:!1}),()=>{z.removeEventListener("touchstart",W),z.removeEventListener("touchmove",oe),z.removeEventListener("touchend",V),A.current&&clearTimeout(A.current)}},[e,t,n,a,i,c,u,h,d,m,f,w,p,y]),{cursorPos:j,cursorPosRef:v,handleToggleInputMode:()=>{o(z=>{const X=z==="touch"?"mouse":"touch";return X==="mouse"&&U(),X})},handleZoomReset:()=>{const z=k?b:1;m(z),i.current=z,h(0),d(0),c.current=0,u.current=0}}}function iu({onAction:e,addLog:t,connState:n,connScreenshot:r,screenshotUsage:o,transportType:a}){const i=l.useRef(null),c=l.useRef(null),u=l.useRef(null),[h,d]=l.useState(null),[m,f]=l.useState(""),[,x]=l.useState(!1),[w,p]=l.useState([]),y=l.useRef(0),[k,b]=l.useState(!1),[j,S]=l.useState(!1),v=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[g,N]=l.useState(v?"mouse":"touch"),[C,A]=l.useState(1),T=l.useRef(!1),[M,L]=l.useState(1),[P,B]=l.useState(0),[K,F]=l.useState(0);mr("RemoteView",{connState:n,hasScreenshot:!!r,inputMode:g,zoom:M,panX:P,panY:K,isMenuOpen:k,isImeOpen:j});const R=l.useRef(0),Q=l.useRef(M),E=l.useRef(P),I=l.useRef(K);l.useEffect(()=>{Q.current=M},[M]),l.useEffect(()=>{E.current=P},[P]),l.useEffect(()=>{I.current=K},[K]),l.useEffect(()=>{var pe;(pe=i.current)==null||pe.focus()},[]);const $=n==="connected",D=r,U=$?"Connected. Waiting for first frame...":n==="connecting"?"Connecting to Host...":"Reconnecting to Host...",Y=$?"The remote stream is warming up":"Waiting for the remote stream to catch up";l.useEffect(()=>{if(!v||T.current||!D)return;const pe=u.current,G=c.current;if(!pe||!G)return;const O=()=>{const Z=G.clientWidth,q=G.clientHeight,me=pe.naturalWidth,Te=pe.naturalHeight;if(!me||!Te||!Z||!q)return;const _=Math.min(Z/me,q/Te),ve=Math.max(Z/me,q/Te)/_;ve>1.01&&(A(ve),L(ve),Q.current=ve),T.current=!0};pe.complete&&pe.naturalWidth?O():pe.addEventListener("load",O,{once:!0})},[D,v]);const ae=.5;l.useEffect(()=>{M<=ae&&(B(0),F(0))},[M,ae]);const z=(pe,G,O)=>{if(O<=ae)return{x:0,y:0};const Z=(O-1)/(2*O)*100,q=(O-1)/(2*O)*100;return{x:Math.max(-Z,Math.min(Z,pe)),y:Math.max(-q,Math.min(q,G))}},X=(pe,G)=>{if(!u.current)return null;const O=u.current.getBoundingClientRect();return!O.width||!O.height?null:{nx:Math.max(0,Math.min(1,(pe-O.left)/O.width)),ny:Math.max(0,Math.min(1,(G-O.top)/O.height))}},de=(pe,G,O)=>{const Z=c.current;if(!Z)return;const q=Z.getBoundingClientRect(),me=++y.current;p(Te=>[...Te,{id:me,x:pe-q.left,y:G-q.top,type:O}]),setTimeout(()=>p(Te=>Te.filter(_=>_.id!==me)),600)},re=(pe,G,O)=>{const Z=u.current,q=c.current;if(!Z||!q)return;const me=Z.getBoundingClientRect(),Te=q.getBoundingClientRect(),_=Z.naturalWidth||me.width,te=Z.naturalHeight||me.height,ve=_/te,ce=me.width/me.height;let H,fe,je,Ce;ve>ce?(H=me.width,fe=me.width/ve,je=0,Ce=(me.height-fe)/2):(fe=me.height,H=me.height*ve,je=(me.width-H)/2,Ce=0);const Be=me.left-Te.left+je+H*pe,Xe=me.top-Te.top+Ce+fe*G,dt=++y.current;p(it=>[...it,{id:dt,x:Be,y:Xe,type:O}]),setTimeout(()=>p(it=>it.filter(he=>he.id!==dt)),600)},W=async pe=>{var O;const G=X(pe.clientX,pe.clientY);if(G){d(`Click: ${Math.round(G.nx*100)}%, ${Math.round(G.ny*100)}%`),de(pe.clientX,pe.clientY,"left"),(O=i.current)==null||O.focus();try{const Z=await e("input_click",{nx:G.nx,ny:G.ny});Z!=null&&Z.success||t(`❌ Click failed: ${Z==null?void 0:Z.error}`)}catch(Z){t(`❌ Click error: ${Z.message||Z}`)}}},oe=async(pe,G,O,Z=0)=>{try{await e("input_key",{type:O?"char":"keyDown",key:pe,code:G,text:O?pe:void 0,unmodifiedText:O?pe:void 0,modifiers:Z})}catch(q){t(`❌ Key error: ${q.message||q}`)}},V=async pe=>{if(pe.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(pe.key)&&pe.preventDefault();let O=0;pe.altKey&&(O|=1),pe.ctrlKey&&(O|=2),pe.metaKey&&(O|=4),pe.shiftKey&&(O|=8),d(`Key: ${pe.key}`),await oe(pe.key,pe.code,pe.key.length===1,O)},ie=async pe=>{if(pe.key==="Enter"){if(pe.nativeEvent.isComposing)return;if(m){const G=m;f(""),d(`IME Sent: ${G}`);try{const O=await e("input_type",{text:G});O!=null&&O.success||t(`❌ IME error: ${O==null?void 0:O.error}`)}catch(O){t(`❌ IME error: ${O.message}`)}}else d("Key: Enter"),await oe("Enter","Enter",!1)}};l.useEffect(()=>{const pe=i.current;if(!pe)return;const G=O=>{var Z;if((Z=u.current)!=null&&Z.contains(O.target)){O.preventDefault();const q=Date.now();if(q-R.current<40)return;R.current=q;const me=X(O.clientX,O.clientY);if(!me)return;d(`Scroll: ${Math.round(O.deltaY)}`),e("input_wheel",{nx:me.nx,ny:me.ny,deltaX:Math.round(O.deltaX),deltaY:Math.round(O.deltaY)}).catch(()=>{})}};return pe.addEventListener("wheel",G,{passive:!1}),()=>pe.removeEventListener("wheel",G)},[e]);const{cursorPos:ke,handleToggleInputMode:xe,handleZoomReset:Se}=jb({containerRef:i,viewportRef:c,imgRef:u,inputMode:g,setInputMode:N,minZoom:ae,zoomRef:Q,panXRef:E,panYRef:I,setPanX:B,setPanY:F,setZoom:L,lastWheelTimeRef:R,onAction:e,setLastActionStatus:d,spawnRippleFromNormalized:re,clampPan:z,isMobile:v,mobileFillZoom:C});return s.jsxs("div",{ref:i,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:V,onContextMenu:pe=>pe.preventDefault(),onFocus:()=>x(!0),onBlur:()=>x(!1),tabIndex:0,children:[s.jsxs("div",{ref:c,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[D?s.jsx("img",{ref:u,src:D,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${M}) translate(${P}%, ${K}%)`,transformOrigin:"center center",cursor:g==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:W,onContextMenu:pe=>pe.preventDefault(),onDragStart:pe=>pe.preventDefault()}):s.jsx(Sb,{waitingLabel:U,waitingHint:Y,transportType:a}),g==="mouse"&&D&&s.jsx(wb,{cursorPos:ke,viewportRef:c,imgRef:u}),w.map(pe=>{const O={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[pe.type];return s.jsxs("div",{style:{position:"absolute",left:pe.x,top:pe.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${O}, 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(${O}, 0.9)`,boxShadow:`0 0 12px rgba(${O}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},pe.id)})]}),s.jsx(kb,{inputMode:g,onToggleInputMode:xe,isImeOpen:j,setIsImeOpen:S,isMenuOpen:k,setIsMenuOpen:b,imeText:m,setImeText:f,handleImeSubmit:ie,isConnActive:$,zoom:M,isMobile:v,mobileFillZoom:C,onZoomOut:()=>L(pe=>Math.max(.5,pe-.25)),onZoomReset:Se,onZoomIn:()=>L(pe=>Math.min(5,pe+.25)),transportType:a,screenshotUsage:o,lastActionStatus:h}),s.jsx("style",{children:`
9
+ @keyframes slideUp {
10
+ from { opacity: 0; transform: translateY(6px); }
11
+ to { opacity: 1; transform: translateY(0); }
12
+ }
13
+ @keyframes slideUpSidebar {
14
+ from { opacity: 0; transform: translateY(6px); }
15
+ to { opacity: 1; transform: translateY(0); }
16
+ }
17
+ @keyframes click-ripple-ring {
18
+ 0% { transform: scale(0.3); opacity: 1; }
19
+ 100% { transform: scale(2.2); opacity: 0; }
20
+ }
21
+ @keyframes click-ripple-dot {
22
+ 0% { transform: scale(1); opacity: 0.9; }
23
+ 50% { transform: scale(1.8); opacity: 0.6; }
24
+ 100% { transform: scale(0.5); opacity: 0; }
25
+ }
26
+ @keyframes remote-float {
27
+ 0% { transform: translateY(0px); }
28
+ 50% { transform: translateY(-7px); }
29
+ 100% { transform: translateY(0px); }
30
+ }
31
+ `})]})}function Fl(e){if(!e||typeof e!="object")return null;const t=e;return typeof t.promptId!="string"||!t.promptId.trim()||typeof t.providerType!="string"||!t.providerType.trim()||!Array.isArray(t.questions)||t.questions.length===0?null:t}function Nb(e){var t;return Fl(e.activeInteractivePrompt)||Fl((t=e.activeChat)==null?void 0:t.activeInteractivePrompt)}function Ab(e){return e.sessionId||e.instanceId||e.id}function Tb(e,t){const n=typeof t=="string"?t.trim():"";for(const r of e){const o=Nb(r);if(!o)continue;const a=Ab(r);if(n&&n!==a&&n!==r.id)continue;return{daemonId:r.daemonId||r.id.split(":")[0]||r.id,sessionId:a,routeId:r.id,providerType:r.type,title:r.title||r.cliName||r.type,prompt:o}}return null}function lu(e,t){var r;const n={};for(const o of e.questions){const a=t[o.questionId]||{},i=Array.from(new Set((a.selectedLabels||[]).map(u=>u.trim()).filter(Boolean))),c=(r=a.freeformText)==null?void 0:r.trim();n[o.questionId]={selectedLabels:i,...c?{freeformText:c}:{}}}return{promptId:e.promptId,answers:n}}const Ib=200;function Hl(e){const t={};for(const n of(e==null?void 0:e.prompt.questions)||[])t[n.questionId]={selectedLabels:[],freeformText:""};return t}function Wl(e,t){var n,r;return!!((n=t==null?void 0:t.freeformText)!=null&&n.trim())||(((r=t==null?void 0:t.selectedLabels)==null?void 0:r.length)||0)>0||e.options.length===0&&e.allowFreeform}function Mb({label:e,description:t,selected:n,multiSelect:r,disabled:o,onClick:a}){return s.jsx("button",{type:"button",disabled:o,role:r?"checkbox":"radio","aria-checked":n,onClick:a,className:`w-full text-left rounded-md border px-3 py-2 transition ${n?"border-accent-primary bg-accent-primary/15 text-text-primary":"border-border-default bg-surface-secondary text-text-secondary hover:bg-surface-secondary hover:text-text-primary"} ${o?"cursor-not-allowed opacity-60":""}`,children:s.jsxs("span",{className:"flex items-start gap-2",children:[s.jsx("span",{className:`mt-0.5 flex h-4 w-4 shrink-0 items-center justify-center border ${r?"rounded-sm":"rounded-full"} ${n?"border-accent-primary bg-accent-primary text-accent-on-primary":"border-border-subtle"}`,children:n?s.jsx(Zd,{size:12}):null}),s.jsxs("span",{className:"min-w-0",children:[s.jsx("span",{className:"block text-sm font-semibold leading-5",children:e}),t&&s.jsx("span",{className:"mt-0.5 line-clamp-3 block text-xs leading-5 text-text-muted",children:t})]})]})})}function cu({promptSession:e,isSubmitting:t=!1,error:n,onSubmit:r,onCancel:o}){var T;const[a,i]=l.useState(()=>Hl(e)),[c,u]=l.useState(0),[h,d]=l.useState(!1),m=l.useRef(!1);l.useEffect(()=>{if(i(Hl(e)),u(0),d(!1),m.current=!1,!(e==null?void 0:e.prompt.promptId))return;const L=setTimeout(()=>{m.current=!0,d(!0)},Ib);return()=>clearTimeout(L)},[e==null?void 0:e.prompt.promptId]);const f=(e==null?void 0:e.prompt.questions)||[],x=f.length,w=c===x-1,p=x===1,y=f[c],k=y?a[y.questionId]:void 0,b=y?Wl(y,k):!1,j=l.useMemo(()=>e?e.prompt.questions.every(M=>Wl(M,a[M.questionId])):!1,[e,a]);if(!e)return null;const S=(M,L)=>{i(P=>{const B=P[M.questionId]||{selectedLabels:[]},K=B.selectedLabels||[],F=M.multiSelect?K.includes(L)?K.filter(R=>R!==L):[...K,L]:[L];return{...P,[M.questionId]:{...B,selectedLabels:F}}})},v=(M,L)=>{i(P=>({...P,[M]:{...P[M]||{selectedLabels:[]},freeformText:L}}))},g=()=>{c<x-1&&u(M=>M+1)},N=()=>{c>0&&u(M=>M-1)},C=()=>{!j||t||!m.current||r(a)},A=lu(e.prompt,a);return s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50 px-4 pt-[calc(24px+env(safe-area-inset-top,0px))] pb-[calc(24px+env(safe-area-inset-bottom,0px))]",children:s.jsxs("div",{className:"flex max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-48px)] w-full max-w-2xl flex-col overflow-hidden rounded-lg border border-border-default bg-surface-primary shadow-2xl",children:[s.jsxs("div",{className:"flex shrink-0 items-start justify-between gap-4 border-b border-border-default px-5 py-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2 text-xs font-bold uppercase tracking-normal text-status-warning",children:[s.jsx(Ys,{size:15})," Action Required"]}),s.jsx("h2",{className:"mt-1 text-lg font-bold text-text-primary",children:e.title||e.providerType})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[!p&&s.jsxs("span",{className:"text-xs text-text-muted",children:[c+1," / ",x]}),s.jsx("button",{type:"button",onClick:o,className:"btn btn-ghost btn-sm h-8 w-8 p-0","aria-label":"Cancel interactive prompt",children:s.jsx(At,{size:16})})]})]}),!p&&s.jsx("div",{className:"flex shrink-0 gap-1.5 px-5 pt-3",children:f.map((M,L)=>s.jsx("div",{className:`h-1.5 flex-1 rounded-full transition-colors ${L<c?"bg-accent-primary":L===c?"bg-accent-primary/60":"bg-border-default"}`},M.questionId))}),s.jsxs("div",{className:"min-h-0 flex-1 space-y-4 overflow-y-auto px-5 py-4",children:[y&&s.jsxs("section",{className:"space-y-3",children:[s.jsxs("div",{children:[y.header&&s.jsx("div",{className:"mb-1 text-xs font-semibold uppercase tracking-normal text-text-muted",children:y.header}),s.jsxs("div",{className:"text-sm font-semibold text-text-primary",children:[p?"":`${c+1}. `,y.question]}),y.multiSelect&&y.options.length>0&&s.jsx("div",{className:"mt-0.5 text-xs text-text-muted",children:"Select all that apply"})]}),s.jsx("div",{className:"grid gap-2",role:y.multiSelect?"group":"radiogroup","aria-label":y.question,children:y.options.map(M=>{var L;return s.jsx(Mb,{label:M.label,description:M.description||M.preview,selected:(((L=A.answers[y.questionId])==null?void 0:L.selectedLabels)||[]).includes(M.label),multiSelect:y.multiSelect,disabled:t,onClick:()=>S(y,M.label)},M.label)})}),y.allowFreeform&&s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1 block text-xs font-semibold text-text-muted",children:"Other"}),s.jsx("textarea",{value:((T=a[y.questionId])==null?void 0:T.freeformText)||"",disabled:t,onChange:M=>v(y.questionId,M.currentTarget.value),className:"w-full min-h-20 rounded-md border border-border-default bg-surface-secondary px-3 py-2 text-sm text-text-primary outline-none focus:border-accent-primary"})]})]}),n&&s.jsx("div",{className:"rounded-md border border-status-error/30 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:n})]}),s.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-2 border-t border-border-default px-5 pt-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))]",children:[s.jsx("div",{children:!p&&c>0&&s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:N,disabled:t,children:"Back"})}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:o,disabled:t,children:"Cancel"}),p||w?s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:C,disabled:!j||t||!h,children:t?"Submitting...":"Submit"}):s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:g,disabled:!b||t,children:"Next"})]})]})]})})}function jo(e,t={}){if(!e)return"";const{suffix:n="",nowLabel:r="now",nowThreshold:o=60}=t,a=Date.now()-e,i=Math.floor(a/1e3);if(i<o)return r;const c=Math.floor(i/60);if(c<60)return`${c}m${n}`;const u=Math.floor(c/60);if(u<24)return`${u}h${n}`;const h=Math.floor(u/24);return h<7?`${h}d${n}`:new Date(e).toLocaleDateString()}const du=e=>jo(e);function Db(e){return{unread:!!e.unread,lastSeenAt:e.lastSeenAt||0,lastUpdated:e.lastUpdated||0,inboxBucket:e.inboxBucket||"idle",surfaceHidden:!!e.surfaceHidden,muted:!!e.muted,completionMarker:typeof e.completionMarker=="string"?e.completionMarker:"",seenCompletionMarker:typeof e.seenCompletionMarker=="string"?e.seenCompletionMarker:""}}function An(e){const t=e.connectionState==="failed"||e.connectionState==="closed",n=e.connectionState==="connecting"||e.connectionState==="new",r=e.status==="generating"||e.status==="no_progress"||e.status==="long_generating"||e.status==="streaming",o=e.status==="waiting_approval";return{isReconnecting:t,isConnecting:n,isGenerating:r,isWaiting:o}}function uu(e){const t=new Map,n=(r,o)=>{r&&t.set(r,{sessionId:r,...Db(o)})};for(const r of e)if(r.type!=="adhdev-daemon"){n(r.sessionId,r);for(const o of r.childSessions||[])n(o.id,o)}return t}function Ds(e,t){if(e.sessionId){const n=t.get(e.sessionId);if(n)return n}return{sessionId:e.sessionId||e.tabKey,unread:!1,lastSeenAt:0,lastUpdated:0,inboxBucket:"idle",surfaceHidden:!1,muted:!1,completionMarker:"",seenCompletionMarker:""}}function No(e,t,n){const r=Ds(e,t),o=An(e),a=o.isReconnecting,i=o.isConnecting,c=o.isGenerating,u=o.isWaiting,h=r.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||u,d=r.inboxBucket==="working"||c,f=!!(r.inboxBucket==="task_complete"&&r.unread&&!(n!=null&&n.hideOpenTaskCompleteUnread&&(n!=null&&n.isOpenConversation)));return{unread:f,requiresAction:h,isWorking:d,isReconnecting:a,isConnecting:i,isGenerating:c,isWaiting:u,inboxBucket:h?"needs_attention":d?"working":f?"task_complete":"idle"}}function Pb(e,t,n){return No(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:n==null?void 0:n.isOpenConversation}).unread}function hu({activeConv:e,onModalButton:t}){const{t:n}=Le(),[r,o]=l.useState(null);if(l.useEffect(()=>{o(null)},[e.modalMessage,e.status,e.connectionState]),!An(e).isWaiting||!e.modalButtons)return null;const i=u=>{r||(o(u),t(u))},c=u=>u.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim();return s.jsxs("div",{className:"text-white py-2.5 px-4 shrink-0 z-[5]",style:{background:"linear-gradient(135deg, var(--status-warning), color-mix(in srgb, var(--status-warning) 85%, #000))"},children:[e.modalMessage&&s.jsx("div",{className:"text-[11px] opacity-85 mb-1.5 whitespace-nowrap overflow-hidden text-ellipsis max-w-full",children:e.modalMessage.replace(/[\n\r]+/g," ").slice(0,120)}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"font-black text-xs flex items-center gap-2",children:[s.jsx(Ys,{size:14})," ",n(r?"approval.processing":"approval.actionRequired")]}),s.jsx("div",{className:"flex gap-2 flex-wrap",children:e.modalButtons.map((u,h)=>{const d=c(u).toLowerCase(),m=/^(run|approve|accept|yes|allow|always)/.test(d),f=/^(reject|deny|delete|remove|abort)/.test(d),x=r===u,w=r!==null;return s.jsx("button",{onClick:()=>i(u),disabled:w,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 ${m?"font-extrabold":f?"bg-red-500/30 text-white font-semibold":"text-white font-semibold"} ${w&&!x?"opacity-40":"opacity-100"} ${w?"cursor-not-allowed":"cursor-pointer"}`,style:m?{color:"var(--status-warning)",background:"var(--surface-primary)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, var(--status-warning) 18%, transparent)"}:f?void 0:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)",boxShadow:"inset 0 0 0 1px color-mix(in srgb, white 10%, transparent)"},children:x?"⏳ ...":c(u)},h)})})]})]})}const Pi="adhdev_controls_bar_visible",Ka="adhdev:controlsbarvisibilitychange";function Vo(e){if(!e)return!1;try{return e.getItem(Pi)==="1"}catch{return!1}}function Lb(e,t){if(t)try{t.setItem(Pi,e?"1":"0")}catch{}}function Rb(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(Ka,{detail:{visible:e}}))}function Li(){const[e,t]=l.useState(()=>typeof window>"u"?!1:Vo(window.localStorage)),n=l.useRef(e),r=l.useCallback((i,c=!0)=>{n.current=i,t(i),typeof window<"u"&&Lb(i,window.localStorage),c&&Rb(i)},[]);l.useEffect(()=>{const i=u=>{const h=u.detail,d=typeof(h==null?void 0:h.visible)=="boolean"?h.visible:Vo(window.localStorage);n.current=d,t(d)},c=u=>{if(u.key!==Pi)return;const h=Vo(window.localStorage);n.current=h,t(h)};return window.addEventListener(Ka,i),window.addEventListener("storage",c),()=>{window.removeEventListener(Ka,i),window.removeEventListener("storage",c)}},[]);const o=l.useCallback(i=>{r(i)},[r]),a=l.useCallback(()=>{r(!n.current)},[r]);return{isVisible:e,setVisibility:o,toggleVisibility:a}}const pu=["en","ko","ja","zh-CN","es"],Qn="en",Yo=[{code:"en",label:"English"},{code:"ko",label:"한국어"},{code:"ja",label:"日本語"},{code:"zh-CN",label:"中文(简体)"},{code:"es",label:"Español"}];function un(e){return typeof e=="string"&&pu.includes(e)}function Eb(e){if(!e)return Qn;const t=e.trim().toLowerCase();if(!t)return Qn;if(t==="zh"||t.startsWith("zh-")||t.startsWith("zh_"))return"zh-CN";const n=t.split(/[-_]/)[0];return n==="en"?"en":n==="ko"?"ko":n==="ja"?"ja":n==="es"?"es":Qn}const _b={label:"Language",select:"Select language"},$b={cancel:"Cancel"},Bb={disconnected:"Disconnected",connected:"Connected",connectedToDashboard:"Connected to dashboard",connectingToMachine:"Connecting to machine...",networkOffline:"Network offline",reconnecting:"Reconnecting",sessionExpired:"Session expired.",logInAgain:"Log in again",connectionFailed:"Connection failed — refresh the page or try again shortly.",reconnectNow:"Reconnect now"},Fb={label:{success:"Done",warning:"Attention",info:"Update"},dismiss:"Dismiss"},Hb={actionNeeded:"Action needed",taskComplete:"Task complete",markRead:"Mark read",markUnread:"Mark unread",delete:"Delete"},Wb={taskCompleted:"{{label}} agent task completed",taskCompletedWithDuration:"{{label}} agent task completed ({{duration}}s)",approvalNeeded:"{{label}} approval needed",noProgress:"{{label}} agent shows no progress",noProgressWithDuration:"{{label}} agent shows no progress ({{minutes}}m)",noProgressTitle:"{{label}} — No Progress",noProgressBody:"Agent has shown no progress for over {{duration}}",viewRequest:"{{requester}} wants to view your session",viewRequestTitle:"View Request",viewRequestApproved:"View request approved",viewRequestDeclined:"{{target}} declined your view request",someoneRequester:"A team member",someoneTarget:"Team member"},Ob={header:{title:"Dashboard",guide:"Dashboard guide",guideOpen:"Open dashboard guide",guideShort:"Guide",openGitStatus:"Open git status",openMeshGraph:"Open live repo mesh graph",meshGraph:"Mesh graph",stopAcpSession:"Stop ACP session",stopCliProcess:"Stop CLI process",chatHistory:"Chat History",remoteControl:"Remote Control",generating:"generating",activityInbox:"Activity inbox"},hidden:{title:"Hidden tabs",dragHint:"Drag a tab here to hide it.",resetPanels:"Reset panels",restoreAll:"Restore all",hideCurrentTab:"Hide current tab",empty:"No hidden tabs."},inbox:{unread:"Unread",read:"Read",empty:"No pending activity."}},Ub={title:"Stop {{agent}}?",gracefulDescription:"Stop asks the provider to exit cleanly when supported. Force Stop ends the runtime immediately.",forceOnlyDescription:"This provider does not support graceful stop. Force Stop will end the runtime immediately.",stop:"Stop",forceStop:"Force Stop"},Gb={processing:"PROCESSING...",actionRequired:"ACTION REQUIRED"},Kb={title:"Start session",close:"Close new session dialog",category:"Category",detectedLocally:"Detected locally",availableToOpen:"Available to open",machine:"Machine",selectMachine:"Select machine {{name}}",workspace:"Workspace",browse:"Browse…",launchTargetType:"Launch target type",modeWorkspace:"Workspace",modeWorkspaceDesc:"Normal session",modeMesh:"Mesh",modeMeshDesc:"Coordinator session",homeDirectory:"Home directory",customFolder:"Custom folder…",launchWithoutWorkspace:"Launch without a workspace.",selectWorkspaceFolder:"Select a workspace folder.",selectFolder:"Select folder",saving:"Saving…",saveWorkspace:"Save workspace",loadingMeshes:"Loading meshes…",noMeshes:"No repo meshes are configured on this machine. Create or sync a mesh first, then reopen this picker.",mesh:"Mesh",repoMesh:"Repo mesh",nodeCount_one:"{{count}} node",nodeCount_other:"{{count}} nodes",coordinatorWorkspace:"Coordinator workspace: {{path}}",chooseIde:"Choose IDE",chooseCliProvider:"Choose CLI provider",chooseAcpProvider:"Choose ACP provider",noProviders:"Nothing usable for this category on the selected machine. Set a custom executable path in Providers if the binary lives outside the default location.",startupArguments:"Startup arguments",optionalFlags:"Optional flags...",modelAndThinking:"Model & thinking (optional)",model:"Model",providerDefault:"(provider default)",custom:"Custom…",typeModelName:"Type a model name",backToModelList:"← Back to model list",thinkingLevel:"Thinking level",selectWorkspaceTitle:"Select workspace",selectWorkspaceDescription:"Pick the folder that should be used for this new session.",start:"Start",starting:"Starting…",startMeshCoordinator:"Start mesh coordinator",startingCoordinator:"Starting coordinator…",startIde:"Start IDE",startingIde:"Starting IDE…",startAcpSession:"Start ACP session",startingAcpSession:"Starting ACP session…",startFresh:"Start fresh",startingFresh:"Starting fresh…",resumeSavedHistory:"Resume saved history",resumingSavedHistory:"Resuming saved history…",errorLoadMeshes:"Could not load meshes",errorLoadFolder:"Could not load folder",errorLoadSavedSessions:"Could not load saved sessions",errorSaveWorkspace:"Could not save workspace",workspaceSaved:"Workspace saved. It will appear in the list once the machine state refreshes.",errorManualMcpSetup:"Manual MCP setup required before this provider can act as mesh coordinator.",errorStartMeshCoordinator:"Could not start mesh coordinator",errorStartSession:"Could not start session",errorResumeSession:"Could not resume session"},zb={machines:"Machines",chats:"Chats",networkOffline:"Network offline",sessionExpired:"Session expired",reconnecting:"Reconnecting",waitingForNetwork:"Waiting for network…",pleaseLogInAgain:"Please log in again.",restoringConnection:"Restoring the server connection…",waitingForDaemon:"Waiting for your daemon",connectYourMachines:"Connect your machines",waitingForDaemonSubtitle:"Start the ADHDev daemon to connect this dashboard. Once it is online, you can launch sessions with any installed provider.",connectYourMachinesSubtitle:"Install ADHDev on a machine, sign in, and it will show up here.",newCount:"{{count}} new",chatCount_one:"{{count}} chat",chatCount_other:"{{count}} chats",idle:"Idle",unreadSuffix:" · {{count}} unread",noActiveChats:"No active chats",needsAttention:"Needs attention",taskComplete:"Task complete",workingNow:"Working now",earlier:"Earlier",connecting:"Connecting…",connectingSubtitle:"Waiting for server connection before loading conversations.",noMachinesConnected:"No machines connected",noMachinesSubtitle:"Switch to the Machines tab to connect your first machine and start chatting with AI agents.",noConversations:"No conversations yet",allCaughtUp:"All caught up.",hiddenTabs:"Hidden tabs",collapsedCount_one:"{{count}} collapsed conversation",collapsedCount_other:"{{count}} collapsed conversations",restoreAll:"Restore all",hide:"Hide",hideTitle:"Hide {{title}}?",hideDescription:"This only collapses the chat locally. You can restore it from Hidden tabs.",reconnectingItem:"Reconnecting…",connectingItem:"Connecting…",actionNeeded:"Action needed",done:"Done",openMeshGraphFor:"Open mesh graph for {{title}}",openLiveMeshGraph:"Open live repo mesh graph",unmute:"Unmute {{title}}",mute:"Mute {{title}}",mutedTitle:"Muted — notifications silenced. Tap to unmute.",muteNotifications:"Mute notifications",hideConversationAria:"Hide {{title}}",hideConversationTitle:"Hide conversation",stopSessionAria:"Stop {{title}} session",stopSessionTitle:"Stop session (terminates the agent)"},qb={help:{toggleAria:"Mesh help",toggleTitle:"Mesh concept help",regionAria:"Mesh concept help",kicker:"Help",title:"Mesh concepts at a glance",close:"Close help",sections:{node:{term:"Node",summary:"A workspace participating in the mesh — a repo checkout or an isolated git worktree.",details:["Base node vs worktree clone node — a clone isolates parallel work without conflicts.","Shows health (online/offline) alongside git state (branch · ahead/behind · dirty).","Multiple nodes can share the same daemon."]},p2p:{term:"P2P connection",summary:"How the selected coordinator reaches each remote node over WebRTC.",details:["direct — a direct host/STUN path; lowest latency.","relay — TURN-relayed; works through restrictive networks but is slower.","disconnected / failed — no live P2P link from the coordinator right now.","P2P connectivity is shown as transport and RTT chips on each node card (and in the node detail panel), not as a graph edge."]},session:{term:"Session",summary:"An agent CLI session running on a node.",details:["status = idle / generating / waiting_approval.","Distinguishes coordinator sessions (which dispatch and collect work) from delegated worker sessions (which do the work)."]},task:{term:"Task",summary:"A single unit of work handled by the queue-based pull model.",details:["States: pending → assigned → completed / failed / cancelled.","Idle nodes claim from the queue automatically; direct dispatch targets a specific session."]},mission:{term:"Mission",summary:"A multi-task batch aimed at one goal, and the durable record of that effort.",details:["States: active / paused / completed / abandoned.","Progress is derived from the states of its member tasks."]},refinery:{term:"Refinery (refine)",summary:"The process of safely converging and merging a worktree branch into the base.",details:["Config-driven (.adhdev/refine.*) — guarded by a patch-equivalence preflight and a no-op guard.","ff-only by principle; no force-push.","If a submodule commit is unreachable from origin it must be published → classified as blocked_review."]},completion:{term:"Completion model",summary:"Completion of delegated work is persisted to the queue (pending-events).",details:["The coordinator learns of completion via periodic polling or events.","Because it is persisted to the queue, completion signals are never lost."]},magi:{term:"MAGI",summary:"Cross-verification: several independent AI agents answer the same question in parallel.",details:["Confidence comes from independence — different AIs on different machines fail in different ways.","When the agents disagree, the disagreement itself flags what to double-check.","Run via mesh_magi_review; the synthesis weighs agreement against source coupling."]},magiPanel:{term:"MAGI panel",summary:"A saved, reusable team of (machine × AI) members you invoke by name across investigations.",details:["Each member is one provider (AI) optionally pinned to a node (machine), with a replica count.","independent — spans ≥2 providers AND ≥2 machines, so agreement adds real confidence.","coupled — collapses to one AI or one machine; repeated members repeat the same mistakes.","Managed machine-locally from the Panels tab; defined in ~/.adhdev/meshes.json."]},convergence:{term:"Branch convergence states",summary:"After worktree work, each branch is classified into exactly one final state.",details:["merged_to_main — merged into the base.","pushed_feature_branch_needs_merge — pushed, awaiting merge.","blocked_review — held back by review/reachability issues.","cleanup_candidate — ready to clean up.","not_mergeable — cannot be merged."]}}},approvals:{title:"PENDING APPROVALS",empty:"No sessions are awaiting an approval decision.",sessionFallback:"session {{id}}",approve:"Approve",reject:"Reject"},chat:{loading:"Loading…",empty:"No messages."},coordinatorBadge:{daemon:"daemon: {{id}}",run:"run: {{id}}",session:"session: {{id}}"},difficulty:{intro:"Map each task difficulty to a brain. The coordinator classifies a task's difficulty; easy work then runs on a cheaper model at low effort, hard work on a stronger model at high effort. Leave a field blank to keep the routed default.",connectPrompt:"Connect to a coordinator daemon to edit brain presets.",errorLoad:"Failed to load brain presets",errorSave:"Failed to save brain presets",provider:"Provider",model:"Model",thinking:"Thinking",routedDefault:"(routed default)",defaultOption:"(default)",modelPlaceholder:"e.g. haiku, sonnet, opus",savePresets:"Save presets",saving:"Saving…",reset:"Reset",loading:"Loading…",easy:"Easy",easyHint:"trivial fixes, renames, docs — save tokens",medium:"Medium",mediumHint:"ordinary feature / bugfix work",difficult:"Difficult",difficultHint:"architecture, tricky debugging, hard reasoning",freeform:"Freeform",freeformHint:"no fixed shape"},magiKind:{intro:"Pick which agents review each task type. Add one row per agent.",refresh:"Refresh",loading:"Loading…",connectPrompt:"Connect to a coordinator daemon to manage kind → panel bindings.",errorLoad:"Failed to load kind panels",errorSave:"Failed to save kind binding",errorRemove:"Failed to remove kind binding",errorSlotProvider:"Slot {{slot}}: provider is required",errorSlotReplica:"Slot {{slot}}: replica count must be ≥ 1",errorNoSlot:"A kind binding needs at least one slot",removeConfirm:'Remove the MAGI panel binding for "{{kind}}"?',kindRca:"Root-cause analysis",kindDesign:"Design / approach review",kindClaimAudit:"Verify specific claims",kindFreeform:"Freeform review",agentCount_one:"{{count}} agent",agentCount_other:"{{count}} agents",off:"off",noAgents:"No agents yet — add one to enable this review type.",machine:"Machine",machineTitle:'Which machine runs this agent. Leave on "any" to let the coordinator route by tags.',anyMachine:"Any machine",offlineSuffix:"{{label}} (offline)",provider:"Provider",providerTitle:"The AI agent this slot runs.",selectProvider:"Select provider…",model:"Model",modelTitle:"Optional model override (best-effort). Blank uses the provider default.",modelDefault:"default",modelCustom:"Custom…",backToModelList:"← Back to model list",copies:"Copies",copiesTitle:"How many parallel copies of this agent to run. Blank = 1.",removeAgent:"Remove agent",addAgent:"+ Add agent",save:"Save",saving:"Saving…",removeBinding:"Remove binding",removeBindingTitle:"Clear this kind binding",removeBindingDisabledTitle:"Nothing to remove — this kind is unconfigured"},synthesis:{empty:"No MAGI cross-verification synthesis has been persisted for this mesh yet. Run a MAGI review (mesh_magi_review) and collect it (mesh_magi_collect); the synthesized summary then appears here, persisted to the mesh ledger.",synthesized:"synthesized",running:"running",answered:"{{answered}}/{{total}} answered",needsVerificationCount:"{{count}} needs verification",agreedCount:"{{count}} agreed",staleCount:"{{count}} stale",gitSkewLabel:"Git skew: ",gitSkewNote_one:"{{count}} branch ({{branches}}) — evidence compares different code.",gitSkewNote_other:"{{count}} branches ({{branches}}) — evidence compares different code.",needsVerification:"Needs verification",openQuestions:"Open questions",rawReplicaAnswers:"Raw replica answers",rawTitleLive:"Best-effort: raw replica text is not persisted — recoverable only from a live coordinator with the replica sessions still reachable.",rawTitleOffline:"A live coordinator daemon is required to fetch raw replica answers.",loading:"Loading…",reloadRaw:"Reload raw answers",loadRaw:"Load raw answers",rawNotice:"Raw per-replica text is not persisted (only this synthesis summary is). It is fetched live from the coordinator and is unavailable once the replica sessions age out or no live session exists.",errorLoadRaw:"Failed to load raw answers",rawEmpty:"No raw answers were returned — the replica transcripts are not retained (raw not persisted), aged out, or no live session is reachable for this group.",truncated:"truncated"},panel:{selectNode:"Select a node to view details.",submoduleBadge:"Submodule",dirtyBadge:"Dirty",outOfSyncBadge:"Out of sync",conflictBadge:"Conflict",orphanBadge:"Orphan",fieldWorkspace:"Workspace",fieldBranch:"Branch",fieldUpstream:"Upstream",fieldUpstreamState:"Upstream state",fieldHead:"HEAD",fieldSubmodulePath:"Submodule path",fieldSubmoduleCommit:"Submodule commit",fieldParentNode:"Parent node",fieldAhead:"Ahead",fieldBehind:"Behind",fieldDirtyFiles:"Dirty files",fieldActiveSessions:"Active sessions",fieldProviders:"Providers",fieldConnection:"Connection",fieldLinkNote:"Link note",fieldError:"Error",orphanReasons:"Orphan reasons",attachedChats:"Attached chats",providerUnknown:"provider unknown",statusAwaiting:"awaiting approval",statusGenerating:"generating",statusIdle:"idle",statusCoordinator:"coordinator",statusWorker:"worker",runtimeAgeNotReported:"runtime age not reported",upstreamVerified:"verified",upstreamUnverifiedFetch:"unverified (fetch failed)",upstreamUnverified:"unverified",upstreamUnavailable:"unavailable",needsFollowUp:"needs follow-up",refined:"refined"},obs:{tabOverview:"Overview",tabStatus:"Status",tabGraph:"Graph",convergenceMergedToMain:"Merged to main",convergenceNeedsMerge:"Needs merge",convergenceBlockedReview:"Blocked — needs review",convergenceCleanup:"Ready to clean up",convergenceNotMergeable:"Not mergeable",followUpLabel:"Follow-up — {{status}}",selectedNode:"Selected node",selectedEdge:"Selected edge",activeSessions:"Active Sessions",ledger:"Ledger (mesh-wide)",queueTasks:"Queue tasks",keyWarning:"Key warning",healResult:"Heal result",healPreview:"Heal preview",noResultCode:"No result code returned.",health:"Health",legend:"Legend",checking:"Checking",heal:"Heal",loadingGraph:"Loading graph…",bootstrapBanner:"Awaiting live data — showing setup inventory until peer mesh_status probes succeed.",emptyGraph:"No live mesh graph is available for this coordinator yet.",fieldMachine:"Machine",fieldLocality:"Locality",fieldWorkspace:"Workspace",fieldHead:"HEAD",fieldDirtyAheadBehind:"Dirty/ahead/behind",fieldSessions:"Sessions",fieldUpstream:"Upstream",fieldSource:"Source",fieldTransport:"Transport",fieldMachineId:"Machine id",fieldDaemonId:"Daemon id",fieldFrom:"From",fieldTo:"To",fieldLabel:"Label",fieldCompleted:"Completed",fieldFailed:"Failed",fieldLaunched:"Launched",fieldRecentFailures:"Recent failures",meshConnecting:"mesh connecting...",connecting:"connecting...",providerUnknown:"provider unknown"}},Vb={page:{title:"Repo Mesh",subtitle:"Multi-workspace orchestration",waitingForDaemon:"Waiting for daemon connection...",observabilitySecondary:"Mesh observability"},list:{title:"Repo Meshes",count_one:"{{count}} mesh",count_other:"{{count}} meshes",createMesh:"+ Create Mesh",createTitle:"Create Repo Mesh",createOnMachine:"Create on machine",createOnMachineHint:"Mesh setup is stored by the selected daemon.",noConnectedDaemon:"No connected daemon",workspace:"Workspace",workspaceHint:"Choose from workspaces registered by the selected daemon.",selectMachineFirst:"Select a machine first",noRegisteredWorkspaces:"No registered workspaces",name:"Name",remoteUrl:"Repo remote URL (optional)",remoteUrlHint:"Provide a remote URL OR a stable identity.",repoIdentity:"Repo identity (optional)",create:"Create",cancel:"Cancel",loading:"Loading meshes...",emptyTitle:"No Repo Meshes",emptyWithDaemons:"Create a mesh to get started.",emptyNoDaemons:"Connect an ADHDev daemon first.",createFirst:"Create First Mesh",noRepoIdentity:"No repo identity",repoMeshFallback:"Repo Mesh",nodesSuffix:"node(s)"},detail:{back:"← Back",probing:"Probing…",refresh:"Refresh",delete:"Delete",observabilityTitle:"Observability",observabilityDescription:"Open the live mesh graph, overview, and runtime status in the observability dialog.",observabilityOpenTitle:"Open the mesh graph / overview / status dialog",observabilityDisabledTitle:"A coordinator daemon must be selected first",observabilityOpen:"Open mesh graph & status",observabilityHint:"Topology graph, overview cards (missions, ledger, queue, nodes, sessions), and per-node runtime drift.",schedulingTitle:"Scheduling",schedulingDescription:"How untargeted queue work is distributed across eligible nodes.",distribution:"Distribution",recommended:"Recommended",saving:"Saving…",visibilityTitle:"Dashboard visibility",visibilityDescription:"Whether the worker sessions this coordinator spawns show up in your dashboard inbox and raise notifications.",visibilityLabel:"Coordinator-spawned worker sessions",visibilityHint:"Hidden = keep the inbox quiet and mute their notifications; you interact through the coordinator session. Visible = show every spawned worker as its own conversation.",visibilityHidden:"Hidden (no notifications, keep inbox quiet)",visibilityVisible:"Visible (show every worker in the dashboard)",magiTitle:"MAGI review panels",magiDescription:"MAGI (Multi-Agent Ground-truth Insight) runs a panel of AI agents that cross-check each other's work to surface the ground truth. Choose which agents handle each review type.",advanced:"advanced",coordinatorPromptTitle:"Coordinator prompt",coordinatorPromptDescription:"Customize the system prompt for coordinator sessions. Per-mesh overrides apply to this mesh only; user-level overrides apply to every mesh this daemon coordinates.",thisMesh:"This mesh",thisMeshHint:"Applies only to coordinator sessions for {{name}}. Leave empty to fall through to the user-level / daemon default.",overrideLabel:"Override (replaces default)",overrideHint:"When set, replaces the daemon's default base prompt. Leave empty to keep the default.",overridePlaceholder:"(empty — daemon default applies)",appendLabel:"Append (added after the base)",appendHint:"Always added after whichever base prompt wins.",appendPlaceholder:"(empty — nothing appended)",availablePlaceholders:"Available placeholders",saveCoordinatorPrompt:"Save coordinator prompt",clear:"Clear",clearTitle:"Clear both fields. Click Save to commit.",userLevel:"User-level (this daemon)",userLevelDescription:"Per-machine prompt files on the coordinator daemon. They apply to every mesh this daemon coordinates and are not synced across daemons. Per-mesh overrides above win over these.",safetyTitle:"Safety & Git",safetyDescription:"Checkpointing, approval gates, and git safety behavior for coordinator-driven tasks.",checkpointBefore:"Auto-commit a checkpoint before each task",checkpointAfter:"Auto-commit a checkpoint after each task",pushApproval:"Push approval",requireApprovalBeforePush:"Require approval before push",doNotRequireApproval:"Do not require approval",destructiveGitApproval:"Destructive git approval",requireApproval:"Require approval",uncommittedChanges:"When the workspace has uncommitted changes",warnAndContinue:"Warn and continue",blockTask:"Block task",checkpointThenContinue:"Checkpoint then continue",autoPublishSubmodule:"Auto-publish submodule commits (advanced)",requireExplicitApproval:"Require explicit approval",allowRefineryPublish:"Allow Refinery non-force publish",autoFastForward:"Auto fast-forward idle nodes",ffEnabled:"Enabled (catch up online, clean, behind nodes)",ffDisabled:"Disabled",includeRemoteNodes:"Include remote nodes",includeRemoteNodesHint:"Off = only the coordinator's local workspace is auto fast-forwarded.",remoteNo:"No (local workspace only)",remoteYes:"Yes (delegate to remote owning daemons)",detectionMode:"Detection mode",detectionModeHint:"Idle = on a node's idle edge. Continuous = also scan periodically (base nodes only).",idleEdgeOnly:"Idle edge only",continuousScan:"Continuous (periodic scan)",sessionCleanupLabel:"When removing a node, its sessions…",sessionCleanupHint:"Separate transcript cleanup from runtime/process cleanup.",mcpMode:"MCP Mode:",mcpDescription:"· The mesh MCP server can be used directly from your CLI agent."},nodeList:{title:"Nodes & Providers ({{count}})",descriptionCloud:"Workspaces in this mesh and their preferred AI tools. Setup inventory only — live graph/git/session truth is owned by the Mesh Host status above.",descriptionStandalone:"Workspaces participating in this mesh and their preferred AI tools.",daemonCandidates:"Machine daemon candidates",daemonCandidatesHint:"Choose connected daemons to attach to the selected Mesh Host setup.",available:"{{count}} available",noDaemonsAvailable:"No connected machine daemons are currently available.",allDaemonsAttached:"All connected machine daemons are already attached.",selectedHost:"selected host",attachMachine:"Attach machine",addNode:"Add node",attachMachineTitle:"Attach Machine Daemon",addNodeTitle:"Add Node",machine:"Machine",selectMachine:"Select a machine...",workspacePath:"Workspace Path",enterCustomPath:"Or enter a custom path →",preferredTools:"Preferred AI tools (in order)",preferredToolsHint:"Order used when launching without an explicit provider.",add:"Add",cancel:"Cancel",setupInventoryWarning:"Setup inventory only — live git/session/branch detail is shown in the graph popup after direct aggregate mesh_status truth is available from the Mesh Host.",emptyTitle:"No nodes",emptyDescription:"Add a workspace to this mesh.",setupInventory:"setup inventory",liveDetailGraphOwned:"Live branch/git/session detail is graph-owned; use the node popup in the live graph above.",slotsLabel:"Preferred AI tools (capability slots)",slotsHint:"Each slot = provider + model + thinking + the task difficulty/capability it handles + a per-slot parallel cap. Tasks are matched to the best-fit slot (order = preference). With no slots, this node uses its legacy provider order.",nodeInstruction:"Node instruction (optional)",nodeInstructionHint:"Surfaced in the coordinator system prompt as 📌 Node instruction.",nodeInstructionPlaceholder:"e.g. 'Run only smoke tests here', 'Use opus on this node'",saveInstruction:"Save instruction",saving:"Saving…",removeNode:"Remove node",details:"Details",nodeId:"Node ID:",launchReady:"Launch ready:",launchReadyYes:"yes",launchReadyNo:"no preferred tool configured",repoRoot:"Repo root:",activeSessionsLabel:"Active sessions:",added:"Added:",activeQueueAssignments:"Active queue assignments",noActiveAssignment:"No active assigned queue task for this node.",activeSessions:"Active sessions",launchBlocked:"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.)",titleNoCount:"Nodes & Providers",workspacesDetected:"{{count}} workspace(s) detected",pickFromSaved:"← Pick from saved workspaces",ownerMachine:"Owner: {{owner}} · Machine: {{machine}}"},host:{coordinatorProvider:"Coordinator CLI provider",coordinatorProviderHint:"Tool launched for the host coordinator session.",useNodePriority:"Use node provider priority",title:"Mesh Host daemon",descriptionSet:"The daemon that owns this mesh's coordinator and live truth (status, queue, graph, node detail). Fixed when the mesh is created — it cannot be reassigned here.",descriptionUnset:"This mesh has no host yet. Launching the coordinator on a connected daemon fixes that daemon as the mesh host (a 1:1 pin); it owns live truth thereafter.",hostLabel:"Host:",hostNode:"Host node:",unknown:"Unknown",hostOffline:"Host offline.",hostOfflineText:"The pinned host daemon is not connected. Live status/queue/graph will not load until it reconnects. You can temporarily route commands through another connected daemon below — this is a routing fallback, not a host reassignment.",reconnectToCommand:"Reconnect to command",reconnectToCommandHint:"Route commands through this connected daemon until the host is back. Does not change the mesh host.",waitForHost:"Wait for host to reconnect",noDaemonsToRoute:"No connected daemons available to route commands through. Bring the host (or another daemon) online.",launching:"Launching...",launchHost:"Launch Host Coordinator",setHostBanner:"Set the mesh host.",setHostBannerText:"The host is the daemon that owns this mesh's coordinator and live truth. Launch the host coordinator below to set it — the host is fixed once established.",hostDaemon:"Host daemon",hostDaemonHint:"Pick the daemon that will host this mesh. Launching the coordinator on it fixes it as the host.",resolvingHost:"Resolving host… (or pick a daemon to host)",launchHostSetsHost:"Launch Host Coordinator (sets host)",noDaemonsToHost:"No connected daemons. Bring a daemon online to host this mesh.",online:"online",offline:"offline",noCommandTarget:"No command target available — bring the host or a daemon online.",pickHostFirst:"Pick a host daemon (or wait for the host pin to resolve) first.",attachNodeFirst:"Attach a workspace from this daemon as a node first."},slotEditor:{empty:"No capability slots set — that's fine. This node still runs tasks using its provider priority order (below). Slots are optional fine-tuning: add one to route specific task difficulties or capabilities to a specific tool.",moveUp:"Move up",moveDown:"Move down",removeSlot:"Remove slot",provider:"Provider",select:"(select)",model:"Model",providerDefault:"(provider default)",custom:"Custom…",modelPlaceholder:"model",backToModelList:"← Back to model list",thinking:"Thinking",thinkingDefault:"(default)",difficulty:"Difficulty (blank = all)",capabilityTags:"Capability tags (comma-separated)",maxParallel:"Max parallel (per slot)",maxParallelPlaceholder:"unlimited",addSlot:"Add slot",saving:"Saving…",saveSlots:"Save slots"},tagEditor:{noSpaces:"Tags cannot contain spaces.",reservedPrefix:"That prefix is auto-derived — pick a different tag.",alreadyAdded:"Already added.",routingTags:"Routing tags",autoDerivedTitle:"Auto-derived — can't be edited",customTagTitle:"Custom tag",remove:"Remove {{tag}}",addPlaceholder:"add a custom tag (e.g. test-runner)",add:"Add",saving:"Saving…",saveTags:"Save tags",empty:"No routing tags — tasks can run here without matching any specific capability. Tags are optional."},missions:{errorFetch:"Failed to fetch full mission goals",title:"Missions",description:"Active and historical missions reported by the coordinator. Expand a goal to fetch its full text on demand.",empty:"No {{status}} missions.",taskCount_one:"{{count}} task",taskCount_other:"{{count}} tasks",goalUnavailable:" … (full goal unavailable)",showLess:"Show less",loading:"Loading…",showFullGoal:"Show full goal",showMore:"Show {{count}} more"},queue:{title:"Queue",description:"Inspect active queue work separately from historical completed, failed, and cancelled task records.",statActive:"Active",statPending:"Pending",statAssigned:"Assigned",statStale:"Stale",statHistorical:"Historical",statCompleted:"Completed",statFailed:"Failed",loading:"Loading...",refresh:"Refresh Queue",refreshHint:"Refresh the queue to view host-owned task counts and recent assignments.",empty:"Queue is empty.",staleBadge:"stale",staleTitle:"Stale assignment",waitingOnTitle:"Waiting on: {{tasks}}",waitsOn_one:"waits on {{count}} task",waitsOn_other:"waits on {{count}} tasks",blocked:"blocked",durationTitle:"Dispatched → terminal wall clock",retry_one:" · {{count}} retry",retry_other:" · {{count}} retries",node:"node {{id}}",session:"session {{id}}"},promptPreview:{connectPrompt:"Connect a daemon to preview the default.",errorRender:"Failed to render the default prompt",hide:"Hide the default prompt",view:"View the default prompt",rendering:"Rendering…",retry:"Retry",info:"This is what a coordinator session gets when Override is empty."},hermesMcp:{title:"Hermes MCP Config",description:"Hermes does not auto-import repo-local .mcp.json. Add this YAML under mcp_servers in Hermes config, then start a fresh Hermes session.",fallbackProvider:"Hermes CLI"}},Yb={copyMessage:"Copy message"},Jb={connectingToMachine:"Connecting to your machine",establishingP2P:"Establishing P2P connection",agentNotMonitored:"Agent not monitored",clickToSwitchMonitoring:"Click to switch monitoring to this agent",agentPanelHidden:"Agent panel is not visible yet",openPanelHint:"Open the agent panel or chat view in the app you are using to start viewing messages",noMessagesYet:"No messages yet",loadingChat:"Loading chat...",openPanel:"Open {{label}} Panel",switchingPanel:"Switching...",openingPanel:"Opening..."},Qb={attachImage:"Attach image",placeholder:"Send message to {{panel}}... (Shift+Enter for newline)",sendMessage:"Send message",dropImage:"Drop image here"},Xb={noConversations:"No conversations yet",waitingForDaemon:"Waiting for your daemon",connectYourMachines:"Connect your machines",daemonDescription:"Start the ADHDev daemon to connect this dashboard. Once it is online, you can launch sessions with any installed provider.",installDescription:"Install ADHDev on a machine, sign in, and it will show up here.",newSession:"New session",newSessionDescription:"A connected machine is ready. Start a new session with any installed provider — CLI, ACP, or IDE."},Zb={loadOlderOutput:"Load older terminal output",loadingOlder:"Loading older...",debug:"Debug",copy:"Copy",openControlKeys:"Open terminal control keys",closeControlKeys:"Close terminal control keys"},eg={muteThis:"Mute this chat",unmuteThis:"Unmute this chat",mutedTitle:"Muted — notifications silenced. Click to unmute.",muteTitle:"Mute notifications for this chat"},tg={switchToTerminal:"Switch to Terminal view",switchToChat:"Switch to Chat view"},sg={resumeSavedHistory:"Resume saved history",startFresh:"Start fresh",resumingSavedHistory:"Resuming saved history…",startingFresh:"Starting fresh…",startIde:"Start IDE",startingIde:"Starting IDE…",startAcpSession:"Start ACP session",startingAcpSession:"Starting ACP session…",recoverHostedRuntime:"Recover hosted runtime",hostedRuntimeRecoveryDescription:"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead.",openSavedHistory:"Open saved history",savedHistoryTitle:"Saved History",savedHistoryHelper:"Use saved history when you want continuity in the same provider conversation.",savedHistoryEmpty:"No saved history found yet.",refreshSavedHistory:"Refresh saved history",refreshingSavedHistory:"Refreshing saved history…",startFreshWith:"Start fresh with {{label}}?",restart:"Restart {{label}}?",startFreshReview:"Review the provider and target folder before starting fresh.",restartIdeReview:"Review or change the target workspace before restarting this IDE.",restartStoppedReview:"Review or change the target workspace before restarting this stopped session.",confirmStartFresh:"Start fresh",confirmRestart:"Restart",confirmStartingFresh:"Starting fresh…",confirmRestarting:"Restarting…",resumeWith:"Resume saved history with {{label}}?",resumeReview:"Review or change the target workspace before resuming saved history."},ng={nav:{dashboard:"Dashboard",settings:"Settings",docs:"Docs",about:"About"},layout:{expandSidebar:"Expand sidebar",collapseSidebar:"Collapse sidebar",collapse:"Collapse"},auth:{loading:"Loading standalone dashboard…",loadError:"Failed to load standalone auth status: {{error}}",signInTitle:"Standalone sign-in",passwordProtected:"This self-hosted dashboard is protected by a local password.",tokenProtected:"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session.",passwordPlaceholder:"Enter standalone password",unlock:"Unlock dashboard",signingIn:"Signing in…",noPasswordEnabled:"Password login is not enabled on this server."},machine:{loading:"⏳ Loading machine...",awaitingInput:"Awaiting your input ↑"},settings:{title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",infoNotice:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint.",publicHostWarning:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token.",daemonSection:"Daemon",daemonDescription:"Connection health and local endpoints for the self-hosted runtime.",versionLabel:"Version",statusLabel:"Status",statusRunning:"● Running",statusNotConnected:"○ Not connected",currentBindLabel:"Current bind",defaultBindLabel:"Default bind",authLabel:"Auth",authPassword:"Password enabled",authToken:"Token enabled",authNone:"No auth configured",networkSection:"Network Access",networkDescription:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",networkHint:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token.",localhostLabel:"Localhost only",localhostHint:"Bind to 127.0.0.1. Best when only this machine should open the dashboard.",allInterfacesLabel:"All interfaces",allInterfacesHint:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points.",saveNetworkMode:"Save default network mode",saving:"Saving…",networkRestartHint:"Applies on next standalone restart. Current run stays bound to {{host}}.",networkSavedAll:"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.",networkSavedLocal:"Default standalone network mode set to localhost only. Restart standalone to apply it.",securitySection:"Dashboard Security",securityDescription:"Self-hosted-only password protection for browsers using this standalone dashboard.",passwordSet:"A local password is currently required for browser access. Existing sessions are rotated when you change it.",passwordNotSet:"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended.",currentPasswordPlaceholder:"Current password",currentPasswordFirstTimePlaceholder:"Current password (not needed for first setup)",newPasswordPlaceholder:"New password",newPasswordFirstTimePlaceholder:"New standalone password",confirmPasswordPlaceholder:"Confirm new password",updatePassword:"Update password",enablePassword:"Enable password",disablePassword:"Disable password",passwordUpdated:"Standalone password updated.",passwordEnabled:"Standalone password enabled.",passwordDisabled:"Standalone password disabled.",passwordTooShort:"Password must be at least 4 characters.",passwordMismatch:"New password and confirmation do not match.",detectedIdesSection:"Detected IDEs",detectedIdesDescription:"Editors discovered by the local daemon on this machine.",noIdesDetected:"No IDEs detected. Start an IDE to see it here.",machineSection:"Machine",machineDescription:"The local burrow exposed by your standalone daemon.",daemonNotConnected:"Daemon not connected. Run 'adhdev-standalone' to start.",appearanceSection:"Appearance",appearanceDescription:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",themeDescription:"Choose a preset or create a custom surface, accent, and chat palette for the standalone UI.",mobileDescription:"Choose whether phones open the dashboard as a chat app first or in the full workspace layout.",fontsLabel:"Fonts",fontsDescription:"Standalone-only typography overrides for chat text, markdown code, and terminal output.",fontsSaved:"Standalone chat fonts saved for this self-hosted dashboard.",notificationsSection:"Notifications",notificationsDescription:"Browser prompts and local sound cues for agent activity.",soundEffectsLabel:"Sound Effects",soundEffectsDescription:"Play a sound when agent completes or needs approval",profileSection:"Profile",profileDescription:"How your name appears in local chat threads and dashboard views.",displayNameLabel:"Display Name",displayNameHint:"Your name shown in chat threads and on the team dashboard.",displayNamePlaceholder:"Anonymous"},onboarding:{title:"Welcome to ADHDev",selectedCount_one:"{{count}} provider selected",selectedCount_other:"{{count}} providers selected",skip:"Skip",installing:"Installing…",done:"Done",installCount:"Install {{count}}",intro:"Pick the providers you want to use. Defaults to the four officially supported CLI providers; you can install IDE, ACP, or extension providers from the tabs below or later from Burrow → Providers → Add provider.",loadingRegistry:"Loading registry…",loadError:"Failed to load registry: {{error}}",noProviders:"No providers in this category.",installed:"✓ installed",installFailed:"✗ {{error}}"},about:{title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",selfHostedEdition:"Self-hosted edition",headline:"Keep the same dashboard experience, with the runtime fully on-device.",description:"Standalone keeps the browser, daemon, screenshots, and control path on your own machine. It is the same core product shape as cloud, just without the remote networking and team layers.",docs:"Docs ↗",github:"GitHub ↗",tryCloud:"Try Cloud ↗",includedSection:"Included in standalone",includedDescription:"The local-first feature set available without the cloud control plane.",inventorySection:"Built-in inventory",inventoryDescription:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",cloudExtrasSection:"Cloud-only extras",cloudExtrasDescription:"Capabilities that need the hosted control plane or team infrastructure.",comparisonSection:"Self-hosted vs Cloud",comparisonDescription:"The product split at a glance.",featureHeader:"Feature",selfhostHeader:"Selfhost",cloudHeader:"Cloud",cloudOptional:"Cloud is optional, not required",cloudOptionalDescription:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",compareCloud:"Compare Cloud ↗",discord:"Discord ↗"},fonts:{fontOverridesNotice:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below.",chat:"Chat text",chatDescription:"Assistant/user prose, markdown text, thought cards, and system notes.",code:"Code blocks",codeDescription:"Markdown code fences, inline code, and preformatted command output.",terminal:"Terminal",terminalDescription:"Terminal transcript cards and tool/command rows in chat mode.",livePreview:"Live preview",resolvedStack:"Resolved stack:",defaults:"Defaults:",saveFontSettings:"Save font settings",revertToSaved:"Revert to saved",resetToDefaults:"Reset to defaults",saving:"Saving…"}},rg={login:{eyebrow:"Cloud sign-in",title:"Sign in to ADHDev",subtitle:"Connect your machines, get approval and completion notifications, and keep your coding agents moving when you are away from your desk.",continueWith:"Continue with {{provider}}",connecting:"Connecting...",devDivider:"dev",devLogin:"Dev Login (test_jwt_token)",providerNote:"GitHub and Google are used only for authentication.",errorUnverifiedEmail:"This login provider did not return a verified email, so we could not safely sign you in.",termsPrefix:"By continuing, you agree to our ",termsLink:"Terms of Service",termsAnd:" and ",privacyLink:"Privacy Policy",termsSuffix:"."},account:{title:"Account",subtitle:"Profile, plan & activity",tabAccount:"Account",tabBilling:"Billing",tabActivity:"Activity",profile:"Profile",noName:"No name",displayName:"Display Name",displayNameDesc:"Your name shown in the dashboard and team workspaces.",nicknamePlaceholder:"Nickname",save:"Save",saving:"...",cancel:"Cancel",saved:"Saved",edit:"Edit",failedToSave:"Failed to save",userId:"User ID",loadingProfile:"Loading profile...",planLimits:"Plan limits",limitMachines:"Machines",limitP2P:"P2P Connections",limitWebhooks:"Webhooks",limitTurnRelay:"TURN Relay",enabled:"Enabled",disabled:"Disabled",frozen:"Frozen",session:"Session",logout:"Logout",logoutConfirm:"Are you sure you want to logout?",logoutDesc:"Sign out of your ADHDev account on this device.",dangerZone:"Danger zone",dangerZoneDesc:"Permanently delete your account and all associated data. This action cannot be undone.",deleteAccount:"Delete account",deleteWillRemove:"This will permanently delete:",deleteItemProfile:"Your profile and login credentials",deleteItemKeys:"All API keys and connection tokens",deleteItemWebhooks:"Webhooks and delivery history",deleteItemPush:"Push notification subscriptions",deleteItemSessions:"Shared sessions and audit logs",deleteTypeConfirm:"Type {{keyword}} to confirm:",deleting:"Deleting...",permanentlyDelete:"Permanently delete",failedToDeleteAccount:"Failed to delete account",registeredMachines:"Registered Machines",machinesSummary:"{{count}} registered · {{online}} online",machinesLimit:"(limit: {{limit}})",loadingMachines:"Loading machines...",noMachinesRegistered:"No machines registered",runSetupPrefix:"Run ",runSetupMiddle:", then start ",runSetupSuffix:" on a machine to register it here.",removeMachineConfirm:"Remove this machine? It will need to run `adhdev setup` again to reconnect.",failedToDeleteMachine:"Failed to delete machine",failedToUpdate:"Failed to update",rename:"Rename",online:"Online",connecting:"Connecting",lastSeen:"Last seen {{time}}",removeMachine:"Remove machine",never:"Never",justNow:"Just now",minutesAgo:"{{minutes}}m ago",hoursAgo:"{{hours}}h ago",daysAgo:"{{days}}d ago"},billing:{title:"Billing",subtitle:"Manage your subscription and plan",currentPlan:"Current Plan:",statusTrial:"Trial",statusActive:"Active",statusPastDue:"Past Due",statusCanceled:"Canceled",nextBilling:"Next billing: {{date}}",trialEnds:"Trial ends: {{date}}",accessUntil:"Access until: {{date}}",updatePayment:"Please update your payment method",managePayment:"Manage Payment & Invoices",couldNotOpenPortal:"Could not open billing portal",statMachines:"Machines",statTeam:"Team",statTurnPerDay:"TURN min/day",monthly:"Monthly",yearly:"Yearly",savePercent:"Save 17%",paddleLoading:"Paddle is loading, please try again.",cancelConfirm:"Are you sure you want to cancel your subscription? You will retain access until the end of your billing period.",teamSeats:"Team Seats",seatsUsed:"{{used}} / {{total}} seats used",pricePerMonth:"${{price}}/mo",cannotReduceSeats:"Cannot reduce below {{count}} seats (currently in use). Remove members first.",removeSeat:"− Remove Seat",addSeat:"+ Add Seat",cancelSubscription:"Cancel Subscription",cancelRetainAccess:"You will retain access to {{plan}} features until the end of your current billing period.",cancelTeamDowngrade:" All team members will be downgraded to their personal plans."},about:{title:"About",subtitle:"Cloud overview, supported surfaces, and plan-level capabilities",cloudEdition:"Cloud edition",heroTitle:"Control your local CLI agents from anywhere — web or mobile.",heroDesc:"ADHDev Cloud surfaces the agents running on your machines in your browser: send prompts, approve actions, orchestrate work across machines, and get notified on your phone — code flows P2P directly to your daemon, never through the server.",openDashboard:"Open Dashboard",viewMachines:"View Machines",docs:"Docs ↗",whyTitle:"Why ADHDev Cloud",whyDesc:"Core capabilities available when your machines are connected through the cloud control plane.",howTitle:"How it works",howDesc:"The cloud onboarding path from install to remote control.",repoMeshTitle:"Repo Mesh",repoMeshDesc:"Orchestrate agents across machines — cloud only.",meshCard1Title:"One coordinator, many agents",meshCard1Desc:"Enqueue tasks against a mission and let idle nodes claim work from a local-first, pull-based queue. Fan out across machines and providers — Claude Code on one, Codex on another — then converge the results from a single coordinator session.",meshCard2Title:"Same repo, many machines at once",meshCard2Desc:"Each node is a checkout or an isolated git worktree, so parallel agents never collide. The refinery converges every branch — validate, merge, push, clean up — with safe submodule handling. Runs over a direct daemon-to-daemon P2P channel; the server only signals and authorizes same-account peers.",worksWith:"Works with",worksWithDesc:"Supported CLI agents, IDEs, and AI extensions.",groupCli:"CLI Agents",groupIdes:"IDEs",groupExtensions:"AI Agents",pricingTitle:"Pricing",pricingDesc:"Current cloud plans and machine capacity by tier.",planPopular:"Popular",planPerMonth:"/mo",readyTitle:"Ready to connect a machine",readyDesc:"Jump into your dashboard, inspect your connected machines, or continue in the docs if you are still setting up.",dashboard:"Dashboard",machines:"Machines",discord:"Discord ↗",github:"GitHub ↗",features:{webControlTitle:"Web control of local CLI agents",webControlDesc:"Drive any local CLI agent — Claude Code, Codex, Gemini — from your browser: send prompts, approve actions, and steer sessions without touching the terminal.",chatRelayTitle:"Agent chat relay",chatRelayDesc:"Read and respond to agent conversations from anywhere, including mobile surfaces.",liveViewTitle:"Live session view",liveViewDesc:"Watch agent activity in real time; for IDE sessions, view and control the screen over P2P without switching windows.",mobileTitle:"Mobile-ready",mobileDesc:"Receive approvals and check progress while away from your development machine.",secureTitle:"Secure by default",secureDesc:"Chat, commands, and screenshots flow directly between your browser and your daemon over WebRTC — the cloud handles auth and signaling metadata only. Your code never routes through the server."},steps:{step1Title:"One-line Install",step1Desc:"Run a single command on any machine you want to drive. It installs the ADHDev daemon plus the adhdev CLI.",step2Title:"Sign In",step2Desc:"Sign in with GitHub or Google and the daemon pairs itself to your account — no token to copy.",step3Title:"Drive Your Agents from Anywhere",step3Desc:"The machine appears in your dashboard instantly. Launch and control Claude Code, Codex, Gemini, and other CLI agents from the web — IDE sessions too."},plans:{freeName:"Free",proName:"Pro",ultraName:"Ultra",freePer:"/mo",proPer:"/mo",ultraPer:"/mo",freeFeature1:"1 machine",freeFeature2:"Real-time chat relay",freeFeature3:"Web control for your local agents",freeFeature4:"Community support",proFeature1:"2 machines",proFeature2:"Unlimited AI agents",proFeature3:"P2P remote view",proFeature4:"7-day free trial",ultraFeature1:"5 machines — flat, not per-seat",ultraFeature2:"Everything in Pro",ultraFeature3:"Higher concurrency & usage limits",ultraFeature4:"Unlimited daily screenshot minutes"}},layout:{navDashboard:"Dashboard",navBurrows:"Burrows",navNotifications:"Notifications",navMesh:"Mesh",navMarketplace:"Marketplace",navTeam:"Team",navApi:"API",navWebhooks:"Webhooks",navAccount:"Account",navSettings:"Settings",navDocs:"Docs",navAbout:"About",adminSection:"Admin",adminOverview:"Overview",adminUsers:"Users",adminAuditLogs:"Audit Logs",adminSystem:"System",adminEntry:"Admin",footerPlanTitle:"Current plan: {{plan}} — manage or upgrade",expandSidebar:"Expand sidebar",collapseSidebar:"Collapse sidebar",collapse:"Collapse",logoutConfirm:"Are you sure you want to logout?",logout:"Logout",machineLimitBanner:"You've reached your Free plan limit of {{count}} machine{{plural}}. Upgrade to add more.",upgradeArrow:"Upgrade →"},settings:{title:"Settings",subtitle:"Appearance & preferences",quickLinksTitle:"Quick links",quickLinksDesc:"Open the pages that are easiest to need from mobile inbox.",linkNotificationsTitle:"Notifications",linkNotificationsSubtitle:"Push, browser alerts, and delivery settings",linkAccountTitle:"Account",linkAccountSubtitle:"Profile, billing, sessions, and delete account",linkAboutTitle:"About",linkAboutSubtitle:"Cloud overview, supported surfaces, and plans",linkDocsTitle:"Docs",linkDocsSubtitle:"Open product docs in a new tab",appearanceTitle:"Appearance"},planCard:{unlimited:"Unlimited",machineSingular:"{{count}} machine",machinePlural:"{{count}} machines",sharedSessionSingular:"{{count}} shared session",sharedSessionPlural:"{{count}} shared sessions",teamMemberSingular:"{{count}} team member",teamMemberPlural:"{{count}} team members",turnPerDay:"{{count}} TURN min/day",recommended:"Recommended",currentPlan:"Current Plan",contactUs:"Contact Us",freeForever:"Free Forever",startTrial:"Start 7-day free trial",upgradeTo:"Upgrade to {{name}}",noChargeCancel:"No charge for 7 days. Cancel anytime.",periodSeatMo:"seat/mo",periodMo:"mo",yearlyNote:"${{yearly}}/year — Save ${{saved}}",pricingCustom:"Custom"},activity:{filterPlaceholder:"Filter by action, resource, or source...",refresh:"Refresh",loading:"Loading...",noLogs:"No logs",noMatchingLogs:"No matching logs found.",logsWillAppear:"Actions will appear here as they happen.",colAction:"Action",colResource:"Resource",colSource:"Source",colTime:"Time",logCount:"{{count}} logs",logCountFiltered:" (filtered from {{total}})"},webhooks:{title:"Webhooks",subtitle:"Real-time event notifications",addWebhook:"+ Add Webhook",eventDaemonConnect:"Daemon Connected",eventDaemonDisconnect:"Daemon Disconnected",eventAgentStatus:"Agent Status Change",eventApprovalRequired:"Approval Required",failed:"Failed",deleteConfirm:"Delete this webhook?",testFailed:"Test failed",secretTitle:"Webhook Secret",secretShownOncePrefix:"Shown ",secretShownOnce:"only once",secretShownOnceSuffix:". Use to verify ",copy:"Copy",done:"Done",newWebhook:"New Webhook",labelUrl:"URL",urlPlaceholder:"https://your-service.com/webhook",labelEvents:"Events",allEvents:"All Events (*)",creating:"Creating...",create:"Create",cancel:"Cancel",loading:"Loading...",noWebhooks:"No webhooks",noWebhooksDesc:"Receive real-time notifications about events.",setupFirst:"Set up first webhook",off:"OFF",autoDisabled:"Auto-disabled",autoDisabledTitle:"Auto-disabled after 10 consecutive failures",failuresWarning:"⚠ {{count}} failures",failuresTitle:"{{count}} consecutive failures — will auto-disable at 10",all:"ALL",history:"History",test:"Test",delete:"Delete",deleting:"...",recentDeliveries:"Recent Deliveries",refresh:"Refresh",noDeliveries:"No deliveries yet. Use 🧪 to send a test.",request:"REQUEST",response:"RESPONSE",securityTitle:"Security",securityVerifyPrefix:"Verify ",securityVerifySuffix:" with your secret",securityHttps:"Use HTTPS endpoints only",securityAsync:"Return 2xx immediately, process async",securityAutoDisable:"Auto-disabled after 10 consecutive failures"},apiKeys:{title:"API Keys",keyCount:"{{count}} keys",playground:"Playground",create:"+ Create",scopeDaemonRead:"Daemon Read",scopeDaemonReadDesc:"List daemons & status",scopeDaemonControl:"Daemon Control",scopeDaemonControlDesc:"Commands, launch/stop, disconnect",scopeAgentRead:"Agent Read",scopeAgentReadDesc:"Status & chat history",scopeAgentControl:"Agent Control",scopeAgentControlDesc:"Send, approve/reject",scopeTerminal:"Terminal",scopeTerminalDesc:"Execute commands",scopeWebhooks:"Webhooks",scopeWebhooksDesc:"Manage hooks & deliveries",frozen:"Frozen",revokeConfirm:"Revoke this API key? This cannot be undone.",failedToLoad:"Failed to load",failed:"Failed",upgradePlan:"Upgrade your plan →",keyCreated:"Key Created!",copyNow:"Copy now — shown only once.",copied:"Copied",copy:"Copy",testKey:"Test",dismiss:"Dismiss",playgroundTitle:"API Playground",enterKeyToTest:"Enter an API key to test.",open:"Open",createKeyTitle:"Create API Key",labelName:"Name",namePlaceholder:"e.g. Production Bot",permissions:"Permissions ({{count}})",createBtn:"Create",cancel:"Cancel",loading:"Loading...",noKeys:"No API Keys",noKeysDesc:"Create a key to integrate with external services.",createFirstKey:"Create First Key",usedDate:"Used {{date}}",neverUsed:"Never used",revoke:"Revoke",usageLabel:"Usage:",apiReference:"API Reference →"},auditLogs:{title:"Audit Logs",subtitle:"Security events & API history",refresh:"Refresh",filterPlaceholder:"Filter by action, resource, or source...",loading:"Loading...",noLogs:"No logs",noMatchingLogs:"No matching logs found.",logsWillAppear:"Actions will appear here as they happen.",colAction:"Action",colResource:"Resource",colSource:"Source",colTime:"Time",logCount:"{{count}} logs",logCountFiltered:" (filtered from {{total}})"},inviteModal:{title:"Invite Team Member",subtitle:"Send an invite link via email",manageSeats:"→ Manage seats in Billing",emailLabel:"Email Address",emailPlaceholder:"colleague@company.com",roleLabel:"Role",roleViewer:"Viewer",roleMember:"Member",roleAdmin:"Admin",roleViewerDesc:"Can view dashboards and chat history",roleMemberDesc:"Can control agents and send commands",roleAdminDesc:"Can manage members and settings",cancel:"Cancel",sending:"Sending...",sendInvite:"Send Invite",inviteSent:"Invite sent!",shareWith:"Share this link with",copied:"Copied!",copy:"Copy",done:"Done"},shareModal:{title:"Share Session",chatLabel:"Chat",chatDesc:"AI conversation only",remoteLabel:"Remote",remoteDesc:"Screenshot + desktop",permissionLabel:"Permission Level",authRequired:"Account required",expiresAfter:"Expires After",maxViewers:"Max Viewers",hide:"Hide",activeShares:"Active Shares",creating:"Creating...",createChatLink:"Create Chat Link",createRemoteLink:"Create Remote Link",expires:"expires",revoke:"Revoke",shareLinkCreated:"Share link created!",viewerMustLogin:"Viewer must be logged in to use this link",copy:"Copy",copied:"Copied!",expiresAt:"Expires:",done:"Done",failedToCreate:"Failed to create share link",expiry1h:"1 hour",expiry6h:"6 hours",expiry24h:"24 hours",expiry7d:"7 days",chatView:{label:"View Only",desc:"Read AI conversation in real-time"},chatControl:{label:"Control",desc:"Read + send messages + approve/reject actions"},remoteView:{label:"View Only",desc:"Watch screenshots + chat in real-time"},remoteControl:{label:"Control",desc:"Screenshots + send messages + approve/reject"},remoteFull:{label:"Full Access",desc:"Full remote control including desktop input"}},onboarding:{title:"Connect your first machine",subtitle:"Install ADHDev on a machine and sign in — it pairs itself and shows up here. Then drive every agent on it from this dashboard.",platformMac:"🍎🐧 macOS / Linux",platformWindows:"🪟 Windows",copyTitle:"Click to copy",copiedLabel:"✓ Copied",copyLabel:"📋 Copy",listeningLabel:"Listening for your daemon — keep this page open, it will appear automatically.",connectingLabel:"Connecting to ADHDev…",step1Title:"Install the daemon",step1Desc:"Run the command above on any machine you want to drive. It installs the daemon plus the adhdev CLI.",step2Title:"Sign in — the machine pairs itself",step2Desc:"The daemon links to this account automatically. No token to copy; it appears here the moment it connects.",step3Title:"Launch your first session",step3Desc:"Once a machine is online, start Claude Code, Codex, Cursor, and other agents straight from the dashboard.",readDocs:"📚 Read the documentation →"},legal:{navHome:"Home",navDashboard:"Dashboard",footerHome:"Home",footerTerms:"Terms",footerPrivacy:"Privacy",footerRefund:"Refund Policy",footerCopyright:"© 2026 RacoLab. All rights reserved."},authCallback:{authFailed:"Authentication Failed",backToLogin:"Back to Login",completing:"Completing authentication...",noTokenError:"No access token received"},cliAuth:{title:"ADHDev CLI Authentication",verifying:"Verifying...",authorizeAs:"Authorize CLI as {{name}}?",noCodeError:"No authentication code provided.",approve:"✓ Approve",signInFirst:"Please sign in first to authorize the CLI.",signIn:"Sign In →",failed:"Failed",successMessage:"CLI authentication complete!",returnToTerminal:"You can return to the terminal."},privacy:{title:"Privacy Policy",lastUpdated:"Last updated: March 23, 2026",intro:'This Privacy Policy describes how RacoLab ("we", "us", "our") collects, uses, and protects your information when you use the ADHDev service ("Service") at',s1Title:"1. Information We Collect",s1h1:"1.1 Account Information",s1p1:"When you create an account, we collect information provided by your authentication provider (GitHub or Google), including your name, email address, and profile picture.",s1h2:"1.2 IDE & Agent Data",s1p2:"When you connect your development environment to the Service, the local daemon may transmit:",s1l1:'IDE type and version (e.g., "Cursor 0.49.1")',s1l2:"Active AI agent information (name, status, current model)",s1l3:"Chat messages between you and AI agents",s1l4:"IDE screenshots (transmitted via P2P, not stored on our servers)",s1l5:"Workspace paths and open file names",s1l6:"Machine information (hostname, OS, memory usage)",s1h3:"1.3 Usage Data",s1p3:"We automatically collect usage information including API calls, feature usage patterns, and connection logs for service improvement and debugging purposes.",s1h4:"1.4 Payment Information",s1p4:"Payment processing is handled entirely by our Merchant of Record, Paddle (Paddle.com Market Limited). We do not directly collect or store credit card numbers, bank account details, or other financial information. Please refer to",s1p4PaddleLink:"Paddle's Privacy Policy",s1p4Suffix:"for their data handling practices.",s2Title:"2. How We Use Your Information",s2p1:"We use collected information to:",s2l1:"Provide and maintain the Service",s2l2:"Authenticate your identity and manage your account",s2l3:"Route commands and data between your dashboard and connected machines",s2l4:"Send notifications (browser and push) about agent status changes",s2l5:"Process billing and subscription management (via Paddle)",s2l6:"Detect and prevent abuse or unauthorized access",s2l7:"Improve the Service and develop new features",s2l8:"Respond to support requests",s3Title:"3. Data Storage & Security",s3h1:"3.1 Infrastructure",s3p1:"Our Service runs on Cloudflare's global network using Cloudflare Workers, Durable Objects, and D1 Database. Data is stored in Cloudflare's infrastructure and is subject to",s3p1CloudflareLink:"Cloudflare's Privacy Policy",s3h2:"3.2 P2P Data",s3p2:"IDE screenshots and real-time terminal data are transmitted directly between your browser and your machine via WebRTC peer-to-peer connections. This data does not pass through or get stored on our servers.",s3h3:"3.3 Security Measures",s3p3:"We implement the following security measures:",s3l1:"JWT-based authentication with short-lived access tokens and refresh token rotation",s3l2:"Encrypted WebSocket connections (WSS/TLS)",s3l3:"Per-connection tokens for daemon authentication",s3l4:"Rate limiting on all API endpoints",s3l5:"Audit logging for security-sensitive operations",s4Title:"4. Data Sharing",s4p1:"We do not sell your personal data to third parties. We may share data with:",s4l1:"Payment processing as Merchant of Record",s4l2:"Infrastructure provider (hosting, CDN, database)",s4l3Label:"Authentication providers",s4l3:"GitHub/Google for OAuth login",s4p2:"We may disclose data if required by law, legal process, or to protect our rights and the safety of our users.",s5Title:"5. Data Retention",s5p1:"We retain your account data for the duration of your active account. Chat messages and agent activity data are retained for up to 90 days for service functionality.",s5p2:"Upon account deletion, we will remove your personal data within 30 days. Some anonymized usage data may be retained for analytical purposes.",s6Title:"6. Your Rights",s6p1:"You have the right to:",s6l1Label:"Access",s6l1:"Request a copy of your personal data",s6l2Label:"Correction",s6l2:"Update or correct your personal information",s6l3Label:"Deletion",s6l3:"Request deletion of your account and associated data",s6l4Label:"Export",s6l4:"Download your data in a portable format",s6l5Label:"Object",s6l5:"Object to certain data processing activities",s6p2:"To exercise these rights, contact us at",s7Title:"7. Cookies",s7p1:"We use essential cookies only for authentication (session tokens) and user preferences (theme, notification settings). We do not use advertising or tracking cookies.",s8Title:"8. Children's Privacy",s8p1:"The Service is not intended for users under the age of 16. We do not knowingly collect personal information from children under 16.",s9Title:"9. International Data Transfers",s9p1:"Your data may be processed in various locations through Cloudflare's global network. By using the Service, you consent to the transfer and processing of your data in these locations.",s10Title:"10. Changes to This Policy",s10p1:"We may update this Privacy Policy from time to time. We will notify you of any material changes by email or through the Service. Your continued use after changes constitutes acceptance of the updated policy.",s11Title:"11. Contact",s11p1:"For questions about this Privacy Policy or data practices:",s11l1Prefix:"Email:",s11l2Prefix:"Website:"},terms:{title:"Terms of Service",lastUpdated:"Last updated: April 11, 2026",intro:'Welcome to ADHDev ("Service"), operated by RacoLab ("we", "us", "our"). By accessing or using our Service at',introSuffix:'you agree to be bound by these Terms of Service ("Terms"). If you do not agree, do not use the Service.',s1Title:"1. Service Description",s1p1:"ADHDev is a cloud developer tool that provides remote monitoring and control of AI coding agents (such as Cursor, VS Code, Antigravity, Claude Code, and others) through web and mobile dashboard surfaces. The Service includes a local daemon, remote dashboards, REST API access, and browser and push notifications.",s2Title:"2. Account Registration",s2p1:"You must create an account to use the Service. You are responsible for maintaining the confidentiality of your account credentials. You agree to provide accurate and complete information during registration and to keep your account information up to date.",s2p2:"You must be at least 16 years old to use the Service. By creating an account, you represent that you meet this age requirement.",s3Title:"3. Subscription Plans & Billing",s3p1:"The Service offers the following plans:",s3l1:"Limited features, 1 connected machine",s3l2:"2 connected machines, unlimited agents, P2P remote view, 7-day free trial",s3l3:"5 connected machines, everything in Pro plus higher concurrency and usage limits (flat price, not per-seat)",s3p2:"Paid subscriptions are billed in advance on a monthly or yearly basis. All payments are processed by our payment partner, Paddle (Paddle.com Market Limited), who acts as the Merchant of Record for all transactions.",s4Title:"4. Refund Policy",s4p1:"We offer a 14-day money-back guarantee for all paid plans. If you are not satisfied with the Service, you may request a full refund within 14 days of your initial purchase by contacting us at",s4p2:"Refunds for renewals are handled on a case-by-case basis. Paddle's refund policies also apply as they are the Merchant of Record.",s5Title:"5. Acceptable Use",s5p1:"You agree not to:",s5l1:"Use the Service for any unlawful purpose or in violation of any applicable laws",s5l2:"Attempt to gain unauthorized access to other users' accounts or data",s5l3:"Reverse-engineer, decompile, or attempt to extract the source code of the Service's server components",s5l4:"Use the Service to transmit malware, spam, or other harmful content",s5l5:"Resell or redistribute the Service without our written consent",s5l6:"Interfere with or disrupt the integrity or performance of the Service",s6Title:"6. Intellectual Property",s6p1:"The Service, including its original content, features, and functionality, is owned by RacoLab and is protected by applicable intellectual property laws. The local daemon component is available under an open-source license as specified in the project repository.",s6p2:"You retain ownership of all data and content you transmit through the Service.",s7Title:"7. Data & Privacy",s7p1:"Your use of the Service is also governed by our",s7PrivacyLink:"Privacy Policy",s7p1Suffix:"The Service processes IDE interactions, chat messages, and screenshots for the purpose of remote monitoring and control. We do not sell your data to third parties.",s8Title:"8. Service Availability",s8p1:"We strive to maintain high availability but do not guarantee uninterrupted access. The Service may be temporarily unavailable due to maintenance, updates, or circumstances beyond our control. We are not liable for any losses resulting from service interruptions.",s9Title:"9. Limitation of Liability",s9p1:"TO THE MAXIMUM EXTENT PERMITTED BY LAW, RacoLab SHALL NOT BE LIABLE FOR ANY INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES, OR ANY LOSS OF PROFITS OR REVENUES, WHETHER INCURRED DIRECTLY OR INDIRECTLY, ARISING OUT OF YOUR USE OF THE SERVICE.",s9p2:"Our total liability for any claim arising from the Service shall not exceed the amount you paid us in the 12 months preceding the claim.",s10Title:"10. Termination",s10p1:"We may suspend or terminate your access to the Service at any time for violations of these Terms or for any other reason at our sole discretion. You may cancel your account at any time through the Settings page. Upon cancellation, your data will be deleted within 30 days.",s11Title:"11. Changes to Terms",s11p1:"We reserve the right to modify these Terms at any time. We will notify you of material changes via email or through the Service. Your continued use after changes constitutes acceptance of the modified Terms.",s12Title:"12. Governing Law",s12p1:"These Terms shall be governed by and construed in accordance with the laws of the Republic of Korea, without regard to conflict of law provisions.",s13Title:"13. Contact",s13p1:"If you have any questions about these Terms, please contact us:",s13l1Prefix:"Email:",s13l2Prefix:"Website:"},refund:{title:"Refund Policy",lastUpdated:"Last updated: March 24, 2026",intro:"ADHDev is operated by RacoLab. All payments are processed by our Merchant of Record,",introSuffix:"who manages billing, invoicing, and refunds on our behalf.",s1Title:"1. 14-Day Money-Back Guarantee",s1p1:"We offer a 14-day money-back guarantee on all paid plans (Pro). If you are not satisfied with the Service for any reason, you may request a full refund within 14 days of your initial subscription purchase.",s1p2:"To request a refund, contact us at",s1p2Suffix:"with your account email and order details. We will process your request within 3 business days.",s2Title:"2. Renewal Refunds",s2p1:"Refunds for subscription renewals (monthly or yearly) are handled on a case-by-case basis. If you were charged for a renewal you did not intend, please contact us within 7 days of the charge at",s3Title:"3. Non-Refundable Cases",s3p1:"Refunds will not be issued for:",s3l1:"Requests made after the 14-day guarantee period for initial purchases",s3l2Prefix:"Accounts suspended or terminated due to violations of our",s3l2Link:"Terms of Service",s3l3:"Partial months of service already used beyond the refund window",s4Title:"4. How Refunds Are Processed",s4p1:"Approved refunds are processed through Paddle and returned to the original payment method. Depending on your bank or card issuer, refunds may take 5–10 business days to appear. Paddle's own",s4p1RefundLink:"refund terms",s4p1Suffix:"also apply.",s5Title:"5. Cancellation",s5p1Prefix:"You may cancel your subscription at any time from the",s5p1BillingLink:"Billing",s5p1Suffix:"page in your dashboard. Cancellation stops future charges. You retain access to your plan's features until the end of the current billing period. Cancellation alone does not trigger a refund.",s6Title:"6. Contact",s6p1:"For refund requests or billing questions:",s6l1Prefix:"Email:",s6l2Prefix:"Website:"},teamWorkspace:{title:"Team",subtitle:"Seat-based team management — $15/seat/mo, centralized billing",planRequired:"Team Plan Required",planDesc:`Team Workspaces are available on the Team plan ($15/seat/mo).
32
+ Manage seats, invite team members, and centrally manage billing for your organization.`,upgradeBtn:"Upgrade to Team →",seatsTitle:"Team Seats",seatsUsedOf:"{{used}} / {{total}} seats used",seatsAvailable:"{{count}} available",seatsFullMsg:"All seats are in use. Add more seats in",seatsBillingLink:"Billing",seatsBillingLinkSuffix:"to invite more members.",newWorkspace:"New Workspace",workspaceNamePlaceholder:"Workspace name...",createBtn:"Create",cancelBtn:"Cancel",noWorkspaceYet:"No team workspace yet",noWorkspaceDesc:"Create a workspace to start managing your team and sharing seats.",createWorkspace:"Create Workspace",membersTab:"Members ({{count}})",sessionsTab:"Sessions",settingsTab:"Settings",membersTitle:"Members ({{count}})",inviteBtn:"+ Invite",pendingInvites:"Pending Invites ({{count}})",pendingBadge:"Pending",removeBtn:"Remove",removeMemberConfirm:"Remove this member? They will lose their Team plan access.",removeSuccess:"Member removed",invitationSent:"Invitation sent!",joinedSuccess:"Successfully joined team workspace!",waitingApproval:"Waiting for {{name}} to approve your view request...",viewRequestSent:"View request sent to {{name}}. Waiting for approval...",viewDeclined:"{{name}} declined the view request",sessionRestricted:"Session viewing is restricted by organization policy (admin_only)",sessionTitle:"Team Sessions",noMembersOnline:"No team members online",selfBadge:"You",machineNoSessions:"Machine online, no active sessions",offline:"Offline",statusGenerating:"Generating...",statusApprovalNeeded:"Approval needed",statusStarting:"Starting...",statusStopped:"Stopped",statusError:"Error",statusDisconnected:"Disconnected",statusHidden:"Hidden",statusUnmonitored:"Unmonitored",statusIdle:"Idle",viewBtn:"View →",requestBtn:"Request →",policyOpen:"Open",policyRequest:"Request",policyAdminOnly:"Admin Only",settingsTitle:"Workspace Settings",sessionVisibilityTitle:"Session Visibility",sessionVisibilityDesc:"Control who can view team members' AI agent sessions",visibilityOpen:"Open",visibilityOpenDesc:"All members can view any session freely",visibilityRequest:"Request-based",visibilityRequestDesc:"Members must request access. Admins can always view.",visibilityAdminOnly:"Admin Only",visibilityAdminOnlyDesc:"Only administrators and the owner can view sessions.",dangerZone:"Danger Zone",dangerZoneDesc:"Irreversible actions",deleteWorkspace:"Delete Workspace",deleteWorkspaceConfirm:"Delete this Team Workspace? All members will lose their Team plan benefits.",leaveWorkspace:"Leave Workspace",leaveWorkspaceConfirm:"Are you sure you want to leave this workspace? Your plan may be downgraded."},sessionShare:{loading:"Loading session...",sessionNotFound:"Session Not Found",noLongerAvailable:"This session is no longer available",homeBtn:"← ADHDev Home",sharedSession:"Shared Session",host:"Host",mode:"Mode",permission:"Permission",auth:"Auth",authRequired:"Account required",viewers:"Viewers",joinChat:"Join Chat",joinSession:"Join Session",expires:"Expires: {{date}}",chatLabel:"Chat",remoteLabel:"Remote",waitingMessages:"Waiting for messages...",connecting:"Connecting... ({{state}})",sendMessageAs:"Send message as {{name}}...",sendAs:"Send as {{name}}...",ownerChat:"{{name}}'s Chat",ownerSession:"{{name}}'s Session",agentName:"{{name}}'s Agent",fullControlBadge:"Full Control Active",failedToJoin:"Failed to join session",sessionRevoked:"Session has been revoked by the host",sessionExpired:"Session has expired",authRequired2:"Authentication required for control share"},apiPlayground:{title:"API Playground",history:"History ({{count}})",apiRelayWarning:"Daemon API relay is opt-in. REST command/chat proxy routes stay disabled unless that daemon explicitly enables them with `adhdev daemon:api enable`.",authBearer:"Authorization: Bearer {{key}}",copyAsCurl:"cURL",copied:"Copied",targetDaemon:"Target Daemon",quickActions:"Quick Actions",requestBody:"Request Body (JSON)",recentRequests:"Recent Requests",clearHistory:"Clear",noDaemonsWarning:"No daemons connected. Start a daemon first or replace {daemonId} manually.",send:"▶ Send",sending:"⏳",close:"Close"}},og={openMenu:"Open menu",closeMenu:"Close menu"},ag={loadingOlderMessages:"Loading older messages...",waitingForMessages:"Waiting for messages...",agentGenerating:"Agent generating...",jumpToTop:"Jump to top",jumpToOldestMessages:"Jump to oldest messages",top:"↑ Top",latest:"↓ Latest",jumpToLatestMessages:"Jump to latest messages",jumpToBottom:"Jump to bottom",showEarlierMessages:"↑ Show {{count}} earlier messages...",showEarlierMessagesHidden:"↑ Show {{count}} earlier messages... ({{total}} hidden)",loadOlderMessages:"↑ Load older messages",loadErrorRetry:"↻ {{error}}"},ig={zoomOut:"Zoom Out",zoomIn:"Zoom In",resetZoom:"Reset Zoom",toggleFullscreen:"Toggle Fullscreen"},lg={mouse:"Mouse",touch:"Touch",connected:"Connected",ws:"WS",direct:"Direct",relay:"Relay",turnBlocked:"TURN blocked",turnUsage:"TURN {{used}}/{{budget}}m",typeAndEnter:"Type & Enter...",settings:"SETTINGS",zoom:"ZOOM:",fill:"FILL",fit:"FIT",directP2PTitle:"Direct P2P connection",turnRelayTitle:"TURN relay in use",dailyTurnTitle:"Daily TURN relay usage"},cg={title:"Session info",loading:"Loading…",refresh:"Refresh",close:"Close",failedToLoad:"Failed to load session info",notCoordinatorSession:"This isn't a mesh coordinator session, so no coordinator-specific prompt was injected. The agent runs with whatever defaults its CLI ships with.",stampedToNode:"This session is stamped to a mesh node that the coordinator no longer reports.",sectionSession:"Session",sectionLaunch:"Launch",sectionMeshNode:"Mesh node",sectionMeshCoordinator:"Mesh coordinator",sectionRuntime:"Runtime",rowSessionId:"Session ID",rowProvider:"Provider",rowTransport:"Transport",rowWorkspace:"Workspace",rowSpawnedAt:"Spawned at",rowProviderSessionId:"Provider session ID",rowMachine:"Machine",rowConnection:"Connection",rowWorkspaceGit:"Workspace git",rowCommand:"Command",rowWorkingDirectory:"Working directory",rowArgs:"Args",rowExtraArgs:"Extra args",rowExtraEnv:"Extra env",rowNodeId:"Node ID",rowRepoRoot:"Repo root",rowDaemonId:"Daemon ID",rowRole:"Role",rowMachineStatus:"Machine status",rowHealth:"Health",rowWorktree:"Worktree",rowLaunchReady:"Launch ready",rowGit:"Git",rowProviders:"Providers",rowProviderPriority:"Provider priority",rowMeshId:"Mesh ID",rowCoordinatorCli:"Coordinator CLI",rowStartedAt:"Started at",rowPromptInjection:"Prompt injection",rowMcpConfig:"MCP config",rowRuntimeId:"Runtime ID",rowLifecycle:"Lifecycle",rowSurface:"Surface",rowRecoveryState:"Recovery state",rowRestoredFromStorage:"Restored from storage",rowAttachedClients:"Attached clients"},dg={status:{schedulingNotReported:"Scheduling runtime not reported by this daemon (older build). Update the coordinator daemon to surface distribution, parallel caps, and per-node load.",schedulingTitle:"Scheduling",distributionTitle:"Distribution only governs how untargeted work is spread across eligible nodes. Per-node load, priority, and provider caps are below.",protocolTitle:"Protocol & provider versions",nodesRuntime:"Nodes — runtime",noNodesReporting:"No nodes reporting runtime yet."},overview:{missionCard:"Missions",ledgerCard:"Ledger",queueCard:"Queue",nodesCard:"Nodes",sessionsCard:"Active sessions",refineCard:"Refine jobs",recentActivity:"Recent activity",recentTasks:"Recent tasks",showFewer:"Show fewer",showMore:"+{{count}} more",noActiveMissions:"No active missions. The coordinator creates a mission for multi-task work.",missionDataUnavailable:"Mission data unavailable from this daemon — update the daemon to see missions.",completedHistory:"Completed / abandoned history",noQueueActivity:"No queue activity.",noNodes:"No nodes in this mesh yet.",noActiveSessions:"No active sessions.",noRefineJobs:"No refine jobs.",closeDetail:"Close detail",loadingGoal:"Loading…",showFullGoal:"Show full goal",statCompleted:"Completed",statAssigned:"Assigned",statPending:"Pending",statFailed:"Failed",statBlocked:"Blocked",statCancelled:"Cancelled",statWallClock:"Wall clock",statTotalRuntime:"Total runtime",statRetries:"Retries",statDispatched:"Dispatched",statStalled:"Stalled",statSessions:"Sessions",statCheckpoints:"Checkpoints",statActive:"Active",recentFailures:"{{count}} recent failures",activeCount:"{{count}} active",failedCount:"{{count}} failed",detailKickerMission:"Mission",detailKickerLedger:"Ledger entry",detailKickerQueue:"Queue task",detailKickerSession:"Session",detailLabelMissionId:"Mission id",detailLabelCreated:"Created",detailLabelUpdated:"Updated",detailLabelLastActivity:"Last task activity",detailLabelIncompleteEvidence:"Incomplete evidence",incompleteTaskCount_one:"{{count}} task",incompleteTaskCount_other:"{{count}} tasks",detailLabelEntryId:"Entry id",detailLabelWhen:"When",detailLabelNode:"Node",detailLabelSession:"Session",detailLabelProvider:"Provider",detailLabelPayload:"Payload",detailLabelTaskId:"Task id",detailLabelAutoLaunch:"Auto launch",detailLabelCancelReason:"Cancel reason",detailLabelRequeueReason:"Requeue reason",detailLabelRequeued:"requeued {{count}}",detailLabelSessionId:"Session id",detailLabelBranch:"Branch",detailLabelRole:"Role",detailLabelStarted:"Started",detailLabelWorkspace:"Workspace"}},ug={launchConfirm:{workspace:"Workspace",languageModel:"Language Model (Optional)",autoDetect:"Auto-detect or default",cliArgs:"CLI Arguments (Optional)",cliArgsPlaceholder:"e.g. --experimental",cancel:"Cancel",closeAria:"Close launch confirmation",launch:"Launch",launching:"Launching…"},confirmExternal:{dialogAria:"Confirm untrusted external provider",title:"Activate untrusted external provider?",description:"This manifest ships JavaScript that the daemon will execute. Treat as untrusted code — review the source before enabling.",proceedWarning:"Only proceed if you trust the source URL you added and have reviewed the manifest.",cancel:"Cancel",activate:"Activate"},workspace:{noWorkspace:"(no workspace — launch in home)",selectWorkspace:"📁 Select workspace…",customPath:"✏️ Custom path…",noWorkspacesSaved:"(no workspaces saved — add in Overview tab)",selectWorkspaceBtn:"Select workspace…",enterAbsolutePath:"Enter absolute path…",browseHint:"Browse to a folder before launching there.",absolutePathHint:"Enter an absolute path to launch there.",defaultWorkspace:"Default workspace",selectedWorkspace:"Selected workspace",noWorkspaceSelected:"No workspace selected. This launches in the home directory."},agentTab:{selectToLaunch:"Select {{label}} to Launch",launchSettings:"Launch Settings",noIdesDetected:"No IDEs detected.",scanSystem:"Scan System",noProviders:"No usable {{category}} providers available.",noProvidersHint:"Set a custom executable path in Providers if the binary is installed outside the default location.",targetModel:"Target Model",leaveEmptyDefault:"Leave empty for default",startupArguments:"Startup Arguments",optionalFlags:"Optional flags...",openSession:"Open Session",starting:"Starting...",configure:"Configure",select:"Select",launching:"⏳ Launching...",launchBtn:"▶ Launch",running:"Running ({{count}})",noRunning:"No {{plural}} running",launchingProcess:"Launching process...",waitingProcess:"Waiting for process and session to register...",startingBadge:"starting",chatView:"Chat view",terminalView:"Terminal view",localTerminal:"Local terminal:",copied:"Copied",copy:"Copy",openRemoteControl:"Open remote control",restart:"Restart",viewChat:"View chat",openInDashboard:"Open current view in dashboard",stop:"Stop",extensions:"Extensions",browseFolderTitle:"Select workspace",browseFolderDesc:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",browseFolderConfirm:"Use this folder",detailMode:"Mode",detailProvider:"Provider",detailResume:"Resume",detailArguments:"Arguments",detailModel:"Model",categoryIde:"IDE",categoryCliPlural:"CLIs",categoryAcp:"ACP Agent",categoryAcpPlural:"ACP agents"},providers:{filter:"Filter",sourceConfigTitle:"Provider source config",sourceConfigDesc:"Where the daemon looks for provider manifests. Affects resolution and reloads.",sourceMode:"Source mode",explicitProviderDir:"Explicit providerDir",providerDirPlaceholder:"Leave blank to use ~/.adhdev/providers",applying:"Applying…",applyReload:"Apply + Reload",userRoot:"User root:",upstreamRoot:"Upstream root:",providerRoots:"Provider roots:",loadingSettings:"Loading provider settings…",noProviders:'No providers installed yet. Open "Add provider" above to install one.',noFilteredProviders:"No {{filter}} providers installed.",refresh:"↻ Refresh",sources:"🌐 Sources",create:"✨ Create",advanced:"⚙ Advanced"},providerRow:{statusDetected:"Detected",statusNotDetected:"Not detected",statusEnabledUnchecked:"Enabled (unchecked)",statusDisabled:"Disabled",labelType:"Type:",labelVersion:"Version:",labelBinary:"Binary:",labelStatus:"Status:",labelDetails:"Details:",labelSource:"Source:",labelTrust:"Trust:",labelLinks:"Links:",labelDetection:"Detection:",labelVerification:"Verification:",saving:"saving…",disable:"Disable",enable:"Enable",detect:"Detect",resetCommand:"Reset command"},providerFix:{aiAgent:"AI Agent",scriptsToFix:"Scripts to Fix",all:"All",none:"None",additionalInstructions:"Additional Instructions",optional:"(optional)",agentOutput:"Agent Output",running:"● Running...",agentGenerating:"Agent is generating...",validateHint:"Run `adhdev provider verify` to validate",cancel:"Cancel",startFix:"🚀 Start Fix",cancelRunning:"⬛ Cancel",back:"← Back",close:"Close",footerHint:"AI agent will implement provider scripts",scriptsSelected_one:"{{count}} script selected",scriptsSelected_other:"{{count}} scripts selected",titlePrefix:"Auto-Fix: {{name}}",descCodex:"OpenAI o3/gpt-5.4",descClaude:"Anthropic Claude",descGemini:"Google Gemini"},providerClone:{title:"✨ Create User Provider",subtitle:"Clone an upstream IDE provider to customize",baseProvider:"Base Provider",providerTypeId:"Provider Type (ID)",typeIdPlaceholder:"my-cursor, custom-windsurf...",typeIdHint:"Lowercase, alphanumeric + hyphens only. Will be created at",displayName:"Display Name",displayNamePlaceholder:"My Custom IDE",cancel:"Cancel",creating:"⏳ Creating...",createProvider:"✨ Create Provider",createdTitle:"Provider Created!",createdDesc:"{{type}} has been created at",createdRunHint:"Run adhdev provider fix {{type}} or use Auto-Fix to implement scripts.",close:"Close"},connectedMachines:{noMachines:"No machines connected",defaultDescription:"Install ADHDev on a machine and sign in to connect it here.",startingUpgrade:"Starting upgrade...",machineDisconnected:"Machine disconnected.",tokenRevoked:"Token revoked. Restart ADHDev on that machine to reconnect.",failedToDisconnect:"Failed to disconnect",failedToRevokeToken:"Failed to revoke token",connectionLostUpgrade:"Connection lost during upgrade",disconnect:"Disconnect",remove:"Remove",disconnectTitle:"🔌 Disconnect Machine",removeTitle:"⚠️ Remove Machine",cancel:"Cancel",noIdesConnected:"No IDEs connected",upgrading:"Upgrading...",updated:"✓ Updated",updateNow:"↑ Update now",updateTo:"↑ Update to v{{version}}",cdpConnected:"CDP connected",cdpConnecting:"CDP connecting...",connecting:"connecting..."}},hg={theme:{helloHelp:"Hello! How can I help?",fixBug:"Fix the bug please",onIt:"On it! ✨",customEditorTitle:"🎨 Custom Theme Editor",darkMode:"🌙 Dark mode",lightMode:"☀️ Light mode",sectionAppBackground:"App Background",sectionAppText:"App Text",sectionBordersAccent:"Borders & Accent",sectionChatBubbles:"Chat Bubbles",sectionChatLayout:"Chat Layout",colorBackground:"Background",colorSurface:"Surface",colorCard:"Card",colorPrimary:"Primary",colorSecondary:"Secondary",colorMuted:"Muted",colorBorderSubtle:"Border subtle",colorBorderDefault:"Border default",colorAccent:"Accent",colorUserBubble:"User bubble",colorUserText:"User text",colorAgentBubble:"Agent bubble",colorAgentText:"Agent text",colorChatBg:"Chat BG",colorSendButton:"Send button",colorInputBorder:"Input border",labelBubbleRadius:"Bubble radius",resetToDefaults:"Reset to defaults",customLabel:"🎨 Custom"}},pg={chatHistory:"Chat History",startNewChat:"+ Start New Chat Session",creating:"⌛ Creating...",searchPlaceholder:"Search title or preview",filterWorkspace:"Filter by workspace",filterModel:"Filter by model",sortRecent:"Most recent",sortOldest:"Oldest first",sortMessages:"Most messages",resumeReadyOnly:"Resume-ready only",untitledSession:"Untitled Session",noSavedPreview:"No saved preview yet",workspaceUnknown:"Workspace unknown",selectedWorkspaceSuffix:" · selected workspace",msgCount:"{{count}} msgs",statusActive:"ACTIVE",statusMissingWorkspace:"MISSING WORKSPACE",statusResumeSelectedWorkspace:"RESUME IN SELECTED WORKSPACE",statusResuming:"RESUMING...",statusResume:"RESUME",noMatchingHistory:"No saved history matches these filters.",noRecentChats:"No recent chat sessions found.",refreshHistory:"Refresh History",refreshing:"⌛ Refreshing..."},mg={nav:{home:"ADHDev Home",mesh:"Mesh",what:"What",agents:"Agents",pricing:"Pricing",install:"Install",github:"GitHub",docs:"Docs",getStarted:"Get started",toggleMenu:"Toggle menu"},hero:{badge:"The multi-vendor, multi-machine agent control plane",title:"Anyone can run ten agents. ADHDev lands the work on main.",subtitle:"Drive any local coding agent — Claude Code, Codex, Cursor — from your browser, then let the Refinery merge finished work back to main <em>unattended</em>: your repo's own gates, patch-equivalence checks, fast-forward only, no force-push. You talk to one coordinator; it runs parallel agents across your own machines asynchronously — no sessions to babysit. Code stays on your machine — P2P, end to end.",selectOs:"Select OS",osUnix:"macOS / Linux",osWindows:"Windows",copyInstall:"Copy install command: {{cmd}}",copied:"Copied",copy:"Copy",getStarted:"Get started",openSource:"Open source on GitHub",joinDiscord:"Join Discord",selfHost:"Self-host it yourself",demoDesktop:"ADHDev command center driving live agent sessions across multiple machines",demoPush:"ADHDev mobile push notification and one-tap approval"},mesh:{sectionTitle:"They parallelize. We land.",sectionSubtitle:"Spawning parallel agents is the easy part — every tool does it now. The hard part is what happens after: ten branches that still have to be verified and merged. The Refinery does that for you, unattended, so finished work arrives on main instead of in your review queue.",refineryHighlight:"The Refinery",refineryTitle:"Finished work lands on main — unattended",refineryDesc:"Anyone can spawn ten parallel agents. The Refinery validates each worktree against your repo's own gates (typecheck, tests, lint), verifies patch equivalence, publishes submodule commits, fast-forwards main, and cleans up — automatically. No force-push, ever. Anything ambiguous is kicked back for review instead of merged.",asyncHighlight:"Async orchestration",asyncTitle:"You talk to one place. It runs the rest.",asyncDesc:"You give work to one coordinator; it drives many workers across many machines on an event loop — reacting only when a completion, approval, or status event arrives. No polling, no window-per-agent to babysit. Unlike a desktop app where you watch each agent session, here the coordinator waits on events, so you don't have to sit synchronously in front of anything.",monoHighlight:"Monorepo-aware",monoTitle:"Safe even with git submodules",monoDesc:"Real production repos nest submodules — and that's exactly where naive auto-merge breaks. The Refinery is submodule-aware: it gates on submodule-commit reachability, judges patch equivalence, and bumps the pointer atomically. This project is itself a root + two-submodule monorepo, converged this way every day.",crossHighlight:"Cross-check",crossTitle:"Consensus over a single opinion",crossDesc:"Fan the same read-only investigation out to several machine × provider replicas and synthesize where they agree and diverge (MAGI). More trustworthy than one agent's take.",tryMesh:"Try Repo Mesh →",seePlans:"See plans",availableOn:"Available on Pro and above. Drive it from the <strong>Repo Mesh</strong> page once connected.",readGuide:"Read the guide"},compare:{sectionTitle:"Parallel agents are everywhere now. Where does the work actually land?",sectionSubtitle:"A fair question. Local CLIs spawn subagents; desktop orchestrators fan work across worktrees with a slick native UI. Both stop at the branch. Here's the honest line — including where each of them beats us — with no hand-waving.",colLocalCli:"Local CLI + subagents",colDesktop:"Desktop orchestrator",colAdhdev:"ADHDev Repo Mesh",rowLandsMain:"Lands finished work on main",rowLandsMainLocalCli:"You run the gates and merge by hand",rowLandsMainDesktop:"Parallelizes the work, then hands you the branches to review",rowLandsMainAdhdev:"The Refinery runs your repo's gates, checks patch equivalence, and fast-forwards main — unattended, no force-push",rowSubmodules:"Safe with git submodules",rowSubmodulesLocalCli:"No merge automation to be aware of them",rowSubmodulesDesktop:"Worktree parallelism, but the merge is yours to get right",rowSubmodulesAdhdev:"Submodule-aware convergence: reachability gate, patch-equivalence check, atomic pointer bump — dogfooded on this monorepo daily",rowAsync:"Talk to one place, async",rowAsyncLocalCli:"One session at a time, synchronously",rowAsyncDesktop:"You supervise each agent window yourself",rowAsyncAdhdev:"One coordinator drives every worker on an event loop — it waits on completion/approval events, you don't poll or babysit",rowMultiMachine:"Multiple physical machines",rowMultiMachineLocalCli:"One host's processes only",rowMultiMachineDesktop:"Bound to the one machine it runs on",rowMultiMachineAdhdev:"Remote daemons over P2P — dispatch across every machine you own (no SSH plumbing)",rowParallelBranch:"Parallel isolated-branch work",rowParallelBranchLocalCli:"Subagents share one working tree — concurrent writes collide",rowParallelBranchDesktop:"One git worktree per task — a core strength",rowParallelBranchAdhdev:"One git worktree per node — parallel across machines, not just cores",rowBrowser:"Drive it from a browser or phone",rowBrowserLocalCli:"You have to be at the terminal",rowBrowserDesktop:"Native desktop app — you're at that desk",rowBrowserAdhdev:"Web-first: control sessions and approve from any browser or phone",rowNativeApp:"Native desktop app",rowNativeAppLocalCli:"Terminal only",rowNativeAppDesktop:"Polished native window — genuinely nicer to sit in front of",rowNativeAppAdhdev:"We're web-first — a browser tab, not a native app",rowRestarts:"Survives restarts & context loss",rowRestartsLocalCli:"State lives in a session — close it and it's gone",rowRestartsDesktop:"State tied to the app process",rowRestartsAdhdev:"Missions persist to disk and resume after a coordinator or daemon restart — append-only, tamper-evident audit trail",rowCrossCheck:"Cross-check the answer",rowCrossCheckLocalCli:"One agent's take, no second opinion",rowCrossCheckDesktop:"Parallel work, single verdict",rowCrossCheckAdhdev:"MAGI fans the same read-only question to independent machine × provider agents and surfaces where they diverge",footnote:"For a single machine, a single branch, a one-shot task — a local CLI with subagents is lighter and works great, and a native desktop orchestrator is a nicer place to sit. Repo Mesh earns its keep when work fans out across machines and branches, needs to survive restarts, and should land on main automatically — controlled from wherever you are."},what:{sectionTitle:"Any agent, mixed freely",sectionSubtitle:"Vendor-neutral by design. Run Claude Code on the Mac, Codex on the Windows GPU box, Gemini for review passes — in the same mesh, under the same policies. Switch vendors without switching platforms.",cliHighlight:"CLI agents",cliTitle:"Drive any terminal agent from the web",cliDesc:"Claude Code, Codex CLI, Cursor CLI, Antigravity CLI, Hermes, Kimi, and OpenCode — attached on your machine through a PTY adapter with proper resume and reconnect, driven from your browser. Send prompts and provide visual context instantly (paste, drag & drop, or upload multiple images at once, up to 5 images / 10MB each). Aider, Gemini CLI, Goose, and other ACP agents connect over stdio.",uiHighlight:"One UI",uiTitle:"Same dashboard, any device",uiDesc:"Cloud-hosted at adhf.dev — drive every agent from a laptop or phone, whether you're at your desk or away from it.",ideHighlight:"IDE agents",ideTitle:"Also: attach to running editors",ideDesc:"Cursor, VS Code, VSCodium, Windsurf, Antigravity, Kiro, PearAI, Trae. Read live chat, send prompts, switch sessions, capture screenshots.",p2pHighlight:"Yours, end to end",p2pTitle:"P2P-first: your data stays yours",p2pDesc:"Chat, commands, and screenshots flow directly between your browser and your daemon over WebRTC. The cloud sees auth and signaling metadata, nothing else — your code never routes through the server."},oss:{sectionTitle:"Open source & self-hostable",sectionSubtitle:"The daemon and dashboard are AGPL-3.0 and available on GitHub. Run them yourself on any machine or server — no account required.",github:"GitHub",selfHostDocs:"Self-hosting docs"},agents:{sectionTitle:"Supported agents",sectionSubtitle:"{{ides}} built-in IDE integrations, {{clis}} built-in CLI agents, {{extensions}} IDE-resident extension agents, and {{acp}}+ ACP (stdio MCP) agents. Provider scripts live in <code>adhdev-providers/</code> — add your own under <code>~/.adhdev/providers/</code>.",tierTested:"Tested",tierTestedDesc:"validated against a real app + version",tierCommunity:"Community",tierCommunityDesc:"built-in and community-supported",groupIdes:"IDEs",hintIdes:"Attached via Chrome DevTools Protocol. Read chat, send prompts, switch sessions, screenshot.",groupCli:"CLI agents",hintCli:"Driven through a PTY adapter with resume and reconnect.",groupExtensions:"In-IDE extension agents",hintExtensions:"CDP webview attachment for agents that live inside another IDE.",acpFootnote:"Plus {{count}}+ ACP agents over stdio (Agent Client Protocol): Codex, Claude Agent, Gemini, Goose, Cline, OpenHands, and more."},pricing:{sectionTitle:"Simple pricing as your agents grow",sectionSubtitle:"Start free on one machine. Go Pro for two, or Ultra for five. No per-seat math, no enterprise sales call — just the plans below.",mostPopular:"Most popular",upgradeToPro:"Upgrade to Pro",footnote:"Simple, transparent pricing — the prices above are what you'll pay. Prefer to self-host? The daemon and dashboard are open source. Prices in USD.",plans:{free:{period:"forever",tagline:"Everything you need to drive one machine from anywhere.",cta:"Start free",features:{machine:"One machine, paired in a single command",p2p:"P2P chat, commands, screenshots, remote input",providers:"Every provider — CLI, IDE, and ACP agents",push:"Push notifications for approvals & completions",share:"One shared session link"}},pro:{period:"/mo",tagline:"Run agents across a couple of machines, with the reliability paid plans need.",cta:"Start 7-day Pro trial",features:{machines:"2 machines — run agents on both",p2p:"More concurrent P2P sessions",push:"Unlimited push notifications",turn:"TURN relay for restrictive networks",mesh:"Repo Mesh — orchestrate agents across machines",share:"More shared sessions"}},ultra:{period:"/mo",tagline:"Everything in Pro, scaled up — more machines and higher limits for heavy parallel work.",cta:"Go Ultra",features:{machines:"5 machines — flat price, not per-seat",everything:"Everything in Pro",p2p:"Highest concurrent P2P sessions",screenshots:"Unlimited daily screenshot minutes",webhooks:"More webhooks & API calls",share:"More shared sessions"}}}},install:{sectionTitle:"Three steps to a working dashboard",sectionSubtitle:"No configuration files. No API keys to wire up. ADHDev does not manage agent auth — each tool keeps its own login.",selectOs:"Select OS",osUnix:"macOS / Linux",osWindows:"Windows",copyInstall:"Copy install command: {{cmd}}",copied:"Copied",copy:"Copy",platformNote:"macOS and Windows are the validated install paths. Linux runs the same Unix script and is community-tested.",arrow:"→",steps:{step1:{title:"Install the daemon",desc:"One curl command installs the daemon plus the adhdev CLI — the launcher you run to pair machines and start the daemon (not to be confused with the CLI agents it drives, like Claude Code or Codex). Same binary powers cloud and standalone."},step2:{title:"Link a machine",desc:"Sign in once with GitHub or Google and the daemon pairs itself — no token to copy."},step3:{title:"Drive your agents",desc:"Launch Claude Code, Codex CLI, Cursor CLI, Antigravity CLI, Hermes, Kimi, and other agents from the dashboard. Read chat, send prompts, provide visual context (paste, drag & drop, or upload multiple images at once), approve actions, and switch sessions."}}},cta:{headline:"Stop juggling tabs. Drive every agent from one dashboard.",subtitle:"One curl command, one daemon, every agent you already use. Drive them all from the web — Cloud is live.",getStarted:"Get started →",github:"GitHub",discord:"Discord"},footer:{docs:"Docs",github:"GitHub",discord:"Discord",dashboard:"Dashboard",terms:"Terms",privacy:"Privacy",contact:"Contact",copyright:"© {{year}} RacoLab. All rights reserved."}},fg={language:_b,common:$b,connection:Bb,toast:Fb,notification:Hb,event:Wb,dashboard:Ob,cliStop:Ub,approval:Gb,newSession:Kb,mobileInbox:zb,meshGraph:qb,repoMesh:Vb,chat:Yb,chatPane:Jb,chatInput:Qb,paneGroup:Xb,terminal:Zb,conversation:eg,cliView:tg,launch:sg,standalone:ng,cloud:rg,app:og,chatList:ag,screenshot:ig,remote:lg,sessionInfo:cg,mesh:dg,machine:ug,settings:hg,historyModal:pg,landing:mg},bg={label:"언어",select:"언어 선택"},gg={cancel:"취소"},xg={disconnected:"연결 끊김",connected:"연결됨",connectedToDashboard:"대시보드에 연결됨",connectingToMachine:"머신에 연결 중...",networkOffline:"네트워크 오프라인",reconnecting:"재연결 중",sessionExpired:"세션이 만료되었습니다.",logInAgain:"다시 로그인",connectionFailed:"연결에 실패했습니다 — 페이지를 새로고침하거나 잠시 후 다시 시도하세요.",reconnectNow:"지금 재연결"},yg={label:{success:"완료",warning:"주의",info:"업데이트"},dismiss:"닫기"},vg={actionNeeded:"조치 필요",taskComplete:"작업 완료",markRead:"읽음 표시",markUnread:"읽지 않음 표시",delete:"삭제"},wg={taskCompleted:"{{label}} 에이전트 작업 완료",taskCompletedWithDuration:"{{label}} 에이전트 작업 완료 ({{duration}}초)",approvalNeeded:"{{label}} 승인 필요",noProgress:"{{label}} 에이전트 진행 없음",noProgressWithDuration:"{{label}} 에이전트 진행 없음 ({{minutes}}분)",noProgressTitle:"{{label}} — 진행 없음",noProgressBody:"에이전트가 {{duration}} 넘게 진행이 없습니다",viewRequest:"{{requester}}님이 세션 보기를 요청합니다",viewRequestTitle:"보기 요청",viewRequestApproved:"보기 요청이 승인되었습니다",viewRequestDeclined:"{{target}}님이 보기 요청을 거절했습니다",someoneRequester:"팀 멤버",someoneTarget:"팀 멤버"},kg={header:{title:"대시보드",guide:"대시보드 가이드",guideOpen:"대시보드 가이드 열기",guideShort:"가이드",openGitStatus:"Git 상태 열기",openMeshGraph:"실시간 리포 메시 그래프 열기",meshGraph:"메시 그래프",stopAcpSession:"ACP 세션 중지",stopCliProcess:"CLI 프로세스 중지",chatHistory:"채팅 기록",remoteControl:"원격 제어",generating:"생성 중",activityInbox:"활동 수신함"},hidden:{title:"숨긴 탭",dragHint:"탭을 여기로 끌어다 놓으면 숨겨집니다.",resetPanels:"패널 초기화",restoreAll:"모두 복원",hideCurrentTab:"현재 탭 숨기기",empty:"숨긴 탭이 없습니다."},inbox:{unread:"읽지 않음",read:"읽음",empty:"대기 중인 활동이 없습니다."}},Sg={title:"{{agent}}을(를) 중지할까요?",gracefulDescription:"중지는 지원되는 경우 프로바이더에게 정상 종료를 요청합니다. 강제 중지는 런타임을 즉시 종료합니다.",forceOnlyDescription:"이 프로바이더는 정상 중지를 지원하지 않습니다. 강제 중지는 런타임을 즉시 종료합니다.",stop:"중지",forceStop:"강제 중지"},Cg={processing:"처리 중...",actionRequired:"조치 필요"},jg={title:"세션 시작",close:"새 세션 대화상자 닫기",category:"카테고리",detectedLocally:"로컬에서 감지됨",availableToOpen:"열기 가능",machine:"머신",selectMachine:"머신 {{name}} 선택",workspace:"워크스페이스",browse:"찾아보기…",launchTargetType:"실행 대상 유형",modeWorkspace:"워크스페이스",modeWorkspaceDesc:"일반 세션",modeMesh:"메시",modeMeshDesc:"코디네이터 세션",homeDirectory:"홈 디렉터리",customFolder:"사용자 지정 폴더…",launchWithoutWorkspace:"워크스페이스 없이 실행합니다.",selectWorkspaceFolder:"워크스페이스 폴더를 선택하세요.",selectFolder:"폴더 선택",saving:"저장 중…",saveWorkspace:"워크스페이스 저장",loadingMeshes:"메시 불러오는 중…",noMeshes:"이 머신에 구성된 리포 메시가 없습니다. 먼저 메시를 생성하거나 동기화한 후 이 선택기를 다시 여세요.",mesh:"메시",repoMesh:"Repo Mesh",nodeCount_one:"노드 {{count}}개",nodeCount_other:"노드 {{count}}개",coordinatorWorkspace:"코디네이터 워크스페이스: {{path}}",chooseIde:"IDE 선택",chooseCliProvider:"CLI 프로바이더 선택",chooseAcpProvider:"ACP 프로바이더 선택",noProviders:"선택한 머신에서 이 카테고리로 사용할 수 있는 것이 없습니다. 바이너리가 기본 위치 밖에 있다면 프로바이더에서 사용자 지정 실행 경로를 설정하세요.",startupArguments:"시작 인자",optionalFlags:"선택적 플래그...",modelAndThinking:"모델 & 사고 수준 (선택)",model:"모델",providerDefault:"(프로바이더 기본값)",custom:"사용자 지정…",typeModelName:"모델 이름 입력",backToModelList:"← 모델 목록으로",thinkingLevel:"사고 수준",selectWorkspaceTitle:"워크스페이스 선택",selectWorkspaceDescription:"이 새 세션에 사용할 폴더를 선택하세요.",start:"시작",starting:"시작 중…",startMeshCoordinator:"메시 코디네이터 시작",startingCoordinator:"코디네이터 시작 중…",startIde:"IDE 시작",startingIde:"IDE 시작 중…",startAcpSession:"ACP 세션 시작",startingAcpSession:"ACP 세션 시작 중…",startFresh:"새로 시작",startingFresh:"새로 시작 중…",resumeSavedHistory:"저장된 기록 재개",resumingSavedHistory:"저장된 기록 재개 중…",errorLoadMeshes:"메시를 불러올 수 없습니다",errorLoadFolder:"폴더를 불러올 수 없습니다",errorLoadSavedSessions:"저장된 세션을 불러올 수 없습니다",errorSaveWorkspace:"워크스페이스를 저장할 수 없습니다",workspaceSaved:"워크스페이스가 저장되었습니다. 머신 상태가 새로고침되면 목록에 표시됩니다.",errorManualMcpSetup:"이 프로바이더가 메시 코디네이터로 작동하려면 수동 MCP 설정이 필요합니다.",errorStartMeshCoordinator:"메시 코디네이터를 시작할 수 없습니다",errorStartSession:"세션을 시작할 수 없습니다",errorResumeSession:"세션을 재개할 수 없습니다"},Ng={machines:"머신",chats:"채팅",networkOffline:"네트워크 오프라인",sessionExpired:"세션 만료됨",reconnecting:"재연결 중",waitingForNetwork:"네트워크 대기 중…",pleaseLogInAgain:"다시 로그인해 주세요.",restoringConnection:"서버 연결을 복원하는 중…",waitingForDaemon:"데몬을 기다리는 중",connectYourMachines:"머신을 연결하세요",waitingForDaemonSubtitle:"ADHDev 데몬을 시작하여 이 대시보드에 연결하세요. 온라인이 되면 설치된 프로바이더로 세션을 실행할 수 있습니다.",connectYourMachinesSubtitle:"머신에 ADHDev를 설치하고 로그인하면 여기에 표시됩니다.",newCount:"새 항목 {{count}}개",chatCount_one:"채팅 {{count}}개",chatCount_other:"채팅 {{count}}개",idle:"유휴",unreadSuffix:" · 읽지 않음 {{count}}개",noActiveChats:"활성 채팅 없음",needsAttention:"조치 필요",taskComplete:"작업 완료",workingNow:"작업 중",earlier:"이전",connecting:"연결 중…",connectingSubtitle:"대화를 불러오기 전에 서버 연결을 기다리는 중입니다.",noMachinesConnected:"연결된 머신 없음",noMachinesSubtitle:"머신 탭으로 전환하여 첫 머신을 연결하고 AI 에이전트와 채팅을 시작하세요.",noConversations:"아직 대화가 없습니다",allCaughtUp:"모두 확인했습니다.",hiddenTabs:"숨긴 탭",collapsedCount_one:"접힌 대화 {{count}}개",collapsedCount_other:"접힌 대화 {{count}}개",restoreAll:"모두 복원",hide:"숨기기",hideTitle:"{{title}}을(를) 숨길까요?",hideDescription:"채팅이 로컬에서만 접힙니다. 숨긴 탭에서 다시 복원할 수 있습니다.",reconnectingItem:"재연결 중…",connectingItem:"연결 중…",actionNeeded:"조치 필요",done:"완료",openMeshGraphFor:"{{title}} 메시 그래프 열기",openLiveMeshGraph:"실시간 리포 메시 그래프 열기",unmute:"{{title}} 음소거 해제",mute:"{{title}} 음소거",mutedTitle:"음소거됨 — 알림이 차단되었습니다. 탭하여 해제하세요.",muteNotifications:"알림 음소거",hideConversationAria:"{{title}} 숨기기",hideConversationTitle:"대화 숨기기",stopSessionAria:"{{title}} 세션 중지",stopSessionTitle:"세션 중지 (에이전트를 종료합니다)"},Ag={help:{toggleAria:"메시 도움말",toggleTitle:"메시 개념 도움말",regionAria:"메시 개념 도움말",kicker:"도움말",title:"메시 개념 한눈에 보기",close:"도움말 닫기",sections:{node:{term:"노드",summary:"메시에 참여하는 워크스페이스 — 리포 체크아웃 또는 격리된 git 워크트리.",details:["베이스 노드 vs 워크트리 클론 노드 — 클론은 충돌 없이 병렬 작업을 격리합니다.","상태(온라인/오프라인)를 git 상태(브랜치 · ahead/behind · dirty)와 함께 표시합니다.","여러 노드가 같은 데몬을 공유할 수 있습니다."]},p2p:{term:"P2P 연결",summary:"선택한 코디네이터가 WebRTC로 각 원격 노드에 도달하는 방식.",details:["direct — 직접 host/STUN 경로; 가장 낮은 지연.","relay — TURN 릴레이; 제한적 네트워크에서도 작동하지만 느립니다.","disconnected / failed — 현재 코디네이터로부터 활성 P2P 링크가 없음.","P2P 연결성은 그래프 엣지가 아니라 각 노드 카드(및 노드 상세 패널)의 transport·RTT 칩으로 표시됩니다."]},session:{term:"세션",summary:"노드에서 실행 중인 에이전트 CLI 세션.",details:["status = idle / generating / waiting_approval.","작업을 디스패치·수집하는 코디네이터 세션과 실제 작업을 수행하는 위임 워커 세션을 구분합니다."]},task:{term:"태스크",summary:"큐 기반 풀 모델로 처리되는 단일 작업 단위.",details:["상태: pending → assigned → completed / failed / cancelled.","유휴 노드는 큐에서 자동으로 클레임하며, 직접 디스패치는 특정 세션을 대상으로 합니다."]},mission:{term:"미션",summary:"하나의 목표를 향한 다중 태스크 배치이자 그 노력의 영속 기록.",details:["상태: active / paused / completed / abandoned.","진행률은 소속 태스크들의 상태에서 파생됩니다."]},refinery:{term:"리파이너리 (refine)",summary:"워크트리 브랜치를 베이스로 안전하게 수렴·머지하는 과정.",details:["구성 기반(.adhdev/refine.*) — 패치 동등성 프리플라이트와 no-op 가드로 보호됩니다.","원칙적으로 ff-only; 강제 푸시 없음.","서브모듈 커밋이 origin에서 도달 불가하면 게시되어야 하며 → blocked_review로 분류됩니다."]},completion:{term:"완료 모델",summary:"위임된 작업의 완료는 큐(pending-events)에 영속됩니다.",details:["코디네이터는 주기적 폴링 또는 이벤트로 완료를 인지합니다.","큐에 영속되므로 완료 신호는 결코 유실되지 않습니다."]},magi:{term:"MAGI",summary:"교차 검증: 여러 독립 AI 에이전트가 같은 질문에 병렬로 답합니다.",details:["신뢰는 독립성에서 나옵니다 — 서로 다른 머신의 서로 다른 AI는 서로 다르게 실패합니다.","에이전트들이 의견이 갈리면 그 불일치 자체가 재확인할 지점을 표시합니다.","mesh_magi_review로 실행하며, 합성은 합의를 소스 결합도와 견주어 평가합니다."]},magiPanel:{term:"MAGI 패널",summary:"이름으로 호출하는, 저장·재사용 가능한 (머신 × AI) 멤버 팀.",details:["각 멤버는 하나의 프로바이더(AI)이며, 선택적으로 노드(머신)에 고정되고 복제 수를 가집니다.","independent — 프로바이더 ≥2 AND 머신 ≥2에 걸쳐 합의가 실질적 신뢰를 더합니다.","coupled — 하나의 AI 또는 머신으로 수렴; 반복 멤버는 같은 실수를 반복합니다.","패널 탭에서 머신 로컬로 관리; ~/.adhdev/meshes.json에 정의됩니다."]},convergence:{term:"브랜치 수렴 상태",summary:"워크트리 작업 후 각 브랜치는 정확히 하나의 최종 상태로 분류됩니다.",details:["merged_to_main — 베이스에 머지됨.","pushed_feature_branch_needs_merge — 푸시됨, 머지 대기.","blocked_review — 리뷰/도달성 문제로 보류됨.","cleanup_candidate — 정리 준비 완료.","not_mergeable — 머지 불가."]}}},approvals:{title:"대기 중인 승인",empty:"승인 결정을 기다리는 세션이 없습니다.",sessionFallback:"세션 {{id}}",approve:"승인",reject:"거절"},chat:{loading:"불러오는 중…",empty:"메시지가 없습니다."},coordinatorBadge:{daemon:"데몬: {{id}}",run:"실행: {{id}}",session:"세션: {{id}}"},difficulty:{intro:"각 태스크 난이도를 브레인에 매핑하세요. 코디네이터가 태스크의 난이도를 분류하며, 쉬운 작업은 저노력의 저렴한 모델에서, 어려운 작업은 고노력의 강력한 모델에서 실행됩니다. 필드를 비워 두면 라우팅된 기본값을 유지합니다.",connectPrompt:"브레인 프리셋을 편집하려면 코디네이터 데몬에 연결하세요.",errorLoad:"브레인 프리셋을 불러오지 못했습니다",errorSave:"브레인 프리셋을 저장하지 못했습니다",provider:"프로바이더",model:"모델",thinking:"사고",routedDefault:"(라우팅 기본값)",defaultOption:"(기본값)",modelPlaceholder:"예: haiku, sonnet, opus",savePresets:"프리셋 저장",saving:"저장 중…",reset:"초기화",loading:"불러오는 중…",easy:"쉬움",easyHint:"사소한 수정, 이름 변경, 문서 — 토큰 절약",medium:"보통",mediumHint:"일반적인 기능 / 버그 수정 작업",difficult:"어려움",difficultHint:"아키텍처, 까다로운 디버깅, 어려운 추론",freeform:"자유형",freeformHint:"고정된 형태 없음"},magiKind:{intro:"각 태스크 유형을 검토할 에이전트를 선택하세요. 에이전트당 한 행씩 추가합니다.",refresh:"새로고침",loading:"불러오는 중…",connectPrompt:"kind → 패널 바인딩을 관리하려면 코디네이터 데몬에 연결하세요.",errorLoad:"kind 패널을 불러오지 못했습니다",errorSave:"kind 바인딩을 저장하지 못했습니다",errorRemove:"kind 바인딩을 제거하지 못했습니다",errorSlotProvider:"슬롯 {{slot}}: 프로바이더가 필요합니다",errorSlotReplica:"슬롯 {{slot}}: 복제 수는 1 이상이어야 합니다",errorNoSlot:"kind 바인딩에는 최소 하나의 슬롯이 필요합니다",removeConfirm:'"{{kind}}"의 MAGI 패널 바인딩을 제거할까요?',kindRca:"근본 원인 분석",kindDesign:"설계 / 접근 검토",kindClaimAudit:"특정 주장 검증",kindFreeform:"자유형 검토",agentCount_one:"에이전트 {{count}}개",agentCount_other:"에이전트 {{count}}개",off:"꺼짐",noAgents:"아직 에이전트가 없습니다 — 하나 추가하여 이 검토 유형을 활성화하세요.",machine:"머신",machineTitle:'이 에이전트를 실행할 머신. "any"로 두면 코디네이터가 태그로 라우팅합니다.',anyMachine:"아무 머신",offlineSuffix:"{{label}} (오프라인)",provider:"프로바이더",providerTitle:"이 슬롯이 실행하는 AI 에이전트.",selectProvider:"프로바이더 선택…",model:"모델",modelTitle:"선택적 모델 재정의(최선). 비워 두면 프로바이더 기본값을 사용합니다.",modelDefault:"기본값",modelCustom:"사용자 지정…",backToModelList:"← 모델 목록으로",copies:"복제 수",copiesTitle:"이 에이전트를 병렬로 몇 개 실행할지. 비우면 = 1.",removeAgent:"에이전트 제거",addAgent:"+ 에이전트 추가",save:"저장",saving:"저장 중…",removeBinding:"바인딩 제거",removeBindingTitle:"이 kind 바인딩 지우기",removeBindingDisabledTitle:"제거할 것이 없습니다 — 이 kind는 구성되지 않았습니다"},synthesis:{empty:"이 메시에 아직 영속된 MAGI 교차 검증 합성이 없습니다. MAGI 리뷰(mesh_magi_review)를 실행하고 수집(mesh_magi_collect)하세요. 합성된 요약이 메시 원장에 영속되어 여기에 표시됩니다.",synthesized:"합성됨",running:"실행 중",answered:"{{answered}}/{{total}} 응답",needsVerificationCount:"{{count}}건 검증 필요",agreedCount:"{{count}}건 합의",staleCount:"{{count}}건 오래됨",gitSkewLabel:"Git 편차: ",gitSkewNote_one:"브랜치 {{count}}개 ({{branches}}) — 증거가 서로 다른 코드를 비교합니다.",gitSkewNote_other:"브랜치 {{count}}개 ({{branches}}) — 증거가 서로 다른 코드를 비교합니다.",needsVerification:"검증 필요",openQuestions:"미해결 질문",rawReplicaAnswers:"원본 복제 답변",rawTitleLive:"최선: 원본 복제 텍스트는 영속되지 않으며, 복제 세션이 아직 도달 가능한 라이브 코디네이터에서만 복구할 수 있습니다.",rawTitleOffline:"원본 복제 답변을 가져오려면 라이브 코디네이터 데몬이 필요합니다.",loading:"불러오는 중…",reloadRaw:"원본 답변 다시 불러오기",loadRaw:"원본 답변 불러오기",rawNotice:"원본 복제별 텍스트는 영속되지 않습니다(이 합성 요약만 영속됨). 코디네이터에서 라이브로 가져오며, 복제 세션이 만료되거나 라이브 세션이 없으면 사용할 수 없습니다.",errorLoadRaw:"원본 답변을 불러오지 못했습니다",rawEmpty:"반환된 원본 답변이 없습니다 — 복제 트랜스크립트가 보존되지 않았거나(원본 미영속), 만료되었거나, 이 그룹에 도달 가능한 라이브 세션이 없습니다.",truncated:"잘림"},panel:{selectNode:"노드를 선택하면 상세 정보를 확인할 수 있습니다.",submoduleBadge:"서브모듈",dirtyBadge:"변경됨",outOfSyncBadge:"미동기화",conflictBadge:"충돌",orphanBadge:"고아",fieldWorkspace:"워크스페이스",fieldBranch:"브랜치",fieldUpstream:"업스트림",fieldUpstreamState:"업스트림 상태",fieldHead:"HEAD",fieldSubmodulePath:"서브모듈 경로",fieldSubmoduleCommit:"서브모듈 커밋",fieldParentNode:"부모 노드",fieldAhead:"앞섬",fieldBehind:"뒤처짐",fieldDirtyFiles:"변경 파일",fieldActiveSessions:"활성 세션",fieldProviders:"프로바이더",fieldConnection:"연결",fieldLinkNote:"링크 비고",fieldError:"오류",orphanReasons:"고아 원인",attachedChats:"연결된 채팅",providerUnknown:"알 수 없는 프로바이더",statusAwaiting:"승인 대기 중",statusGenerating:"생성 중",statusIdle:"유휴",statusCoordinator:"코디네이터",statusWorker:"워커",runtimeAgeNotReported:"런타임 경과 시간 미보고",upstreamVerified:"확인됨",upstreamUnverifiedFetch:"미확인 (fetch 실패)",upstreamUnverified:"미확인",upstreamUnavailable:"사용 불가",needsFollowUp:"후속 작업 필요",refined:"정제됨"},obs:{tabOverview:"개요",tabStatus:"상태",tabGraph:"그래프",convergenceMergedToMain:"main에 병합됨",convergenceNeedsMerge:"병합 필요",convergenceBlockedReview:"차단됨 — 리뷰 필요",convergenceCleanup:"정리 준비 완료",convergenceNotMergeable:"병합 불가",followUpLabel:"후속 작업 — {{status}}",selectedNode:"선택된 노드",selectedEdge:"선택된 엣지",activeSessions:"활성 세션",ledger:"원장 (메시 전체)",queueTasks:"큐 작업",keyWarning:"핵심 경고",healResult:"힐 결과",healPreview:"힐 미리보기",noResultCode:"반환된 결과 코드가 없습니다.",health:"헬스",legend:"범례",checking:"확인 중",heal:"힐",loadingGraph:"그래프 로딩 중…",bootstrapBanner:"라이브 데이터 대기 중 — 피어 mesh_status 프로브 성공 전까지 설정 인벤토리를 표시합니다.",emptyGraph:"이 코디네이터에 대한 라이브 메시 그래프가 아직 없습니다.",fieldMachine:"머신",fieldLocality:"로컬리티",fieldWorkspace:"워크스페이스",fieldHead:"HEAD",fieldDirtyAheadBehind:"변경/앞섬/뒤처짐",fieldSessions:"세션",fieldUpstream:"업스트림",fieldSource:"소스",fieldTransport:"전송",fieldMachineId:"머신 ID",fieldDaemonId:"데몬 ID",fieldFrom:"출발",fieldTo:"도착",fieldLabel:"레이블",fieldCompleted:"완료",fieldFailed:"실패",fieldLaunched:"시작됨",fieldRecentFailures:"최근 실패",meshConnecting:"메시 연결 중...",connecting:"연결 중...",providerUnknown:"알 수 없는 프로바이더"}},Tg={page:{title:"Repo Mesh",subtitle:"다중 워크스페이스 오케스트레이션",waitingForDaemon:"데몬 연결 대기 중...",observabilitySecondary:"메시 관측성"},list:{title:"Repo Meshes",count_one:"메시 {{count}}개",count_other:"메시 {{count}}개",createMesh:"+ 메시 생성",createTitle:"Create Repo Mesh",createOnMachine:"생성할 머신",createOnMachineHint:"메시 설정은 선택한 데몬에 저장됩니다.",noConnectedDaemon:"연결된 데몬 없음",workspace:"워크스페이스",workspaceHint:"선택한 데몬에 등록된 워크스페이스에서 선택하세요.",selectMachineFirst:"머신을 먼저 선택하세요",noRegisteredWorkspaces:"등록된 워크스페이스 없음",name:"이름",remoteUrl:"리포 리모트 URL (선택)",remoteUrlHint:"리모트 URL 또는 안정적인 식별자 중 하나를 제공하세요.",repoIdentity:"리포 식별자 (선택)",create:"생성",cancel:"취소",loading:"메시 불러오는 중...",emptyTitle:"No Repo Meshes",emptyWithDaemons:"메시를 생성하여 시작하세요.",emptyNoDaemons:"먼저 ADHDev 데몬을 연결하세요.",createFirst:"첫 메시 생성",noRepoIdentity:"리포 식별자 없음",repoMeshFallback:"Repo Mesh",nodesSuffix:"노드"},detail:{back:"← 뒤로",probing:"탐색 중…",refresh:"새로고침",delete:"삭제",observabilityTitle:"관측성",observabilityDescription:"관측성 대화상자에서 라이브 메시 그래프, 개요, 런타임 상태를 엽니다.",observabilityOpenTitle:"메시 그래프 / 개요 / 상태 대화상자 열기",observabilityDisabledTitle:"코디네이터 데몬을 먼저 선택해야 합니다",observabilityOpen:"메시 그래프 & 상태 열기",observabilityHint:"토폴로지 그래프, 개요 카드(미션, 원장, 큐, 노드, 세션), 노드별 런타임 편차.",schedulingTitle:"스케줄링",schedulingDescription:"대상 미지정 큐 작업이 적격 노드에 분배되는 방식.",distribution:"분배",recommended:"권장",saving:"저장 중…",visibilityTitle:"대시보드 노출",visibilityDescription:"이 코디네이터가 스폰하는 워커 세션이 대시보드 수신함에 표시되고 알림을 발생시킬지 여부.",visibilityLabel:"코디네이터가 스폰한 워커 세션",visibilityHint:"숨김 = 수신함을 조용히 유지하고 알림을 음소거; 코디네이터 세션을 통해 상호작용합니다. 표시 = 스폰된 모든 워커를 각각의 대화로 표시합니다.",visibilityHidden:"숨김 (알림 없음, 수신함 조용히 유지)",visibilityVisible:"표시 (모든 워커를 대시보드에 표시)",magiTitle:"MAGI 검토 패널",magiDescription:"MAGI(Multi-Agent Ground-truth Insight)는 서로의 작업을 교차 검증하여 실측을 드러내는 AI 에이전트 패널을 실행합니다. 각 검토 유형을 처리할 에이전트를 선택하세요.",advanced:"고급",coordinatorPromptTitle:"코디네이터 프롬프트",coordinatorPromptDescription:"코디네이터 세션의 시스템 프롬프트를 사용자 지정합니다. 메시별 재정의는 이 메시에만 적용되고, 사용자 수준 재정의는 이 데몬이 코디네이트하는 모든 메시에 적용됩니다.",thisMesh:"이 메시",thisMeshHint:"{{name}}의 코디네이터 세션에만 적용됩니다. 비워 두면 사용자 수준 / 데몬 기본값으로 넘어갑니다.",overrideLabel:"재정의 (기본값 대체)",overrideHint:"설정하면 데몬의 기본 베이스 프롬프트를 대체합니다. 비워 두면 기본값을 유지합니다.",overridePlaceholder:"(비어 있음 — 데몬 기본값 적용)",appendLabel:"추가 (베이스 뒤에 추가)",appendHint:"어떤 베이스 프롬프트가 선택되든 항상 그 뒤에 추가됩니다.",appendPlaceholder:"(비어 있음 — 추가 없음)",availablePlaceholders:"사용 가능한 플레이스홀더",saveCoordinatorPrompt:"코디네이터 프롬프트 저장",clear:"지우기",clearTitle:"두 필드를 모두 지웁니다. 저장을 클릭하여 커밋하세요.",userLevel:"사용자 수준 (이 데몬)",userLevelDescription:"코디네이터 데몬의 머신별 프롬프트 파일. 이 데몬이 코디네이트하는 모든 메시에 적용되며 데몬 간 동기화되지 않습니다. 위의 메시별 재정의가 이보다 우선합니다.",safetyTitle:"안전 & Git",safetyDescription:"코디네이터 주도 작업의 체크포인트, 승인 게이트, git 안전 동작.",checkpointBefore:"각 작업 전에 체크포인트 자동 커밋",checkpointAfter:"각 작업 후에 체크포인트 자동 커밋",pushApproval:"푸시 승인",requireApprovalBeforePush:"푸시 전 승인 필요",doNotRequireApproval:"승인 불필요",destructiveGitApproval:"파괴적 git 승인",requireApproval:"승인 필요",uncommittedChanges:"워크스페이스에 커밋되지 않은 변경이 있을 때",warnAndContinue:"경고 후 계속",blockTask:"작업 차단",checkpointThenContinue:"체크포인트 후 계속",autoPublishSubmodule:"서브모듈 커밋 자동 게시 (고급)",requireExplicitApproval:"명시적 승인 필요",allowRefineryPublish:"리파이너리 비강제 게시 허용",autoFastForward:"유휴 노드 자동 fast-forward",ffEnabled:"활성화 (온라인·클린·뒤처진 노드 따라잡기)",ffDisabled:"비활성화",includeRemoteNodes:"원격 노드 포함",includeRemoteNodesHint:"끄면 = 코디네이터의 로컬 워크스페이스만 자동 fast-forward됩니다.",remoteNo:"아니요 (로컬 워크스페이스만)",remoteYes:"예 (원격 소유 데몬에 위임)",detectionMode:"감지 모드",detectionModeHint:"Idle = 노드의 유휴 에지에서. Continuous = 주기적으로도 스캔(베이스 노드만).",idleEdgeOnly:"유휴 에지만",continuousScan:"연속 (주기적 스캔)",sessionCleanupLabel:"노드 제거 시 해당 세션은…",sessionCleanupHint:"트랜스크립트 정리를 런타임/프로세스 정리와 분리합니다.",mcpMode:"MCP 모드:",mcpDescription:"· 메시 MCP 서버는 CLI 에이전트에서 직접 사용할 수 있습니다."},nodeList:{title:"노드 & 프로바이더 ({{count}})",descriptionCloud:"이 메시의 워크스페이스와 선호 AI 도구. 설정 인벤토리 전용 — 라이브 그래프/git/세션 실측은 위의 메시 호스트 상태가 소유합니다.",descriptionStandalone:"이 메시에 참여하는 워크스페이스와 선호 AI 도구.",daemonCandidates:"머신 데몬 후보",daemonCandidatesHint:"선택한 메시 호스트 설정에 연결할 연결된 데몬을 선택하세요.",available:"{{count}}개 사용 가능",noDaemonsAvailable:"현재 사용 가능한 연결된 머신 데몬이 없습니다.",allDaemonsAttached:"연결된 모든 머신 데몬이 이미 연결되어 있습니다.",selectedHost:"선택된 호스트",attachMachine:"머신 연결",addNode:"노드 추가",attachMachineTitle:"머신 데몬 연결",addNodeTitle:"노드 추가",machine:"머신",selectMachine:"머신을 선택하세요...",workspacePath:"워크스페이스 경로",enterCustomPath:"또는 사용자 지정 경로 입력 →",preferredTools:"선호 AI 도구 (순서대로)",preferredToolsHint:"명시적 프로바이더 없이 실행할 때 사용되는 순서.",add:"추가",cancel:"취소",setupInventoryWarning:"설정 인벤토리 전용 — 라이브 git/세션/브랜치 세부 정보는 메시 호스트에서 직접 집계된 mesh_status 실측이 확보된 후 그래프 팝업에 표시됩니다.",emptyTitle:"노드 없음",emptyDescription:"이 메시에 워크스페이스를 추가하세요.",setupInventory:"설정 인벤토리",liveDetailGraphOwned:"라이브 브랜치/git/세션 세부 정보는 그래프가 소유합니다. 위 라이브 그래프의 노드 팝업을 사용하세요.",slotsLabel:"선호 AI 도구 (역량 슬롯)",slotsHint:"각 슬롯 = 프로바이더 + 모델 + 사고 + 처리할 작업 난이도/역량 + 슬롯별 병렬 상한. 작업은 최적 슬롯에 매칭됩니다(순서 = 선호도). 슬롯이 없으면 이 노드는 레거시 프로바이더 순서를 사용합니다.",nodeInstruction:"노드 지시 (선택)",nodeInstructionHint:"코디네이터 시스템 프롬프트에 📌 Node instruction으로 표시됩니다.",nodeInstructionPlaceholder:"예: '여기서는 스모크 테스트만 실행', '이 노드에서는 opus 사용'",saveInstruction:"지시 저장",saving:"저장 중…",removeNode:"노드 제거",details:"세부 정보",nodeId:"노드 ID:",launchReady:"실행 준비:",launchReadyYes:"예",launchReadyNo:"선호 도구가 구성되지 않음",repoRoot:"리포 루트:",activeSessionsLabel:"활성 세션:",added:"추가됨:",activeQueueAssignments:"활성 큐 배정",noActiveAssignment:"이 노드에 활성 배정된 큐 작업이 없습니다.",activeSessions:"활성 세션",launchBlocked:"이 노드에서 감지된 프로바이더가 없습니다 — 프로바이더가 선택되거나 설치될 때까지 작업 실행이 차단됩니다. (빈 역량 슬롯만으로는 실행이 차단되지 않습니다. 이것은 프로바이더를 찾지 못했다는 의미입니다.)",titleNoCount:"노드 및 제공자",workspacesDetected:"워크스페이스 {{count}}개 감지됨",pickFromSaved:"← 저장된 워크스페이스에서 선택",ownerMachine:"소유자: {{owner}} · 머신: {{machine}}"},host:{coordinatorProvider:"코디네이터 CLI 프로바이더",coordinatorProviderHint:"호스트 코디네이터 세션에 실행되는 도구.",useNodePriority:"노드 프로바이더 우선순위 사용",title:"메시 호스트 데몬",descriptionSet:"이 메시의 코디네이터와 라이브 실측(상태, 큐, 그래프, 노드 세부)을 소유하는 데몬. 메시 생성 시 고정되며 여기서 재할당할 수 없습니다.",descriptionUnset:"이 메시에는 아직 호스트가 없습니다. 연결된 데몬에서 코디네이터를 실행하면 그 데몬이 메시 호스트로 고정됩니다(1:1 핀). 이후 라이브 실측을 소유합니다.",hostLabel:"호스트:",hostNode:"호스트 노드:",unknown:"알 수 없음",hostOffline:"호스트 오프라인.",hostOfflineText:"고정된 호스트 데몬이 연결되지 않았습니다. 재연결될 때까지 라이브 상태/큐/그래프가 로드되지 않습니다. 아래에서 다른 연결된 데몬을 통해 일시적으로 명령을 라우팅할 수 있습니다 — 이는 라우팅 폴백이며 호스트 재할당이 아닙니다.",reconnectToCommand:"명령 재연결",reconnectToCommandHint:"호스트가 복귀할 때까지 이 연결된 데몬을 통해 명령을 라우팅합니다. 메시 호스트를 변경하지 않습니다.",waitForHost:"호스트 재연결 대기",noDaemonsToRoute:"명령을 라우팅할 연결된 데몬이 없습니다. 호스트(또는 다른 데몬)를 온라인으로 만드세요.",launching:"실행 중...",launchHost:"호스트 코디네이터 실행",setHostBanner:"메시 호스트를 설정하세요.",setHostBannerText:"호스트는 이 메시의 코디네이터와 라이브 실측을 소유하는 데몬입니다. 아래에서 호스트 코디네이터를 실행하여 설정하세요 — 호스트는 한 번 확립되면 고정됩니다.",hostDaemon:"호스트 데몬",hostDaemonHint:"이 메시를 호스팅할 데몬을 선택하세요. 그 위에서 코디네이터를 실행하면 호스트로 고정됩니다.",resolvingHost:"호스트 확인 중… (또는 호스팅할 데몬 선택)",launchHostSetsHost:"호스트 코디네이터 실행 (호스트 설정)",noDaemonsToHost:"연결된 데몬이 없습니다. 이 메시를 호스팅할 데몬을 온라인으로 만드세요.",online:"온라인",offline:"오프라인",noCommandTarget:"사용 가능한 명령 대상이 없습니다 — 호스트 또는 데몬을 온라인 상태로 만드세요.",pickHostFirst:"먼저 호스트 데몬을 선택하세요(또는 호스트 핀이 확정될 때까지 기다리세요).",attachNodeFirst:"먼저 이 데몬의 워크스페이스를 노드로 연결하세요."},slotEditor:{empty:"설정된 역량 슬롯이 없습니다 — 괜찮습니다. 이 노드는 여전히 프로바이더 우선순위(아래)로 작업을 실행합니다. 슬롯은 선택적 미세 조정입니다: 특정 작업 난이도나 역량을 특정 도구로 라우팅하려면 하나 추가하세요.",moveUp:"위로 이동",moveDown:"아래로 이동",removeSlot:"슬롯 제거",provider:"프로바이더",select:"(선택)",model:"모델",providerDefault:"(프로바이더 기본값)",custom:"사용자 지정…",modelPlaceholder:"모델",backToModelList:"← 모델 목록으로",thinking:"사고",thinkingDefault:"(기본값)",difficulty:"난이도 (비우면 = 전체)",capabilityTags:"역량 태그 (쉼표 구분)",maxParallel:"최대 병렬 (슬롯당)",maxParallelPlaceholder:"무제한",addSlot:"슬롯 추가",saving:"저장 중…",saveSlots:"슬롯 저장"},tagEditor:{noSpaces:"태그에는 공백을 포함할 수 없습니다.",reservedPrefix:"그 접두사는 자동 파생됩니다 — 다른 태그를 선택하세요.",alreadyAdded:"이미 추가됨.",routingTags:"라우팅 태그",autoDerivedTitle:"자동 파생 — 편집할 수 없음",customTagTitle:"사용자 지정 태그",remove:"{{tag}} 제거",addPlaceholder:"사용자 지정 태그 추가 (예: test-runner)",add:"추가",saving:"저장 중…",saveTags:"태그 저장",empty:"라우팅 태그 없음 — 특정 역량과 매칭 없이 여기서 작업을 실행할 수 있습니다. 태그는 선택 사항입니다."},missions:{errorFetch:"전체 미션 목표를 가져오지 못했습니다",title:"미션",description:"코디네이터가 보고한 활성 및 과거 미션. 목표를 펼치면 전체 텍스트를 온디맨드로 가져옵니다.",empty:"{{status}} 미션이 없습니다.",taskCount_one:"태스크 {{count}}개",taskCount_other:"태스크 {{count}}개",goalUnavailable:" … (전체 목표 사용 불가)",showLess:"간략히 보기",loading:"불러오는 중…",showFullGoal:"전체 목표 보기",showMore:"{{count}}개 더 보기"},queue:{title:"큐",description:"활성 큐 작업을 과거의 완료·실패·취소된 작업 기록과 분리하여 검사합니다.",statActive:"활성",statPending:"대기",statAssigned:"배정됨",statStale:"오래됨",statHistorical:"과거",statCompleted:"완료",statFailed:"실패",loading:"불러오는 중...",refresh:"큐 새로고침",refreshHint:"호스트 소유 작업 수와 최근 배정을 보려면 큐를 새로고침하세요.",empty:"큐가 비어 있습니다.",staleBadge:"오래됨",staleTitle:"오래된 배정",waitingOnTitle:"대기 대상: {{tasks}}",waitsOn_one:"태스크 {{count}}개 대기",waitsOn_other:"태스크 {{count}}개 대기",blocked:"차단됨",durationTitle:"디스패치 → 종료 실시간",retry_one:" · 재시도 {{count}}회",retry_other:" · 재시도 {{count}}회",node:"노드 {{id}}",session:"세션 {{id}}"},promptPreview:{connectPrompt:"기본값을 미리 보려면 데몬을 연결하세요.",errorRender:"기본 프롬프트를 렌더링하지 못했습니다",hide:"기본 프롬프트 숨기기",view:"기본 프롬프트 보기",rendering:"렌더링 중…",retry:"다시 시도",info:"재정의가 비어 있을 때 코디네이터 세션이 받는 내용입니다."},hermesMcp:{title:"Hermes MCP 구성",description:"Hermes는 리포 로컬 .mcp.json을 자동 가져오지 않습니다. Hermes 구성의 mcp_servers 아래에 이 YAML을 추가한 뒤 새 Hermes 세션을 시작하세요.",fallbackProvider:"Hermes CLI"}},Ig={copyMessage:"메시지 복사"},Mg={connectingToMachine:"머신에 연결 중",establishingP2P:"P2P 연결 설정 중",agentNotMonitored:"에이전트 모니터링 안 됨",clickToSwitchMonitoring:"이 에이전트로 모니터링 전환하려면 클릭하세요",agentPanelHidden:"에이전트 패널이 아직 표시되지 않습니다",openPanelHint:"사용 중인 앱에서 에이전트 패널이나 채팅 보기를 열어 메시지를 확인하세요",noMessagesYet:"아직 메시지가 없습니다",loadingChat:"채팅 불러오는 중...",openPanel:"{{label}} 패널 열기",switchingPanel:"전환 중...",openingPanel:"여는 중..."},Dg={attachImage:"이미지 첨부",placeholder:"{{panel}}에 메시지 전송... (줄바꿈은 Shift+Enter)",sendMessage:"메시지 전송",dropImage:"여기에 이미지를 놓으세요"},Pg={noConversations:"아직 대화가 없습니다",waitingForDaemon:"데몬을 기다리는 중",connectYourMachines:"머신을 연결하세요",daemonDescription:"ADHDev 데몬을 시작하여 이 대시보드에 연결하세요. 온라인이 되면 설치된 프로바이더로 세션을 실행할 수 있습니다.",installDescription:"머신에 ADHDev를 설치하고 로그인하면 여기에 표시됩니다.",newSession:"새 세션",newSessionDescription:"연결된 머신이 준비되었습니다. CLI, ACP, IDE 중 설치된 프로바이더로 새 세션을 시작하세요."},Lg={loadOlderOutput:"이전 터미널 출력 불러오기",loadingOlder:"이전 항목 불러오는 중...",debug:"디버그",copy:"복사",openControlKeys:"터미널 제어 키 열기",closeControlKeys:"터미널 제어 키 닫기"},Rg={muteThis:"이 채팅 음소거",unmuteThis:"이 채팅 음소거 해제",mutedTitle:"음소거됨 — 알림이 차단되었습니다. 클릭하여 해제하세요.",muteTitle:"이 채팅 알림 음소거"},Eg={switchToTerminal:"터미널 보기로 전환",switchToChat:"채팅 보기로 전환"},_g={resumeSavedHistory:"저장된 기록 재개",startFresh:"새로 시작",resumingSavedHistory:"저장된 기록 재개 중…",startingFresh:"새로 시작 중…",startIde:"IDE 시작",startingIde:"IDE 시작 중…",startAcpSession:"ACP 세션 시작",startingAcpSession:"ACP 세션 시작 중…",recoverHostedRuntime:"호스팅 런타임 복구",hostedRuntimeRecoveryDescription:"중단 후 호스팅 런타임의 폴백 복구. 일반적인 연속성을 위해서는 저장된 기록을 여세요.",openSavedHistory:"저장된 기록 열기",savedHistoryTitle:"저장된 기록",savedHistoryHelper:"같은 프로바이더 대화의 연속성을 원할 때 저장된 기록을 사용하세요.",savedHistoryEmpty:"아직 저장된 기록이 없습니다.",refreshSavedHistory:"저장된 기록 새로고침",refreshingSavedHistory:"저장된 기록 새로고침 중…",startFreshWith:"{{label}}(으)로 새로 시작할까요?",restart:"{{label}}을(를) 재시작할까요?",startFreshReview:"새로 시작하기 전에 프로바이더와 대상 폴더를 확인하세요.",restartIdeReview:"IDE를 재시작하기 전에 대상 워크스페이스를 확인하거나 변경하세요.",restartStoppedReview:"중지된 세션을 재시작하기 전에 대상 워크스페이스를 확인하거나 변경하세요.",confirmStartFresh:"새로 시작",confirmRestart:"재시작",confirmStartingFresh:"새로 시작 중…",confirmRestarting:"재시작 중…",resumeWith:"{{label}}(으)로 저장된 기록을 재개할까요?",resumeReview:"저장된 기록을 재개하기 전에 대상 워크스페이스를 확인하거나 변경하세요."},$g={nav:{dashboard:"대시보드",settings:"설정",docs:"문서",about:"정보"},layout:{expandSidebar:"사이드바 펼치기",collapseSidebar:"사이드바 접기",collapse:"접기"},auth:{loading:"스탠드얼론 대시보드 로드 중…",loadError:"스탠드얼론 인증 상태 로드 실패: {{error}}",signInTitle:"스탠드얼론 로그인",passwordProtected:"이 셀프호스트 대시보드는 로컬 비밀번호로 보호되어 있습니다.",tokenProtected:"이 스탠드얼론 서버는 토큰으로 보호되어 있습니다. 토큰이 포함된 URL로 접근하거나, 이미 인증된 세션에서 비밀번호를 설정하세요.",passwordPlaceholder:"스탠드얼론 비밀번호 입력",unlock:"대시보드 잠금 해제",signingIn:"로그인 중…",noPasswordEnabled:"이 서버에서는 비밀번호 로그인이 활성화되어 있지 않습니다."},machine:{loading:"⏳ 머신 로드 중...",awaitingInput:"입력을 기다리는 중 ↑"},settings:{title:"설정",subtitle:"로컬 데몬 구성, 외관 및 기기 내 환경설정",infoNotice:"스탠드얼론 설정은 이 머신에만 저장됩니다. 브라우저는 localhost 또는 셀프호스트 LAN 엔드포인트를 통해 로컬 데몬에만 연결합니다.",publicHostWarning:"이 스탠드얼론 서버가 현재 인증 없이 0.0.0.0에 바인딩되어 있습니다. 비밀번호나 토큰을 설정하기 전까지 같은 LAN의 누구나 대시보드에 접근할 수 있습니다.",daemonSection:"데몬",daemonDescription:"셀프호스트 런타임의 연결 상태 및 로컬 엔드포인트.",versionLabel:"버전",statusLabel:"상태",statusRunning:"● 실행 중",statusNotConnected:"○ 연결되지 않음",currentBindLabel:"현재 바인드",defaultBindLabel:"기본 바인드",authLabel:"인증",authPassword:"비밀번호 활성화됨",authToken:"토큰 활성화됨",authNone:"인증 미설정",networkSection:"네트워크 접근",networkDescription:"향후 스탠드얼론 실행에 사용할 기본 바인드 호스트를 선택하세요. CLI --host 플래그는 일회성 실행에 대해 이를 재정의합니다.",networkHint:"이 대시보드를 현재 머신에서만 사용하려면 localhost 전용을 선택하세요. 폰, 태블릿 또는 LAN의 다른 기기에서 접근하려면 모든 인터페이스를 선택하세요. 외부에 더 넓게 노출한다면 비밀번호나 토큰을 설정하세요.",localhostLabel:"Localhost 전용",localhostHint:"127.0.0.1에 바인딩. 이 머신에서만 대시보드를 열 때 적합합니다.",allInterfacesLabel:"모든 인터페이스",allInterfacesHint:"0.0.0.0에 바인딩. LAN 접근, 리버스 프록시, 또는 외부 진입점에 적합합니다.",saveNetworkMode:"기본 네트워크 모드 저장",saving:"저장 중…",networkRestartHint:"다음 스탠드얼론 재시작 시 적용됩니다. 현재 실행은 {{host}}에 바인딩된 상태로 유지됩니다.",networkSavedAll:"기본 스탠드얼론 네트워크 모드가 모든 인터페이스(0.0.0.0)로 설정되었습니다. 적용하려면 스탠드얼론을 재시작하세요.",networkSavedLocal:"기본 스탠드얼론 네트워크 모드가 localhost 전용으로 설정되었습니다. 적용하려면 스탠드얼론을 재시작하세요.",securitySection:"대시보드 보안",securityDescription:"이 스탠드얼론 대시보드를 사용하는 브라우저에 대한 셀프호스트 전용 비밀번호 보호.",passwordSet:"현재 브라우저 접근에 로컬 비밀번호가 필요합니다. 변경 시 기존 세션이 갱신됩니다.",passwordNotSet:"스탠드얼론 비밀번호가 아직 설정되지 않았습니다. --host로 실행하는 경우 비밀번호 설정을 강력히 권장합니다.",currentPasswordPlaceholder:"현재 비밀번호",currentPasswordFirstTimePlaceholder:"현재 비밀번호 (최초 설정 시 불필요)",newPasswordPlaceholder:"새 비밀번호",newPasswordFirstTimePlaceholder:"새 스탠드얼론 비밀번호",confirmPasswordPlaceholder:"새 비밀번호 확인",updatePassword:"비밀번호 변경",enablePassword:"비밀번호 활성화",disablePassword:"비밀번호 비활성화",passwordUpdated:"스탠드얼론 비밀번호가 변경되었습니다.",passwordEnabled:"스탠드얼론 비밀번호가 활성화되었습니다.",passwordDisabled:"스탠드얼론 비밀번호가 비활성화되었습니다.",passwordTooShort:"비밀번호는 최소 4자 이상이어야 합니다.",passwordMismatch:"새 비밀번호와 확인 비밀번호가 일치하지 않습니다.",detectedIdesSection:"감지된 IDE",detectedIdesDescription:"이 머신에서 로컬 데몬이 발견한 편집기.",noIdesDetected:"감지된 IDE가 없습니다. IDE를 시작하면 여기에 표시됩니다.",machineSection:"머신",machineDescription:"스탠드얼론 데몬이 노출하는 로컬 burrow.",daemonNotConnected:"데몬이 연결되지 않았습니다. 'adhdev-standalone'을 실행하여 시작하세요.",appearanceSection:"외관",appearanceDescription:"모드, 테마, 스탠드얼론 전용 폰트 재정의를 한 곳에서 관리합니다.",themeDescription:"스탠드얼론 UI에 맞는 프리셋을 선택하거나 서피스, 액센트, 채팅 팔레트를 직접 커스터마이즈하세요.",mobileDescription:"폰에서 대시보드를 채팅 앱 우선으로 열지, 전체 워크스페이스 레이아웃으로 열지 선택하세요.",fontsLabel:"폰트",fontsDescription:"채팅 텍스트, 마크다운 코드, 터미널 출력에 대한 스탠드얼론 전용 타이포그래피 재정의.",fontsSaved:"이 셀프호스트 대시보드에 스탠드얼론 채팅 폰트가 저장되었습니다.",notificationsSection:"알림",notificationsDescription:"에이전트 활동에 대한 브라우저 알림 및 로컬 사운드 신호.",soundEffectsLabel:"효과음",soundEffectsDescription:"에이전트가 완료되거나 승인이 필요할 때 소리 재생",profileSection:"프로필",profileDescription:"로컬 채팅 스레드 및 대시보드 뷰에 이름이 표시되는 방식.",displayNameLabel:"표시 이름",displayNameHint:"채팅 스레드 및 팀 대시보드에 표시되는 이름.",displayNamePlaceholder:"익명"},onboarding:{title:"ADHDev에 오신 것을 환영합니다",selectedCount_one:"{{count}}개 프로바이더 선택됨",selectedCount_other:"{{count}}개 프로바이더 선택됨",skip:"건너뛰기",installing:"설치 중…",done:"완료",installCount:"{{count}}개 설치",intro:"사용할 프로바이더를 선택하세요. 기본값은 공식 지원 CLI 프로바이더 4개입니다. 아래 탭에서 IDE, ACP, 익스텐션 프로바이더를 설치하거나 나중에 Burrow → Providers → Add provider에서 추가할 수 있습니다.",loadingRegistry:"레지스트리 로드 중…",loadError:"레지스트리 로드 실패: {{error}}",noProviders:"이 카테고리에 프로바이더가 없습니다.",installed:"✓ 설치됨",installFailed:"✗ {{error}}"},about:{title:"정보",subtitle:"셀프호스트 ADHDev 개요, 내장 서피스, Cloud와의 차이점",selfHostedEdition:"셀프호스트 에디션",headline:"런타임을 온디바이스에서 완전히 실행하면서 동일한 대시보드 경험을 유지하세요.",description:"Standalone은 브라우저, 데몬, 스크린샷, 제어 경로를 모두 본인 머신에 유지합니다. 원격 네트워킹과 팀 레이어 없이 Cloud와 동일한 핵심 제품 형태입니다.",docs:"문서 ↗",github:"GitHub ↗",tryCloud:"Cloud 체험 ↗",includedSection:"스탠드얼론 포함 기능",includedDescription:"Cloud 컨트롤 플레인 없이 사용 가능한 로컬 우선 기능 세트.",inventorySection:"내장 인벤토리",inventoryDescription:"스탠드얼론 대시보드에 노출된 번들 편집기 및 에이전트 서피스. 이 목록은 인벤토리를 설명하며 지원 여부를 보장하지 않습니다.",cloudExtrasSection:"Cloud 전용 추가 기능",cloudExtrasDescription:"호스트된 컨트롤 플레인 또는 팀 인프라가 필요한 기능.",comparisonSection:"셀프호스트 vs Cloud",comparisonDescription:"제품 분리 한눈에 보기.",featureHeader:"기능",selfhostHeader:"셀프호스트",cloudHeader:"Cloud",cloudOptional:"Cloud는 선택 사항입니다",cloudOptionalDescription:"Standalone에서 완전히 로컬로 유지하다가 나중에 대시보드 사용 방식을 바꾸지 않고 Cloud로 이전할 수 있습니다.",compareCloud:"Cloud 비교 ↗",discord:"Discord ↗"},fonts:{fontOverridesNotice:"스탠드얼론 전용 폰트 재정의. Cloud 대시보드에는 영향을 주지 않습니다. 채팅 버블, 마크다운 산문, 코드 블록, 툴 행, 터미널 출력은 모두 아래 환경설정을 따릅니다.",chat:"채팅 텍스트",chatDescription:"어시스턴트/사용자 산문, 마크다운 텍스트, 생각 카드, 시스템 메모.",code:"코드 블록",codeDescription:"마크다운 코드 펜스, 인라인 코드, 서식 있는 명령 출력.",terminal:"터미널",terminalDescription:"채팅 모드에서 터미널 트랜스크립트 카드 및 툴/명령 행.",livePreview:"라이브 미리보기",resolvedStack:"해결된 스택:",defaults:"기본값:",saveFontSettings:"폰트 설정 저장",revertToSaved:"저장된 값으로 되돌리기",resetToDefaults:"기본값으로 재설정",saving:"저장 중…"}},Bg={login:{eyebrow:"클라우드 로그인",title:"ADHDev에 로그인",subtitle:"머신을 연결하고, 승인·완료 알림을 받고, 자리를 비운 동안에도 코딩 에이전트를 계속 진행시키세요.",continueWith:"{{provider}}(으)로 계속하기",connecting:"연결 중...",devDivider:"개발",devLogin:"개발 로그인 (test_jwt_token)",providerNote:"GitHub와 Google은 인증 용도로만 사용됩니다.",errorUnverifiedEmail:"이 로그인 제공자가 인증된 이메일을 반환하지 않아 안전하게 로그인할 수 없었습니다.",termsPrefix:"계속 진행하면 ",termsLink:"서비스 약관",termsAnd:" 및 ",privacyLink:"개인정보 처리방침",termsSuffix:"에 동의하게 됩니다."},account:{title:"계정",subtitle:"프로필, 플랜 및 활동",tabAccount:"계정",tabBilling:"결제",tabActivity:"활동",profile:"프로필",noName:"이름 없음",displayName:"표시 이름",displayNameDesc:"대시보드와 팀 워크스페이스에 표시되는 이름입니다.",nicknamePlaceholder:"닉네임",save:"저장",saving:"...",cancel:"취소",saved:"저장됨",edit:"편집",failedToSave:"저장 실패",userId:"사용자 ID",loadingProfile:"프로필 불러오는 중...",planLimits:"플랜 한도",limitMachines:"머신",limitP2P:"P2P 연결",limitWebhooks:"웹훅",limitTurnRelay:"TURN 릴레이",enabled:"사용",disabled:"사용 안 함",frozen:"동결됨",session:"세션",logout:"로그아웃",logoutConfirm:"정말 로그아웃하시겠습니까?",logoutDesc:"이 기기에서 ADHDev 계정을 로그아웃합니다.",dangerZone:"위험 구역",dangerZoneDesc:"계정과 관련된 모든 데이터를 영구적으로 삭제합니다. 이 작업은 되돌릴 수 없습니다.",deleteAccount:"계정 삭제",deleteWillRemove:"다음 항목이 영구적으로 삭제됩니다:",deleteItemProfile:"프로필 및 로그인 자격 증명",deleteItemKeys:"모든 API 키 및 연결 토큰",deleteItemWebhooks:"웹훅 및 전송 기록",deleteItemPush:"푸시 알림 구독",deleteItemSessions:"공유 세션 및 감사 로그",deleteTypeConfirm:"{{keyword}}(을)를 입력하여 확인하세요:",deleting:"삭제 중...",permanentlyDelete:"영구 삭제",failedToDeleteAccount:"계정 삭제 실패",registeredMachines:"등록된 머신",machinesSummary:"{{count}}개 등록 · {{online}}개 온라인",machinesLimit:"(한도: {{limit}})",loadingMachines:"머신 불러오는 중...",noMachinesRegistered:"등록된 머신 없음",runSetupPrefix:"머신에서 ",runSetupMiddle:"을(를) 실행한 다음 ",runSetupSuffix:"을(를) 시작하면 여기에 등록됩니다.",removeMachineConfirm:"이 머신을 제거하시겠습니까? 다시 연결하려면 `adhdev setup`을 다시 실행해야 합니다.",failedToDeleteMachine:"머신 삭제 실패",failedToUpdate:"업데이트 실패",rename:"이름 변경",online:"온라인",connecting:"연결 중",lastSeen:"마지막 접속 {{time}}",removeMachine:"머신 제거",never:"없음",justNow:"방금 전",minutesAgo:"{{minutes}}분 전",hoursAgo:"{{hours}}시간 전",daysAgo:"{{days}}일 전"},billing:{title:"결제",subtitle:"구독 및 플랜 관리",currentPlan:"현재 플랜:",statusTrial:"체험판",statusActive:"활성",statusPastDue:"연체",statusCanceled:"취소됨",nextBilling:"다음 결제: {{date}}",trialEnds:"체험 종료: {{date}}",accessUntil:"이용 가능 기한: {{date}}",updatePayment:"결제 수단을 업데이트해 주세요",managePayment:"결제 및 청구서 관리",couldNotOpenPortal:"결제 포털을 열 수 없습니다",statMachines:"머신",statTeam:"팀",statTurnPerDay:"TURN 분/일",monthly:"월간",yearly:"연간",savePercent:"17% 절약",paddleLoading:"Paddle을 불러오는 중입니다. 다시 시도해 주세요.",cancelConfirm:"정말 구독을 취소하시겠습니까? 결제 기간이 끝날 때까지는 계속 이용할 수 있습니다.",teamSeats:"팀 좌석",seatsUsed:"{{total}}개 중 {{used}}개 사용 중",pricePerMonth:"${{price}}/월",cannotReduceSeats:"{{count}}개 미만으로 줄일 수 없습니다(현재 사용 중). 먼저 멤버를 제거하세요.",removeSeat:"− 좌석 제거",addSeat:"+ 좌석 추가",cancelSubscription:"구독 취소",cancelRetainAccess:"현재 결제 기간이 끝날 때까지 {{plan}} 기능을 계속 이용할 수 있습니다.",cancelTeamDowngrade:" 모든 팀 멤버는 개인 플랜으로 다운그레이드됩니다."},about:{title:"소개",subtitle:"클라우드 개요, 지원 환경, 플랜별 기능",cloudEdition:"클라우드 버전",heroTitle:"어디서든 로컬 CLI 에이전트를 웹으로 제어하세요.",heroDesc:"ADHDev Cloud는 여러분 머신에서 실행 중인 에이전트를 브라우저에 표시합니다: 프롬프트 전송, 액션 승인, 머신 간 작업 오케스트레이션, 폰 알림 — 코드는 P2P로 데몬에 직접 전달되며 서버를 통하지 않습니다.",openDashboard:"대시보드 열기",viewMachines:"머신 보기",docs:"문서 ↗",whyTitle:"ADHDev Cloud를 쓰는 이유",whyDesc:"머신이 클라우드 컨트롤 플레인을 통해 연결될 때 사용할 수 있는 핵심 기능.",howTitle:"작동 방식",howDesc:"설치부터 원격 제어까지의 클라우드 온보딩 경로.",repoMeshTitle:"Repo Mesh",repoMeshDesc:"머신 간 에이전트 오케스트레이션 — 클라우드 전용.",meshCard1Title:"코디네이터 하나, 많은 에이전트",meshCard1Desc:"미션에 태스크를 등록하고 유휴 노드가 로컬 우선, 풀 기반 큐에서 작업을 가져가게 합니다. 머신과 프로바이더에 걸쳐 분산 — 하나에 Claude Code, 다른 곳에 Codex — 그리고 단일 코디네이터 세션에서 결과를 수렴합니다.",meshCard2Title:"같은 레포, 여러 머신 동시에",meshCard2Desc:"각 노드는 체크아웃 또는 격리된 git 워크트리여서 병렬 에이전트가 충돌하지 않습니다. Refinery가 모든 브랜치를 수렴 — 검증, 머지, 푸시, 정리 — 안전한 서브모듈 처리와 함께. 데몬 간 직접 P2P 채널로 실행되며 서버는 동일 계정 피어를 시그널링하고 인증만 합니다.",worksWith:"지원 대상",worksWithDesc:"지원되는 CLI 에이전트, IDE, AI 익스텐션.",groupCli:"CLI 에이전트",groupIdes:"IDE",groupExtensions:"AI 에이전트",pricingTitle:"요금제",pricingDesc:"현재 클라우드 플랜과 티어별 머신 용량.",planPopular:"인기",planPerMonth:"/월",readyTitle:"머신을 연결할 준비가 됐습니다",readyDesc:"대시보드로 이동하거나, 연결된 머신을 확인하거나, 아직 설정 중이라면 문서를 계속 읽으세요.",dashboard:"대시보드",machines:"머신",discord:"Discord ↗",github:"GitHub ↗",features:{webControlTitle:"로컬 CLI 에이전트 웹 제어",webControlDesc:"Claude Code, Codex, Gemini 등 어떤 로컬 CLI 에이전트든 브라우저에서 구동하세요: 프롬프트 전송, 액션 승인, 터미널 없이 세션 조종.",chatRelayTitle:"에이전트 채팅 릴레이",chatRelayDesc:"모바일 포함 어디서든 에이전트 대화를 읽고 응답합니다.",liveViewTitle:"실시간 세션 보기",liveViewDesc:"에이전트 활동을 실시간으로 확인하고, IDE 세션은 창 전환 없이 P2P로 화면을 보고 제어합니다.",mobileTitle:"모바일 지원",mobileDesc:"개발 머신을 떠나서도 승인을 받고 진행 상황을 확인합니다.",secureTitle:"기본으로 안전",secureDesc:"채팅, 명령어, 스크린샷은 WebRTC를 통해 브라우저와 데몬 사이를 직접 흐릅니다 — 클라우드는 인증과 시그널링 메타데이터만 처리합니다. 코드는 절대 서버를 통해 라우팅되지 않습니다."},steps:{step1Title:"한 줄 설치",step1Desc:"구동하려는 모든 머신에서 명령어 하나를 실행하세요. ADHDev 데몬과 adhdev CLI를 설치합니다.",step2Title:"로그인",step2Desc:"GitHub 또는 Google로 한 번 로그인하면 데몬이 계정에 스스로 페어링됩니다 — 복사할 토큰이 없습니다.",step3Title:"어디서든 에이전트 구동",step3Desc:"머신이 즉시 대시보드에 나타납니다. Claude Code, Codex, Gemini 등 CLI 에이전트를 웹에서 실행하고 제어하세요 — IDE 세션도 마찬가지입니다."},plans:{freeName:"Free",proName:"Pro",ultraName:"Ultra",freePer:"/월",proPer:"/월",ultraPer:"/월",freeFeature1:"머신 1개",freeFeature2:"실시간 채팅 릴레이",freeFeature3:"로컬 에이전트 웹 제어",freeFeature4:"커뮤니티 지원",proFeature1:"머신 2개",proFeature2:"AI 에이전트 무제한",proFeature3:"P2P 원격 보기",proFeature4:"7일 무료 체험",ultraFeature1:"머신 5개 — 고정 가격, 좌석당 아님",ultraFeature2:"Pro의 모든 것 포함",ultraFeature3:"더 높은 동시성 및 사용 한도",ultraFeature4:"무제한 일일 스크린샷 시간"}},layout:{navDashboard:"대시보드",navBurrows:"Burrows",navNotifications:"알림",navMesh:"Mesh",navMarketplace:"마켓플레이스",navTeam:"팀",navApi:"API",navWebhooks:"웹훅",navAccount:"계정",navSettings:"설정",navDocs:"문서",navAbout:"소개",adminSection:"관리자",adminOverview:"개요",adminUsers:"사용자",adminAuditLogs:"감사 로그",adminSystem:"시스템",adminEntry:"관리자",footerPlanTitle:"현재 플랜: {{plan}} — 관리 또는 업그레이드",expandSidebar:"사이드바 펼치기",collapseSidebar:"사이드바 접기",collapse:"접기",logoutConfirm:"정말 로그아웃하시겠습니까?",logout:"로그아웃",machineLimitBanner:"Free 플랜 머신 한도({{count}}개{{plural}})에 도달했습니다. 더 추가하려면 업그레이드하세요.",upgradeArrow:"업그레이드 →"},settings:{title:"설정",subtitle:"외관 및 환경설정",quickLinksTitle:"빠른 링크",quickLinksDesc:"모바일 수신함에서 가장 자주 필요한 페이지를 바로 열기.",linkNotificationsTitle:"알림",linkNotificationsSubtitle:"푸시, 브라우저 알림, 전달 설정",linkAccountTitle:"계정",linkAccountSubtitle:"프로필, 결제, 세션, 계정 삭제",linkAboutTitle:"소개",linkAboutSubtitle:"클라우드 개요, 지원 환경, 플랜",linkDocsTitle:"문서",linkDocsSubtitle:"새 탭에서 제품 문서 열기",appearanceTitle:"외관"},planCard:{unlimited:"무제한",machineSingular:"{{count}}개 머신",machinePlural:"{{count}}개 머신",sharedSessionSingular:"공유 세션 {{count}}개",sharedSessionPlural:"공유 세션 {{count}}개",teamMemberSingular:"팀 멤버 {{count}}명",teamMemberPlural:"팀 멤버 {{count}}명",turnPerDay:"TURN {{count}}분/일",recommended:"추천",currentPlan:"현재 플랜",contactUs:"문의하기",freeForever:"영구 무료",startTrial:"7일 무료 체험 시작",upgradeTo:"{{name}}으로 업그레이드",noChargeCancel:"7일간 무료. 언제든 취소 가능.",periodSeatMo:"좌석/월",periodMo:"월",yearlyNote:"${{yearly}}/년 — ${{saved}} 절약",pricingCustom:"맞춤 견적"},activity:{filterPlaceholder:"작업, 리소스 또는 소스로 필터...",refresh:"새로고침",loading:"불러오는 중...",noLogs:"로그 없음",noMatchingLogs:"일치하는 로그가 없습니다.",logsWillAppear:"작업이 발생하면 여기에 표시됩니다.",colAction:"작업",colResource:"리소스",colSource:"소스",colTime:"시간",logCount:"로그 {{count}}개",logCountFiltered:" ({{total}}개에서 필터됨)"},webhooks:{title:"웹훅",subtitle:"실시간 이벤트 알림",addWebhook:"+ 웹훅 추가",eventDaemonConnect:"데몬 연결됨",eventDaemonDisconnect:"데몬 연결 해제됨",eventAgentStatus:"에이전트 상태 변경",eventApprovalRequired:"승인 필요",failed:"실패",deleteConfirm:"이 웹훅을 삭제하시겠습니까?",testFailed:"테스트 실패",secretTitle:"웹훅 시크릿",secretShownOncePrefix:"",secretShownOnce:"한 번만",secretShownOnceSuffix:" 표시됩니다. 다음을 검증하는 데 사용하세요: ",copy:"복사",done:"완료",newWebhook:"새 웹훅",labelUrl:"URL",urlPlaceholder:"https://your-service.com/webhook",labelEvents:"이벤트",allEvents:"모든 이벤트 (*)",creating:"생성 중...",create:"생성",cancel:"취소",loading:"불러오는 중...",noWebhooks:"웹훅 없음",noWebhooksDesc:"이벤트에 대한 실시간 알림을 받으세요.",setupFirst:"첫 웹훅 설정",off:"꺼짐",autoDisabled:"자동 비활성화됨",autoDisabledTitle:"연속 10회 실패 후 자동 비활성화됨",failuresWarning:"⚠ 실패 {{count}}회",failuresTitle:"연속 {{count}}회 실패 — 10회에서 자동 비활성화됩니다",all:"전체",history:"기록",test:"테스트",delete:"삭제",deleting:"...",recentDeliveries:"최근 전송",refresh:"새로고침",noDeliveries:"아직 전송 내역이 없습니다. 🧪로 테스트를 보내세요.",request:"요청",response:"응답",securityTitle:"보안",securityVerifyPrefix:"",securityVerifySuffix:"을(를) 시크릿으로 검증하세요",securityHttps:"HTTPS 엔드포인트만 사용하세요",securityAsync:"즉시 2xx를 반환하고 비동기로 처리하세요",securityAutoDisable:"연속 10회 실패 후 자동 비활성화됨"},apiKeys:{title:"API 키",keyCount:"키 {{count}}개",playground:"플레이그라운드",create:"+ 생성",scopeDaemonRead:"데몬 읽기",scopeDaemonReadDesc:"데몬 목록 및 상태 조회",scopeDaemonControl:"데몬 제어",scopeDaemonControlDesc:"명령, 실행/중지, 연결 해제",scopeAgentRead:"에이전트 읽기",scopeAgentReadDesc:"상태 및 채팅 기록",scopeAgentControl:"에이전트 제어",scopeAgentControlDesc:"전송, 승인/거부",scopeTerminal:"터미널",scopeTerminalDesc:"명령 실행",scopeWebhooks:"웹훅",scopeWebhooksDesc:"훅 및 전송 관리",frozen:"동결됨",revokeConfirm:"이 API 키를 취소하시겠습니까? 되돌릴 수 없습니다.",failedToLoad:"불러오기 실패",failed:"실패",upgradePlan:"플랜 업그레이드 →",keyCreated:"키 생성됨!",copyNow:"지금 복사하세요 — 한 번만 표시됩니다.",copied:"복사됨",copy:"복사",testKey:"테스트",dismiss:"닫기",playgroundTitle:"API 플레이그라운드",enterKeyToTest:"테스트할 API 키를 입력하세요.",open:"열기",createKeyTitle:"API 키 생성",labelName:"이름",namePlaceholder:"예: Production Bot",permissions:"권한 ({{count}})",createBtn:"생성",cancel:"취소",loading:"불러오는 중...",noKeys:"API 키 없음",noKeysDesc:"외부 서비스와 연동할 키를 생성하세요.",createFirstKey:"첫 키 생성",usedDate:"{{date}} 사용",neverUsed:"사용 안 함",revoke:"취소",usageLabel:"사용법:",apiReference:"API 레퍼런스 →"},auditLogs:{title:"감사 로그",subtitle:"보안 이벤트 및 API 기록",refresh:"새로고침",filterPlaceholder:"작업, 리소스 또는 소스로 필터...",loading:"불러오는 중...",noLogs:"로그 없음",noMatchingLogs:"일치하는 로그가 없습니다.",logsWillAppear:"작업이 발생하면 여기에 표시됩니다.",colAction:"작업",colResource:"리소스",colSource:"소스",colTime:"시간",logCount:"로그 {{count}}개",logCountFiltered:" ({{total}}개에서 필터됨)"},inviteModal:{title:"팀원 초대",subtitle:"이메일로 초대 링크를 보내세요",manageSeats:"→ 결제에서 시트 관리",emailLabel:"이메일 주소",emailPlaceholder:"colleague@company.com",roleLabel:"역할",roleViewer:"뷰어",roleMember:"멤버",roleAdmin:"관리자",roleViewerDesc:"대시보드 및 채팅 기록을 볼 수 있습니다",roleMemberDesc:"에이전트를 제어하고 명령을 보낼 수 있습니다",roleAdminDesc:"멤버 및 설정을 관리할 수 있습니다",cancel:"취소",sending:"전송 중...",sendInvite:"초대 보내기",inviteSent:"초대를 보냈습니다!",shareWith:"이 링크를 공유하세요",copied:"복사됨!",copy:"복사",done:"완료"},shareModal:{title:"세션 공유",chatLabel:"채팅",chatDesc:"AI 대화만",remoteLabel:"원격",remoteDesc:"스크린샷 + 데스크탑",permissionLabel:"권한 수준",authRequired:"계정 필요",expiresAfter:"만료 기간",maxViewers:"최대 시청자",hide:"숨기기",activeShares:"활성 공유",creating:"생성 중...",createChatLink:"채팅 링크 생성",createRemoteLink:"원격 링크 생성",expires:"만료",revoke:"취소",shareLinkCreated:"공유 링크가 생성되었습니다!",viewerMustLogin:"이 링크를 사용하려면 시청자가 로그인해야 합니다",copy:"복사",copied:"복사됨!",expiresAt:"만료:",done:"완료",failedToCreate:"공유 링크를 만들지 못했습니다",expiry1h:"1시간",expiry6h:"6시간",expiry24h:"24시간",expiry7d:"7일",chatView:{label:"보기 전용",desc:"AI 대화를 실시간으로 읽기"},chatControl:{label:"제어",desc:"읽기 + 메시지 보내기 + 작업 승인/거부"},remoteView:{label:"보기 전용",desc:"스크린샷 + 채팅을 실시간으로 보기"},remoteControl:{label:"제어",desc:"스크린샷 + 메시지 보내기 + 승인/거부"},remoteFull:{label:"전체 접근",desc:"데스크탑 입력을 포함한 전체 원격 제어"}},onboarding:{title:"첫 번째 머신을 연결하세요",subtitle:"머신에 ADHDev를 설치하고 로그인하면 자동으로 연결되어 여기에 표시됩니다. 그런 다음 이 대시보드에서 모든 에이전트를 제어하세요.",platformMac:"🍎🐧 macOS / Linux",platformWindows:"🪟 Windows",copyTitle:"클릭하여 복사",copiedLabel:"✓ 복사됨",copyLabel:"📋 복사",listeningLabel:"데몬을 기다리는 중 — 페이지를 열어두세요, 자동으로 나타납니다.",connectingLabel:"ADHDev에 연결 중…",step1Title:"데몬 설치",step1Desc:"제어하려는 머신에서 위 명령을 실행하세요. 데몬과 adhdev CLI가 함께 설치됩니다.",step2Title:"로그인 — 머신이 자동으로 연결됩니다",step2Desc:"데몬이 이 계정에 자동으로 연결됩니다. 토큰을 복사할 필요 없이 연결되는 순간 여기에 나타납니다.",step3Title:"첫 세션을 시작하세요",step3Desc:"머신이 온라인 상태가 되면 대시보드에서 Claude Code, Codex, Cursor 등을 바로 시작할 수 있습니다.",readDocs:"📚 문서 읽기 →"},legal:{navHome:"홈",navDashboard:"대시보드",footerHome:"홈",footerTerms:"이용약관",footerPrivacy:"개인정보처리방침",footerRefund:"환불 정책",footerCopyright:"© 2026 RacoLab. All rights reserved."},authCallback:{authFailed:"인증 실패",backToLogin:"로그인으로 돌아가기",completing:"인증을 완료하는 중...",noTokenError:"액세스 토큰을 받지 못했습니다"},cliAuth:{title:"ADHDev CLI 인증",verifying:"확인 중...",authorizeAs:"{{name}}(으)로 CLI를 승인하시겠습니까?",noCodeError:"인증 코드가 제공되지 않았습니다.",approve:"✓ 승인",signInFirst:"CLI를 승인하려면 먼저 로그인해 주세요.",signIn:"로그인 →",failed:"실패",successMessage:"CLI 인증이 완료되었습니다!",returnToTerminal:"터미널로 돌아갈 수 있습니다."},privacy:{title:"개인정보처리방침",lastUpdated:"최종 업데이트: 2026년 3월 23일",intro:'이 개인정보처리방침은 RacoLab("당사")이 ADHDev 서비스("서비스")를 통해 정보를 수집, 사용 및 보호하는 방법을 설명합니다. 서비스 주소:',s1Title:"1. 수집하는 정보",s1h1:"1.1 계정 정보",s1p1:"계정을 생성할 때, 인증 제공자(GitHub 또는 Google)가 제공하는 이름, 이메일 주소, 프로필 사진 등의 정보를 수집합니다.",s1h2:"1.2 IDE 및 에이전트 데이터",s1p2:"개발 환경을 서비스에 연결하면 로컬 데몬이 다음 정보를 전송할 수 있습니다:",s1l1:'IDE 유형 및 버전 (예: "Cursor 0.49.1")',s1l2:"활성 AI 에이전트 정보 (이름, 상태, 현재 모델)",s1l3:"사용자와 AI 에이전트 간의 채팅 메시지",s1l4:"IDE 스크린샷 (P2P로 전송되며 당사 서버에 저장되지 않음)",s1l5:"워크스페이스 경로 및 열린 파일 이름",s1l6:"머신 정보 (호스트명, OS, 메모리 사용량)",s1h3:"1.3 사용 데이터",s1p3:"서비스 개선 및 디버깅을 위해 API 호출, 기능 사용 패턴, 연결 로그 등의 사용 정보를 자동으로 수집합니다.",s1h4:"1.4 결제 정보",s1p4:"결제 처리는 당사의 판매 대리인인 Paddle(Paddle.com Market Limited)이 전담합니다. 당사는 신용카드 번호, 은행 계좌 정보 또는 기타 금융 정보를 직접 수집하거나 저장하지 않습니다. Paddle의 데이터 처리 관행에 대해서는",s1p4PaddleLink:"Paddle 개인정보처리방침",s1p4Suffix:"을 참조하십시오.",s2Title:"2. 정보 이용 방법",s2p1:"수집된 정보는 다음 목적에 사용됩니다:",s2l1:"서비스 제공 및 유지",s2l2:"신원 인증 및 계정 관리",s2l3:"대시보드와 연결된 머신 간의 명령 및 데이터 라우팅",s2l4:"에이전트 상태 변경에 대한 알림(브라우저 및 푸시) 전송",s2l5:"결제 및 구독 관리 처리 (Paddle을 통해)",s2l6:"남용 또는 무단 접근 감지 및 방지",s2l7:"서비스 개선 및 새 기능 개발",s2l8:"지원 요청 응답",s3Title:"3. 데이터 저장 및 보안",s3h1:"3.1 인프라",s3p1:"당사 서비스는 Cloudflare Workers, Durable Objects 및 D1 Database를 활용하는 Cloudflare의 글로벌 네트워크에서 운영됩니다. 데이터는 Cloudflare 인프라에 저장되며",s3p1CloudflareLink:"Cloudflare 개인정보처리방침",s3h2:"3.2 P2P 데이터",s3p2:"IDE 스크린샷 및 실시간 터미널 데이터는 WebRTC 피어투피어 연결을 통해 브라우저와 머신 간에 직접 전송됩니다. 이 데이터는 당사 서버를 경유하거나 저장되지 않습니다.",s3h3:"3.3 보안 조치",s3p3:"당사는 다음과 같은 보안 조치를 구현합니다:",s3l1:"단기 액세스 토큰 및 리프레시 토큰 순환을 활용한 JWT 기반 인증",s3l2:"암호화된 WebSocket 연결 (WSS/TLS)",s3l3:"데몬 인증을 위한 연결별 토큰",s3l4:"모든 API 엔드포인트에 대한 속도 제한",s3l5:"보안 민감 작업에 대한 감사 로깅",s4Title:"4. 데이터 공유",s4p1:"당사는 개인 데이터를 제3자에게 판매하지 않습니다. 다음과 같은 경우 데이터를 공유할 수 있습니다:",s4l1:"판매 대리인으로서의 결제 처리",s4l2:"인프라 제공업체 (호스팅, CDN, 데이터베이스)",s4l3Label:"인증 제공업체",s4l3:"OAuth 로그인을 위한 GitHub/Google",s4p2:"법률, 법적 절차에 의해 요구되거나 당사의 권리 및 사용자의 안전을 보호하기 위해 필요한 경우 데이터를 공개할 수 있습니다.",s5Title:"5. 데이터 보존",s5p1:"계정이 활성 상태인 동안 계정 데이터를 보존합니다. 채팅 메시지 및 에이전트 활동 데이터는 서비스 기능을 위해 최대 90일간 보존됩니다.",s5p2:"계정 삭제 시 30일 이내에 개인 데이터를 삭제합니다. 일부 익명화된 사용 데이터는 분석 목적으로 보존될 수 있습니다.",s6Title:"6. 귀하의 권리",s6p1:"귀하는 다음과 같은 권리를 보유합니다:",s6l1Label:"열람",s6l1:"개인 데이터 사본 요청",s6l2Label:"정정",s6l2:"개인 정보 업데이트 또는 수정",s6l3Label:"삭제",s6l3:"계정 및 관련 데이터 삭제 요청",s6l4Label:"이동",s6l4:"이동 가능한 형식으로 데이터 다운로드",s6l5Label:"이의",s6l5:"특정 데이터 처리 활동에 대한 이의 제기",s6p2:"이러한 권리를 행사하려면 다음으로 문의하십시오:",s7Title:"7. 쿠키",s7p1:"당사는 인증(세션 토큰) 및 사용자 환경설정(테마, 알림 설정)에 필수 쿠키만 사용합니다. 광고 또는 추적 쿠키는 사용하지 않습니다.",s8Title:"8. 아동 개인정보",s8p1:"서비스는 만 16세 미만의 사용자를 대상으로 하지 않습니다. 당사는 만 16세 미만의 아동으로부터 의도적으로 개인 정보를 수집하지 않습니다.",s9Title:"9. 국제 데이터 이전",s9p1:"귀하의 데이터는 Cloudflare의 글로벌 네트워크를 통해 다양한 위치에서 처리될 수 있습니다. 서비스를 이용함으로써 귀하는 이러한 위치에서의 데이터 이전 및 처리에 동의합니다.",s10Title:"10. 정책 변경",s10p1:"당사는 수시로 이 개인정보처리방침을 업데이트할 수 있습니다. 중요한 변경 사항은 이메일 또는 서비스를 통해 알려드립니다. 변경 후 서비스를 계속 이용하면 업데이트된 정책에 동의한 것으로 간주됩니다.",s11Title:"11. 문의",s11p1:"이 개인정보처리방침 또는 데이터 관행에 대한 문의:",s11l1Prefix:"이메일:",s11l2Prefix:"웹사이트:"},terms:{title:"이용약관",lastUpdated:"최종 업데이트: 2026년 4월 11일",intro:'ADHDev("서비스")에 오신 것을 환영합니다. 서비스는 RacoLab("당사")이 운영합니다.',introSuffix:'에서 서비스에 접근하거나 이용함으로써 이 이용약관("약관")에 동의하게 됩니다. 동의하지 않으시면 서비스를 이용하지 마십시오.',s1Title:"1. 서비스 설명",s1p1:"ADHDev는 웹 및 모바일 대시보드를 통해 AI 코딩 에이전트(Cursor, VS Code, Antigravity, Claude Code 등)를 원격으로 모니터링하고 제어할 수 있는 클라우드 개발자 도구입니다. 서비스에는 로컬 데몬, 원격 대시보드, REST API 접근, 브라우저 및 푸시 알림이 포함됩니다.",s2Title:"2. 계정 등록",s2p1:"서비스를 이용하려면 계정을 생성해야 합니다. 계정 자격증명의 기밀 유지는 귀하의 책임입니다. 등록 시 정확하고 완전한 정보를 제공하고 계정 정보를 최신 상태로 유지하는 데 동의합니다.",s2p2:"서비스를 이용하려면 만 16세 이상이어야 합니다. 계정을 생성함으로써 이 연령 요건을 충족함을 확인합니다.",s3Title:"3. 구독 플랜 및 결제",s3p1:"서비스는 다음 플랜을 제공합니다:",s3l1:"제한된 기능, 연결 머신 1대",s3l2:"연결 머신 2대, 무제한 에이전트, P2P 원격 보기, 7일 무료 체험",s3l3:"연결 머신 5대, Pro의 모든 기능 및 더 높은 동시성과 사용 한도 (좌석당이 아닌 정액 요금)",s3p2:"유료 구독은 월별 또는 연간 단위로 선불 청구됩니다. 모든 결제는 당사의 결제 파트너인 Paddle(Paddle.com Market Limited)이 처리하며, Paddle은 모든 거래에서 판매 대리인으로 활동합니다.",s4Title:"4. 환불 정책",s4p1:"당사는 모든 유료 플랜에 대해 14일 환불 보장을 제공합니다. 서비스에 만족하지 못하시면 최초 구매 후 14일 이내에 다음 주소로 문의하여 전액 환불을 요청할 수 있습니다:",s4p2:"갱신에 대한 환불은 사례별로 처리됩니다. 판매 대리인인 Paddle의 환불 정책도 적용됩니다.",s5Title:"5. 허용 사용",s5p1:"귀하는 다음 행위를 하지 않는 데 동의합니다:",s5l1:"불법적인 목적이나 관련 법률을 위반하여 서비스 사용",s5l2:"다른 사용자의 계정이나 데이터에 무단으로 접근 시도",s5l3:"서비스 서버 구성 요소의 소스 코드를 역공학, 디컴파일 또는 추출 시도",s5l4:"악성 소프트웨어, 스팸 또는 기타 유해 콘텐츠 전송에 서비스 사용",s5l5:"당사의 서면 동의 없이 서비스 재판매 또는 재배포",s5l6:"서비스의 무결성 또는 성능 방해 또는 중단",s6Title:"6. 지식재산권",s6p1:"원본 콘텐츠, 기능 및 기능성을 포함한 서비스는 RacoLab이 소유하며 관련 지식재산법의 보호를 받습니다. 로컬 데몬 구성 요소는 프로젝트 저장소에 명시된 오픈소스 라이선스 하에 제공됩니다.",s6p2:"귀하는 서비스를 통해 전송하는 모든 데이터 및 콘텐츠의 소유권을 보유합니다.",s7Title:"7. 데이터 및 개인정보",s7p1:"서비스 이용은 당사의",s7PrivacyLink:"개인정보처리방침",s7p1Suffix:"에도 적용됩니다. 서비스는 원격 모니터링 및 제어 목적으로 IDE 상호작용, 채팅 메시지 및 스크린샷을 처리합니다. 당사는 귀하의 데이터를 제3자에게 판매하지 않습니다.",s8Title:"8. 서비스 가용성",s8p1:"당사는 높은 가용성을 유지하려 노력하지만 중단 없는 접근을 보장하지는 않습니다. 서비스는 유지보수, 업데이트 또는 당사의 통제 밖의 상황으로 인해 일시적으로 이용 불가할 수 있습니다. 당사는 서비스 중단으로 인한 손실에 대해 책임을 지지 않습니다.",s9Title:"9. 책임의 제한",s9p1:"법이 허용하는 최대 범위 내에서, RacoLab은 서비스 이용으로 인해 발생하는 간접적, 부수적, 특별, 결과적 또는 징벌적 손해, 또는 이익이나 수익 손실에 대해 직간접적으로 책임을 지지 않습니다.",s9p2:"서비스로부터 발생하는 모든 청구에 대한 당사의 총 책임은 청구 이전 12개월 동안 귀하가 지불한 금액을 초과하지 않습니다.",s10Title:"10. 해지",s10p1:"당사는 이 약관 위반이나 기타 이유로 언제든지 귀하의 서비스 접근을 정지하거나 종료할 수 있습니다. 귀하는 설정 페이지를 통해 언제든지 계정을 취소할 수 있습니다. 취소 후 30일 이내에 귀하의 데이터가 삭제됩니다.",s11Title:"11. 약관 변경",s11p1:"당사는 언제든지 이 약관을 수정할 권리를 보유합니다. 중요한 변경 사항은 이메일 또는 서비스를 통해 알려드립니다. 변경 후 서비스를 계속 이용하면 수정된 약관에 동의한 것으로 간주됩니다.",s12Title:"12. 준거법",s12p1:"이 약관은 법률 충돌 조항에 관계없이 대한민국 법률에 따라 해석됩니다.",s13Title:"13. 문의",s13p1:"이 약관에 대한 질문이 있으시면 문의해 주세요:",s13l1Prefix:"이메일:",s13l2Prefix:"웹사이트:"},refund:{title:"환불 정책",lastUpdated:"최종 업데이트: 2026년 3월 24일",intro:"ADHDev는 RacoLab이 운영합니다. 모든 결제는 당사의 판매 대리인인",introSuffix:"이 결제, 청구서 발행 및 환불을 대신 처리합니다.",s1Title:"1. 14일 환불 보장",s1p1:"당사는 모든 유료 플랜(Pro)에 대해 14일 환불 보장을 제공합니다. 어떤 이유로든 서비스에 만족하지 못하신다면, 최초 구독 구매 후 14일 이내에 전액 환불을 요청할 수 있습니다.",s1p2:"환불을 요청하려면 다음 이메일로 계정 이메일과 주문 정보를 포함하여 문의하십시오:",s1p2Suffix:"3영업일 이내에 요청을 처리해 드리겠습니다.",s2Title:"2. 갱신 환불",s2p1:"구독 갱신(월별 또는 연간)에 대한 환불은 사례별로 처리됩니다. 의도치 않은 갱신 요금이 청구된 경우, 청구 후 7일 이내에 다음으로 문의해 주세요:",s3Title:"3. 환불 불가 사례",s3p1:"다음의 경우 환불이 제공되지 않습니다:",s3l1:"최초 구매 14일 보장 기간 이후에 요청된 환불",s3l2Prefix:"다음을 위반하여 정지 또는 해지된 계정:",s3l2Link:"이용약관",s3l3:"환불 기간을 초과하여 이미 사용된 부분 서비스 기간",s4Title:"4. 환불 처리 방법",s4p1:"승인된 환불은 Paddle을 통해 처리되어 원래 결제 수단으로 반환됩니다. 은행이나 카드사에 따라 환불이 나타나는 데 5~10영업일이 소요될 수 있습니다. Paddle의",s4p1RefundLink:"환불 약관",s4p1Suffix:"도 적용됩니다.",s5Title:"5. 취소",s5p1Prefix:"대시보드의",s5p1BillingLink:"결제",s5p1Suffix:"페이지에서 언제든지 구독을 취소할 수 있습니다. 취소하면 이후 요금이 청구되지 않습니다. 현재 결제 기간이 끝날 때까지 플랜 기능을 계속 이용할 수 있습니다. 취소 자체로는 환불이 발생하지 않습니다.",s6Title:"6. 문의",s6p1:"환불 요청 또는 결제 관련 문의:",s6l1Prefix:"이메일:",s6l2Prefix:"웹사이트:"},teamWorkspace:{title:"팀",subtitle:"시트 기반 팀 관리 — 시트당 월 $15, 중앙 집중 결제",planRequired:"팀 플랜 필요",planDesc:`팀 워크스페이스는 팀 플랜(시트당 월 $15)에서 사용 가능합니다.
33
+ 시트 관리, 팀원 초대, 조직 전체 결제 관리를 중앙에서 처리하세요.`,upgradeBtn:"팀으로 업그레이드 →",seatsTitle:"팀 시트",seatsUsedOf:"{{used}} / {{total}} 시트 사용 중",seatsAvailable:"{{count}}개 사용 가능",seatsFullMsg:"모든 시트가 사용 중입니다. 더 많은 시트를 추가하려면",seatsBillingLink:"결제",seatsBillingLinkSuffix:"페이지를 방문하세요.",newWorkspace:"새 워크스페이스",workspaceNamePlaceholder:"워크스페이스 이름...",createBtn:"만들기",cancelBtn:"취소",noWorkspaceYet:"아직 팀 워크스페이스가 없습니다",noWorkspaceDesc:"워크스페이스를 만들어 팀을 관리하고 시트를 공유하세요.",createWorkspace:"워크스페이스 만들기",membersTab:"멤버 ({{count}})",sessionsTab:"세션",settingsTab:"설정",membersTitle:"멤버 ({{count}})",inviteBtn:"+ 초대",pendingInvites:"대기 중인 초대 ({{count}})",pendingBadge:"대기 중",removeBtn:"제거",removeMemberConfirm:"이 멤버를 제거하시겠습니까? 해당 멤버는 팀 플랜 접근 권한을 잃게 됩니다.",removeSuccess:"멤버가 제거되었습니다",invitationSent:"초대가 전송되었습니다!",joinedSuccess:"팀 워크스페이스에 성공적으로 참여했습니다!",waitingApproval:"{{name}}님의 세션 보기 요청 승인을 기다리는 중...",viewRequestSent:"{{name}}님에게 보기 요청을 전송했습니다. 승인을 기다리는 중...",viewDeclined:"{{name}}님이 보기 요청을 거절했습니다",sessionRestricted:"조직 정책에 의해 세션 보기가 제한되어 있습니다 (admin_only)",sessionTitle:"팀 세션",noMembersOnline:"온라인 팀원 없음",selfBadge:"나",machineNoSessions:"머신 온라인, 활성 세션 없음",offline:"오프라인",statusGenerating:"생성 중...",statusApprovalNeeded:"승인 필요",statusStarting:"시작 중...",statusStopped:"중지됨",statusError:"오류",statusDisconnected:"연결 끊김",statusHidden:"숨김",statusUnmonitored:"모니터링 안 됨",statusIdle:"대기 중",viewBtn:"보기 →",requestBtn:"요청 →",policyOpen:"공개",policyRequest:"요청",policyAdminOnly:"관리자 전용",settingsTitle:"워크스페이스 설정",sessionVisibilityTitle:"세션 공개 범위",sessionVisibilityDesc:"팀원의 AI 에이전트 세션을 볼 수 있는 대상을 설정합니다",visibilityOpen:"공개",visibilityOpenDesc:"모든 멤버가 세션을 자유롭게 볼 수 있습니다",visibilityRequest:"요청 기반",visibilityRequestDesc:"멤버는 접근을 요청해야 합니다. 관리자는 항상 볼 수 있습니다.",visibilityAdminOnly:"관리자 전용",visibilityAdminOnlyDesc:"관리자와 소유자만 세션을 볼 수 있습니다.",dangerZone:"위험 구역",dangerZoneDesc:"되돌릴 수 없는 작업",deleteWorkspace:"워크스페이스 삭제",deleteWorkspaceConfirm:"이 팀 워크스페이스를 삭제하시겠습니까? 모든 멤버가 팀 플랜 혜택을 잃게 됩니다.",leaveWorkspace:"워크스페이스 나가기",leaveWorkspaceConfirm:"정말 이 워크스페이스를 나가시겠습니까? 플랜이 다운그레이드될 수 있습니다."},sessionShare:{loading:"세션 불러오는 중...",sessionNotFound:"세션을 찾을 수 없음",noLongerAvailable:"이 세션은 더 이상 사용할 수 없습니다",homeBtn:"← ADHDev 홈",sharedSession:"공유된 세션",host:"호스트",mode:"모드",permission:"권한",auth:"인증",authRequired:"계정 필요",viewers:"시청자",joinChat:"채팅 참여",joinSession:"세션 참여",expires:"만료: {{date}}",chatLabel:"채팅",remoteLabel:"원격",waitingMessages:"메시지 대기 중...",connecting:"연결 중... ({{state}})",sendMessageAs:"{{name}}으로 메시지 전송...",sendAs:"{{name}}으로 전송...",ownerChat:"{{name}}의 채팅",ownerSession:"{{name}}의 세션",agentName:"{{name}}의 에이전트",fullControlBadge:"전체 제어 활성",failedToJoin:"세션 참여 실패",sessionRevoked:"호스트가 세션을 취소했습니다",sessionExpired:"세션이 만료되었습니다",authRequired2:"제어 공유에는 인증이 필요합니다"},apiPlayground:{title:"API 플레이그라운드",history:"기록 ({{count}})",apiRelayWarning:"데몬 API 릴레이는 선택 사항입니다. 해당 데몬에서 `adhdev daemon:api enable`로 명시적으로 활성화하지 않으면 REST 명령/채팅 프록시 경로가 비활성화됩니다.",authBearer:"Authorization: Bearer {{key}}",copyAsCurl:"cURL",copied:"복사됨",targetDaemon:"대상 데몬",quickActions:"빠른 작업",requestBody:"요청 본문 (JSON)",recentRequests:"최근 요청",clearHistory:"지우기",noDaemonsWarning:"연결된 데몬이 없습니다. 먼저 데몬을 시작하거나 {daemonId}를 직접 교체하세요.",send:"▶ 전송",sending:"⏳",close:"닫기"}},Fg={openMenu:"메뉴 열기",closeMenu:"메뉴 닫기"},Hg={loadingOlderMessages:"이전 메시지 불러오는 중...",waitingForMessages:"메시지를 기다리는 중...",agentGenerating:"에이전트가 응답 중...",jumpToTop:"맨 위로 이동",jumpToOldestMessages:"가장 오래된 메시지로 이동",top:"↑ 맨 위",latest:"↓ 최신",jumpToLatestMessages:"최신 메시지로 이동",jumpToBottom:"맨 아래로 이동",showEarlierMessages:"↑ 이전 메시지 {{count}}개 표시...",showEarlierMessagesHidden:"↑ 이전 메시지 {{count}}개 표시... ({{total}}개 숨김)",loadOlderMessages:"↑ 이전 메시지 불러오기",loadErrorRetry:"↻ {{error}}"},Wg={zoomOut:"축소",zoomIn:"확대",resetZoom:"확대/축소 초기화",toggleFullscreen:"전체화면 전환"},Og={mouse:"마우스",touch:"터치",connected:"연결됨",ws:"WS",direct:"직접",relay:"릴레이",turnBlocked:"TURN 차단됨",turnUsage:"TURN {{used}}/{{budget}}분",typeAndEnter:"입력 후 Enter...",settings:"설정",zoom:"확대/축소:",fill:"꽉 채우기",fit:"맞추기",directP2PTitle:"직접 P2P 연결",turnRelayTitle:"TURN 릴레이 사용 중",dailyTurnTitle:"일일 TURN 릴레이 사용량"},Ug={title:"세션 정보",loading:"불러오는 중…",refresh:"새로고침",close:"닫기",failedToLoad:"세션 정보를 불러오지 못했습니다",notCoordinatorSession:"이 세션은 mesh 코디네이터 세션이 아니므로 코디네이터 전용 프롬프트가 주입되지 않았습니다. 에이전트는 해당 CLI의 기본 설정으로 실행됩니다.",stampedToNode:"이 세션은 코디네이터가 더 이상 보고하지 않는 mesh 노드에 스탬프되어 있습니다.",sectionSession:"세션",sectionLaunch:"실행",sectionMeshNode:"Mesh 노드",sectionMeshCoordinator:"Mesh 코디네이터",sectionRuntime:"런타임",rowSessionId:"세션 ID",rowProvider:"프로바이더",rowTransport:"전송",rowWorkspace:"워크스페이스",rowSpawnedAt:"생성 시각",rowProviderSessionId:"프로바이더 세션 ID",rowMachine:"머신",rowConnection:"연결",rowWorkspaceGit:"워크스페이스 git",rowCommand:"명령어",rowWorkingDirectory:"작업 디렉토리",rowArgs:"인수",rowExtraArgs:"추가 인수",rowExtraEnv:"추가 환경 변수",rowNodeId:"노드 ID",rowRepoRoot:"저장소 루트",rowDaemonId:"데몬 ID",rowRole:"역할",rowMachineStatus:"머신 상태",rowHealth:"상태",rowWorktree:"Worktree",rowLaunchReady:"실행 준비",rowGit:"Git",rowProviders:"프로바이더",rowProviderPriority:"프로바이더 우선순위",rowMeshId:"Mesh ID",rowCoordinatorCli:"코디네이터 CLI",rowStartedAt:"시작 시각",rowPromptInjection:"프롬프트 주입",rowMcpConfig:"MCP 설정",rowRuntimeId:"런타임 ID",rowLifecycle:"라이프사이클",rowSurface:"화면",rowRecoveryState:"복구 상태",rowRestoredFromStorage:"스토리지에서 복원됨",rowAttachedClients:"연결된 클라이언트"},Gg={status:{schedulingNotReported:"이 데몬에서 스케줄링 런타임을 보고하지 않습니다(구버전 빌드). 코디네이터 데몬을 업데이트하면 분배, 병렬 제한, 노드별 부하를 확인할 수 있습니다.",schedulingTitle:"스케줄링",distributionTitle:"분배는 미대상 작업이 적격 노드에 분산되는 방식만 관리합니다. 노드별 부하, 우선순위, 프로바이더 제한은 아래에 있습니다.",protocolTitle:"프로토콜 및 프로바이더 버전",nodesRuntime:"노드 — 런타임",noNodesReporting:"아직 런타임을 보고하는 노드가 없습니다."},overview:{missionCard:"미션",ledgerCard:"원장",queueCard:"큐",nodesCard:"노드",sessionsCard:"활성 세션",refineCard:"Refine 작업",recentActivity:"최근 활동",recentTasks:"최근 태스크",showFewer:"간략히 보기",showMore:"+{{count}}개 더",noActiveMissions:"활성 미션이 없습니다. 코디네이터가 여러 태스크 작업을 위해 미션을 생성합니다.",missionDataUnavailable:"이 데몬에서 미션 데이터를 제공하지 않습니다 — 데몬을 업데이트하여 미션을 확인하세요.",completedHistory:"완료 / 포기 기록",noQueueActivity:"큐 활동이 없습니다.",noNodes:"이 mesh에 노드가 아직 없습니다.",noActiveSessions:"활성 세션이 없습니다.",noRefineJobs:"Refine 작업이 없습니다.",closeDetail:"상세 닫기",loadingGoal:"불러오는 중…",showFullGoal:"전체 목표 보기",statCompleted:"완료",statAssigned:"할당됨",statPending:"대기 중",statFailed:"실패",statBlocked:"차단됨",statCancelled:"취소됨",statWallClock:"경과 시간",statTotalRuntime:"총 실행 시간",statRetries:"재시도",statDispatched:"디스패치됨",statStalled:"지연됨",statSessions:"세션",statCheckpoints:"체크포인트",statActive:"활성",recentFailures:"최근 실패 {{count}}건",activeCount:"{{count}}개 활성",failedCount:"{{count}}개 실패",detailKickerMission:"미션",detailKickerLedger:"원장 항목",detailKickerQueue:"큐 태스크",detailKickerSession:"세션",detailLabelMissionId:"미션 ID",detailLabelCreated:"생성 시각",detailLabelUpdated:"업데이트 시각",detailLabelLastActivity:"마지막 태스크 활동",detailLabelIncompleteEvidence:"미완료 증거",incompleteTaskCount_one:"태스크 {{count}}개",incompleteTaskCount_other:"태스크 {{count}}개",detailLabelEntryId:"항목 ID",detailLabelWhen:"시각",detailLabelNode:"노드",detailLabelSession:"세션",detailLabelProvider:"프로바이더",detailLabelPayload:"페이로드",detailLabelTaskId:"태스크 ID",detailLabelAutoLaunch:"자동 실행",detailLabelCancelReason:"취소 사유",detailLabelRequeueReason:"재큐 사유",detailLabelRequeued:"{{count}}회 재큐됨",detailLabelSessionId:"세션 ID",detailLabelBranch:"브랜치",detailLabelRole:"역할",detailLabelStarted:"시작 시각",detailLabelWorkspace:"워크스페이스"}},Kg={launchConfirm:{workspace:"워크스페이스",languageModel:"언어 모델 (선택 사항)",autoDetect:"자동 감지 또는 기본값",cliArgs:"CLI 인수 (선택 사항)",cliArgsPlaceholder:"예: --experimental",cancel:"취소",closeAria:"실행 확인 닫기",launch:"실행",launching:"실행 중…"},confirmExternal:{dialogAria:"신뢰할 수 없는 외부 프로바이더 확인",title:"신뢰할 수 없는 외부 프로바이더를 활성화하시겠습니까?",description:"이 manifest는 데몬이 실행할 JavaScript를 포함하고 있습니다. 신뢰할 수 없는 코드로 취급하여 활성화 전에 소스를 검토하세요.",proceedWarning:"추가한 소스 URL을 신뢰하고 manifest를 검토한 경우에만 진행하세요.",cancel:"취소",activate:"활성화"},workspace:{noWorkspace:"(워크스페이스 없음 — 홈 디렉토리에서 실행)",selectWorkspace:"📁 워크스페이스 선택…",customPath:"✏️ 직접 입력…",noWorkspacesSaved:"(저장된 워크스페이스 없음 — 개요 탭에서 추가)",selectWorkspaceBtn:"워크스페이스 선택…",enterAbsolutePath:"절대 경로 입력…",browseHint:"실행할 폴더를 탐색해 선택하세요.",absolutePathHint:"실행할 절대 경로를 입력하세요.",defaultWorkspace:"기본 워크스페이스",selectedWorkspace:"선택된 워크스페이스",noWorkspaceSelected:"워크스페이스가 선택되지 않았습니다. 홈 디렉토리에서 실행됩니다."},agentTab:{selectToLaunch:"{{label}} 실행 선택",launchSettings:"실행 설정",noIdesDetected:"감지된 IDE가 없습니다.",scanSystem:"시스템 검사",noProviders:"사용 가능한 {{category}} 프로바이더가 없습니다.",noProvidersHint:"바이너리가 기본 위치 외에 설치된 경우 프로바이더에서 실행 파일 경로를 직접 지정하세요.",targetModel:"대상 모델",leaveEmptyDefault:"기본값은 비워두세요",startupArguments:"시작 인수",optionalFlags:"선택적 플래그...",openSession:"세션 열기",starting:"시작 중...",configure:"설정",select:"선택",launching:"⏳ 실행 중...",launchBtn:"▶ 실행",running:"실행 중 ({{count}})",noRunning:"실행 중인 {{plural}} 없음",launchingProcess:"프로세스 실행 중...",waitingProcess:"프로세스 및 세션 등록을 기다리는 중...",startingBadge:"시작 중",chatView:"채팅 보기",terminalView:"터미널 보기",localTerminal:"로컬 터미널:",copied:"복사됨",copy:"복사",openRemoteControl:"원격 제어 열기",restart:"재시작",viewChat:"채팅 보기",openInDashboard:"현재 화면을 대시보드에서 열기",stop:"중지",extensions:"익스텐션",browseFolderTitle:"워크스페이스 선택",browseFolderDesc:"일반 탐색기 방식으로 폴더를 선택한 후 실행 대상으로 사용하세요.",browseFolderConfirm:"이 폴더 사용",detailMode:"모드",detailProvider:"프로바이더",detailResume:"이어하기",detailArguments:"인수",detailModel:"모델",categoryIde:"IDE",categoryCliPlural:"CLI",categoryAcp:"ACP 에이전트",categoryAcpPlural:"ACP 에이전트"},providers:{filter:"필터",sourceConfigTitle:"프로바이더 소스 설정",sourceConfigDesc:"데몬이 프로바이더 manifest를 찾는 위치입니다. 해석 및 재로드에 영향을 줍니다.",sourceMode:"소스 모드",explicitProviderDir:"프로바이더 디렉토리 직접 지정",providerDirPlaceholder:"비워두면 ~/.adhdev/providers 사용",applying:"적용 중…",applyReload:"적용 + 재로드",userRoot:"사용자 루트:",upstreamRoot:"업스트림 루트:",providerRoots:"프로바이더 루트:",loadingSettings:"프로바이더 설정 불러오는 중…",noProviders:"설치된 프로바이더가 없습니다. 위의 '프로바이더 추가'를 열어 설치하세요.",noFilteredProviders:"{{filter}} 프로바이더가 설치되어 있지 않습니다.",refresh:"↻ 새로고침",sources:"🌐 소스",create:"✨ 생성",advanced:"⚙ 고급"},providerRow:{statusDetected:"감지됨",statusNotDetected:"감지되지 않음",statusEnabledUnchecked:"활성화됨 (미확인)",statusDisabled:"비활성화됨",labelType:"유형:",labelVersion:"버전:",labelBinary:"바이너리:",labelStatus:"상태:",labelDetails:"상세:",labelSource:"소스:",labelTrust:"신뢰:",labelLinks:"링크:",labelDetection:"감지:",labelVerification:"검증:",saving:"저장 중…",disable:"비활성화",enable:"활성화",detect:"감지",resetCommand:"명령어 초기화"},providerFix:{aiAgent:"AI 에이전트",scriptsToFix:"수정할 스크립트",all:"전체",none:"없음",additionalInstructions:"추가 지침",optional:"(선택 사항)",agentOutput:"에이전트 출력",running:"● 실행 중...",agentGenerating:"에이전트가 응답을 생성하는 중...",validateHint:"`adhdev provider verify`를 실행하여 검증하세요",cancel:"취소",startFix:"🚀 수정 시작",cancelRunning:"⬛ 취소",back:"← 뒤로",close:"닫기",footerHint:"AI 에이전트가 프로바이더 스크립트를 구현합니다",scriptsSelected_one:"스크립트 {{count}}개 선택됨",scriptsSelected_other:"스크립트 {{count}}개 선택됨",titlePrefix:"자동 수정: {{name}}",descCodex:"OpenAI o3/gpt-5.4",descClaude:"Anthropic Claude",descGemini:"Google Gemini"},providerClone:{title:"✨ 사용자 프로바이더 생성",subtitle:"업스트림 IDE 프로바이더를 복제하여 커스터마이즈",baseProvider:"기본 프로바이더",providerTypeId:"프로바이더 유형 (ID)",typeIdPlaceholder:"my-cursor, custom-windsurf...",typeIdHint:"소문자, 영숫자 + 하이픈만 가능합니다. 생성 위치:",displayName:"표시 이름",displayNamePlaceholder:"My Custom IDE",cancel:"취소",creating:"⏳ 생성 중...",createProvider:"✨ 프로바이더 생성",createdTitle:"프로바이더가 생성되었습니다!",createdDesc:"{{type}}이(가) 생성되었습니다:",createdRunHint:"adhdev provider fix {{type}}을 실행하거나 자동 수정을 사용하여 스크립트를 구현하세요.",close:"닫기"},connectedMachines:{noMachines:"연결된 머신이 없습니다",defaultDescription:"머신에 ADHDev를 설치하고 로그인하면 여기에 표시됩니다.",startingUpgrade:"업그레이드 시작 중...",machineDisconnected:"머신이 연결 해제되었습니다.",tokenRevoked:"토큰이 취소되었습니다. 해당 머신에서 ADHDev를 재시작하여 다시 연결하세요.",failedToDisconnect:"연결 해제에 실패했습니다",failedToRevokeToken:"토큰 취소에 실패했습니다",connectionLostUpgrade:"업그레이드 중 연결이 끊겼습니다",disconnect:"연결 해제",remove:"제거",disconnectTitle:"🔌 머신 연결 해제",removeTitle:"⚠️ 머신 제거",cancel:"취소",noIdesConnected:"연결된 IDE가 없습니다",upgrading:"업그레이드 중...",updated:"✓ 업데이트됨",updateNow:"↑ 지금 업데이트",updateTo:"↑ v{{version}}으로 업데이트",cdpConnected:"CDP 연결됨",cdpConnecting:"CDP 연결 중...",connecting:"연결 중..."}},zg={theme:{helloHelp:"안녕하세요! 어떻게 도와드릴까요?",fixBug:"버그를 고쳐주세요",onIt:"알겠습니다! ✨",customEditorTitle:"🎨 커스텀 테마 편집기",darkMode:"🌙 다크 모드",lightMode:"☀️ 라이트 모드",sectionAppBackground:"앱 배경",sectionAppText:"앱 텍스트",sectionBordersAccent:"테두리 및 강조색",sectionChatBubbles:"채팅 말풍선",sectionChatLayout:"채팅 레이아웃",colorBackground:"배경",colorSurface:"서피스",colorCard:"카드",colorPrimary:"기본",colorSecondary:"보조",colorMuted:"흐림",colorBorderSubtle:"테두리 (미묘)",colorBorderDefault:"테두리 (기본)",colorAccent:"강조색",colorUserBubble:"사용자 말풍선",colorUserText:"사용자 텍스트",colorAgentBubble:"에이전트 말풍선",colorAgentText:"에이전트 텍스트",colorChatBg:"채팅 배경",colorSendButton:"전송 버튼",colorInputBorder:"입력 테두리",labelBubbleRadius:"말풍선 둥글기",resetToDefaults:"기본값으로 초기화",customLabel:"🎨 커스텀"}},qg={chatHistory:"채팅 기록",startNewChat:"+ 새 채팅 세션 시작",creating:"⌛ 생성 중...",searchPlaceholder:"제목 또는 미리보기 검색",filterWorkspace:"워크스페이스로 필터",filterModel:"모델로 필터",sortRecent:"최신순",sortOldest:"오래된순",sortMessages:"메시지 많은순",resumeReadyOnly:"재개 가능만",untitledSession:"제목 없는 세션",noSavedPreview:"저장된 미리보기 없음",workspaceUnknown:"워크스페이스 알 수 없음",selectedWorkspaceSuffix:" · 선택한 워크스페이스",msgCount:"메시지 {{count}}개",statusActive:"활성",statusMissingWorkspace:"워크스페이스 없음",statusResumeSelectedWorkspace:"선택한 워크스페이스에서 재개",statusResuming:"재개 중...",statusResume:"재개",noMatchingHistory:"이 필터와 일치하는 저장 기록이 없습니다.",noRecentChats:"최근 채팅 세션이 없습니다.",refreshHistory:"기록 새로고침",refreshing:"⌛ 새로고침 중..."},Vg={nav:{home:"ADHDev 홈",mesh:"Mesh",what:"소개",agents:"에이전트",pricing:"요금제",install:"설치",github:"GitHub",docs:"문서",getStarted:"시작하기",toggleMenu:"메뉴 토글"},hero:{badge:"멀티 벤더, 멀티 머신 에이전트 컨트롤 플레인",title:"누구나 에이전트 열 개를 돌릴 수 있습니다. ADHDev는 그 결과를 main에 착지시킵니다.",subtitle:"Claude Code, Codex, Cursor 등 어떤 로컬 코딩 에이전트든 브라우저에서 구동하고, Refinery가 완료된 작업을 main으로 자동 머지합니다 — 여러분 레포의 게이트, 패치 동등성 검사, fast-forward만, force-push 없이. 코디네이터 하나에 지시하면 여러 머신에서 에이전트들이 비동기로 실행됩니다. 세션을 지켜볼 필요 없습니다. 코드는 P2P로 여러분 머신에만 머뭅니다.",selectOs:"OS 선택",osUnix:"macOS / Linux",osWindows:"Windows",copyInstall:"설치 명령어 복사: {{cmd}}",copied:"복사됨",copy:"복사",getStarted:"시작하기",openSource:"GitHub 오픈소스",joinDiscord:"Discord 참여",selfHost:"직접 셀프 호스팅",demoDesktop:"ADHDev 커맨드 센터가 여러 머신의 에이전트 세션을 실시간으로 구동하는 모습",demoPush:"ADHDev 모바일 푸시 알림 및 원탭 승인"},mesh:{sectionTitle:"They parallelize. We land.",sectionSubtitle:"병렬 에이전트를 생성하는 건 쉬운 부분입니다 — 이제 모든 도구가 그걸 합니다. 어려운 건 그 이후입니다: 검증하고 머지해야 할 브랜치 열 개. Refinery가 그걸 대신 처리합니다 — 자동으로, 여러분 검토 큐 대신 main에 작업이 도착합니다.",refineryHighlight:"The Refinery",refineryTitle:"완료된 작업이 자동으로 main에 착지합니다",refineryDesc:"누구나 병렬 에이전트 열 개를 생성할 수 있습니다. Refinery는 각 워크트리를 레포의 게이트(타입체크, 테스트, 린트)로 검증하고, 패치 동등성을 확인하고, 서브모듈 커밋을 퍼블리시하고, main을 fast-forward한 후 정리합니다 — 자동으로. force-push는 절대 없습니다. 모호한 것은 머지 대신 검토로 돌려보냅니다.",asyncHighlight:"비동기 오케스트레이션",asyncTitle:"한 곳에 지시하면, 나머지는 알아서 실행됩니다.",asyncDesc:"코디네이터 하나에 작업을 주면, 이벤트 루프로 여러 머신의 여러 워커를 구동합니다 — 완료, 승인, 상태 이벤트가 올 때만 반응합니다. 폴링 없음, 에이전트 창 감시 없음. 각 에이전트 세션을 직접 보는 데스크톱 앱과 달리, 코디네이터가 이벤트를 기다리므로 여러분이 앞에 앉아 있을 필요가 없습니다.",monoHighlight:"모노레포 인식",monoTitle:"git 서브모듈에서도 안전합니다",monoDesc:"실제 프로덕션 레포는 서브모듈을 중첩합니다 — 그리고 그것이 바로 단순한 자동 머지가 깨지는 지점입니다. Refinery는 서브모듈을 인식합니다: 서브모듈 커밋 도달 가능성 게이트, 패치 동등성 판단, 원자적 포인터 범프. 이 프로젝트 자체가 루트 + 서브모듈 2개 모노레포로, 매일 이 방식으로 수렴됩니다.",crossHighlight:"교차 검증",crossTitle:"단일 의견이 아닌 합의",crossDesc:"동일한 읽기 전용 조사를 여러 머신 × 프로바이더 레플리카에 펼쳐 일치하는 부분과 다른 부분을 합성합니다(MAGI). 에이전트 한 개의 판단보다 신뢰할 수 있습니다.",tryMesh:"Repo Mesh 사용해보기 →",seePlans:"요금제 보기",availableOn:"Pro 이상에서 사용 가능합니다. 연결 후 <strong>Repo Mesh</strong> 페이지에서 구동하세요.",readGuide:"가이드 읽기"},compare:{sectionTitle:"병렬 에이전트는 이제 어디에나 있습니다. 그 결과물은 실제로 어디에 착지하나요?",sectionSubtitle:"합당한 질문입니다. 로컬 CLI는 서브에이전트를 생성하고, 데스크톱 오케스트레이터는 세련된 네이티브 UI로 워크트리에 작업을 분배합니다. 둘 다 브랜치에서 멈춥니다. 우리가 그들보다 나은 점과 부족한 점을 솔직하게 정리했습니다.",colLocalCli:"로컬 CLI + 서브에이전트",colDesktop:"데스크톱 오케스트레이터",colAdhdev:"ADHDev Repo Mesh",rowLandsMain:"완료 작업을 main에 착지",rowLandsMainLocalCli:"게이트 실행과 머지를 직접 해야 합니다",rowLandsMainDesktop:"작업을 병렬화한 후 브랜치를 검토하도록 넘겨줍니다",rowLandsMainAdhdev:"Refinery가 레포의 게이트를 실행하고, 패치 동등성을 확인하고, main을 fast-forward합니다 — 자동, force-push 없음",rowSubmodules:"git 서브모듈 안전 처리",rowSubmodulesLocalCli:"서브모듈을 인식하는 머지 자동화 없음",rowSubmodulesDesktop:"워크트리 병렬화는 있지만 머지는 직접 해야 합니다",rowSubmodulesAdhdev:"서브모듈 인식 수렴: 도달 가능성 게이트, 패치 동등성 검사, 원자적 포인터 범프 — 이 모노레포에서 매일 검증됨",rowAsync:"한 곳에 비동기로 지시",rowAsyncLocalCli:"한 번에 하나의 세션, 동기적으로",rowAsyncDesktop:"각 에이전트 창을 직접 감시해야 합니다",rowAsyncAdhdev:"코디네이터 하나가 이벤트 루프로 모든 워커를 구동 — 완료/승인 이벤트를 기다리므로 폴링이나 감시 불필요",rowMultiMachine:"여러 물리 머신",rowMultiMachineLocalCli:"하나의 호스트 프로세스만",rowMultiMachineDesktop:"실행 중인 하나의 머신에만 종속",rowMultiMachineAdhdev:"P2P 원격 데몬 — 소유한 모든 머신에 디스패치 (SSH 설정 불필요)",rowParallelBranch:"병렬 격리 브랜치 작업",rowParallelBranchLocalCli:"서브에이전트가 하나의 작업 트리를 공유 — 동시 쓰기 충돌",rowParallelBranchDesktop:"태스크당 git 워크트리 하나 — 핵심 강점",rowParallelBranchAdhdev:"노드당 git 워크트리 하나 — 코어뿐 아니라 머신 간 병렬",rowBrowser:"브라우저나 폰에서 구동",rowBrowserLocalCli:"터미널 앞에 있어야 합니다",rowBrowserDesktop:"네이티브 데스크톱 앱 — 그 책상에 있어야 합니다",rowBrowserAdhdev:"웹 퍼스트: 어떤 브라우저나 폰에서도 세션 제어 및 승인 가능",rowNativeApp:"네이티브 데스크톱 앱",rowNativeAppLocalCli:"터미널만",rowNativeAppDesktop:"세련된 네이티브 창 — 앞에 앉아 있기에 훨씬 좋습니다",rowNativeAppAdhdev:"웹 퍼스트입니다 — 네이티브 앱이 아닌 브라우저 탭",rowRestarts:"재시작 및 컨텍스트 손실 후에도 유지",rowRestartsLocalCli:"상태가 세션에 살아 있음 — 닫으면 사라집니다",rowRestartsDesktop:"상태가 앱 프로세스에 종속",rowRestartsAdhdev:"미션은 디스크에 지속되며 코디네이터나 데몬 재시작 후에도 재개 — 추가만 가능한 변조 불가 감사 로그",rowCrossCheck:"답을 교차 검증",rowCrossCheckLocalCli:"에이전트 하나의 판단, 두 번째 의견 없음",rowCrossCheckDesktop:"병렬 작업, 단일 판정",rowCrossCheckAdhdev:"MAGI가 동일한 읽기 전용 질문을 독립적인 머신 × 프로바이더 에이전트에 분배하고 차이를 표시합니다",footnote:"단일 머신, 단일 브랜치, 일회성 작업이라면 — 서브에이전트를 가진 로컬 CLI가 더 가볍고 잘 작동하며, 네이티브 데스크톱 오케스트레이터가 더 쾌적합니다. Repo Mesh는 작업이 여러 머신과 브랜치로 분산되고, 재시작 후에도 유지되어야 하며, 어디서든 제어하면서 자동으로 main에 착지해야 할 때 진가를 발휘합니다."},what:{sectionTitle:"어떤 에이전트든, 자유롭게 혼합",sectionSubtitle:"설계부터 벤더 중립. Mac에서 Claude Code, Windows GPU 박스에서 Codex, 리뷰 패스에 Gemini — 동일한 메시에서, 동일한 정책 아래. 플랫폼을 바꾸지 않고 벤더를 바꿉니다.",cliHighlight:"CLI 에이전트",cliTitle:"어떤 터미널 에이전트든 웹에서 구동",cliDesc:"Claude Code, Codex CLI, Cursor CLI, Antigravity CLI, Hermes, Kimi, OpenCode — PTY 어댑터를 통해 머신에 연결되어 재개 및 재연결이 가능하며, 브라우저에서 구동됩니다. 즉시 프롬프트를 보내고 시각적 컨텍스트를 제공하세요(붙여넣기, 드래그 앤 드롭, 또는 한 번에 최대 5개 이미지/10MB 업로드). Aider, Gemini CLI, Goose 등 ACP 에이전트는 stdio로 연결됩니다.",uiHighlight:"하나의 UI",uiTitle:"같은 대시보드, 어떤 기기에서든",uiDesc:"adhf.dev에 클라우드로 호스팅 — 책상에 있든 없든 노트북이나 폰에서 모든 에이전트를 구동합니다.",ideHighlight:"IDE 에이전트",ideTitle:"실행 중인 에디터에도 연결",ideDesc:"Cursor, VS Code, VSCodium, Windsurf, Antigravity, Kiro, PearAI, Trae. 실시간 채팅 읽기, 프롬프트 전송, 세션 전환, 스크린샷 캡처.",p2pHighlight:"처음부터 끝까지 여러분의 것",p2pTitle:"P2P 우선: 데이터는 여러분 것으로 유지",p2pDesc:"채팅, 명령어, 스크린샷은 WebRTC를 통해 브라우저와 데몬 사이를 직접 흐릅니다. 클라우드는 인증과 시그널링 메타데이터만 볼 뿐 — 코드는 절대 서버를 통해 라우팅되지 않습니다."},oss:{sectionTitle:"오픈소스 & 셀프 호스팅 가능",sectionSubtitle:"데몬과 대시보드는 AGPL-3.0으로 GitHub에 공개되어 있습니다. 어떤 머신이나 서버에서든 직접 실행하세요 — 계정 불필요.",github:"GitHub",selfHostDocs:"셀프 호스팅 문서"},agents:{sectionTitle:"지원 에이전트",sectionSubtitle:"{{ides}}개 내장 IDE 통합, {{clis}}개 내장 CLI 에이전트, {{extensions}}개 IDE 내장 익스텐션 에이전트, {{acp}}개 이상의 ACP(stdio MCP) 에이전트. 프로바이더 스크립트는 <code>adhdev-providers/</code>에 있으며 <code>~/.adhdev/providers/</code>에 직접 추가할 수 있습니다.",tierTested:"Tested",tierTestedDesc:"실제 앱 + 버전으로 검증됨",tierCommunity:"Community",tierCommunityDesc:"내장 및 커뮤니티 지원",groupIdes:"IDE",hintIdes:"Chrome DevTools Protocol로 연결. 채팅 읽기, 프롬프트 전송, 세션 전환, 스크린샷.",groupCli:"CLI 에이전트",hintCli:"재개 및 재연결이 가능한 PTY 어댑터로 구동.",groupExtensions:"IDE 내장 익스텐션 에이전트",hintExtensions:"다른 IDE 안에서 실행되는 에이전트를 위한 CDP 웹뷰 연결.",acpFootnote:"stdio(Agent Client Protocol)를 통한 {{count}}개 이상의 ACP 에이전트 추가 지원: Codex, Claude Agent, Gemini, Goose, Cline, OpenHands 등."},pricing:{sectionTitle:"에이전트 규모에 맞는 단순한 요금제",sectionSubtitle:"한 머신에서 무료로 시작하세요. 두 머신은 Pro, 다섯 머신은 Ultra. 좌석당 계산 없음, 엔터프라이즈 영업 전화 없음 — 아래 요금제가 전부입니다.",mostPopular:"가장 인기 있는",upgradeToPro:"Pro로 업그레이드",footnote:"단순하고 투명한 가격 — 위에 표시된 가격이 실제 결제 금액입니다. 셀프 호스팅을 선호하신다면? 데몬과 대시보드는 오픈소스입니다. 가격은 USD 기준.",plans:{free:{period:"영구 무료",tagline:"어디서든 머신 하나를 구동하는 데 필요한 모든 것.",cta:"무료로 시작",features:{machine:"머신 하나, 명령어 하나로 페어링",p2p:"P2P 채팅, 명령어, 스크린샷, 원격 입력",providers:"모든 프로바이더 — CLI, IDE, ACP 에이전트",push:"승인 및 완료 푸시 알림",share:"공유 세션 링크 하나"}},pro:{period:"/월",tagline:"두 머신에서 에이전트를 실행하고, 유료 플랜에 필요한 안정성을 갖춥니다.",cta:"Pro 7일 체험 시작",features:{machines:"머신 2개 — 양쪽에서 에이전트 실행",p2p:"더 많은 동시 P2P 세션",push:"무제한 푸시 알림",turn:"제한적 네트워크를 위한 TURN 릴레이",mesh:"Repo Mesh — 머신 간 에이전트 오케스트레이션",share:"더 많은 공유 세션"}},ultra:{period:"/월",tagline:"Pro의 모든 것에서 확장 — 대규모 병렬 작업을 위한 더 많은 머신과 높은 한도.",cta:"Ultra 시작",features:{machines:"머신 5개 — 좌석당이 아닌 고정 가격",everything:"Pro의 모든 것 포함",p2p:"최고 동시 P2P 세션",screenshots:"무제한 일일 스크린샷 시간",webhooks:"더 많은 웹훅 및 API 호출",share:"더 많은 공유 세션"}}}},install:{sectionTitle:"세 단계로 작동하는 대시보드",sectionSubtitle:"설정 파일 없음. 연결할 API 키 없음. ADHDev는 에이전트 인증을 관리하지 않습니다 — 각 도구가 자체 로그인을 유지합니다.",selectOs:"OS 선택",osUnix:"macOS / Linux",osWindows:"Windows",copyInstall:"설치 명령어 복사: {{cmd}}",copied:"복사됨",copy:"복사",platformNote:"macOS와 Windows는 검증된 설치 경로입니다. Linux는 동일한 Unix 스크립트를 실행하며 커뮤니티 테스트됩니다.",arrow:"→",steps:{step1:{title:"데몬 설치",desc:"curl 명령어 하나로 데몬과 adhdev CLI를 설치합니다 — 머신을 페어링하고 데몬을 시작하는 런처입니다(Claude Code나 Codex 같은 CLI 에이전트와 혼동하지 마세요). 동일한 바이너리가 클라우드와 스탠드얼론을 모두 지원합니다."},step2:{title:"머신 연결",desc:"GitHub 또는 Google로 한 번 로그인하면 데몬이 스스로 페어링됩니다 — 복사할 토큰이 없습니다."},step3:{title:"에이전트 구동",desc:"대시보드에서 Claude Code, Codex CLI, Cursor CLI, Antigravity CLI, Hermes, Kimi 등 에이전트를 실행하세요. 채팅 읽기, 프롬프트 전송, 시각적 컨텍스트 제공(붙여넣기, 드래그 앤 드롭, 또는 한 번에 여러 이미지 업로드), 액션 승인, 세션 전환."}}},cta:{headline:"탭 정글에서 벗어나세요. 모든 에이전트를 하나의 대시보드에서 구동하세요.",subtitle:"curl 명령어 하나, 데몬 하나, 이미 쓰고 있는 모든 에이전트. 웹에서 전부 구동하세요 — Cloud가 라이브입니다.",getStarted:"시작하기 →",github:"GitHub",discord:"Discord"},footer:{docs:"문서",github:"GitHub",discord:"Discord",dashboard:"대시보드",terms:"이용약관",privacy:"개인정보처리방침",contact:"문의",copyright:"© {{year}} RacoLab. All rights reserved."}},Yg={language:bg,common:gg,connection:xg,toast:yg,notification:vg,event:wg,dashboard:kg,cliStop:Sg,approval:Cg,newSession:jg,mobileInbox:Ng,meshGraph:Ag,repoMesh:Tg,chat:Ig,chatPane:Mg,chatInput:Dg,paneGroup:Pg,terminal:Lg,conversation:Rg,cliView:Eg,launch:_g,standalone:$g,cloud:Bg,app:Fg,chatList:Hg,screenshot:Wg,remote:Og,sessionInfo:Ug,mesh:Gg,machine:Kg,settings:zg,historyModal:qg,landing:Vg},Jg={copyMessage:"メッセージをコピー"},Qg={connectingToMachine:"マシンに接続しています",establishingP2P:"P2P接続を確立中",agentNotMonitored:"エージェントが監視されていません",clickToSwitchMonitoring:"クリックしてこのエージェントの監視に切り替えます",agentPanelHidden:"エージェントパネルがまだ表示されていません",openPanelHint:"使用しているアプリでエージェントパネルまたはチャットビューを開いてメッセージを表示してください",noMessagesYet:"まだメッセージはありません",loadingChat:"チャットを読み込み中...",openPanel:"{{label}}パネルを開く",switchingPanel:"切り替え中...",openingPanel:"開いています..."},Xg={attachImage:"画像を添付",placeholder:"{{panel}}にメッセージを送信...(改行はShift+Enter)",sendMessage:"メッセージを送信",dropImage:"ここに画像をドロップ"},Zg={noConversations:"まだ会話はありません",waitingForDaemon:"デーモンを待っています",connectYourMachines:"マシンを接続してください",daemonDescription:"ADHDevデーモンを起動してこのダッシュボードに接続してください。オンラインになると、インストールされたプロバイダーでセッションを開始できます。",installDescription:"マシンにADHDevをインストールしてサインインすると、ここに表示されます。",newSession:"新しいセッション",newSessionDescription:"接続されたマシンの準備ができています。CLI、ACP、またはIDEのインストール済みプロバイダーで新しいセッションを開始してください。"},ex={loadOlderOutput:"古いターミナル出力を読み込む",loadingOlder:"古いものを読み込み中...",debug:"デバッグ",copy:"コピー",openControlKeys:"ターミナル制御キーを開く",closeControlKeys:"ターミナル制御キーを閉じる"},tx={muteThis:"このチャットをミュート",unmuteThis:"このチャットのミュートを解除",mutedTitle:"ミュート中 — 通知はオフです。クリックで解除します。",muteTitle:"このチャットの通知をミュート"},sx={switchToTerminal:"ターミナルビューに切り替え",switchToChat:"チャットビューに切り替え"},nx={resumeSavedHistory:"保存済み履歴を再開",startFresh:"新しく開始",resumingSavedHistory:"保存済み履歴を再開中…",startingFresh:"新しく開始中…",startIde:"IDEを起動",startingIde:"IDEを起動中…",startAcpSession:"ACPセッションを開始",startingAcpSession:"ACPセッションを開始中…",recoverHostedRuntime:"ホストされたランタイムを復元",hostedRuntimeRecoveryDescription:"中断後のホストされたランタイムのフォールバック復元。通常の継続性のためには、保存済み履歴を開いてください。",openSavedHistory:"保存済み履歴を開く",savedHistoryTitle:"保存済み履歴",savedHistoryHelper:"同じプロバイダーの会話で継続性を保ちたい場合は、保存済み履歴を使用してください。",savedHistoryEmpty:"保存済み履歴がまだ見つかりません。",refreshSavedHistory:"保存済み履歴を更新",refreshingSavedHistory:"保存済み履歴を更新中…",startFreshWith:"{{label}}で新しく開始しますか?",restart:"{{label}}を再起動しますか?",startFreshReview:"新しく開始する前にプロバイダーとターゲットフォルダーを確認してください。",restartIdeReview:"このIDEを再起動する前にターゲットワークスペースを確認または変更してください。",restartStoppedReview:"この停止したセッションを再起動する前にターゲットワークスペースを確認または変更してください。",confirmStartFresh:"新しく開始",confirmRestart:"再起動",confirmStartingFresh:"新しく開始中…",confirmRestarting:"再起動中…",resumeWith:"{{label}}で保存済み履歴を再開しますか?",resumeReview:"保存済み履歴を再開する前にターゲットワークスペースを確認または変更してください。"},rx={nav:{dashboard:"Dashboard",settings:"Settings",docs:"Docs",about:"About"},layout:{expandSidebar:"Expand sidebar",collapseSidebar:"Collapse sidebar",collapse:"Collapse"},auth:{loading:"Loading standalone dashboard…",loadError:"Failed to load standalone auth status: {{error}}",signInTitle:"Standalone sign-in",passwordProtected:"This self-hosted dashboard is protected by a local password.",tokenProtected:"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session.",passwordPlaceholder:"Enter standalone password",unlock:"Unlock dashboard",signingIn:"Signing in…",noPasswordEnabled:"Password login is not enabled on this server."},machine:{loading:"⏳ Loading machine...",awaitingInput:"Awaiting your input ↑"},settings:{title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",infoNotice:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint.",publicHostWarning:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token.",daemonSection:"Daemon",daemonDescription:"Connection health and local endpoints for the self-hosted runtime.",versionLabel:"Version",statusLabel:"Status",statusRunning:"● Running",statusNotConnected:"○ Not connected",currentBindLabel:"Current bind",defaultBindLabel:"Default bind",authLabel:"Auth",authPassword:"Password enabled",authToken:"Token enabled",authNone:"No auth configured",networkSection:"Network Access",networkDescription:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",networkHint:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token.",localhostLabel:"Localhost only",localhostHint:"Bind to 127.0.0.1. Best when only this machine should open the dashboard.",allInterfacesLabel:"All interfaces",allInterfacesHint:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points.",saveNetworkMode:"Save default network mode",saving:"Saving…",networkRestartHint:"Applies on next standalone restart. Current run stays bound to {{host}}.",networkSavedAll:"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.",networkSavedLocal:"Default standalone network mode set to localhost only. Restart standalone to apply it.",securitySection:"Dashboard Security",securityDescription:"Self-hosted-only password protection for browsers using this standalone dashboard.",passwordSet:"A local password is currently required for browser access. Existing sessions are rotated when you change it.",passwordNotSet:"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended.",currentPasswordPlaceholder:"Current password",currentPasswordFirstTimePlaceholder:"Current password (not needed for first setup)",newPasswordPlaceholder:"New password",newPasswordFirstTimePlaceholder:"New standalone password",confirmPasswordPlaceholder:"Confirm new password",updatePassword:"Update password",enablePassword:"Enable password",disablePassword:"Disable password",passwordUpdated:"Standalone password updated.",passwordEnabled:"Standalone password enabled.",passwordDisabled:"Standalone password disabled.",passwordTooShort:"Password must be at least 4 characters.",passwordMismatch:"New password and confirmation do not match.",detectedIdesSection:"Detected IDEs",detectedIdesDescription:"Editors discovered by the local daemon on this machine.",noIdesDetected:"No IDEs detected. Start an IDE to see it here.",machineSection:"Machine",machineDescription:"The local burrow exposed by your standalone daemon.",daemonNotConnected:"Daemon not connected. Run 'adhdev-standalone' to start.",appearanceSection:"Appearance",appearanceDescription:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",themeDescription:"Choose a preset or create a custom surface, accent, and chat palette for the standalone UI.",mobileDescription:"Choose whether phones open the dashboard as a chat app first or in the full workspace layout.",fontsLabel:"Fonts",fontsDescription:"Standalone-only typography overrides for chat text, markdown code, and terminal output.",fontsSaved:"Standalone chat fonts saved for this self-hosted dashboard.",notificationsSection:"Notifications",notificationsDescription:"Browser prompts and local sound cues for agent activity.",soundEffectsLabel:"Sound Effects",soundEffectsDescription:"Play a sound when agent completes or needs approval",profileSection:"Profile",profileDescription:"How your name appears in local chat threads and dashboard views.",displayNameLabel:"Display Name",displayNameHint:"Your name shown in chat threads and on the team dashboard.",displayNamePlaceholder:"Anonymous"},onboarding:{title:"Welcome to ADHDev",selectedCount_one:"{{count}} provider selected",selectedCount_other:"{{count}} providers selected",skip:"Skip",installing:"Installing…",done:"Done",installCount:"Install {{count}}",intro:"Pick the providers you want to use. Defaults to the four officially supported CLI providers; you can install IDE, ACP, or extension providers from the tabs below or later from Burrow → Providers → Add provider.",loadingRegistry:"Loading registry…",loadError:"Failed to load registry: {{error}}",noProviders:"No providers in this category.",installed:"✓ installed",installFailed:"✗ {{error}}"},about:{title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",selfHostedEdition:"Self-hosted edition",headline:"Keep the same dashboard experience, with the runtime fully on-device.",description:"Standalone keeps the browser, daemon, screenshots, and control path on your own machine. It is the same core product shape as cloud, just without the remote networking and team layers.",docs:"Docs ↗",github:"GitHub ↗",tryCloud:"Try Cloud ↗",includedSection:"Included in standalone",includedDescription:"The local-first feature set available without the cloud control plane.",inventorySection:"Built-in inventory",inventoryDescription:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",cloudExtrasSection:"Cloud-only extras",cloudExtrasDescription:"Capabilities that need the hosted control plane or team infrastructure.",comparisonSection:"Self-hosted vs Cloud",comparisonDescription:"The product split at a glance.",featureHeader:"Feature",selfhostHeader:"Selfhost",cloudHeader:"Cloud",cloudOptional:"Cloud is optional, not required",cloudOptionalDescription:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",compareCloud:"Compare Cloud ↗",discord:"Discord ↗"},fonts:{fontOverridesNotice:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below.",chat:"Chat text",chatDescription:"Assistant/user prose, markdown text, thought cards, and system notes.",code:"Code blocks",codeDescription:"Markdown code fences, inline code, and preformatted command output.",terminal:"Terminal",terminalDescription:"Terminal transcript cards and tool/command rows in chat mode.",livePreview:"Live preview",resolvedStack:"Resolved stack:",defaults:"Defaults:",saveFontSettings:"Save font settings",revertToSaved:"Revert to saved",resetToDefaults:"Reset to defaults",saving:"Saving…"}},ox={panel:{selectNode:"Select a node to view details.",submoduleBadge:"Submodule",dirtyBadge:"Dirty",outOfSyncBadge:"Out of sync",conflictBadge:"Conflict",orphanBadge:"Orphan",fieldWorkspace:"Workspace",fieldBranch:"Branch",fieldUpstream:"Upstream",fieldUpstreamState:"Upstream state",fieldHead:"HEAD",fieldSubmodulePath:"Submodule path",fieldSubmoduleCommit:"Submodule commit",fieldParentNode:"Parent node",fieldAhead:"Ahead",fieldBehind:"Behind",fieldDirtyFiles:"Dirty files",fieldActiveSessions:"Active sessions",fieldProviders:"Providers",fieldConnection:"Connection",fieldLinkNote:"Link note",fieldError:"Error",orphanReasons:"Orphan reasons",attachedChats:"Attached chats",providerUnknown:"provider unknown",statusAwaiting:"awaiting approval",statusGenerating:"generating",statusIdle:"idle",statusCoordinator:"coordinator",statusWorker:"worker",runtimeAgeNotReported:"runtime age not reported",upstreamVerified:"verified",upstreamUnverifiedFetch:"unverified (fetch failed)",upstreamUnverified:"unverified",upstreamUnavailable:"unavailable",needsFollowUp:"needs follow-up",refined:"refined"},obs:{tabOverview:"Overview",tabStatus:"Status",tabGraph:"Graph",convergenceMergedToMain:"Merged to main",convergenceNeedsMerge:"Needs merge",convergenceBlockedReview:"Blocked — needs review",convergenceCleanup:"Ready to clean up",convergenceNotMergeable:"Not mergeable",followUpLabel:"Follow-up — {{status}}",selectedNode:"Selected node",selectedEdge:"Selected edge",activeSessions:"Active Sessions",ledger:"Ledger (mesh-wide)",queueTasks:"Queue tasks",keyWarning:"Key warning",healResult:"Heal result",healPreview:"Heal preview",noResultCode:"No result code returned.",health:"Health",legend:"Legend",checking:"Checking",heal:"Heal",loadingGraph:"Loading graph…",bootstrapBanner:"Awaiting live data — showing setup inventory until peer mesh_status probes succeed.",emptyGraph:"No live mesh graph is available for this coordinator yet.",fieldMachine:"Machine",fieldLocality:"Locality",fieldWorkspace:"Workspace",fieldHead:"HEAD",fieldDirtyAheadBehind:"Dirty/ahead/behind",fieldSessions:"Sessions",fieldUpstream:"Upstream",fieldSource:"Source",fieldTransport:"Transport",fieldMachineId:"Machine id",fieldDaemonId:"Daemon id",fieldFrom:"From",fieldTo:"To",fieldLabel:"Label",fieldCompleted:"Completed",fieldFailed:"Failed",fieldLaunched:"Launched",fieldRecentFailures:"Recent failures",meshConnecting:"mesh connecting...",connecting:"connecting...",providerUnknown:"provider unknown"}},ax={login:{eyebrow:"クラウドサインイン",title:"ADHDev にサインイン",subtitle:"マシンを接続し、承認・完了の通知を受け取り、デスクを離れている間もコーディングエージェントを動かし続けましょう。",continueWith:"{{provider}} で続行",connecting:"接続中...",devDivider:"開発",devLogin:"開発ログイン (test_jwt_token)",providerNote:"GitHub と Google は認証のみに使用されます。",errorUnverifiedEmail:"このログインプロバイダーが確認済みのメールアドレスを返さなかったため、安全にサインインできませんでした。",termsPrefix:"続行することで、",termsLink:"利用規約",termsAnd:" および ",privacyLink:"プライバシーポリシー",termsSuffix:" に同意したものとみなされます。"},account:{title:"アカウント",subtitle:"プロフィール、プラン、アクティビティ",tabAccount:"アカウント",tabBilling:"請求",tabActivity:"アクティビティ",profile:"プロフィール",noName:"名前なし",displayName:"表示名",displayNameDesc:"ダッシュボードやチームワークスペースに表示される名前です。",nicknamePlaceholder:"ニックネーム",save:"保存",saving:"...",cancel:"キャンセル",saved:"保存しました",edit:"編集",failedToSave:"保存に失敗しました",userId:"ユーザー ID",loadingProfile:"プロフィールを読み込み中...",planLimits:"プラン上限",limitMachines:"マシン",limitP2P:"P2P 接続",limitWebhooks:"Webhook",limitTurnRelay:"TURN リレー",enabled:"有効",disabled:"無効",frozen:"凍結",session:"セッション",logout:"ログアウト",logoutConfirm:"本当にログアウトしますか?",logoutDesc:"このデバイスで ADHDev アカウントからサインアウトします。",dangerZone:"危険ゾーン",dangerZoneDesc:"アカウントと関連するすべてのデータを完全に削除します。この操作は元に戻せません。",deleteAccount:"アカウントを削除",deleteWillRemove:"以下が完全に削除されます:",deleteItemProfile:"プロフィールとログイン認証情報",deleteItemKeys:"すべての API キーと接続トークン",deleteItemWebhooks:"Webhook と配信履歴",deleteItemPush:"プッシュ通知の購読",deleteItemSessions:"共有セッションと監査ログ",deleteTypeConfirm:"{{keyword}} と入力して確認してください:",deleting:"削除中...",permanentlyDelete:"完全に削除",failedToDeleteAccount:"アカウントの削除に失敗しました",registeredMachines:"登録済みマシン",machinesSummary:"{{count}} 台登録 · {{online}} 台オンライン",machinesLimit:"(上限: {{limit}})",loadingMachines:"マシンを読み込み中...",noMachinesRegistered:"登録済みマシンなし",runSetupPrefix:"マシンで ",runSetupMiddle:" を実行し、次に ",runSetupSuffix:" を起動するとここに登録されます。",removeMachineConfirm:"このマシンを削除しますか?再接続するには `adhdev setup` を再実行する必要があります。",failedToDeleteMachine:"マシンの削除に失敗しました",failedToUpdate:"更新に失敗しました",rename:"名前を変更",online:"オンライン",connecting:"接続中",lastSeen:"最終接続 {{time}}",removeMachine:"マシンを削除",never:"なし",justNow:"たった今",minutesAgo:"{{minutes}} 分前",hoursAgo:"{{hours}} 時間前",daysAgo:"{{days}} 日前"},billing:{title:"Billing",subtitle:"Manage your subscription and plan",currentPlan:"現在のプラン:",statusTrial:"トライアル",statusActive:"有効",statusPastDue:"支払い延滞",statusCanceled:"キャンセル済み",nextBilling:"次回請求: {{date}}",trialEnds:"トライアル終了: {{date}}",accessUntil:"利用期限: {{date}}",updatePayment:"お支払い方法を更新してください",managePayment:"支払いと請求書の管理",couldNotOpenPortal:"請求ポータルを開けませんでした",statMachines:"マシン",statTeam:"チーム",statTurnPerDay:"TURN 分/日",monthly:"月払い",yearly:"年払い",savePercent:"17% お得",paddleLoading:"Paddle を読み込み中です。もう一度お試しください。",cancelConfirm:"本当にサブスクリプションをキャンセルしますか?請求期間の終了まではご利用いただけます。",teamSeats:"チームシート",seatsUsed:"{{used}} / {{total}} シート使用中",pricePerMonth:"${{price}}/月",cannotReduceSeats:"{{count}} シート未満には減らせません(現在使用中)。先にメンバーを削除してください。",removeSeat:"− シートを削除",addSeat:"+ シートを追加",cancelSubscription:"サブスクリプションをキャンセル",cancelRetainAccess:"現在の請求期間の終了まで {{plan}} 機能をご利用いただけます。",cancelTeamDowngrade:" すべてのチームメンバーは個人プランにダウングレードされます。"},about:{title:"About",subtitle:"Cloud overview, supported surfaces, and plan-level capabilities",cloudEdition:"Cloud edition",heroTitle:"Control your local CLI agents from anywhere — web or mobile.",heroDesc:"ADHDev Cloud surfaces the agents running on your machines in your browser: send prompts, approve actions, orchestrate work across machines, and get notified on your phone — code flows P2P directly to your daemon, never through the server.",openDashboard:"Open Dashboard",viewMachines:"View Machines",docs:"Docs ↗",whyTitle:"Why ADHDev Cloud",whyDesc:"Core capabilities available when your machines are connected through the cloud control plane.",howTitle:"How it works",howDesc:"The cloud onboarding path from install to remote control.",repoMeshTitle:"Repo Mesh",repoMeshDesc:"Orchestrate agents across machines — cloud only.",meshCard1Title:"One coordinator, many agents",meshCard1Desc:"Enqueue tasks against a mission and let idle nodes claim work from a local-first, pull-based queue. Fan out across machines and providers — Claude Code on one, Codex on another — then converge the results from a single coordinator session.",meshCard2Title:"Same repo, many machines at once",meshCard2Desc:"Each node is a checkout or an isolated git worktree, so parallel agents never collide. The refinery converges every branch — validate, merge, push, clean up — with safe submodule handling. Runs over a direct daemon-to-daemon P2P channel; the server only signals and authorizes same-account peers.",worksWith:"Works with",worksWithDesc:"Supported CLI agents, IDEs, and AI extensions.",groupCli:"CLI Agents",groupIdes:"IDEs",groupExtensions:"AI Agents",pricingTitle:"Pricing",pricingDesc:"Current cloud plans and machine capacity by tier.",planPopular:"Popular",planPerMonth:"/mo",readyTitle:"Ready to connect a machine",readyDesc:"Jump into your dashboard, inspect your connected machines, or continue in the docs if you are still setting up.",dashboard:"Dashboard",machines:"Machines",discord:"Discord ↗",github:"GitHub ↗",features:{webControlTitle:"Web control of local CLI agents",webControlDesc:"Drive any local CLI agent — Claude Code, Codex, Gemini — from your browser: send prompts, approve actions, and steer sessions without touching the terminal.",chatRelayTitle:"Agent chat relay",chatRelayDesc:"Read and respond to agent conversations from anywhere, including mobile surfaces.",liveViewTitle:"Live session view",liveViewDesc:"Watch agent activity in real time; for IDE sessions, view and control the screen over P2P without switching windows.",mobileTitle:"Mobile-ready",mobileDesc:"Receive approvals and check progress while away from your development machine.",secureTitle:"Secure by default",secureDesc:"Chat, commands, and screenshots flow directly between your browser and your daemon over WebRTC — the cloud handles auth and signaling metadata only. Your code never routes through the server."},steps:{step1Title:"One-line Install",step1Desc:"Run a single command on any machine you want to drive. It installs the ADHDev daemon plus the adhdev CLI.",step2Title:"Sign In",step2Desc:"Sign in with GitHub or Google and the daemon pairs itself to your account — no token to copy.",step3Title:"Drive Your Agents from Anywhere",step3Desc:"The machine appears in your dashboard instantly. Launch and control Claude Code, Codex, Gemini, and other CLI agents from the web — IDE sessions too."},plans:{freeName:"Free",proName:"Pro",ultraName:"Ultra",freePer:"/mo",proPer:"/mo",ultraPer:"/mo",freeFeature1:"1 machine",freeFeature2:"Real-time chat relay",freeFeature3:"Web control for your local agents",freeFeature4:"Community support",proFeature1:"2 machines",proFeature2:"Unlimited AI agents",proFeature3:"P2P remote view",proFeature4:"7-day free trial",ultraFeature1:"5 machines — flat, not per-seat",ultraFeature2:"Everything in Pro",ultraFeature3:"Higher concurrency & usage limits",ultraFeature4:"Unlimited daily screenshot minutes"}},layout:{navDashboard:"Dashboard",navBurrows:"Burrows",navNotifications:"Notifications",navMesh:"Mesh",navMarketplace:"Marketplace",navTeam:"Team",navApi:"API",navWebhooks:"Webhooks",navAccount:"Account",navSettings:"Settings",navDocs:"Docs",navAbout:"About",adminSection:"Admin",adminOverview:"Overview",adminUsers:"Users",adminAuditLogs:"Audit Logs",adminSystem:"System",adminEntry:"Admin",footerPlanTitle:"Current plan: {{plan}} — manage or upgrade",expandSidebar:"Expand sidebar",collapseSidebar:"Collapse sidebar",collapse:"Collapse",logoutConfirm:"Are you sure you want to logout?",logout:"Logout",machineLimitBanner:"You've reached your Free plan limit of {{count}} machine{{plural}}. Upgrade to add more.",upgradeArrow:"Upgrade →"},settings:{title:"Settings",subtitle:"Appearance & preferences",quickLinksTitle:"Quick links",quickLinksDesc:"Open the pages that are easiest to need from mobile inbox.",linkNotificationsTitle:"Notifications",linkNotificationsSubtitle:"Push, browser alerts, and delivery settings",linkAccountTitle:"Account",linkAccountSubtitle:"Profile, billing, sessions, and delete account",linkAboutTitle:"About",linkAboutSubtitle:"Cloud overview, supported surfaces, and plans",linkDocsTitle:"Docs",linkDocsSubtitle:"Open product docs in a new tab",appearanceTitle:"Appearance"},planCard:{unlimited:"Unlimited",machineSingular:"{{count}} machine",machinePlural:"{{count}} machines",sharedSessionSingular:"{{count}} shared session",sharedSessionPlural:"{{count}} shared sessions",teamMemberSingular:"{{count}} team member",teamMemberPlural:"{{count}} team members",turnPerDay:"{{count}} TURN min/day",recommended:"Recommended",currentPlan:"Current Plan",contactUs:"Contact Us",freeForever:"Free Forever",startTrial:"Start 7-day free trial",upgradeTo:"Upgrade to {{name}}",noChargeCancel:"No charge for 7 days. Cancel anytime.",periodSeatMo:"seat/mo",periodMo:"mo",yearlyNote:"${{yearly}}/year — Save ${{saved}}",pricingCustom:"Custom"},activity:{filterPlaceholder:"アクション、リソース、ソースで絞り込み...",refresh:"更新",loading:"読み込み中...",noLogs:"ログなし",noMatchingLogs:"一致するログが見つかりません。",logsWillAppear:"アクションが発生するとここに表示されます。",colAction:"アクション",colResource:"リソース",colSource:"ソース",colTime:"時刻",logCount:"ログ {{count}} 件",logCountFiltered:" ({{total}} 件から絞り込み)"},webhooks:{title:"Webhook",subtitle:"リアルタイムイベント通知",addWebhook:"+ Webhook を追加",eventDaemonConnect:"デーモン接続",eventDaemonDisconnect:"デーモン切断",eventAgentStatus:"エージェント状態変更",eventApprovalRequired:"承認が必要",failed:"失敗",deleteConfirm:"この Webhook を削除しますか?",testFailed:"テストに失敗しました",secretTitle:"Webhook シークレット",secretShownOncePrefix:"",secretShownOnce:"一度だけ",secretShownOnceSuffix:"表示されます。次の検証に使用してください: ",copy:"コピー",done:"完了",newWebhook:"新しい Webhook",labelUrl:"URL",urlPlaceholder:"https://your-service.com/webhook",labelEvents:"イベント",allEvents:"すべてのイベント (*)",creating:"作成中...",create:"作成",cancel:"キャンセル",loading:"読み込み中...",noWebhooks:"Webhook なし",noWebhooksDesc:"イベントに関するリアルタイム通知を受け取ります。",setupFirst:"最初の Webhook を設定",off:"オフ",autoDisabled:"自動無効化",autoDisabledTitle:"連続 10 回失敗後に自動無効化されました",failuresWarning:"⚠ {{count}} 回失敗",failuresTitle:"連続 {{count}} 回失敗 — 10 回で自動無効化されます",all:"すべて",history:"履歴",test:"テスト",delete:"削除",deleting:"...",recentDeliveries:"最近の配信",refresh:"更新",noDeliveries:"まだ配信はありません。🧪 でテストを送信してください。",request:"リクエスト",response:"レスポンス",securityTitle:"セキュリティ",securityVerifyPrefix:"",securityVerifySuffix:" をシークレットで検証してください",securityHttps:"HTTPS エンドポイントのみを使用してください",securityAsync:"すぐに 2xx を返し、非同期で処理してください",securityAutoDisable:"連続 10 回失敗後に自動無効化されました"},apiKeys:{title:"API キー",keyCount:"キー {{count}} 個",playground:"プレイグラウンド",create:"+ 作成",scopeDaemonRead:"デーモン読み取り",scopeDaemonReadDesc:"デーモン一覧と状態",scopeDaemonControl:"デーモン制御",scopeDaemonControlDesc:"コマンド、起動/停止、切断",scopeAgentRead:"エージェント読み取り",scopeAgentReadDesc:"状態とチャット履歴",scopeAgentControl:"エージェント制御",scopeAgentControlDesc:"送信、承認/拒否",scopeTerminal:"ターミナル",scopeTerminalDesc:"コマンドを実行",scopeWebhooks:"Webhook",scopeWebhooksDesc:"フックと配信を管理",frozen:"凍結",revokeConfirm:"この API キーを取り消しますか?元に戻せません。",failedToLoad:"読み込みに失敗しました",failed:"失敗",upgradePlan:"プランをアップグレード →",keyCreated:"キーを作成しました!",copyNow:"今すぐコピー — 一度だけ表示されます。",copied:"コピーしました",copy:"コピー",testKey:"テスト",dismiss:"閉じる",playgroundTitle:"API プレイグラウンド",enterKeyToTest:"テストする API キーを入力してください。",open:"開く",createKeyTitle:"API キーを作成",labelName:"名前",namePlaceholder:"例: Production Bot",permissions:"権限 ({{count}})",createBtn:"作成",cancel:"キャンセル",loading:"読み込み中...",noKeys:"API キーなし",noKeysDesc:"外部サービスと連携するキーを作成してください。",createFirstKey:"最初のキーを作成",usedDate:"{{date}} に使用",neverUsed:"未使用",revoke:"取り消し",usageLabel:"使用法:",apiReference:"API リファレンス →"},auditLogs:{title:"監査ログ",subtitle:"セキュリティイベントと API 履歴",refresh:"更新",filterPlaceholder:"アクション、リソース、ソースで絞り込み...",loading:"読み込み中...",noLogs:"ログなし",noMatchingLogs:"一致するログが見つかりません。",logsWillAppear:"アクションが発生するとここに表示されます。",colAction:"アクション",colResource:"リソース",colSource:"ソース",colTime:"時刻",logCount:"ログ {{count}} 件",logCountFiltered:" ({{total}} 件から絞り込み)"},inviteModal:{title:"Invite Team Member",subtitle:"Send an invite link via email",manageSeats:"→ Manage seats in Billing",emailLabel:"Email Address",emailPlaceholder:"colleague@company.com",roleLabel:"Role",roleViewer:"Viewer",roleMember:"Member",roleAdmin:"Admin",roleViewerDesc:"Can view dashboards and chat history",roleMemberDesc:"Can control agents and send commands",roleAdminDesc:"Can manage members and settings",cancel:"Cancel",sending:"Sending...",sendInvite:"Send Invite",inviteSent:"Invite sent!",shareWith:"Share this link with",copied:"Copied!",copy:"Copy",done:"Done"},shareModal:{title:"Share Session",chatLabel:"Chat",chatDesc:"AI conversation only",remoteLabel:"Remote",remoteDesc:"Screenshot + desktop",permissionLabel:"Permission Level",authRequired:"Account required",expiresAfter:"Expires After",maxViewers:"Max Viewers",hide:"Hide",activeShares:"Active Shares",creating:"Creating...",createChatLink:"Create Chat Link",createRemoteLink:"Create Remote Link",expires:"expires",revoke:"Revoke",shareLinkCreated:"Share link created!",viewerMustLogin:"Viewer must be logged in to use this link",copy:"Copy",copied:"Copied!",expiresAt:"Expires:",done:"Done",failedToCreate:"Failed to create share link",expiry1h:"1 hour",expiry6h:"6 hours",expiry24h:"24 hours",expiry7d:"7 days",chatView:{label:"View Only",desc:"Read AI conversation in real-time"},chatControl:{label:"Control",desc:"Read + send messages + approve/reject actions"},remoteView:{label:"View Only",desc:"Watch screenshots + chat in real-time"},remoteControl:{label:"Control",desc:"Screenshots + send messages + approve/reject"},remoteFull:{label:"Full Access",desc:"Full remote control including desktop input"}},onboarding:{title:"Connect your first machine",subtitle:"Install ADHDev on a machine and sign in — it pairs itself and shows up here. Then drive every agent on it from this dashboard.",platformMac:"🍎🐧 macOS / Linux",platformWindows:"🪟 Windows",copyTitle:"Click to copy",copiedLabel:"✓ Copied",copyLabel:"📋 Copy",listeningLabel:"Listening for your daemon — keep this page open, it will appear automatically.",connectingLabel:"Connecting to ADHDev…",step1Title:"Install the daemon",step1Desc:"Run the command above on any machine you want to drive. It installs the daemon plus the adhdev CLI.",step2Title:"Sign in — the machine pairs itself",step2Desc:"The daemon links to this account automatically. No token to copy; it appears here the moment it connects.",step3Title:"Launch your first session",step3Desc:"Once a machine is online, start Claude Code, Codex, Cursor, and other agents straight from the dashboard.",readDocs:"📚 Read the documentation →"},legal:{navHome:"Home",navDashboard:"Dashboard",footerHome:"Home",footerTerms:"Terms",footerPrivacy:"Privacy",footerRefund:"Refund Policy",footerCopyright:"© 2026 RacoLab. All rights reserved."},authCallback:{authFailed:"Authentication Failed",backToLogin:"Back to Login",completing:"Completing authentication...",noTokenError:"No access token received"},cliAuth:{title:"ADHDev CLI Authentication",verifying:"Verifying...",authorizeAs:"Authorize CLI as {{name}}?",noCodeError:"No authentication code provided.",approve:"✓ Approve",signInFirst:"Please sign in first to authorize the CLI.",signIn:"Sign In →",failed:"Failed",successMessage:"CLI authentication complete!",returnToTerminal:"You can return to the terminal."},privacy:{title:"Privacy Policy",lastUpdated:"Last updated: March 23, 2026",intro:'This Privacy Policy describes how RacoLab ("we", "us", "our") collects, uses, and protects your information when you use the ADHDev service ("Service") at',s1Title:"1. Information We Collect",s1h1:"1.1 Account Information",s1p1:"When you create an account, we collect information provided by your authentication provider (GitHub or Google), including your name, email address, and profile picture.",s1h2:"1.2 IDE & Agent Data",s1p2:"When you connect your development environment to the Service, the local daemon may transmit:",s1l1:'IDE type and version (e.g., "Cursor 0.49.1")',s1l2:"Active AI agent information (name, status, current model)",s1l3:"Chat messages between you and AI agents",s1l4:"IDE screenshots (transmitted via P2P, not stored on our servers)",s1l5:"Workspace paths and open file names",s1l6:"Machine information (hostname, OS, memory usage)",s1h3:"1.3 Usage Data",s1p3:"We automatically collect usage information including API calls, feature usage patterns, and connection logs for service improvement and debugging purposes.",s1h4:"1.4 Payment Information",s1p4:"Payment processing is handled entirely by our Merchant of Record, Paddle (Paddle.com Market Limited). We do not directly collect or store credit card numbers, bank account details, or other financial information. Please refer to",s1p4PaddleLink:"Paddle's Privacy Policy",s1p4Suffix:"for their data handling practices.",s2Title:"2. How We Use Your Information",s2p1:"We use collected information to:",s2l1:"Provide and maintain the Service",s2l2:"Authenticate your identity and manage your account",s2l3:"Route commands and data between your dashboard and connected machines",s2l4:"Send notifications (browser and push) about agent status changes",s2l5:"Process billing and subscription management (via Paddle)",s2l6:"Detect and prevent abuse or unauthorized access",s2l7:"Improve the Service and develop new features",s2l8:"Respond to support requests",s3Title:"3. Data Storage & Security",s3h1:"3.1 Infrastructure",s3p1:"Our Service runs on Cloudflare's global network using Cloudflare Workers, Durable Objects, and D1 Database. Data is stored in Cloudflare's infrastructure and is subject to",s3p1CloudflareLink:"Cloudflare's Privacy Policy",s3h2:"3.2 P2P Data",s3p2:"IDE screenshots and real-time terminal data are transmitted directly between your browser and your machine via WebRTC peer-to-peer connections. This data does not pass through or get stored on our servers.",s3h3:"3.3 Security Measures",s3p3:"We implement the following security measures:",s3l1:"JWT-based authentication with short-lived access tokens and refresh token rotation",s3l2:"Encrypted WebSocket connections (WSS/TLS)",s3l3:"Per-connection tokens for daemon authentication",s3l4:"Rate limiting on all API endpoints",s3l5:"Audit logging for security-sensitive operations",s4Title:"4. Data Sharing",s4p1:"We do not sell your personal data to third parties. We may share data with:",s4l1:"Payment processing as Merchant of Record",s4l2:"Infrastructure provider (hosting, CDN, database)",s4l3Label:"Authentication providers",s4l3:"GitHub/Google for OAuth login",s4p2:"We may disclose data if required by law, legal process, or to protect our rights and the safety of our users.",s5Title:"5. Data Retention",s5p1:"We retain your account data for the duration of your active account. Chat messages and agent activity data are retained for up to 90 days for service functionality.",s5p2:"Upon account deletion, we will remove your personal data within 30 days. Some anonymized usage data may be retained for analytical purposes.",s6Title:"6. Your Rights",s6p1:"You have the right to:",s6l1Label:"Access",s6l1:"Request a copy of your personal data",s6l2Label:"Correction",s6l2:"Update or correct your personal information",s6l3Label:"Deletion",s6l3:"Request deletion of your account and associated data",s6l4Label:"Export",s6l4:"Download your data in a portable format",s6l5Label:"Object",s6l5:"Object to certain data processing activities",s6p2:"To exercise these rights, contact us at",s7Title:"7. Cookies",s7p1:"We use essential cookies only for authentication (session tokens) and user preferences (theme, notification settings). We do not use advertising or tracking cookies.",s8Title:"8. Children's Privacy",s8p1:"The Service is not intended for users under the age of 16. We do not knowingly collect personal information from children under 16.",s9Title:"9. International Data Transfers",s9p1:"Your data may be processed in various locations through Cloudflare's global network. By using the Service, you consent to the transfer and processing of your data in these locations.",s10Title:"10. Changes to This Policy",s10p1:"We may update this Privacy Policy from time to time. We will notify you of any material changes by email or through the Service. Your continued use after changes constitutes acceptance of the updated policy.",s11Title:"11. Contact",s11p1:"For questions about this Privacy Policy or data practices:",s11l1Prefix:"Email:",s11l2Prefix:"Website:"},terms:{title:"Terms of Service",lastUpdated:"Last updated: April 11, 2026",intro:'Welcome to ADHDev ("Service"), operated by RacoLab ("we", "us", "our"). By accessing or using our Service at',introSuffix:'you agree to be bound by these Terms of Service ("Terms"). If you do not agree, do not use the Service.',s1Title:"1. Service Description",s1p1:"ADHDev is a cloud developer tool that provides remote monitoring and control of AI coding agents (such as Cursor, VS Code, Antigravity, Claude Code, and others) through web and mobile dashboard surfaces. The Service includes a local daemon, remote dashboards, REST API access, and browser and push notifications.",s2Title:"2. Account Registration",s2p1:"You must create an account to use the Service. You are responsible for maintaining the confidentiality of your account credentials. You agree to provide accurate and complete information during registration and to keep your account information up to date.",s2p2:"You must be at least 16 years old to use the Service. By creating an account, you represent that you meet this age requirement.",s3Title:"3. Subscription Plans & Billing",s3p1:"The Service offers the following plans:",s3l1:"Limited features, 1 connected machine",s3l2:"2 connected machines, unlimited agents, P2P remote view, 7-day free trial",s3l3:"5 connected machines, everything in Pro plus higher concurrency and usage limits (flat price, not per-seat)",s3p2:"Paid subscriptions are billed in advance on a monthly or yearly basis. All payments are processed by our payment partner, Paddle (Paddle.com Market Limited), who acts as the Merchant of Record for all transactions.",s4Title:"4. Refund Policy",s4p1:"We offer a 14-day money-back guarantee for all paid plans. If you are not satisfied with the Service, you may request a full refund within 14 days of your initial purchase by contacting us at",s4p2:"Refunds for renewals are handled on a case-by-case basis. Paddle's refund policies also apply as they are the Merchant of Record.",s5Title:"5. Acceptable Use",s5p1:"You agree not to:",s5l1:"Use the Service for any unlawful purpose or in violation of any applicable laws",s5l2:"Attempt to gain unauthorized access to other users' accounts or data",s5l3:"Reverse-engineer, decompile, or attempt to extract the source code of the Service's server components",s5l4:"Use the Service to transmit malware, spam, or other harmful content",s5l5:"Resell or redistribute the Service without our written consent",s5l6:"Interfere with or disrupt the integrity or performance of the Service",s6Title:"6. Intellectual Property",s6p1:"The Service, including its original content, features, and functionality, is owned by RacoLab and is protected by applicable intellectual property laws. The local daemon component is available under an open-source license as specified in the project repository.",s6p2:"You retain ownership of all data and content you transmit through the Service.",s7Title:"7. Data & Privacy",s7p1:"Your use of the Service is also governed by our",s7PrivacyLink:"Privacy Policy",s7p1Suffix:"The Service processes IDE interactions, chat messages, and screenshots for the purpose of remote monitoring and control. We do not sell your data to third parties.",s8Title:"8. Service Availability",s8p1:"We strive to maintain high availability but do not guarantee uninterrupted access. The Service may be temporarily unavailable due to maintenance, updates, or circumstances beyond our control. We are not liable for any losses resulting from service interruptions.",s9Title:"9. Limitation of Liability",s9p1:"TO THE MAXIMUM EXTENT PERMITTED BY LAW, RacoLab SHALL NOT BE LIABLE FOR ANY INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES, OR ANY LOSS OF PROFITS OR REVENUES, WHETHER INCURRED DIRECTLY OR INDIRECTLY, ARISING OUT OF YOUR USE OF THE SERVICE.",s9p2:"Our total liability for any claim arising from the Service shall not exceed the amount you paid us in the 12 months preceding the claim.",s10Title:"10. Termination",s10p1:"We may suspend or terminate your access to the Service at any time for violations of these Terms or for any other reason at our sole discretion. You may cancel your account at any time through the Settings page. Upon cancellation, your data will be deleted within 30 days.",s11Title:"11. Changes to Terms",s11p1:"We reserve the right to modify these Terms at any time. We will notify you of material changes via email or through the Service. Your continued use after changes constitutes acceptance of the modified Terms.",s12Title:"12. Governing Law",s12p1:"These Terms shall be governed by and construed in accordance with the laws of the Republic of Korea, without regard to conflict of law provisions.",s13Title:"13. Contact",s13p1:"If you have any questions about these Terms, please contact us:",s13l1Prefix:"Email:",s13l2Prefix:"Website:"},refund:{title:"Refund Policy",lastUpdated:"Last updated: March 24, 2026",intro:"ADHDev is operated by RacoLab. All payments are processed by our Merchant of Record,",introSuffix:"who manages billing, invoicing, and refunds on our behalf.",s1Title:"1. 14-Day Money-Back Guarantee",s1p1:"We offer a 14-day money-back guarantee on all paid plans (Pro). If you are not satisfied with the Service for any reason, you may request a full refund within 14 days of your initial subscription purchase.",s1p2:"To request a refund, contact us at",s1p2Suffix:"with your account email and order details. We will process your request within 3 business days.",s2Title:"2. Renewal Refunds",s2p1:"Refunds for subscription renewals (monthly or yearly) are handled on a case-by-case basis. If you were charged for a renewal you did not intend, please contact us within 7 days of the charge at",s3Title:"3. Non-Refundable Cases",s3p1:"Refunds will not be issued for:",s3l1:"Requests made after the 14-day guarantee period for initial purchases",s3l2Prefix:"Accounts suspended or terminated due to violations of our",s3l2Link:"Terms of Service",s3l3:"Partial months of service already used beyond the refund window",s4Title:"4. How Refunds Are Processed",s4p1:"Approved refunds are processed through Paddle and returned to the original payment method. Depending on your bank or card issuer, refunds may take 5–10 business days to appear. Paddle's own",s4p1RefundLink:"refund terms",s4p1Suffix:"also apply.",s5Title:"5. Cancellation",s5p1Prefix:"You may cancel your subscription at any time from the",s5p1BillingLink:"Billing",s5p1Suffix:"page in your dashboard. Cancellation stops future charges. You retain access to your plan's features until the end of the current billing period. Cancellation alone does not trigger a refund.",s6Title:"6. Contact",s6p1:"For refund requests or billing questions:",s6l1Prefix:"Email:",s6l2Prefix:"Website:"},teamWorkspace:{title:"Team",subtitle:"Seat-based team management — $15/seat/mo, centralized billing",planRequired:"Team Plan Required",planDesc:`Team Workspaces are available on the Team plan ($15/seat/mo).
34
+ Manage seats, invite team members, and centrally manage billing for your organization.`,upgradeBtn:"Upgrade to Team →",seatsTitle:"Team Seats",seatsUsedOf:"{{used}} / {{total}} seats used",seatsAvailable:"{{count}} available",seatsFullMsg:"All seats are in use. Add more seats in",seatsBillingLink:"Billing",seatsBillingLinkSuffix:"to invite more members.",newWorkspace:"New Workspace",workspaceNamePlaceholder:"Workspace name...",createBtn:"Create",cancelBtn:"Cancel",noWorkspaceYet:"No team workspace yet",noWorkspaceDesc:"Create a workspace to start managing your team and sharing seats.",createWorkspace:"Create Workspace",membersTab:"Members ({{count}})",sessionsTab:"Sessions",settingsTab:"Settings",membersTitle:"Members ({{count}})",inviteBtn:"+ Invite",pendingInvites:"Pending Invites ({{count}})",pendingBadge:"Pending",removeBtn:"Remove",removeMemberConfirm:"Remove this member? They will lose their Team plan access.",removeSuccess:"Member removed",invitationSent:"Invitation sent!",joinedSuccess:"Successfully joined team workspace!",waitingApproval:"Waiting for {{name}} to approve your view request...",viewRequestSent:"View request sent to {{name}}. Waiting for approval...",viewDeclined:"{{name}} declined the view request",sessionRestricted:"Session viewing is restricted by organization policy (admin_only)",sessionTitle:"Team Sessions",noMembersOnline:"No team members online",selfBadge:"You",machineNoSessions:"Machine online, no active sessions",offline:"Offline",statusGenerating:"Generating...",statusApprovalNeeded:"Approval needed",statusStarting:"Starting...",statusStopped:"Stopped",statusError:"Error",statusDisconnected:"Disconnected",statusHidden:"Hidden",statusUnmonitored:"Unmonitored",statusIdle:"Idle",viewBtn:"View →",requestBtn:"Request →",policyOpen:"Open",policyRequest:"Request",policyAdminOnly:"Admin Only",settingsTitle:"Workspace Settings",sessionVisibilityTitle:"Session Visibility",sessionVisibilityDesc:"Control who can view team members' AI agent sessions",visibilityOpen:"Open",visibilityOpenDesc:"All members can view any session freely",visibilityRequest:"Request-based",visibilityRequestDesc:"Members must request access. Admins can always view.",visibilityAdminOnly:"Admin Only",visibilityAdminOnlyDesc:"Only administrators and the owner can view sessions.",dangerZone:"Danger Zone",dangerZoneDesc:"Irreversible actions",deleteWorkspace:"Delete Workspace",deleteWorkspaceConfirm:"Delete this Team Workspace? All members will lose their Team plan benefits.",leaveWorkspace:"Leave Workspace",leaveWorkspaceConfirm:"Are you sure you want to leave this workspace? Your plan may be downgraded."},sessionShare:{loading:"Loading session...",sessionNotFound:"Session Not Found",noLongerAvailable:"This session is no longer available",homeBtn:"← ADHDev Home",sharedSession:"Shared Session",host:"Host",mode:"Mode",permission:"Permission",auth:"Auth",authRequired:"Account required",viewers:"Viewers",joinChat:"Join Chat",joinSession:"Join Session",expires:"Expires: {{date}}",chatLabel:"Chat",remoteLabel:"Remote",waitingMessages:"Waiting for messages...",connecting:"Connecting... ({{state}})",sendMessageAs:"Send message as {{name}}...",sendAs:"Send as {{name}}...",ownerChat:"{{name}}'s Chat",ownerSession:"{{name}}'s Session",agentName:"{{name}}'s Agent",fullControlBadge:"Full Control Active",failedToJoin:"Failed to join session",sessionRevoked:"Session has been revoked by the host",sessionExpired:"Session has expired",authRequired2:"Authentication required for control share"},apiPlayground:{title:"API Playground",history:"History ({{count}})",apiRelayWarning:"Daemon API relay is opt-in. REST command/chat proxy routes stay disabled unless that daemon explicitly enables them with `adhdev daemon:api enable`.",authBearer:"Authorization: Bearer {{key}}",copyAsCurl:"cURL",copied:"Copied",targetDaemon:"Target Daemon",quickActions:"Quick Actions",requestBody:"Request Body (JSON)",recentRequests:"Recent Requests",clearHistory:"Clear",noDaemonsWarning:"No daemons connected. Start a daemon first or replace {daemonId} manually.",send:"▶ Send",sending:"⏳",close:"Close"}},ix={openMenu:"Open menu",closeMenu:"Close menu"},lx={loadingOlderMessages:"Loading older messages...",waitingForMessages:"Waiting for messages...",agentGenerating:"Agent generating...",jumpToTop:"Jump to top",jumpToOldestMessages:"Jump to oldest messages",top:"↑ Top",latest:"↓ Latest",jumpToLatestMessages:"Jump to latest messages",jumpToBottom:"Jump to bottom",showEarlierMessages:"↑ Show {{count}} earlier messages...",showEarlierMessagesHidden:"↑ Show {{count}} earlier messages... ({{total}} hidden)",loadOlderMessages:"↑ Load older messages",loadErrorRetry:"↻ {{error}}"},cx={zoomOut:"Zoom Out",zoomIn:"Zoom In",resetZoom:"Reset Zoom",toggleFullscreen:"Toggle Fullscreen"},dx={mouse:"Mouse",touch:"Touch",connected:"Connected",ws:"WS",direct:"Direct",relay:"Relay",turnBlocked:"TURN blocked",turnUsage:"TURN {{used}}/{{budget}}m",typeAndEnter:"Type & Enter...",settings:"SETTINGS",zoom:"ZOOM:",fill:"FILL",fit:"FIT",directP2PTitle:"Direct P2P connection",turnRelayTitle:"TURN relay in use",dailyTurnTitle:"Daily TURN relay usage"},ux={title:"Session info",loading:"Loading…",refresh:"Refresh",close:"Close",failedToLoad:"Failed to load session info",notCoordinatorSession:"This isn't a mesh coordinator session, so no coordinator-specific prompt was injected. The agent runs with whatever defaults its CLI ships with.",stampedToNode:"This session is stamped to a mesh node that the coordinator no longer reports.",sectionSession:"Session",sectionLaunch:"Launch",sectionMeshNode:"Mesh node",sectionMeshCoordinator:"Mesh coordinator",sectionRuntime:"Runtime",rowSessionId:"Session ID",rowProvider:"Provider",rowTransport:"Transport",rowWorkspace:"Workspace",rowSpawnedAt:"Spawned at",rowProviderSessionId:"Provider session ID",rowMachine:"Machine",rowConnection:"Connection",rowWorkspaceGit:"Workspace git",rowCommand:"Command",rowWorkingDirectory:"Working directory",rowArgs:"Args",rowExtraArgs:"Extra args",rowExtraEnv:"Extra env",rowNodeId:"Node ID",rowRepoRoot:"Repo root",rowDaemonId:"Daemon ID",rowRole:"Role",rowMachineStatus:"Machine status",rowHealth:"Health",rowWorktree:"Worktree",rowLaunchReady:"Launch ready",rowGit:"Git",rowProviders:"Providers",rowProviderPriority:"Provider priority",rowMeshId:"Mesh ID",rowCoordinatorCli:"Coordinator CLI",rowStartedAt:"Started at",rowPromptInjection:"Prompt injection",rowMcpConfig:"MCP config",rowRuntimeId:"Runtime ID",rowLifecycle:"Lifecycle",rowSurface:"Surface",rowRecoveryState:"Recovery state",rowRestoredFromStorage:"Restored from storage",rowAttachedClients:"Attached clients"},hx={status:{schedulingNotReported:"Scheduling runtime not reported by this daemon (older build). Update the coordinator daemon to surface distribution, parallel caps, and per-node load.",schedulingTitle:"Scheduling",distributionTitle:"Distribution only governs how untargeted work is spread across eligible nodes. Per-node load, priority, and provider caps are below.",protocolTitle:"Protocol & provider versions",nodesRuntime:"Nodes — runtime",noNodesReporting:"No nodes reporting runtime yet."},overview:{missionCard:"Missions",ledgerCard:"Ledger",queueCard:"Queue",nodesCard:"Nodes",sessionsCard:"Active sessions",refineCard:"Refine jobs",recentActivity:"Recent activity",recentTasks:"Recent tasks",showFewer:"Show fewer",showMore:"+{{count}} more",noActiveMissions:"No active missions. The coordinator creates a mission for multi-task work.",missionDataUnavailable:"Mission data unavailable from this daemon — update the daemon to see missions.",completedHistory:"Completed / abandoned history",noQueueActivity:"No queue activity.",noNodes:"No nodes in this mesh yet.",noActiveSessions:"No active sessions.",noRefineJobs:"No refine jobs.",closeDetail:"Close detail",loadingGoal:"Loading…",showFullGoal:"Show full goal",statCompleted:"Completed",statAssigned:"Assigned",statPending:"Pending",statFailed:"Failed",statBlocked:"Blocked",statCancelled:"Cancelled",statWallClock:"Wall clock",statTotalRuntime:"Total runtime",statRetries:"Retries",statDispatched:"Dispatched",statStalled:"Stalled",statSessions:"Sessions",statCheckpoints:"Checkpoints",statActive:"Active",recentFailures:"{{count}} recent failures",activeCount:"{{count}} active",failedCount:"{{count}} failed",detailKickerMission:"Mission",detailKickerLedger:"Ledger entry",detailKickerQueue:"Queue task",detailKickerSession:"Session",detailLabelMissionId:"Mission id",detailLabelCreated:"Created",detailLabelUpdated:"Updated",detailLabelLastActivity:"Last task activity",detailLabelIncompleteEvidence:"Incomplete evidence",incompleteTaskCount_one:"{{count}} task",incompleteTaskCount_other:"{{count}} tasks",detailLabelEntryId:"Entry id",detailLabelWhen:"When",detailLabelNode:"Node",detailLabelSession:"Session",detailLabelProvider:"Provider",detailLabelPayload:"Payload",detailLabelTaskId:"Task id",detailLabelAutoLaunch:"Auto launch",detailLabelCancelReason:"Cancel reason",detailLabelRequeueReason:"Requeue reason",detailLabelRequeued:"requeued {{count}}",detailLabelSessionId:"Session id",detailLabelBranch:"Branch",detailLabelRole:"Role",detailLabelStarted:"Started",detailLabelWorkspace:"Workspace"}},px={launchConfirm:{workspace:"Workspace",languageModel:"Language Model (Optional)",autoDetect:"Auto-detect or default",cliArgs:"CLI Arguments (Optional)",cliArgsPlaceholder:"e.g. --experimental",cancel:"Cancel",closeAria:"Close launch confirmation",launch:"Launch",launching:"Launching…"},confirmExternal:{dialogAria:"Confirm untrusted external provider",title:"Activate untrusted external provider?",description:"This manifest ships JavaScript that the daemon will execute. Treat as untrusted code — review the source before enabling.",proceedWarning:"Only proceed if you trust the source URL you added and have reviewed the manifest.",cancel:"Cancel",activate:"Activate"},workspace:{noWorkspace:"(no workspace — launch in home)",selectWorkspace:"📁 Select workspace…",customPath:"✏️ Custom path…",noWorkspacesSaved:"(no workspaces saved — add in Overview tab)",selectWorkspaceBtn:"Select workspace…",enterAbsolutePath:"Enter absolute path…",browseHint:"Browse to a folder before launching there.",absolutePathHint:"Enter an absolute path to launch there.",defaultWorkspace:"Default workspace",selectedWorkspace:"Selected workspace",noWorkspaceSelected:"No workspace selected. This launches in the home directory."},agentTab:{selectToLaunch:"Select {{label}} to Launch",launchSettings:"Launch Settings",noIdesDetected:"No IDEs detected.",scanSystem:"Scan System",noProviders:"No usable {{category}} providers available.",noProvidersHint:"Set a custom executable path in Providers if the binary is installed outside the default location.",targetModel:"Target Model",leaveEmptyDefault:"Leave empty for default",startupArguments:"Startup Arguments",optionalFlags:"Optional flags...",openSession:"Open Session",starting:"Starting...",configure:"Configure",select:"Select",launching:"⏳ Launching...",launchBtn:"▶ Launch",running:"Running ({{count}})",noRunning:"No {{plural}} running",launchingProcess:"Launching process...",waitingProcess:"Waiting for process and session to register...",startingBadge:"starting",chatView:"Chat view",terminalView:"Terminal view",localTerminal:"Local terminal:",copied:"Copied",copy:"Copy",openRemoteControl:"Open remote control",restart:"Restart",viewChat:"View chat",openInDashboard:"Open current view in dashboard",stop:"Stop",extensions:"Extensions",browseFolderTitle:"Select workspace",browseFolderDesc:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",browseFolderConfirm:"Use this folder",detailMode:"Mode",detailProvider:"Provider",detailResume:"Resume",detailArguments:"Arguments",detailModel:"Model",categoryIde:"IDE",categoryCliPlural:"CLIs",categoryAcp:"ACP Agent",categoryAcpPlural:"ACP agents"},providers:{filter:"Filter",sourceConfigTitle:"Provider source config",sourceConfigDesc:"Where the daemon looks for provider manifests. Affects resolution and reloads.",sourceMode:"Source mode",explicitProviderDir:"Explicit providerDir",providerDirPlaceholder:"Leave blank to use ~/.adhdev/providers",applying:"Applying…",applyReload:"Apply + Reload",userRoot:"User root:",upstreamRoot:"Upstream root:",providerRoots:"Provider roots:",loadingSettings:"Loading provider settings…",noProviders:'No providers installed yet. Open "Add provider" above to install one.',noFilteredProviders:"No {{filter}} providers installed.",refresh:"↻ Refresh",sources:"🌐 Sources",create:"✨ Create",advanced:"⚙ Advanced"},providerRow:{statusDetected:"Detected",statusNotDetected:"Not detected",statusEnabledUnchecked:"Enabled (unchecked)",statusDisabled:"Disabled",labelType:"Type:",labelVersion:"Version:",labelBinary:"Binary:",labelStatus:"Status:",labelDetails:"Details:",labelSource:"Source:",labelTrust:"Trust:",labelLinks:"Links:",labelDetection:"Detection:",labelVerification:"Verification:",saving:"saving…",disable:"Disable",enable:"Enable",detect:"Detect",resetCommand:"Reset command"},providerFix:{aiAgent:"AI Agent",scriptsToFix:"Scripts to Fix",all:"All",none:"None",additionalInstructions:"Additional Instructions",optional:"(optional)",agentOutput:"Agent Output",running:"● Running...",agentGenerating:"Agent is generating...",validateHint:"Run `adhdev provider verify` to validate",cancel:"Cancel",startFix:"🚀 Start Fix",cancelRunning:"⬛ Cancel",back:"← Back",close:"Close",footerHint:"AI agent will implement provider scripts",scriptsSelected_one:"{{count}} script selected",scriptsSelected_other:"{{count}} scripts selected",titlePrefix:"Auto-Fix: {{name}}",descCodex:"OpenAI o3/gpt-5.4",descClaude:"Anthropic Claude",descGemini:"Google Gemini"},providerClone:{title:"✨ Create User Provider",subtitle:"Clone an upstream IDE provider to customize",baseProvider:"Base Provider",providerTypeId:"Provider Type (ID)",typeIdPlaceholder:"my-cursor, custom-windsurf...",typeIdHint:"Lowercase, alphanumeric + hyphens only. Will be created at",displayName:"Display Name",displayNamePlaceholder:"My Custom IDE",cancel:"Cancel",creating:"⏳ Creating...",createProvider:"✨ Create Provider",createdTitle:"Provider Created!",createdDesc:"{{type}} has been created at",createdRunHint:"Run adhdev provider fix {{type}} or use Auto-Fix to implement scripts.",close:"Close"},connectedMachines:{noMachines:"No machines connected",defaultDescription:"Install ADHDev on a machine and sign in to connect it here.",startingUpgrade:"Starting upgrade...",machineDisconnected:"Machine disconnected.",tokenRevoked:"Token revoked. Restart ADHDev on that machine to reconnect.",failedToDisconnect:"Failed to disconnect",failedToRevokeToken:"Failed to revoke token",connectionLostUpgrade:"Connection lost during upgrade",disconnect:"Disconnect",remove:"Remove",disconnectTitle:"🔌 Disconnect Machine",removeTitle:"⚠️ Remove Machine",cancel:"Cancel",noIdesConnected:"No IDEs connected",upgrading:"Upgrading...",updated:"✓ Updated",updateNow:"↑ Update now",updateTo:"↑ Update to v{{version}}",cdpConnected:"CDP connected",cdpConnecting:"CDP connecting...",connecting:"connecting..."}},mx={theme:{helloHelp:"Hello! How can I help?",fixBug:"Fix the bug please",onIt:"On it! ✨",customEditorTitle:"🎨 Custom Theme Editor",darkMode:"🌙 Dark mode",lightMode:"☀️ Light mode",sectionAppBackground:"App Background",sectionAppText:"App Text",sectionBordersAccent:"Borders & Accent",sectionChatBubbles:"Chat Bubbles",sectionChatLayout:"Chat Layout",colorBackground:"Background",colorSurface:"Surface",colorCard:"Card",colorPrimary:"Primary",colorSecondary:"Secondary",colorMuted:"Muted",colorBorderSubtle:"Border subtle",colorBorderDefault:"Border default",colorAccent:"Accent",colorUserBubble:"User bubble",colorUserText:"User text",colorAgentBubble:"Agent bubble",colorAgentText:"Agent text",colorChatBg:"Chat BG",colorSendButton:"Send button",colorInputBorder:"Input border",labelBubbleRadius:"Bubble radius",resetToDefaults:"Reset to defaults",customLabel:"🎨 Custom"}},fx={chatHistory:"チャット履歴",startNewChat:"+ 新しいチャットセッションを開始",creating:"⌛ 作成中...",searchPlaceholder:"タイトルまたはプレビューを検索",filterWorkspace:"ワークスペースで絞り込み",filterModel:"モデルで絞り込み",sortRecent:"最新順",sortOldest:"古い順",sortMessages:"メッセージ数順",resumeReadyOnly:"再開可能のみ",untitledSession:"無題のセッション",noSavedPreview:"保存されたプレビューはありません",workspaceUnknown:"ワークスペース不明",selectedWorkspaceSuffix:" · 選択したワークスペース",msgCount:"{{count}} 件のメッセージ",statusActive:"アクティブ",statusMissingWorkspace:"ワークスペースなし",statusResumeSelectedWorkspace:"選択したワークスペースで再開",statusResuming:"再開中...",statusResume:"再開",noMatchingHistory:"これらのフィルターに一致する保存履歴はありません。",noRecentChats:"最近のチャットセッションが見つかりません。",refreshHistory:"履歴を更新",refreshing:"⌛ 更新中..."},bx={nav:{home:"ADHDev Home",mesh:"Mesh",what:"What",agents:"Agents",pricing:"Pricing",install:"Install",github:"GitHub",docs:"Docs",getStarted:"Get started",toggleMenu:"Toggle menu"},hero:{badge:"The multi-vendor, multi-machine agent control plane",title:"Anyone can run ten agents. ADHDev lands the work on main.",subtitle:"Drive any local coding agent — Claude Code, Codex, Cursor — from your browser, then let the Refinery merge finished work back to main <em>unattended</em>: your repo's own gates, patch-equivalence checks, fast-forward only, no force-push. You talk to one coordinator; it runs parallel agents across your own machines asynchronously — no sessions to babysit. Code stays on your machine — P2P, end to end.",selectOs:"Select OS",osUnix:"macOS / Linux",osWindows:"Windows",copyInstall:"Copy install command: {{cmd}}",copied:"Copied",copy:"Copy",getStarted:"Get started",openSource:"Open source on GitHub",joinDiscord:"Join Discord",selfHost:"Self-host it yourself",demoDesktop:"ADHDev command center driving live agent sessions across multiple machines",demoPush:"ADHDev mobile push notification and one-tap approval"},mesh:{sectionTitle:"They parallelize. We land.",sectionSubtitle:"Spawning parallel agents is the easy part — every tool does it now. The hard part is what happens after: ten branches that still have to be verified and merged. The Refinery does that for you, unattended, so finished work arrives on main instead of in your review queue.",refineryHighlight:"The Refinery",refineryTitle:"Finished work lands on main — unattended",refineryDesc:"Anyone can spawn ten parallel agents. The Refinery validates each worktree against your repo's own gates (typecheck, tests, lint), verifies patch equivalence, publishes submodule commits, fast-forwards main, and cleans up — automatically. No force-push, ever. Anything ambiguous is kicked back for review instead of merged.",asyncHighlight:"Async orchestration",asyncTitle:"You talk to one place. It runs the rest.",asyncDesc:"You give work to one coordinator; it drives many workers across many machines on an event loop — reacting only when a completion, approval, or status event arrives. No polling, no window-per-agent to babysit. Unlike a desktop app where you watch each agent session, here the coordinator waits on events, so you don't have to sit synchronously in front of anything.",monoHighlight:"Monorepo-aware",monoTitle:"Safe even with git submodules",monoDesc:"Real production repos nest submodules — and that's exactly where naive auto-merge breaks. The Refinery is submodule-aware: it gates on submodule-commit reachability, judges patch equivalence, and bumps the pointer atomically. This project is itself a root + two-submodule monorepo, converged this way every day.",crossHighlight:"Cross-check",crossTitle:"Consensus over a single opinion",crossDesc:"Fan the same read-only investigation out to several machine × provider replicas and synthesize where they agree and diverge (MAGI). More trustworthy than one agent's take.",tryMesh:"Try Repo Mesh →",seePlans:"See plans",availableOn:"Available on Pro and above. Drive it from the <strong>Repo Mesh</strong> page once connected.",readGuide:"Read the guide"},compare:{sectionTitle:"Parallel agents are everywhere now. Where does the work actually land?",sectionSubtitle:"A fair question. Local CLIs spawn subagents; desktop orchestrators fan work across worktrees with a slick native UI. Both stop at the branch. Here's the honest line — including where each of them beats us — with no hand-waving.",colLocalCli:"Local CLI + subagents",colDesktop:"Desktop orchestrator",colAdhdev:"ADHDev Repo Mesh",rowLandsMain:"Lands finished work on main",rowLandsMainLocalCli:"You run the gates and merge by hand",rowLandsMainDesktop:"Parallelizes the work, then hands you the branches to review",rowLandsMainAdhdev:"The Refinery runs your repo's gates, checks patch equivalence, and fast-forwards main — unattended, no force-push",rowSubmodules:"Safe with git submodules",rowSubmodulesLocalCli:"No merge automation to be aware of them",rowSubmodulesDesktop:"Worktree parallelism, but the merge is yours to get right",rowSubmodulesAdhdev:"Submodule-aware convergence: reachability gate, patch-equivalence check, atomic pointer bump — dogfooded on this monorepo daily",rowAsync:"Talk to one place, async",rowAsyncLocalCli:"One session at a time, synchronously",rowAsyncDesktop:"You supervise each agent window yourself",rowAsyncAdhdev:"One coordinator drives every worker on an event loop — it waits on completion/approval events, you don't poll or babysit",rowMultiMachine:"Multiple physical machines",rowMultiMachineLocalCli:"One host's processes only",rowMultiMachineDesktop:"Bound to the one machine it runs on",rowMultiMachineAdhdev:"Remote daemons over P2P — dispatch across every machine you own (no SSH plumbing)",rowParallelBranch:"Parallel isolated-branch work",rowParallelBranchLocalCli:"Subagents share one working tree — concurrent writes collide",rowParallelBranchDesktop:"One git worktree per task — a core strength",rowParallelBranchAdhdev:"One git worktree per node — parallel across machines, not just cores",rowBrowser:"Drive it from a browser or phone",rowBrowserLocalCli:"You have to be at the terminal",rowBrowserDesktop:"Native desktop app — you're at that desk",rowBrowserAdhdev:"Web-first: control sessions and approve from any browser or phone",rowNativeApp:"Native desktop app",rowNativeAppLocalCli:"Terminal only",rowNativeAppDesktop:"Polished native window — genuinely nicer to sit in front of",rowNativeAppAdhdev:"We're web-first — a browser tab, not a native app",rowRestarts:"Survives restarts & context loss",rowRestartsLocalCli:"State lives in a session — close it and it's gone",rowRestartsDesktop:"State tied to the app process",rowRestartsAdhdev:"Missions persist to disk and resume after a coordinator or daemon restart — append-only, tamper-evident audit trail",rowCrossCheck:"Cross-check the answer",rowCrossCheckLocalCli:"One agent's take, no second opinion",rowCrossCheckDesktop:"Parallel work, single verdict",rowCrossCheckAdhdev:"MAGI fans the same read-only question to independent machine × provider agents and surfaces where they diverge",footnote:"For a single machine, a single branch, a one-shot task — a local CLI with subagents is lighter and works great, and a native desktop orchestrator is a nicer place to sit. Repo Mesh earns its keep when work fans out across machines and branches, needs to survive restarts, and should land on main automatically — controlled from wherever you are."},what:{sectionTitle:"Any agent, mixed freely",sectionSubtitle:"Vendor-neutral by design. Run Claude Code on the Mac, Codex on the Windows GPU box, Gemini for review passes — in the same mesh, under the same policies. Switch vendors without switching platforms.",cliHighlight:"CLI agents",cliTitle:"Drive any terminal agent from the web",cliDesc:"Claude Code, Codex CLI, Cursor CLI, Antigravity CLI, Hermes, Kimi, and OpenCode — attached on your machine through a PTY adapter with proper resume and reconnect, driven from your browser. Send prompts and provide visual context instantly (paste, drag & drop, or upload multiple images at once, up to 5 images / 10MB each). Aider, Gemini CLI, Goose, and other ACP agents connect over stdio.",uiHighlight:"One UI",uiTitle:"Same dashboard, any device",uiDesc:"Cloud-hosted at adhf.dev — drive every agent from a laptop or phone, whether you're at your desk or away from it.",ideHighlight:"IDE agents",ideTitle:"Also: attach to running editors",ideDesc:"Cursor, VS Code, VSCodium, Windsurf, Antigravity, Kiro, PearAI, Trae. Read live chat, send prompts, switch sessions, capture screenshots.",p2pHighlight:"Yours, end to end",p2pTitle:"P2P-first: your data stays yours",p2pDesc:"Chat, commands, and screenshots flow directly between your browser and your daemon over WebRTC. The cloud sees auth and signaling metadata, nothing else — your code never routes through the server."},oss:{sectionTitle:"Open source & self-hostable",sectionSubtitle:"The daemon and dashboard are AGPL-3.0 and available on GitHub. Run them yourself on any machine or server — no account required.",github:"GitHub",selfHostDocs:"Self-hosting docs"},agents:{sectionTitle:"Supported agents",sectionSubtitle:"{{ides}} built-in IDE integrations, {{clis}} built-in CLI agents, {{extensions}} IDE-resident extension agents, and {{acp}}+ ACP (stdio MCP) agents. Provider scripts live in <code>adhdev-providers/</code> — add your own under <code>~/.adhdev/providers/</code>.",tierTested:"Tested",tierTestedDesc:"validated against a real app + version",tierCommunity:"Community",tierCommunityDesc:"built-in and community-supported",groupIdes:"IDEs",hintIdes:"Attached via Chrome DevTools Protocol. Read chat, send prompts, switch sessions, screenshot.",groupCli:"CLI agents",hintCli:"Driven through a PTY adapter with resume and reconnect.",groupExtensions:"In-IDE extension agents",hintExtensions:"CDP webview attachment for agents that live inside another IDE.",acpFootnote:"Plus {{count}}+ ACP agents over stdio (Agent Client Protocol): Codex, Claude Agent, Gemini, Goose, Cline, OpenHands, and more."},pricing:{sectionTitle:"Simple pricing as your agents grow",sectionSubtitle:"Start free on one machine. Go Pro for two, or Ultra for five. No per-seat math, no enterprise sales call — just the plans below.",mostPopular:"Most popular",upgradeToPro:"Upgrade to Pro",footnote:"Simple, transparent pricing — the prices above are what you'll pay. Prefer to self-host? The daemon and dashboard are open source. Prices in USD.",plans:{free:{period:"forever",tagline:"Everything you need to drive one machine from anywhere.",cta:"Start free",features:{machine:"One machine, paired in a single command",p2p:"P2P chat, commands, screenshots, remote input",providers:"Every provider — CLI, IDE, and ACP agents",push:"Push notifications for approvals & completions",share:"One shared session link"}},pro:{period:"/mo",tagline:"Run agents across a couple of machines, with the reliability paid plans need.",cta:"Start 7-day Pro trial",features:{machines:"2 machines — run agents on both",p2p:"More concurrent P2P sessions",push:"Unlimited push notifications",turn:"TURN relay for restrictive networks",mesh:"Repo Mesh — orchestrate agents across machines",share:"More shared sessions"}},ultra:{period:"/mo",tagline:"Everything in Pro, scaled up — more machines and higher limits for heavy parallel work.",cta:"Go Ultra",features:{machines:"5 machines — flat price, not per-seat",everything:"Everything in Pro",p2p:"Highest concurrent P2P sessions",screenshots:"Unlimited daily screenshot minutes",webhooks:"More webhooks & API calls",share:"More shared sessions"}}}},install:{sectionTitle:"Three steps to a working dashboard",sectionSubtitle:"No configuration files. No API keys to wire up. ADHDev does not manage agent auth — each tool keeps its own login.",selectOs:"Select OS",osUnix:"macOS / Linux",osWindows:"Windows",copyInstall:"Copy install command: {{cmd}}",copied:"Copied",copy:"Copy",platformNote:"macOS and Windows are the validated install paths. Linux runs the same Unix script and is community-tested.",arrow:"→",steps:{step1:{title:"Install the daemon",desc:"One curl command installs the daemon plus the adhdev CLI — the launcher you run to pair machines and start the daemon (not to be confused with the CLI agents it drives, like Claude Code or Codex). Same binary powers cloud and standalone."},step2:{title:"Link a machine",desc:"Sign in once with GitHub or Google and the daemon pairs itself — no token to copy."},step3:{title:"Drive your agents",desc:"Launch Claude Code, Codex CLI, Cursor CLI, Antigravity CLI, Hermes, Kimi, and other agents from the dashboard. Read chat, send prompts, provide visual context (paste, drag & drop, or upload multiple images at once), approve actions, and switch sessions."}}},cta:{headline:"Stop juggling tabs. Drive every agent from one dashboard.",subtitle:"One curl command, one daemon, every agent you already use. Drive them all from the web — Cloud is live.",getStarted:"Get started →",github:"GitHub",discord:"Discord"},footer:{docs:"Docs",github:"GitHub",discord:"Discord",dashboard:"Dashboard",terms:"Terms",privacy:"Privacy",contact:"Contact",copyright:"© {{year}} RacoLab. All rights reserved."}},gx={chat:Jg,chatPane:Qg,chatInput:Xg,paneGroup:Zg,terminal:ex,conversation:tx,cliView:sx,launch:nx,standalone:rx,meshGraph:ox,cloud:ax,app:ix,chatList:lx,screenshot:cx,remote:dx,sessionInfo:ux,mesh:hx,machine:px,settings:mx,historyModal:fx,landing:bx},xx={copyMessage:"复制消息"},yx={connectingToMachine:"正在连接到您的机器",establishingP2P:"正在建立P2P连接",agentNotMonitored:"代理未被监控",clickToSwitchMonitoring:"点击切换到监控此代理",agentPanelHidden:"代理面板尚不可见",openPanelHint:"在您使用的应用中打开代理面板或聊天视图以开始查看消息",noMessagesYet:"暂无消息",loadingChat:"正在加载聊天...",openPanel:"打开{{label}}面板",switchingPanel:"切换中...",openingPanel:"正在打开..."},vx={attachImage:"附加图片",placeholder:"向{{panel}}发送消息...(Shift+Enter换行)",sendMessage:"发送消息",dropImage:"将图片拖放到此处"},wx={noConversations:"还没有对话",waitingForDaemon:"等待守护进程",connectYourMachines:"连接您的机器",daemonDescription:"启动ADHDev守护进程以连接此仪表板。一旦在线,您可以使用任何已安装的提供商启动会话。",installDescription:"在机器上安装ADHDev并登录,它将显示在这里。",newSession:"新建会话",newSessionDescription:"已连接的机器已就绪。使用任何已安装的提供商(CLI、ACP或IDE)开始新会话。"},kx={loadOlderOutput:"加载较旧的终端输出",loadingOlder:"正在加载较旧内容...",debug:"调试",copy:"复制",openControlKeys:"打开终端控制键",closeControlKeys:"关闭终端控制键"},Sx={muteThis:"静音此聊天",unmuteThis:"取消静音此聊天",mutedTitle:"已静音 — 通知已关闭。点击取消静音。",muteTitle:"静音此聊天的通知"},Cx={switchToTerminal:"切换到终端视图",switchToChat:"切换到聊天视图"},jx={resumeSavedHistory:"恢复保存的历史记录",startFresh:"重新开始",resumingSavedHistory:"正在恢复保存的历史记录…",startingFresh:"正在重新开始…",startIde:"启动IDE",startingIde:"正在启动IDE…",startAcpSession:"开始ACP会话",startingAcpSession:"正在开始ACP会话…",recoverHostedRuntime:"恢复托管运行时",hostedRuntimeRecoveryDescription:"中断后托管运行时的回退恢复。要正常延续,请改为打开保存的历史记录。",openSavedHistory:"打开保存的历史记录",savedHistoryTitle:"保存的历史记录",savedHistoryHelper:"当您希望在同一提供商对话中保持连续性时,请使用保存的历史记录。",savedHistoryEmpty:"尚未找到保存的历史记录。",refreshSavedHistory:"刷新保存的历史记录",refreshingSavedHistory:"正在刷新保存的历史记录…",startFreshWith:"使用{{label}}重新开始?",restart:"重启{{label}}?",startFreshReview:"重新开始前请检查提供商和目标文件夹。",restartIdeReview:"重启此IDE前,请查看或更改目标工作区。",restartStoppedReview:"重启此已停止的会话前,请查看或更改目标工作区。",confirmStartFresh:"重新开始",confirmRestart:"重启",confirmStartingFresh:"正在重新开始…",confirmRestarting:"正在重启…",resumeWith:"使用{{label}}恢复保存的历史记录?",resumeReview:"恢复保存的历史记录前,请查看或更改目标工作区。"},Nx={nav:{dashboard:"Dashboard",settings:"Settings",docs:"Docs",about:"About"},layout:{expandSidebar:"Expand sidebar",collapseSidebar:"Collapse sidebar",collapse:"Collapse"},auth:{loading:"Loading standalone dashboard…",loadError:"Failed to load standalone auth status: {{error}}",signInTitle:"Standalone sign-in",passwordProtected:"This self-hosted dashboard is protected by a local password.",tokenProtected:"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session.",passwordPlaceholder:"Enter standalone password",unlock:"Unlock dashboard",signingIn:"Signing in…",noPasswordEnabled:"Password login is not enabled on this server."},machine:{loading:"⏳ Loading machine...",awaitingInput:"Awaiting your input ↑"},settings:{title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",infoNotice:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint.",publicHostWarning:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token.",daemonSection:"Daemon",daemonDescription:"Connection health and local endpoints for the self-hosted runtime.",versionLabel:"Version",statusLabel:"Status",statusRunning:"● Running",statusNotConnected:"○ Not connected",currentBindLabel:"Current bind",defaultBindLabel:"Default bind",authLabel:"Auth",authPassword:"Password enabled",authToken:"Token enabled",authNone:"No auth configured",networkSection:"Network Access",networkDescription:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",networkHint:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token.",localhostLabel:"Localhost only",localhostHint:"Bind to 127.0.0.1. Best when only this machine should open the dashboard.",allInterfacesLabel:"All interfaces",allInterfacesHint:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points.",saveNetworkMode:"Save default network mode",saving:"Saving…",networkRestartHint:"Applies on next standalone restart. Current run stays bound to {{host}}.",networkSavedAll:"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.",networkSavedLocal:"Default standalone network mode set to localhost only. Restart standalone to apply it.",securitySection:"Dashboard Security",securityDescription:"Self-hosted-only password protection for browsers using this standalone dashboard.",passwordSet:"A local password is currently required for browser access. Existing sessions are rotated when you change it.",passwordNotSet:"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended.",currentPasswordPlaceholder:"Current password",currentPasswordFirstTimePlaceholder:"Current password (not needed for first setup)",newPasswordPlaceholder:"New password",newPasswordFirstTimePlaceholder:"New standalone password",confirmPasswordPlaceholder:"Confirm new password",updatePassword:"Update password",enablePassword:"Enable password",disablePassword:"Disable password",passwordUpdated:"Standalone password updated.",passwordEnabled:"Standalone password enabled.",passwordDisabled:"Standalone password disabled.",passwordTooShort:"Password must be at least 4 characters.",passwordMismatch:"New password and confirmation do not match.",detectedIdesSection:"Detected IDEs",detectedIdesDescription:"Editors discovered by the local daemon on this machine.",noIdesDetected:"No IDEs detected. Start an IDE to see it here.",machineSection:"Machine",machineDescription:"The local burrow exposed by your standalone daemon.",daemonNotConnected:"Daemon not connected. Run 'adhdev-standalone' to start.",appearanceSection:"Appearance",appearanceDescription:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",themeDescription:"Choose a preset or create a custom surface, accent, and chat palette for the standalone UI.",mobileDescription:"Choose whether phones open the dashboard as a chat app first or in the full workspace layout.",fontsLabel:"Fonts",fontsDescription:"Standalone-only typography overrides for chat text, markdown code, and terminal output.",fontsSaved:"Standalone chat fonts saved for this self-hosted dashboard.",notificationsSection:"Notifications",notificationsDescription:"Browser prompts and local sound cues for agent activity.",soundEffectsLabel:"Sound Effects",soundEffectsDescription:"Play a sound when agent completes or needs approval",profileSection:"Profile",profileDescription:"How your name appears in local chat threads and dashboard views.",displayNameLabel:"Display Name",displayNameHint:"Your name shown in chat threads and on the team dashboard.",displayNamePlaceholder:"Anonymous"},onboarding:{title:"Welcome to ADHDev",selectedCount_one:"{{count}} provider selected",selectedCount_other:"{{count}} providers selected",skip:"Skip",installing:"Installing…",done:"Done",installCount:"Install {{count}}",intro:"Pick the providers you want to use. Defaults to the four officially supported CLI providers; you can install IDE, ACP, or extension providers from the tabs below or later from Burrow → Providers → Add provider.",loadingRegistry:"Loading registry…",loadError:"Failed to load registry: {{error}}",noProviders:"No providers in this category.",installed:"✓ installed",installFailed:"✗ {{error}}"},about:{title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",selfHostedEdition:"Self-hosted edition",headline:"Keep the same dashboard experience, with the runtime fully on-device.",description:"Standalone keeps the browser, daemon, screenshots, and control path on your own machine. It is the same core product shape as cloud, just without the remote networking and team layers.",docs:"Docs ↗",github:"GitHub ↗",tryCloud:"Try Cloud ↗",includedSection:"Included in standalone",includedDescription:"The local-first feature set available without the cloud control plane.",inventorySection:"Built-in inventory",inventoryDescription:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",cloudExtrasSection:"Cloud-only extras",cloudExtrasDescription:"Capabilities that need the hosted control plane or team infrastructure.",comparisonSection:"Self-hosted vs Cloud",comparisonDescription:"The product split at a glance.",featureHeader:"Feature",selfhostHeader:"Selfhost",cloudHeader:"Cloud",cloudOptional:"Cloud is optional, not required",cloudOptionalDescription:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",compareCloud:"Compare Cloud ↗",discord:"Discord ↗"},fonts:{fontOverridesNotice:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below.",chat:"Chat text",chatDescription:"Assistant/user prose, markdown text, thought cards, and system notes.",code:"Code blocks",codeDescription:"Markdown code fences, inline code, and preformatted command output.",terminal:"Terminal",terminalDescription:"Terminal transcript cards and tool/command rows in chat mode.",livePreview:"Live preview",resolvedStack:"Resolved stack:",defaults:"Defaults:",saveFontSettings:"Save font settings",revertToSaved:"Revert to saved",resetToDefaults:"Reset to defaults",saving:"Saving…"}},Ax={panel:{selectNode:"Select a node to view details.",submoduleBadge:"Submodule",dirtyBadge:"Dirty",outOfSyncBadge:"Out of sync",conflictBadge:"Conflict",orphanBadge:"Orphan",fieldWorkspace:"Workspace",fieldBranch:"Branch",fieldUpstream:"Upstream",fieldUpstreamState:"Upstream state",fieldHead:"HEAD",fieldSubmodulePath:"Submodule path",fieldSubmoduleCommit:"Submodule commit",fieldParentNode:"Parent node",fieldAhead:"Ahead",fieldBehind:"Behind",fieldDirtyFiles:"Dirty files",fieldActiveSessions:"Active sessions",fieldProviders:"Providers",fieldConnection:"Connection",fieldLinkNote:"Link note",fieldError:"Error",orphanReasons:"Orphan reasons",attachedChats:"Attached chats",providerUnknown:"provider unknown",statusAwaiting:"awaiting approval",statusGenerating:"generating",statusIdle:"idle",statusCoordinator:"coordinator",statusWorker:"worker",runtimeAgeNotReported:"runtime age not reported",upstreamVerified:"verified",upstreamUnverifiedFetch:"unverified (fetch failed)",upstreamUnverified:"unverified",upstreamUnavailable:"unavailable",needsFollowUp:"needs follow-up",refined:"refined"},obs:{tabOverview:"Overview",tabStatus:"Status",tabGraph:"Graph",convergenceMergedToMain:"Merged to main",convergenceNeedsMerge:"Needs merge",convergenceBlockedReview:"Blocked — needs review",convergenceCleanup:"Ready to clean up",convergenceNotMergeable:"Not mergeable",followUpLabel:"Follow-up — {{status}}",selectedNode:"Selected node",selectedEdge:"Selected edge",activeSessions:"Active Sessions",ledger:"Ledger (mesh-wide)",queueTasks:"Queue tasks",keyWarning:"Key warning",healResult:"Heal result",healPreview:"Heal preview",noResultCode:"No result code returned.",health:"Health",legend:"Legend",checking:"Checking",heal:"Heal",loadingGraph:"Loading graph…",bootstrapBanner:"Awaiting live data — showing setup inventory until peer mesh_status probes succeed.",emptyGraph:"No live mesh graph is available for this coordinator yet.",fieldMachine:"Machine",fieldLocality:"Locality",fieldWorkspace:"Workspace",fieldHead:"HEAD",fieldDirtyAheadBehind:"Dirty/ahead/behind",fieldSessions:"Sessions",fieldUpstream:"Upstream",fieldSource:"Source",fieldTransport:"Transport",fieldMachineId:"Machine id",fieldDaemonId:"Daemon id",fieldFrom:"From",fieldTo:"To",fieldLabel:"Label",fieldCompleted:"Completed",fieldFailed:"Failed",fieldLaunched:"Launched",fieldRecentFailures:"Recent failures",meshConnecting:"mesh connecting...",connecting:"connecting...",providerUnknown:"provider unknown"}},Tx={login:{eyebrow:"云端登录",title:"登录 ADHDev",subtitle:"连接你的机器,接收审批和完成通知,让你的编码代理在你离开电脑时也能持续运行。",continueWith:"使用 {{provider}} 继续",connecting:"连接中...",devDivider:"开发",devLogin:"开发登录 (test_jwt_token)",providerNote:"GitHub 和 Google 仅用于身份验证。",errorUnverifiedEmail:"此登录提供方未返回已验证的邮箱,因此我们无法安全地为你登录。",termsPrefix:"继续即表示你同意我们的",termsLink:"服务条款",termsAnd:" 和 ",privacyLink:"隐私政策",termsSuffix:"。"},account:{title:"账户",subtitle:"个人资料、套餐和活动",tabAccount:"账户",tabBilling:"账单",tabActivity:"活动",profile:"个人资料",noName:"无名称",displayName:"显示名称",displayNameDesc:"在仪表板和团队工作区中显示的名称。",nicknamePlaceholder:"昵称",save:"保存",saving:"...",cancel:"取消",saved:"已保存",edit:"编辑",failedToSave:"保存失败",userId:"用户 ID",loadingProfile:"正在加载个人资料...",planLimits:"套餐限额",limitMachines:"机器",limitP2P:"P2P 连接",limitWebhooks:"Webhook",limitTurnRelay:"TURN 中继",enabled:"已启用",disabled:"已禁用",frozen:"已冻结",session:"会话",logout:"退出登录",logoutConfirm:"确定要退出登录吗?",logoutDesc:"在此设备上退出你的 ADHDev 账户。",dangerZone:"危险区域",dangerZoneDesc:"永久删除你的账户及所有相关数据。此操作无法撤销。",deleteAccount:"删除账户",deleteWillRemove:"这将永久删除:",deleteItemProfile:"你的个人资料和登录凭据",deleteItemKeys:"所有 API 密钥和连接令牌",deleteItemWebhooks:"Webhook 和投递历史",deleteItemPush:"推送通知订阅",deleteItemSessions:"共享会话和审计日志",deleteTypeConfirm:"输入 {{keyword}} 以确认:",deleting:"正在删除...",permanentlyDelete:"永久删除",failedToDeleteAccount:"删除账户失败",registeredMachines:"已注册的机器",machinesSummary:"已注册 {{count}} 台 · {{online}} 台在线",machinesLimit:"(上限: {{limit}})",loadingMachines:"正在加载机器...",noMachinesRegistered:"没有已注册的机器",runSetupPrefix:"在机器上运行 ",runSetupMiddle:",然后启动 ",runSetupSuffix:" 即可在此注册。",removeMachineConfirm:"移除此机器?重新连接时需再次运行 `adhdev setup`。",failedToDeleteMachine:"删除机器失败",failedToUpdate:"更新失败",rename:"重命名",online:"在线",connecting:"连接中",lastSeen:"最后在线 {{time}}",removeMachine:"移除机器",never:"从未",justNow:"刚刚",minutesAgo:"{{minutes}} 分钟前",hoursAgo:"{{hours}} 小时前",daysAgo:"{{days}} 天前"},billing:{title:"Billing",subtitle:"Manage your subscription and plan",currentPlan:"当前套餐:",statusTrial:"试用",statusActive:"有效",statusPastDue:"逾期",statusCanceled:"已取消",nextBilling:"下次扣款: {{date}}",trialEnds:"试用结束: {{date}}",accessUntil:"可用至: {{date}}",updatePayment:"请更新你的付款方式",managePayment:"管理付款和发票",couldNotOpenPortal:"无法打开账单门户",statMachines:"机器",statTeam:"团队",statTurnPerDay:"TURN 分钟/天",monthly:"按月",yearly:"按年",savePercent:"省 17%",paddleLoading:"Paddle 正在加载,请重试。",cancelConfirm:"确定要取消订阅吗?在计费周期结束前你仍可继续使用。",teamSeats:"团队席位",seatsUsed:"已使用 {{used}} / {{total}} 个席位",pricePerMonth:"${{price}}/月",cannotReduceSeats:"无法减少到 {{count}} 个席位以下(当前正在使用)。请先移除成员。",removeSeat:"− 移除席位",addSeat:"+ 添加席位",cancelSubscription:"取消订阅",cancelRetainAccess:"在当前计费周期结束前,你仍可使用 {{plan}} 功能。",cancelTeamDowngrade:" 所有团队成员将被降级为各自的个人套餐。"},about:{title:"About",subtitle:"Cloud overview, supported surfaces, and plan-level capabilities",cloudEdition:"Cloud edition",heroTitle:"Control your local CLI agents from anywhere — web or mobile.",heroDesc:"ADHDev Cloud surfaces the agents running on your machines in your browser: send prompts, approve actions, orchestrate work across machines, and get notified on your phone — code flows P2P directly to your daemon, never through the server.",openDashboard:"Open Dashboard",viewMachines:"View Machines",docs:"Docs ↗",whyTitle:"Why ADHDev Cloud",whyDesc:"Core capabilities available when your machines are connected through the cloud control plane.",howTitle:"How it works",howDesc:"The cloud onboarding path from install to remote control.",repoMeshTitle:"Repo Mesh",repoMeshDesc:"Orchestrate agents across machines — cloud only.",meshCard1Title:"One coordinator, many agents",meshCard1Desc:"Enqueue tasks against a mission and let idle nodes claim work from a local-first, pull-based queue. Fan out across machines and providers — Claude Code on one, Codex on another — then converge the results from a single coordinator session.",meshCard2Title:"Same repo, many machines at once",meshCard2Desc:"Each node is a checkout or an isolated git worktree, so parallel agents never collide. The refinery converges every branch — validate, merge, push, clean up — with safe submodule handling. Runs over a direct daemon-to-daemon P2P channel; the server only signals and authorizes same-account peers.",worksWith:"Works with",worksWithDesc:"Supported CLI agents, IDEs, and AI extensions.",groupCli:"CLI Agents",groupIdes:"IDEs",groupExtensions:"AI Agents",pricingTitle:"Pricing",pricingDesc:"Current cloud plans and machine capacity by tier.",planPopular:"Popular",planPerMonth:"/mo",readyTitle:"Ready to connect a machine",readyDesc:"Jump into your dashboard, inspect your connected machines, or continue in the docs if you are still setting up.",dashboard:"Dashboard",machines:"Machines",discord:"Discord ↗",github:"GitHub ↗",features:{webControlTitle:"Web control of local CLI agents",webControlDesc:"Drive any local CLI agent — Claude Code, Codex, Gemini — from your browser: send prompts, approve actions, and steer sessions without touching the terminal.",chatRelayTitle:"Agent chat relay",chatRelayDesc:"Read and respond to agent conversations from anywhere, including mobile surfaces.",liveViewTitle:"Live session view",liveViewDesc:"Watch agent activity in real time; for IDE sessions, view and control the screen over P2P without switching windows.",mobileTitle:"Mobile-ready",mobileDesc:"Receive approvals and check progress while away from your development machine.",secureTitle:"Secure by default",secureDesc:"Chat, commands, and screenshots flow directly between your browser and your daemon over WebRTC — the cloud handles auth and signaling metadata only. Your code never routes through the server."},steps:{step1Title:"One-line Install",step1Desc:"Run a single command on any machine you want to drive. It installs the ADHDev daemon plus the adhdev CLI.",step2Title:"Sign In",step2Desc:"Sign in with GitHub or Google and the daemon pairs itself to your account — no token to copy.",step3Title:"Drive Your Agents from Anywhere",step3Desc:"The machine appears in your dashboard instantly. Launch and control Claude Code, Codex, Gemini, and other CLI agents from the web — IDE sessions too."},plans:{freeName:"Free",proName:"Pro",ultraName:"Ultra",freePer:"/mo",proPer:"/mo",ultraPer:"/mo",freeFeature1:"1 machine",freeFeature2:"Real-time chat relay",freeFeature3:"Web control for your local agents",freeFeature4:"Community support",proFeature1:"2 machines",proFeature2:"Unlimited AI agents",proFeature3:"P2P remote view",proFeature4:"7-day free trial",ultraFeature1:"5 machines — flat, not per-seat",ultraFeature2:"Everything in Pro",ultraFeature3:"Higher concurrency & usage limits",ultraFeature4:"Unlimited daily screenshot minutes"}},layout:{navDashboard:"Dashboard",navBurrows:"Burrows",navNotifications:"Notifications",navMesh:"Mesh",navMarketplace:"Marketplace",navTeam:"Team",navApi:"API",navWebhooks:"Webhooks",navAccount:"Account",navSettings:"Settings",navDocs:"Docs",navAbout:"About",adminSection:"Admin",adminOverview:"Overview",adminUsers:"Users",adminAuditLogs:"Audit Logs",adminSystem:"System",adminEntry:"Admin",footerPlanTitle:"Current plan: {{plan}} — manage or upgrade",expandSidebar:"Expand sidebar",collapseSidebar:"Collapse sidebar",collapse:"Collapse",logoutConfirm:"Are you sure you want to logout?",logout:"Logout",machineLimitBanner:"You've reached your Free plan limit of {{count}} machine{{plural}}. Upgrade to add more.",upgradeArrow:"Upgrade →"},settings:{title:"Settings",subtitle:"Appearance & preferences",quickLinksTitle:"Quick links",quickLinksDesc:"Open the pages that are easiest to need from mobile inbox.",linkNotificationsTitle:"Notifications",linkNotificationsSubtitle:"Push, browser alerts, and delivery settings",linkAccountTitle:"Account",linkAccountSubtitle:"Profile, billing, sessions, and delete account",linkAboutTitle:"About",linkAboutSubtitle:"Cloud overview, supported surfaces, and plans",linkDocsTitle:"Docs",linkDocsSubtitle:"Open product docs in a new tab",appearanceTitle:"Appearance"},planCard:{unlimited:"Unlimited",machineSingular:"{{count}} machine",machinePlural:"{{count}} machines",sharedSessionSingular:"{{count}} shared session",sharedSessionPlural:"{{count}} shared sessions",teamMemberSingular:"{{count}} team member",teamMemberPlural:"{{count}} team members",turnPerDay:"{{count}} TURN min/day",recommended:"Recommended",currentPlan:"Current Plan",contactUs:"Contact Us",freeForever:"Free Forever",startTrial:"Start 7-day free trial",upgradeTo:"Upgrade to {{name}}",noChargeCancel:"No charge for 7 days. Cancel anytime.",periodSeatMo:"seat/mo",periodMo:"mo",yearlyNote:"${{yearly}}/year — Save ${{saved}}",pricingCustom:"Custom"},activity:{filterPlaceholder:"按操作、资源或来源筛选...",refresh:"刷新",loading:"加载中...",noLogs:"无日志",noMatchingLogs:"未找到匹配的日志。",logsWillAppear:"操作发生时将显示在此处。",colAction:"操作",colResource:"资源",colSource:"来源",colTime:"时间",logCount:"{{count}} 条日志",logCountFiltered:" (从 {{total}} 条中筛选)"},webhooks:{title:"Webhook",subtitle:"实时事件通知",addWebhook:"+ 添加 Webhook",eventDaemonConnect:"守护进程已连接",eventDaemonDisconnect:"守护进程已断开",eventAgentStatus:"代理状态变更",eventApprovalRequired:"需要审批",failed:"失败",deleteConfirm:"删除此 Webhook?",testFailed:"测试失败",secretTitle:"Webhook 密钥",secretShownOncePrefix:"",secretShownOnce:"仅显示一次",secretShownOnceSuffix:"。用于验证 ",copy:"复制",done:"完成",newWebhook:"新建 Webhook",labelUrl:"URL",urlPlaceholder:"https://your-service.com/webhook",labelEvents:"事件",allEvents:"所有事件 (*)",creating:"创建中...",create:"创建",cancel:"取消",loading:"加载中...",noWebhooks:"无 Webhook",noWebhooksDesc:"接收有关事件的实时通知。",setupFirst:"设置第一个 Webhook",off:"关闭",autoDisabled:"已自动禁用",autoDisabledTitle:"连续 10 次失败后自动禁用",failuresWarning:"⚠ 失败 {{count}} 次",failuresTitle:"连续失败 {{count}} 次 — 将在 10 次时自动禁用",all:"全部",history:"历史",test:"测试",delete:"删除",deleting:"...",recentDeliveries:"最近投递",refresh:"刷新",noDeliveries:"暂无投递。使用 🧪 发送测试。",request:"请求",response:"响应",securityTitle:"安全",securityVerifyPrefix:"",securityVerifySuffix:" 与你的密钥进行验证",securityHttps:"仅使用 HTTPS 端点",securityAsync:"立即返回 2xx,异步处理",securityAutoDisable:"连续 10 次失败后自动禁用"},apiKeys:{title:"API 密钥",keyCount:"{{count}} 个密钥",playground:"调试台",create:"+ 创建",scopeDaemonRead:"守护进程读取",scopeDaemonReadDesc:"列出守护进程和状态",scopeDaemonControl:"守护进程控制",scopeDaemonControlDesc:"命令、启动/停止、断开",scopeAgentRead:"代理读取",scopeAgentReadDesc:"状态和聊天记录",scopeAgentControl:"代理控制",scopeAgentControlDesc:"发送、批准/拒绝",scopeTerminal:"终端",scopeTerminalDesc:"执行命令",scopeWebhooks:"Webhook",scopeWebhooksDesc:"管理钩子和投递",frozen:"已冻结",revokeConfirm:"撤销此 API 密钥?此操作无法撤销。",failedToLoad:"加载失败",failed:"失败",upgradePlan:"升级你的套餐 →",keyCreated:"密钥已创建!",copyNow:"立即复制 — 仅显示一次。",copied:"已复制",copy:"复制",testKey:"测试",dismiss:"关闭",playgroundTitle:"API 调试台",enterKeyToTest:"输入要测试的 API 密钥。",open:"打开",createKeyTitle:"创建 API 密钥",labelName:"名称",namePlaceholder:"例如 Production Bot",permissions:"权限 ({{count}})",createBtn:"创建",cancel:"取消",loading:"加载中...",noKeys:"无 API 密钥",noKeysDesc:"创建密钥以与外部服务集成。",createFirstKey:"创建第一个密钥",usedDate:"于 {{date}} 使用",neverUsed:"从未使用",revoke:"撤销",usageLabel:"用法:",apiReference:"API 参考 →"},auditLogs:{title:"审计日志",subtitle:"安全事件和 API 历史",refresh:"刷新",filterPlaceholder:"按操作、资源或来源筛选...",loading:"加载中...",noLogs:"无日志",noMatchingLogs:"未找到匹配的日志。",logsWillAppear:"操作发生时将显示在此处。",colAction:"操作",colResource:"资源",colSource:"来源",colTime:"时间",logCount:"{{count}} 条日志",logCountFiltered:" (从 {{total}} 条中筛选)"},inviteModal:{title:"Invite Team Member",subtitle:"Send an invite link via email",manageSeats:"→ Manage seats in Billing",emailLabel:"Email Address",emailPlaceholder:"colleague@company.com",roleLabel:"Role",roleViewer:"Viewer",roleMember:"Member",roleAdmin:"Admin",roleViewerDesc:"Can view dashboards and chat history",roleMemberDesc:"Can control agents and send commands",roleAdminDesc:"Can manage members and settings",cancel:"Cancel",sending:"Sending...",sendInvite:"Send Invite",inviteSent:"Invite sent!",shareWith:"Share this link with",copied:"Copied!",copy:"Copy",done:"Done"},shareModal:{title:"Share Session",chatLabel:"Chat",chatDesc:"AI conversation only",remoteLabel:"Remote",remoteDesc:"Screenshot + desktop",permissionLabel:"Permission Level",authRequired:"Account required",expiresAfter:"Expires After",maxViewers:"Max Viewers",hide:"Hide",activeShares:"Active Shares",creating:"Creating...",createChatLink:"Create Chat Link",createRemoteLink:"Create Remote Link",expires:"expires",revoke:"Revoke",shareLinkCreated:"Share link created!",viewerMustLogin:"Viewer must be logged in to use this link",copy:"Copy",copied:"Copied!",expiresAt:"Expires:",done:"Done",failedToCreate:"Failed to create share link",expiry1h:"1 hour",expiry6h:"6 hours",expiry24h:"24 hours",expiry7d:"7 days",chatView:{label:"View Only",desc:"Read AI conversation in real-time"},chatControl:{label:"Control",desc:"Read + send messages + approve/reject actions"},remoteView:{label:"View Only",desc:"Watch screenshots + chat in real-time"},remoteControl:{label:"Control",desc:"Screenshots + send messages + approve/reject"},remoteFull:{label:"Full Access",desc:"Full remote control including desktop input"}},onboarding:{title:"Connect your first machine",subtitle:"Install ADHDev on a machine and sign in — it pairs itself and shows up here. Then drive every agent on it from this dashboard.",platformMac:"🍎🐧 macOS / Linux",platformWindows:"🪟 Windows",copyTitle:"Click to copy",copiedLabel:"✓ Copied",copyLabel:"📋 Copy",listeningLabel:"Listening for your daemon — keep this page open, it will appear automatically.",connectingLabel:"Connecting to ADHDev…",step1Title:"Install the daemon",step1Desc:"Run the command above on any machine you want to drive. It installs the daemon plus the adhdev CLI.",step2Title:"Sign in — the machine pairs itself",step2Desc:"The daemon links to this account automatically. No token to copy; it appears here the moment it connects.",step3Title:"Launch your first session",step3Desc:"Once a machine is online, start Claude Code, Codex, Cursor, and other agents straight from the dashboard.",readDocs:"📚 Read the documentation →"},legal:{navHome:"Home",navDashboard:"Dashboard",footerHome:"Home",footerTerms:"Terms",footerPrivacy:"Privacy",footerRefund:"Refund Policy",footerCopyright:"© 2026 RacoLab. All rights reserved."},authCallback:{authFailed:"Authentication Failed",backToLogin:"Back to Login",completing:"Completing authentication...",noTokenError:"No access token received"},cliAuth:{title:"ADHDev CLI Authentication",verifying:"Verifying...",authorizeAs:"Authorize CLI as {{name}}?",noCodeError:"No authentication code provided.",approve:"✓ Approve",signInFirst:"Please sign in first to authorize the CLI.",signIn:"Sign In →",failed:"Failed",successMessage:"CLI authentication complete!",returnToTerminal:"You can return to the terminal."},privacy:{title:"Privacy Policy",lastUpdated:"Last updated: March 23, 2026",intro:'This Privacy Policy describes how RacoLab ("we", "us", "our") collects, uses, and protects your information when you use the ADHDev service ("Service") at',s1Title:"1. Information We Collect",s1h1:"1.1 Account Information",s1p1:"When you create an account, we collect information provided by your authentication provider (GitHub or Google), including your name, email address, and profile picture.",s1h2:"1.2 IDE & Agent Data",s1p2:"When you connect your development environment to the Service, the local daemon may transmit:",s1l1:'IDE type and version (e.g., "Cursor 0.49.1")',s1l2:"Active AI agent information (name, status, current model)",s1l3:"Chat messages between you and AI agents",s1l4:"IDE screenshots (transmitted via P2P, not stored on our servers)",s1l5:"Workspace paths and open file names",s1l6:"Machine information (hostname, OS, memory usage)",s1h3:"1.3 Usage Data",s1p3:"We automatically collect usage information including API calls, feature usage patterns, and connection logs for service improvement and debugging purposes.",s1h4:"1.4 Payment Information",s1p4:"Payment processing is handled entirely by our Merchant of Record, Paddle (Paddle.com Market Limited). We do not directly collect or store credit card numbers, bank account details, or other financial information. Please refer to",s1p4PaddleLink:"Paddle's Privacy Policy",s1p4Suffix:"for their data handling practices.",s2Title:"2. How We Use Your Information",s2p1:"We use collected information to:",s2l1:"Provide and maintain the Service",s2l2:"Authenticate your identity and manage your account",s2l3:"Route commands and data between your dashboard and connected machines",s2l4:"Send notifications (browser and push) about agent status changes",s2l5:"Process billing and subscription management (via Paddle)",s2l6:"Detect and prevent abuse or unauthorized access",s2l7:"Improve the Service and develop new features",s2l8:"Respond to support requests",s3Title:"3. Data Storage & Security",s3h1:"3.1 Infrastructure",s3p1:"Our Service runs on Cloudflare's global network using Cloudflare Workers, Durable Objects, and D1 Database. Data is stored in Cloudflare's infrastructure and is subject to",s3p1CloudflareLink:"Cloudflare's Privacy Policy",s3h2:"3.2 P2P Data",s3p2:"IDE screenshots and real-time terminal data are transmitted directly between your browser and your machine via WebRTC peer-to-peer connections. This data does not pass through or get stored on our servers.",s3h3:"3.3 Security Measures",s3p3:"We implement the following security measures:",s3l1:"JWT-based authentication with short-lived access tokens and refresh token rotation",s3l2:"Encrypted WebSocket connections (WSS/TLS)",s3l3:"Per-connection tokens for daemon authentication",s3l4:"Rate limiting on all API endpoints",s3l5:"Audit logging for security-sensitive operations",s4Title:"4. Data Sharing",s4p1:"We do not sell your personal data to third parties. We may share data with:",s4l1:"Payment processing as Merchant of Record",s4l2:"Infrastructure provider (hosting, CDN, database)",s4l3Label:"Authentication providers",s4l3:"GitHub/Google for OAuth login",s4p2:"We may disclose data if required by law, legal process, or to protect our rights and the safety of our users.",s5Title:"5. Data Retention",s5p1:"We retain your account data for the duration of your active account. Chat messages and agent activity data are retained for up to 90 days for service functionality.",s5p2:"Upon account deletion, we will remove your personal data within 30 days. Some anonymized usage data may be retained for analytical purposes.",s6Title:"6. Your Rights",s6p1:"You have the right to:",s6l1Label:"Access",s6l1:"Request a copy of your personal data",s6l2Label:"Correction",s6l2:"Update or correct your personal information",s6l3Label:"Deletion",s6l3:"Request deletion of your account and associated data",s6l4Label:"Export",s6l4:"Download your data in a portable format",s6l5Label:"Object",s6l5:"Object to certain data processing activities",s6p2:"To exercise these rights, contact us at",s7Title:"7. Cookies",s7p1:"We use essential cookies only for authentication (session tokens) and user preferences (theme, notification settings). We do not use advertising or tracking cookies.",s8Title:"8. Children's Privacy",s8p1:"The Service is not intended for users under the age of 16. We do not knowingly collect personal information from children under 16.",s9Title:"9. International Data Transfers",s9p1:"Your data may be processed in various locations through Cloudflare's global network. By using the Service, you consent to the transfer and processing of your data in these locations.",s10Title:"10. Changes to This Policy",s10p1:"We may update this Privacy Policy from time to time. We will notify you of any material changes by email or through the Service. Your continued use after changes constitutes acceptance of the updated policy.",s11Title:"11. Contact",s11p1:"For questions about this Privacy Policy or data practices:",s11l1Prefix:"Email:",s11l2Prefix:"Website:"},terms:{title:"Terms of Service",lastUpdated:"Last updated: April 11, 2026",intro:'Welcome to ADHDev ("Service"), operated by RacoLab ("we", "us", "our"). By accessing or using our Service at',introSuffix:'you agree to be bound by these Terms of Service ("Terms"). If you do not agree, do not use the Service.',s1Title:"1. Service Description",s1p1:"ADHDev is a cloud developer tool that provides remote monitoring and control of AI coding agents (such as Cursor, VS Code, Antigravity, Claude Code, and others) through web and mobile dashboard surfaces. The Service includes a local daemon, remote dashboards, REST API access, and browser and push notifications.",s2Title:"2. Account Registration",s2p1:"You must create an account to use the Service. You are responsible for maintaining the confidentiality of your account credentials. You agree to provide accurate and complete information during registration and to keep your account information up to date.",s2p2:"You must be at least 16 years old to use the Service. By creating an account, you represent that you meet this age requirement.",s3Title:"3. Subscription Plans & Billing",s3p1:"The Service offers the following plans:",s3l1:"Limited features, 1 connected machine",s3l2:"2 connected machines, unlimited agents, P2P remote view, 7-day free trial",s3l3:"5 connected machines, everything in Pro plus higher concurrency and usage limits (flat price, not per-seat)",s3p2:"Paid subscriptions are billed in advance on a monthly or yearly basis. All payments are processed by our payment partner, Paddle (Paddle.com Market Limited), who acts as the Merchant of Record for all transactions.",s4Title:"4. Refund Policy",s4p1:"We offer a 14-day money-back guarantee for all paid plans. If you are not satisfied with the Service, you may request a full refund within 14 days of your initial purchase by contacting us at",s4p2:"Refunds for renewals are handled on a case-by-case basis. Paddle's refund policies also apply as they are the Merchant of Record.",s5Title:"5. Acceptable Use",s5p1:"You agree not to:",s5l1:"Use the Service for any unlawful purpose or in violation of any applicable laws",s5l2:"Attempt to gain unauthorized access to other users' accounts or data",s5l3:"Reverse-engineer, decompile, or attempt to extract the source code of the Service's server components",s5l4:"Use the Service to transmit malware, spam, or other harmful content",s5l5:"Resell or redistribute the Service without our written consent",s5l6:"Interfere with or disrupt the integrity or performance of the Service",s6Title:"6. Intellectual Property",s6p1:"The Service, including its original content, features, and functionality, is owned by RacoLab and is protected by applicable intellectual property laws. The local daemon component is available under an open-source license as specified in the project repository.",s6p2:"You retain ownership of all data and content you transmit through the Service.",s7Title:"7. Data & Privacy",s7p1:"Your use of the Service is also governed by our",s7PrivacyLink:"Privacy Policy",s7p1Suffix:"The Service processes IDE interactions, chat messages, and screenshots for the purpose of remote monitoring and control. We do not sell your data to third parties.",s8Title:"8. Service Availability",s8p1:"We strive to maintain high availability but do not guarantee uninterrupted access. The Service may be temporarily unavailable due to maintenance, updates, or circumstances beyond our control. We are not liable for any losses resulting from service interruptions.",s9Title:"9. Limitation of Liability",s9p1:"TO THE MAXIMUM EXTENT PERMITTED BY LAW, RacoLab SHALL NOT BE LIABLE FOR ANY INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES, OR ANY LOSS OF PROFITS OR REVENUES, WHETHER INCURRED DIRECTLY OR INDIRECTLY, ARISING OUT OF YOUR USE OF THE SERVICE.",s9p2:"Our total liability for any claim arising from the Service shall not exceed the amount you paid us in the 12 months preceding the claim.",s10Title:"10. Termination",s10p1:"We may suspend or terminate your access to the Service at any time for violations of these Terms or for any other reason at our sole discretion. You may cancel your account at any time through the Settings page. Upon cancellation, your data will be deleted within 30 days.",s11Title:"11. Changes to Terms",s11p1:"We reserve the right to modify these Terms at any time. We will notify you of material changes via email or through the Service. Your continued use after changes constitutes acceptance of the modified Terms.",s12Title:"12. Governing Law",s12p1:"These Terms shall be governed by and construed in accordance with the laws of the Republic of Korea, without regard to conflict of law provisions.",s13Title:"13. Contact",s13p1:"If you have any questions about these Terms, please contact us:",s13l1Prefix:"Email:",s13l2Prefix:"Website:"},refund:{title:"Refund Policy",lastUpdated:"Last updated: March 24, 2026",intro:"ADHDev is operated by RacoLab. All payments are processed by our Merchant of Record,",introSuffix:"who manages billing, invoicing, and refunds on our behalf.",s1Title:"1. 14-Day Money-Back Guarantee",s1p1:"We offer a 14-day money-back guarantee on all paid plans (Pro). If you are not satisfied with the Service for any reason, you may request a full refund within 14 days of your initial subscription purchase.",s1p2:"To request a refund, contact us at",s1p2Suffix:"with your account email and order details. We will process your request within 3 business days.",s2Title:"2. Renewal Refunds",s2p1:"Refunds for subscription renewals (monthly or yearly) are handled on a case-by-case basis. If you were charged for a renewal you did not intend, please contact us within 7 days of the charge at",s3Title:"3. Non-Refundable Cases",s3p1:"Refunds will not be issued for:",s3l1:"Requests made after the 14-day guarantee period for initial purchases",s3l2Prefix:"Accounts suspended or terminated due to violations of our",s3l2Link:"Terms of Service",s3l3:"Partial months of service already used beyond the refund window",s4Title:"4. How Refunds Are Processed",s4p1:"Approved refunds are processed through Paddle and returned to the original payment method. Depending on your bank or card issuer, refunds may take 5–10 business days to appear. Paddle's own",s4p1RefundLink:"refund terms",s4p1Suffix:"also apply.",s5Title:"5. Cancellation",s5p1Prefix:"You may cancel your subscription at any time from the",s5p1BillingLink:"Billing",s5p1Suffix:"page in your dashboard. Cancellation stops future charges. You retain access to your plan's features until the end of the current billing period. Cancellation alone does not trigger a refund.",s6Title:"6. Contact",s6p1:"For refund requests or billing questions:",s6l1Prefix:"Email:",s6l2Prefix:"Website:"},teamWorkspace:{title:"Team",subtitle:"Seat-based team management — $15/seat/mo, centralized billing",planRequired:"Team Plan Required",planDesc:`Team Workspaces are available on the Team plan ($15/seat/mo).
35
+ Manage seats, invite team members, and centrally manage billing for your organization.`,upgradeBtn:"Upgrade to Team →",seatsTitle:"Team Seats",seatsUsedOf:"{{used}} / {{total}} seats used",seatsAvailable:"{{count}} available",seatsFullMsg:"All seats are in use. Add more seats in",seatsBillingLink:"Billing",seatsBillingLinkSuffix:"to invite more members.",newWorkspace:"New Workspace",workspaceNamePlaceholder:"Workspace name...",createBtn:"Create",cancelBtn:"Cancel",noWorkspaceYet:"No team workspace yet",noWorkspaceDesc:"Create a workspace to start managing your team and sharing seats.",createWorkspace:"Create Workspace",membersTab:"Members ({{count}})",sessionsTab:"Sessions",settingsTab:"Settings",membersTitle:"Members ({{count}})",inviteBtn:"+ Invite",pendingInvites:"Pending Invites ({{count}})",pendingBadge:"Pending",removeBtn:"Remove",removeMemberConfirm:"Remove this member? They will lose their Team plan access.",removeSuccess:"Member removed",invitationSent:"Invitation sent!",joinedSuccess:"Successfully joined team workspace!",waitingApproval:"Waiting for {{name}} to approve your view request...",viewRequestSent:"View request sent to {{name}}. Waiting for approval...",viewDeclined:"{{name}} declined the view request",sessionRestricted:"Session viewing is restricted by organization policy (admin_only)",sessionTitle:"Team Sessions",noMembersOnline:"No team members online",selfBadge:"You",machineNoSessions:"Machine online, no active sessions",offline:"Offline",statusGenerating:"Generating...",statusApprovalNeeded:"Approval needed",statusStarting:"Starting...",statusStopped:"Stopped",statusError:"Error",statusDisconnected:"Disconnected",statusHidden:"Hidden",statusUnmonitored:"Unmonitored",statusIdle:"Idle",viewBtn:"View →",requestBtn:"Request →",policyOpen:"Open",policyRequest:"Request",policyAdminOnly:"Admin Only",settingsTitle:"Workspace Settings",sessionVisibilityTitle:"Session Visibility",sessionVisibilityDesc:"Control who can view team members' AI agent sessions",visibilityOpen:"Open",visibilityOpenDesc:"All members can view any session freely",visibilityRequest:"Request-based",visibilityRequestDesc:"Members must request access. Admins can always view.",visibilityAdminOnly:"Admin Only",visibilityAdminOnlyDesc:"Only administrators and the owner can view sessions.",dangerZone:"Danger Zone",dangerZoneDesc:"Irreversible actions",deleteWorkspace:"Delete Workspace",deleteWorkspaceConfirm:"Delete this Team Workspace? All members will lose their Team plan benefits.",leaveWorkspace:"Leave Workspace",leaveWorkspaceConfirm:"Are you sure you want to leave this workspace? Your plan may be downgraded."},sessionShare:{loading:"Loading session...",sessionNotFound:"Session Not Found",noLongerAvailable:"This session is no longer available",homeBtn:"← ADHDev Home",sharedSession:"Shared Session",host:"Host",mode:"Mode",permission:"Permission",auth:"Auth",authRequired:"Account required",viewers:"Viewers",joinChat:"Join Chat",joinSession:"Join Session",expires:"Expires: {{date}}",chatLabel:"Chat",remoteLabel:"Remote",waitingMessages:"Waiting for messages...",connecting:"Connecting... ({{state}})",sendMessageAs:"Send message as {{name}}...",sendAs:"Send as {{name}}...",ownerChat:"{{name}}'s Chat",ownerSession:"{{name}}'s Session",agentName:"{{name}}'s Agent",fullControlBadge:"Full Control Active",failedToJoin:"Failed to join session",sessionRevoked:"Session has been revoked by the host",sessionExpired:"Session has expired",authRequired2:"Authentication required for control share"},apiPlayground:{title:"API Playground",history:"History ({{count}})",apiRelayWarning:"Daemon API relay is opt-in. REST command/chat proxy routes stay disabled unless that daemon explicitly enables them with `adhdev daemon:api enable`.",authBearer:"Authorization: Bearer {{key}}",copyAsCurl:"cURL",copied:"Copied",targetDaemon:"Target Daemon",quickActions:"Quick Actions",requestBody:"Request Body (JSON)",recentRequests:"Recent Requests",clearHistory:"Clear",noDaemonsWarning:"No daemons connected. Start a daemon first or replace {daemonId} manually.",send:"▶ Send",sending:"⏳",close:"Close"}},Ix={openMenu:"Open menu",closeMenu:"Close menu"},Mx={loadingOlderMessages:"Loading older messages...",waitingForMessages:"Waiting for messages...",agentGenerating:"Agent generating...",jumpToTop:"Jump to top",jumpToOldestMessages:"Jump to oldest messages",top:"↑ Top",latest:"↓ Latest",jumpToLatestMessages:"Jump to latest messages",jumpToBottom:"Jump to bottom",showEarlierMessages:"↑ Show {{count}} earlier messages...",showEarlierMessagesHidden:"↑ Show {{count}} earlier messages... ({{total}} hidden)",loadOlderMessages:"↑ Load older messages",loadErrorRetry:"↻ {{error}}"},Dx={zoomOut:"Zoom Out",zoomIn:"Zoom In",resetZoom:"Reset Zoom",toggleFullscreen:"Toggle Fullscreen"},Px={mouse:"Mouse",touch:"Touch",connected:"Connected",ws:"WS",direct:"Direct",relay:"Relay",turnBlocked:"TURN blocked",turnUsage:"TURN {{used}}/{{budget}}m",typeAndEnter:"Type & Enter...",settings:"SETTINGS",zoom:"ZOOM:",fill:"FILL",fit:"FIT",directP2PTitle:"Direct P2P connection",turnRelayTitle:"TURN relay in use",dailyTurnTitle:"Daily TURN relay usage"},Lx={title:"Session info",loading:"Loading…",refresh:"Refresh",close:"Close",failedToLoad:"Failed to load session info",notCoordinatorSession:"This isn't a mesh coordinator session, so no coordinator-specific prompt was injected. The agent runs with whatever defaults its CLI ships with.",stampedToNode:"This session is stamped to a mesh node that the coordinator no longer reports.",sectionSession:"Session",sectionLaunch:"Launch",sectionMeshNode:"Mesh node",sectionMeshCoordinator:"Mesh coordinator",sectionRuntime:"Runtime",rowSessionId:"Session ID",rowProvider:"Provider",rowTransport:"Transport",rowWorkspace:"Workspace",rowSpawnedAt:"Spawned at",rowProviderSessionId:"Provider session ID",rowMachine:"Machine",rowConnection:"Connection",rowWorkspaceGit:"Workspace git",rowCommand:"Command",rowWorkingDirectory:"Working directory",rowArgs:"Args",rowExtraArgs:"Extra args",rowExtraEnv:"Extra env",rowNodeId:"Node ID",rowRepoRoot:"Repo root",rowDaemonId:"Daemon ID",rowRole:"Role",rowMachineStatus:"Machine status",rowHealth:"Health",rowWorktree:"Worktree",rowLaunchReady:"Launch ready",rowGit:"Git",rowProviders:"Providers",rowProviderPriority:"Provider priority",rowMeshId:"Mesh ID",rowCoordinatorCli:"Coordinator CLI",rowStartedAt:"Started at",rowPromptInjection:"Prompt injection",rowMcpConfig:"MCP config",rowRuntimeId:"Runtime ID",rowLifecycle:"Lifecycle",rowSurface:"Surface",rowRecoveryState:"Recovery state",rowRestoredFromStorage:"Restored from storage",rowAttachedClients:"Attached clients"},Rx={status:{schedulingNotReported:"Scheduling runtime not reported by this daemon (older build). Update the coordinator daemon to surface distribution, parallel caps, and per-node load.",schedulingTitle:"Scheduling",distributionTitle:"Distribution only governs how untargeted work is spread across eligible nodes. Per-node load, priority, and provider caps are below.",protocolTitle:"Protocol & provider versions",nodesRuntime:"Nodes — runtime",noNodesReporting:"No nodes reporting runtime yet."},overview:{missionCard:"Missions",ledgerCard:"Ledger",queueCard:"Queue",nodesCard:"Nodes",sessionsCard:"Active sessions",refineCard:"Refine jobs",recentActivity:"Recent activity",recentTasks:"Recent tasks",showFewer:"Show fewer",showMore:"+{{count}} more",noActiveMissions:"No active missions. The coordinator creates a mission for multi-task work.",missionDataUnavailable:"Mission data unavailable from this daemon — update the daemon to see missions.",completedHistory:"Completed / abandoned history",noQueueActivity:"No queue activity.",noNodes:"No nodes in this mesh yet.",noActiveSessions:"No active sessions.",noRefineJobs:"No refine jobs.",closeDetail:"Close detail",loadingGoal:"Loading…",showFullGoal:"Show full goal",statCompleted:"Completed",statAssigned:"Assigned",statPending:"Pending",statFailed:"Failed",statBlocked:"Blocked",statCancelled:"Cancelled",statWallClock:"Wall clock",statTotalRuntime:"Total runtime",statRetries:"Retries",statDispatched:"Dispatched",statStalled:"Stalled",statSessions:"Sessions",statCheckpoints:"Checkpoints",statActive:"Active",recentFailures:"{{count}} recent failures",activeCount:"{{count}} active",failedCount:"{{count}} failed",detailKickerMission:"Mission",detailKickerLedger:"Ledger entry",detailKickerQueue:"Queue task",detailKickerSession:"Session",detailLabelMissionId:"Mission id",detailLabelCreated:"Created",detailLabelUpdated:"Updated",detailLabelLastActivity:"Last task activity",detailLabelIncompleteEvidence:"Incomplete evidence",incompleteTaskCount_one:"{{count}} task",incompleteTaskCount_other:"{{count}} tasks",detailLabelEntryId:"Entry id",detailLabelWhen:"When",detailLabelNode:"Node",detailLabelSession:"Session",detailLabelProvider:"Provider",detailLabelPayload:"Payload",detailLabelTaskId:"Task id",detailLabelAutoLaunch:"Auto launch",detailLabelCancelReason:"Cancel reason",detailLabelRequeueReason:"Requeue reason",detailLabelRequeued:"requeued {{count}}",detailLabelSessionId:"Session id",detailLabelBranch:"Branch",detailLabelRole:"Role",detailLabelStarted:"Started",detailLabelWorkspace:"Workspace"}},Ex={launchConfirm:{workspace:"Workspace",languageModel:"Language Model (Optional)",autoDetect:"Auto-detect or default",cliArgs:"CLI Arguments (Optional)",cliArgsPlaceholder:"e.g. --experimental",cancel:"Cancel",closeAria:"Close launch confirmation",launch:"Launch",launching:"Launching…"},confirmExternal:{dialogAria:"Confirm untrusted external provider",title:"Activate untrusted external provider?",description:"This manifest ships JavaScript that the daemon will execute. Treat as untrusted code — review the source before enabling.",proceedWarning:"Only proceed if you trust the source URL you added and have reviewed the manifest.",cancel:"Cancel",activate:"Activate"},workspace:{noWorkspace:"(no workspace — launch in home)",selectWorkspace:"📁 Select workspace…",customPath:"✏️ Custom path…",noWorkspacesSaved:"(no workspaces saved — add in Overview tab)",selectWorkspaceBtn:"Select workspace…",enterAbsolutePath:"Enter absolute path…",browseHint:"Browse to a folder before launching there.",absolutePathHint:"Enter an absolute path to launch there.",defaultWorkspace:"Default workspace",selectedWorkspace:"Selected workspace",noWorkspaceSelected:"No workspace selected. This launches in the home directory."},agentTab:{selectToLaunch:"Select {{label}} to Launch",launchSettings:"Launch Settings",noIdesDetected:"No IDEs detected.",scanSystem:"Scan System",noProviders:"No usable {{category}} providers available.",noProvidersHint:"Set a custom executable path in Providers if the binary is installed outside the default location.",targetModel:"Target Model",leaveEmptyDefault:"Leave empty for default",startupArguments:"Startup Arguments",optionalFlags:"Optional flags...",openSession:"Open Session",starting:"Starting...",configure:"Configure",select:"Select",launching:"⏳ Launching...",launchBtn:"▶ Launch",running:"Running ({{count}})",noRunning:"No {{plural}} running",launchingProcess:"Launching process...",waitingProcess:"Waiting for process and session to register...",startingBadge:"starting",chatView:"Chat view",terminalView:"Terminal view",localTerminal:"Local terminal:",copied:"Copied",copy:"Copy",openRemoteControl:"Open remote control",restart:"Restart",viewChat:"View chat",openInDashboard:"Open current view in dashboard",stop:"Stop",extensions:"Extensions",browseFolderTitle:"Select workspace",browseFolderDesc:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",browseFolderConfirm:"Use this folder",detailMode:"Mode",detailProvider:"Provider",detailResume:"Resume",detailArguments:"Arguments",detailModel:"Model",categoryIde:"IDE",categoryCliPlural:"CLIs",categoryAcp:"ACP Agent",categoryAcpPlural:"ACP agents"},providers:{filter:"Filter",sourceConfigTitle:"Provider source config",sourceConfigDesc:"Where the daemon looks for provider manifests. Affects resolution and reloads.",sourceMode:"Source mode",explicitProviderDir:"Explicit providerDir",providerDirPlaceholder:"Leave blank to use ~/.adhdev/providers",applying:"Applying…",applyReload:"Apply + Reload",userRoot:"User root:",upstreamRoot:"Upstream root:",providerRoots:"Provider roots:",loadingSettings:"Loading provider settings…",noProviders:'No providers installed yet. Open "Add provider" above to install one.',noFilteredProviders:"No {{filter}} providers installed.",refresh:"↻ Refresh",sources:"🌐 Sources",create:"✨ Create",advanced:"⚙ Advanced"},providerRow:{statusDetected:"Detected",statusNotDetected:"Not detected",statusEnabledUnchecked:"Enabled (unchecked)",statusDisabled:"Disabled",labelType:"Type:",labelVersion:"Version:",labelBinary:"Binary:",labelStatus:"Status:",labelDetails:"Details:",labelSource:"Source:",labelTrust:"Trust:",labelLinks:"Links:",labelDetection:"Detection:",labelVerification:"Verification:",saving:"saving…",disable:"Disable",enable:"Enable",detect:"Detect",resetCommand:"Reset command"},providerFix:{aiAgent:"AI Agent",scriptsToFix:"Scripts to Fix",all:"All",none:"None",additionalInstructions:"Additional Instructions",optional:"(optional)",agentOutput:"Agent Output",running:"● Running...",agentGenerating:"Agent is generating...",validateHint:"Run `adhdev provider verify` to validate",cancel:"Cancel",startFix:"🚀 Start Fix",cancelRunning:"⬛ Cancel",back:"← Back",close:"Close",footerHint:"AI agent will implement provider scripts",scriptsSelected_one:"{{count}} script selected",scriptsSelected_other:"{{count}} scripts selected",titlePrefix:"Auto-Fix: {{name}}",descCodex:"OpenAI o3/gpt-5.4",descClaude:"Anthropic Claude",descGemini:"Google Gemini"},providerClone:{title:"✨ Create User Provider",subtitle:"Clone an upstream IDE provider to customize",baseProvider:"Base Provider",providerTypeId:"Provider Type (ID)",typeIdPlaceholder:"my-cursor, custom-windsurf...",typeIdHint:"Lowercase, alphanumeric + hyphens only. Will be created at",displayName:"Display Name",displayNamePlaceholder:"My Custom IDE",cancel:"Cancel",creating:"⏳ Creating...",createProvider:"✨ Create Provider",createdTitle:"Provider Created!",createdDesc:"{{type}} has been created at",createdRunHint:"Run adhdev provider fix {{type}} or use Auto-Fix to implement scripts.",close:"Close"},connectedMachines:{noMachines:"No machines connected",defaultDescription:"Install ADHDev on a machine and sign in to connect it here.",startingUpgrade:"Starting upgrade...",machineDisconnected:"Machine disconnected.",tokenRevoked:"Token revoked. Restart ADHDev on that machine to reconnect.",failedToDisconnect:"Failed to disconnect",failedToRevokeToken:"Failed to revoke token",connectionLostUpgrade:"Connection lost during upgrade",disconnect:"Disconnect",remove:"Remove",disconnectTitle:"🔌 Disconnect Machine",removeTitle:"⚠️ Remove Machine",cancel:"Cancel",noIdesConnected:"No IDEs connected",upgrading:"Upgrading...",updated:"✓ Updated",updateNow:"↑ Update now",updateTo:"↑ Update to v{{version}}",cdpConnected:"CDP connected",cdpConnecting:"CDP connecting...",connecting:"connecting..."}},_x={theme:{helloHelp:"Hello! How can I help?",fixBug:"Fix the bug please",onIt:"On it! ✨",customEditorTitle:"🎨 Custom Theme Editor",darkMode:"🌙 Dark mode",lightMode:"☀️ Light mode",sectionAppBackground:"App Background",sectionAppText:"App Text",sectionBordersAccent:"Borders & Accent",sectionChatBubbles:"Chat Bubbles",sectionChatLayout:"Chat Layout",colorBackground:"Background",colorSurface:"Surface",colorCard:"Card",colorPrimary:"Primary",colorSecondary:"Secondary",colorMuted:"Muted",colorBorderSubtle:"Border subtle",colorBorderDefault:"Border default",colorAccent:"Accent",colorUserBubble:"User bubble",colorUserText:"User text",colorAgentBubble:"Agent bubble",colorAgentText:"Agent text",colorChatBg:"Chat BG",colorSendButton:"Send button",colorInputBorder:"Input border",labelBubbleRadius:"Bubble radius",resetToDefaults:"Reset to defaults",customLabel:"🎨 Custom"}},$x={chatHistory:"聊天记录",startNewChat:"+ 开始新聊天会话",creating:"⌛ 创建中...",searchPlaceholder:"搜索标题或预览",filterWorkspace:"按工作区筛选",filterModel:"按模型筛选",sortRecent:"最新",sortOldest:"最早",sortMessages:"消息最多",resumeReadyOnly:"仅可恢复",untitledSession:"无标题会话",noSavedPreview:"暂无保存的预览",workspaceUnknown:"工作区未知",selectedWorkspaceSuffix:" · 选定的工作区",msgCount:"{{count}} 条消息",statusActive:"活动",statusMissingWorkspace:"缺少工作区",statusResumeSelectedWorkspace:"在选定的工作区中恢复",statusResuming:"恢复中...",statusResume:"恢复",noMatchingHistory:"没有符合这些筛选条件的保存记录。",noRecentChats:"未找到最近的聊天会话。",refreshHistory:"刷新记录",refreshing:"⌛ 刷新中..."},Bx={nav:{home:"ADHDev Home",mesh:"Mesh",what:"What",agents:"Agents",pricing:"Pricing",install:"Install",github:"GitHub",docs:"Docs",getStarted:"Get started",toggleMenu:"Toggle menu"},hero:{badge:"The multi-vendor, multi-machine agent control plane",title:"Anyone can run ten agents. ADHDev lands the work on main.",subtitle:"Drive any local coding agent — Claude Code, Codex, Cursor — from your browser, then let the Refinery merge finished work back to main <em>unattended</em>: your repo's own gates, patch-equivalence checks, fast-forward only, no force-push. You talk to one coordinator; it runs parallel agents across your own machines asynchronously — no sessions to babysit. Code stays on your machine — P2P, end to end.",selectOs:"Select OS",osUnix:"macOS / Linux",osWindows:"Windows",copyInstall:"Copy install command: {{cmd}}",copied:"Copied",copy:"Copy",getStarted:"Get started",openSource:"Open source on GitHub",joinDiscord:"Join Discord",selfHost:"Self-host it yourself",demoDesktop:"ADHDev command center driving live agent sessions across multiple machines",demoPush:"ADHDev mobile push notification and one-tap approval"},mesh:{sectionTitle:"They parallelize. We land.",sectionSubtitle:"Spawning parallel agents is the easy part — every tool does it now. The hard part is what happens after: ten branches that still have to be verified and merged. The Refinery does that for you, unattended, so finished work arrives on main instead of in your review queue.",refineryHighlight:"The Refinery",refineryTitle:"Finished work lands on main — unattended",refineryDesc:"Anyone can spawn ten parallel agents. The Refinery validates each worktree against your repo's own gates (typecheck, tests, lint), verifies patch equivalence, publishes submodule commits, fast-forwards main, and cleans up — automatically. No force-push, ever. Anything ambiguous is kicked back for review instead of merged.",asyncHighlight:"Async orchestration",asyncTitle:"You talk to one place. It runs the rest.",asyncDesc:"You give work to one coordinator; it drives many workers across many machines on an event loop — reacting only when a completion, approval, or status event arrives. No polling, no window-per-agent to babysit. Unlike a desktop app where you watch each agent session, here the coordinator waits on events, so you don't have to sit synchronously in front of anything.",monoHighlight:"Monorepo-aware",monoTitle:"Safe even with git submodules",monoDesc:"Real production repos nest submodules — and that's exactly where naive auto-merge breaks. The Refinery is submodule-aware: it gates on submodule-commit reachability, judges patch equivalence, and bumps the pointer atomically. This project is itself a root + two-submodule monorepo, converged this way every day.",crossHighlight:"Cross-check",crossTitle:"Consensus over a single opinion",crossDesc:"Fan the same read-only investigation out to several machine × provider replicas and synthesize where they agree and diverge (MAGI). More trustworthy than one agent's take.",tryMesh:"Try Repo Mesh →",seePlans:"See plans",availableOn:"Available on Pro and above. Drive it from the <strong>Repo Mesh</strong> page once connected.",readGuide:"Read the guide"},compare:{sectionTitle:"Parallel agents are everywhere now. Where does the work actually land?",sectionSubtitle:"A fair question. Local CLIs spawn subagents; desktop orchestrators fan work across worktrees with a slick native UI. Both stop at the branch. Here's the honest line — including where each of them beats us — with no hand-waving.",colLocalCli:"Local CLI + subagents",colDesktop:"Desktop orchestrator",colAdhdev:"ADHDev Repo Mesh",rowLandsMain:"Lands finished work on main",rowLandsMainLocalCli:"You run the gates and merge by hand",rowLandsMainDesktop:"Parallelizes the work, then hands you the branches to review",rowLandsMainAdhdev:"The Refinery runs your repo's gates, checks patch equivalence, and fast-forwards main — unattended, no force-push",rowSubmodules:"Safe with git submodules",rowSubmodulesLocalCli:"No merge automation to be aware of them",rowSubmodulesDesktop:"Worktree parallelism, but the merge is yours to get right",rowSubmodulesAdhdev:"Submodule-aware convergence: reachability gate, patch-equivalence check, atomic pointer bump — dogfooded on this monorepo daily",rowAsync:"Talk to one place, async",rowAsyncLocalCli:"One session at a time, synchronously",rowAsyncDesktop:"You supervise each agent window yourself",rowAsyncAdhdev:"One coordinator drives every worker on an event loop — it waits on completion/approval events, you don't poll or babysit",rowMultiMachine:"Multiple physical machines",rowMultiMachineLocalCli:"One host's processes only",rowMultiMachineDesktop:"Bound to the one machine it runs on",rowMultiMachineAdhdev:"Remote daemons over P2P — dispatch across every machine you own (no SSH plumbing)",rowParallelBranch:"Parallel isolated-branch work",rowParallelBranchLocalCli:"Subagents share one working tree — concurrent writes collide",rowParallelBranchDesktop:"One git worktree per task — a core strength",rowParallelBranchAdhdev:"One git worktree per node — parallel across machines, not just cores",rowBrowser:"Drive it from a browser or phone",rowBrowserLocalCli:"You have to be at the terminal",rowBrowserDesktop:"Native desktop app — you're at that desk",rowBrowserAdhdev:"Web-first: control sessions and approve from any browser or phone",rowNativeApp:"Native desktop app",rowNativeAppLocalCli:"Terminal only",rowNativeAppDesktop:"Polished native window — genuinely nicer to sit in front of",rowNativeAppAdhdev:"We're web-first — a browser tab, not a native app",rowRestarts:"Survives restarts & context loss",rowRestartsLocalCli:"State lives in a session — close it and it's gone",rowRestartsDesktop:"State tied to the app process",rowRestartsAdhdev:"Missions persist to disk and resume after a coordinator or daemon restart — append-only, tamper-evident audit trail",rowCrossCheck:"Cross-check the answer",rowCrossCheckLocalCli:"One agent's take, no second opinion",rowCrossCheckDesktop:"Parallel work, single verdict",rowCrossCheckAdhdev:"MAGI fans the same read-only question to independent machine × provider agents and surfaces where they diverge",footnote:"For a single machine, a single branch, a one-shot task — a local CLI with subagents is lighter and works great, and a native desktop orchestrator is a nicer place to sit. Repo Mesh earns its keep when work fans out across machines and branches, needs to survive restarts, and should land on main automatically — controlled from wherever you are."},what:{sectionTitle:"Any agent, mixed freely",sectionSubtitle:"Vendor-neutral by design. Run Claude Code on the Mac, Codex on the Windows GPU box, Gemini for review passes — in the same mesh, under the same policies. Switch vendors without switching platforms.",cliHighlight:"CLI agents",cliTitle:"Drive any terminal agent from the web",cliDesc:"Claude Code, Codex CLI, Cursor CLI, Antigravity CLI, Hermes, Kimi, and OpenCode — attached on your machine through a PTY adapter with proper resume and reconnect, driven from your browser. Send prompts and provide visual context instantly (paste, drag & drop, or upload multiple images at once, up to 5 images / 10MB each). Aider, Gemini CLI, Goose, and other ACP agents connect over stdio.",uiHighlight:"One UI",uiTitle:"Same dashboard, any device",uiDesc:"Cloud-hosted at adhf.dev — drive every agent from a laptop or phone, whether you're at your desk or away from it.",ideHighlight:"IDE agents",ideTitle:"Also: attach to running editors",ideDesc:"Cursor, VS Code, VSCodium, Windsurf, Antigravity, Kiro, PearAI, Trae. Read live chat, send prompts, switch sessions, capture screenshots.",p2pHighlight:"Yours, end to end",p2pTitle:"P2P-first: your data stays yours",p2pDesc:"Chat, commands, and screenshots flow directly between your browser and your daemon over WebRTC. The cloud sees auth and signaling metadata, nothing else — your code never routes through the server."},oss:{sectionTitle:"Open source & self-hostable",sectionSubtitle:"The daemon and dashboard are AGPL-3.0 and available on GitHub. Run them yourself on any machine or server — no account required.",github:"GitHub",selfHostDocs:"Self-hosting docs"},agents:{sectionTitle:"Supported agents",sectionSubtitle:"{{ides}} built-in IDE integrations, {{clis}} built-in CLI agents, {{extensions}} IDE-resident extension agents, and {{acp}}+ ACP (stdio MCP) agents. Provider scripts live in <code>adhdev-providers/</code> — add your own under <code>~/.adhdev/providers/</code>.",tierTested:"Tested",tierTestedDesc:"validated against a real app + version",tierCommunity:"Community",tierCommunityDesc:"built-in and community-supported",groupIdes:"IDEs",hintIdes:"Attached via Chrome DevTools Protocol. Read chat, send prompts, switch sessions, screenshot.",groupCli:"CLI agents",hintCli:"Driven through a PTY adapter with resume and reconnect.",groupExtensions:"In-IDE extension agents",hintExtensions:"CDP webview attachment for agents that live inside another IDE.",acpFootnote:"Plus {{count}}+ ACP agents over stdio (Agent Client Protocol): Codex, Claude Agent, Gemini, Goose, Cline, OpenHands, and more."},pricing:{sectionTitle:"Simple pricing as your agents grow",sectionSubtitle:"Start free on one machine. Go Pro for two, or Ultra for five. No per-seat math, no enterprise sales call — just the plans below.",mostPopular:"Most popular",upgradeToPro:"Upgrade to Pro",footnote:"Simple, transparent pricing — the prices above are what you'll pay. Prefer to self-host? The daemon and dashboard are open source. Prices in USD.",plans:{free:{period:"forever",tagline:"Everything you need to drive one machine from anywhere.",cta:"Start free",features:{machine:"One machine, paired in a single command",p2p:"P2P chat, commands, screenshots, remote input",providers:"Every provider — CLI, IDE, and ACP agents",push:"Push notifications for approvals & completions",share:"One shared session link"}},pro:{period:"/mo",tagline:"Run agents across a couple of machines, with the reliability paid plans need.",cta:"Start 7-day Pro trial",features:{machines:"2 machines — run agents on both",p2p:"More concurrent P2P sessions",push:"Unlimited push notifications",turn:"TURN relay for restrictive networks",mesh:"Repo Mesh — orchestrate agents across machines",share:"More shared sessions"}},ultra:{period:"/mo",tagline:"Everything in Pro, scaled up — more machines and higher limits for heavy parallel work.",cta:"Go Ultra",features:{machines:"5 machines — flat price, not per-seat",everything:"Everything in Pro",p2p:"Highest concurrent P2P sessions",screenshots:"Unlimited daily screenshot minutes",webhooks:"More webhooks & API calls",share:"More shared sessions"}}}},install:{sectionTitle:"Three steps to a working dashboard",sectionSubtitle:"No configuration files. No API keys to wire up. ADHDev does not manage agent auth — each tool keeps its own login.",selectOs:"Select OS",osUnix:"macOS / Linux",osWindows:"Windows",copyInstall:"Copy install command: {{cmd}}",copied:"Copied",copy:"Copy",platformNote:"macOS and Windows are the validated install paths. Linux runs the same Unix script and is community-tested.",arrow:"→",steps:{step1:{title:"Install the daemon",desc:"One curl command installs the daemon plus the adhdev CLI — the launcher you run to pair machines and start the daemon (not to be confused with the CLI agents it drives, like Claude Code or Codex). Same binary powers cloud and standalone."},step2:{title:"Link a machine",desc:"Sign in once with GitHub or Google and the daemon pairs itself — no token to copy."},step3:{title:"Drive your agents",desc:"Launch Claude Code, Codex CLI, Cursor CLI, Antigravity CLI, Hermes, Kimi, and other agents from the dashboard. Read chat, send prompts, provide visual context (paste, drag & drop, or upload multiple images at once), approve actions, and switch sessions."}}},cta:{headline:"Stop juggling tabs. Drive every agent from one dashboard.",subtitle:"One curl command, one daemon, every agent you already use. Drive them all from the web — Cloud is live.",getStarted:"Get started →",github:"GitHub",discord:"Discord"},footer:{docs:"Docs",github:"GitHub",discord:"Discord",dashboard:"Dashboard",terms:"Terms",privacy:"Privacy",contact:"Contact",copyright:"© {{year}} RacoLab. All rights reserved."}},Fx={chat:xx,chatPane:yx,chatInput:vx,paneGroup:wx,terminal:kx,conversation:Sx,cliView:Cx,launch:jx,standalone:Nx,meshGraph:Ax,cloud:Tx,app:Ix,chatList:Mx,screenshot:Dx,remote:Px,sessionInfo:Lx,mesh:Rx,machine:Ex,settings:_x,historyModal:$x,landing:Bx},Hx={copyMessage:"Copiar mensaje"},Wx={connectingToMachine:"Conectando con tu máquina",establishingP2P:"Estableciendo conexión P2P",agentNotMonitored:"Agente no supervisado",clickToSwitchMonitoring:"Haz clic para cambiar la supervisión a este agente",agentPanelHidden:"El panel del agente aún no es visible",openPanelHint:"Abre el panel del agente o la vista de chat en la aplicación que estás usando para ver los mensajes",noMessagesYet:"Todavía no hay mensajes",loadingChat:"Cargando chat...",openPanel:"Abrir panel de {{label}}",switchingPanel:"Cambiando...",openingPanel:"Abriendo..."},Ox={attachImage:"Adjuntar imagen",placeholder:"Enviar mensaje a {{panel}}... (Shift+Enter para nueva línea)",sendMessage:"Enviar mensaje",dropImage:"Suelta la imagen aquí"},Ux={noConversations:"Todavía no hay conversaciones",waitingForDaemon:"Esperando tu daemon",connectYourMachines:"Conecta tus máquinas",daemonDescription:"Inicia el daemon de ADHDev para conectar este panel. Una vez en línea, puedes iniciar sesiones con cualquier proveedor instalado.",installDescription:"Instala ADHDev en una máquina, inicia sesión y aparecerá aquí.",newSession:"Nueva sesión",newSessionDescription:"Una máquina conectada está lista. Inicia una nueva sesión con cualquier proveedor instalado — CLI, ACP o IDE."},Gx={loadOlderOutput:"Cargar salida de terminal anterior",loadingOlder:"Cargando anteriores...",debug:"Depurar",copy:"Copiar",openControlKeys:"Abrir teclas de control del terminal",closeControlKeys:"Cerrar teclas de control del terminal"},Kx={muteThis:"Silenciar este chat",unmuteThis:"Activar sonido de este chat",mutedTitle:"Silenciado — notificaciones desactivadas. Clic para reactivar.",muteTitle:"Silenciar notificaciones de este chat"},zx={switchToTerminal:"Cambiar a vista Terminal",switchToChat:"Cambiar a vista Chat"},qx={resumeSavedHistory:"Reanudar historial guardado",startFresh:"Empezar de nuevo",resumingSavedHistory:"Reanudando historial guardado…",startingFresh:"Empezando de nuevo…",startIde:"Iniciar IDE",startingIde:"Iniciando IDE…",startAcpSession:"Iniciar sesión ACP",startingAcpSession:"Iniciando sesión ACP…",recoverHostedRuntime:"Recuperar runtime alojado",hostedRuntimeRecoveryDescription:"Recuperación de respaldo para runtimes alojados tras interrupciones. Para continuidad normal, abre el historial guardado.",openSavedHistory:"Abrir historial guardado",savedHistoryTitle:"Historial guardado",savedHistoryHelper:"Usa el historial guardado cuando quieras continuidad en la misma conversación del proveedor.",savedHistoryEmpty:"Todavía no se encontró historial guardado.",refreshSavedHistory:"Actualizar historial guardado",refreshingSavedHistory:"Actualizando historial guardado…",startFreshWith:"¿Empezar de nuevo con {{label}}?",restart:"¿Reiniciar {{label}}?",startFreshReview:"Revisa el proveedor y la carpeta de destino antes de empezar de nuevo.",restartIdeReview:"Revisa o cambia el espacio de trabajo de destino antes de reiniciar este IDE.",restartStoppedReview:"Revisa o cambia el espacio de trabajo de destino antes de reiniciar esta sesión detenida.",confirmStartFresh:"Empezar de nuevo",confirmRestart:"Reiniciar",confirmStartingFresh:"Empezando de nuevo…",confirmRestarting:"Reiniciando…",resumeWith:"¿Reanudar el historial guardado con {{label}}?",resumeReview:"Revisa o cambia el espacio de trabajo de destino antes de reanudar el historial guardado."},Vx={nav:{dashboard:"Dashboard",settings:"Settings",docs:"Docs",about:"About"},layout:{expandSidebar:"Expand sidebar",collapseSidebar:"Collapse sidebar",collapse:"Collapse"},auth:{loading:"Loading standalone dashboard…",loadError:"Failed to load standalone auth status: {{error}}",signInTitle:"Standalone sign-in",passwordProtected:"This self-hosted dashboard is protected by a local password.",tokenProtected:"This standalone server is protected by a token. Open it using the tokenized URL or set a password from an already-authenticated session.",passwordPlaceholder:"Enter standalone password",unlock:"Unlock dashboard",signingIn:"Signing in…",noPasswordEnabled:"Password login is not enabled on this server."},machine:{loading:"⏳ Loading machine...",awaitingInput:"Awaiting your input ↑"},settings:{title:"Settings",subtitle:"Local daemon configuration, appearance, and on-device preferences",infoNotice:"Standalone settings stay on this machine. The browser only talks to your local daemon over localhost or your self-hosted LAN endpoint.",publicHostWarning:"This standalone server is currently bound to 0.0.0.0 without auth. Anyone on your LAN can open the dashboard until you set a password or token.",daemonSection:"Daemon",daemonDescription:"Connection health and local endpoints for the self-hosted runtime.",versionLabel:"Version",statusLabel:"Status",statusRunning:"● Running",statusNotConnected:"○ Not connected",currentBindLabel:"Current bind",defaultBindLabel:"Default bind",authLabel:"Auth",authPassword:"Password enabled",authToken:"Token enabled",authNone:"No auth configured",networkSection:"Network Access",networkDescription:"Choose the default bind host for future standalone launches. CLI --host still overrides this for one-off runs.",networkHint:"Use localhost-only if this dashboard should stay on the current machine. Use all interfaces if you usually access it from phones, tablets, or other devices on your LAN. If you expose that machine more broadly, set a password or token.",localhostLabel:"Localhost only",localhostHint:"Bind to 127.0.0.1. Best when only this machine should open the dashboard.",allInterfacesLabel:"All interfaces",allInterfacesHint:"Bind to 0.0.0.0. Good for LAN access, reverse proxies, or other external entry points.",saveNetworkMode:"Save default network mode",saving:"Saving…",networkRestartHint:"Applies on next standalone restart. Current run stays bound to {{host}}.",networkSavedAll:"Default standalone network mode set to all interfaces (0.0.0.0). Restart standalone to apply it.",networkSavedLocal:"Default standalone network mode set to localhost only. Restart standalone to apply it.",securitySection:"Dashboard Security",securityDescription:"Self-hosted-only password protection for browsers using this standalone dashboard.",passwordSet:"A local password is currently required for browser access. Existing sessions are rotated when you change it.",passwordNotSet:"No standalone password is set yet. If you usually run with --host, setting one is strongly recommended.",currentPasswordPlaceholder:"Current password",currentPasswordFirstTimePlaceholder:"Current password (not needed for first setup)",newPasswordPlaceholder:"New password",newPasswordFirstTimePlaceholder:"New standalone password",confirmPasswordPlaceholder:"Confirm new password",updatePassword:"Update password",enablePassword:"Enable password",disablePassword:"Disable password",passwordUpdated:"Standalone password updated.",passwordEnabled:"Standalone password enabled.",passwordDisabled:"Standalone password disabled.",passwordTooShort:"Password must be at least 4 characters.",passwordMismatch:"New password and confirmation do not match.",detectedIdesSection:"Detected IDEs",detectedIdesDescription:"Editors discovered by the local daemon on this machine.",noIdesDetected:"No IDEs detected. Start an IDE to see it here.",machineSection:"Machine",machineDescription:"The local burrow exposed by your standalone daemon.",daemonNotConnected:"Daemon not connected. Run 'adhdev-standalone' to start.",appearanceSection:"Appearance",appearanceDescription:"Match the rest of the dashboard with a single place for mode, theme, and standalone-only font overrides.",themeDescription:"Choose a preset or create a custom surface, accent, and chat palette for the standalone UI.",mobileDescription:"Choose whether phones open the dashboard as a chat app first or in the full workspace layout.",fontsLabel:"Fonts",fontsDescription:"Standalone-only typography overrides for chat text, markdown code, and terminal output.",fontsSaved:"Standalone chat fonts saved for this self-hosted dashboard.",notificationsSection:"Notifications",notificationsDescription:"Browser prompts and local sound cues for agent activity.",soundEffectsLabel:"Sound Effects",soundEffectsDescription:"Play a sound when agent completes or needs approval",profileSection:"Profile",profileDescription:"How your name appears in local chat threads and dashboard views.",displayNameLabel:"Display Name",displayNameHint:"Your name shown in chat threads and on the team dashboard.",displayNamePlaceholder:"Anonymous"},onboarding:{title:"Welcome to ADHDev",selectedCount_one:"{{count}} provider selected",selectedCount_other:"{{count}} providers selected",skip:"Skip",installing:"Installing…",done:"Done",installCount:"Install {{count}}",intro:"Pick the providers you want to use. Defaults to the four officially supported CLI providers; you can install IDE, ACP, or extension providers from the tabs below or later from Burrow → Providers → Add provider.",loadingRegistry:"Loading registry…",loadError:"Failed to load registry: {{error}}",noProviders:"No providers in this category.",installed:"✓ installed",installFailed:"✗ {{error}}"},about:{title:"About",subtitle:"Self-hosted ADHDev overview, built-in surfaces, and what changes in Cloud",selfHostedEdition:"Self-hosted edition",headline:"Keep the same dashboard experience, with the runtime fully on-device.",description:"Standalone keeps the browser, daemon, screenshots, and control path on your own machine. It is the same core product shape as cloud, just without the remote networking and team layers.",docs:"Docs ↗",github:"GitHub ↗",tryCloud:"Try Cloud ↗",includedSection:"Included in standalone",includedDescription:"The local-first feature set available without the cloud control plane.",inventorySection:"Built-in inventory",inventoryDescription:"Bundled editors and agent surfaces exposed in the standalone dashboard. These lists describe inventory, not verified support.",cloudExtrasSection:"Cloud-only extras",cloudExtrasDescription:"Capabilities that need the hosted control plane or team infrastructure.",comparisonSection:"Self-hosted vs Cloud",comparisonDescription:"The product split at a glance.",featureHeader:"Feature",selfhostHeader:"Selfhost",cloudHeader:"Cloud",cloudOptional:"Cloud is optional, not required",cloudOptionalDescription:"You can stay fully local in standalone, and move to cloud later without changing how you use the dashboard.",compareCloud:"Compare Cloud ↗",discord:"Discord ↗"},fonts:{fontOverridesNotice:"Standalone-only font overrides. These do not affect the cloud dashboard. Chat bubbles, markdown prose, code blocks, tool rows, and terminal output all use the preferences below.",chat:"Chat text",chatDescription:"Assistant/user prose, markdown text, thought cards, and system notes.",code:"Code blocks",codeDescription:"Markdown code fences, inline code, and preformatted command output.",terminal:"Terminal",terminalDescription:"Terminal transcript cards and tool/command rows in chat mode.",livePreview:"Live preview",resolvedStack:"Resolved stack:",defaults:"Defaults:",saveFontSettings:"Save font settings",revertToSaved:"Revert to saved",resetToDefaults:"Reset to defaults",saving:"Saving…"}},Yx={panel:{selectNode:"Select a node to view details.",submoduleBadge:"Submodule",dirtyBadge:"Dirty",outOfSyncBadge:"Out of sync",conflictBadge:"Conflict",orphanBadge:"Orphan",fieldWorkspace:"Workspace",fieldBranch:"Branch",fieldUpstream:"Upstream",fieldUpstreamState:"Upstream state",fieldHead:"HEAD",fieldSubmodulePath:"Submodule path",fieldSubmoduleCommit:"Submodule commit",fieldParentNode:"Parent node",fieldAhead:"Ahead",fieldBehind:"Behind",fieldDirtyFiles:"Dirty files",fieldActiveSessions:"Active sessions",fieldProviders:"Providers",fieldConnection:"Connection",fieldLinkNote:"Link note",fieldError:"Error",orphanReasons:"Orphan reasons",attachedChats:"Attached chats",providerUnknown:"provider unknown",statusAwaiting:"awaiting approval",statusGenerating:"generating",statusIdle:"idle",statusCoordinator:"coordinator",statusWorker:"worker",runtimeAgeNotReported:"runtime age not reported",upstreamVerified:"verified",upstreamUnverifiedFetch:"unverified (fetch failed)",upstreamUnverified:"unverified",upstreamUnavailable:"unavailable",needsFollowUp:"needs follow-up",refined:"refined"},obs:{tabOverview:"Overview",tabStatus:"Status",tabGraph:"Graph",convergenceMergedToMain:"Merged to main",convergenceNeedsMerge:"Needs merge",convergenceBlockedReview:"Blocked — needs review",convergenceCleanup:"Ready to clean up",convergenceNotMergeable:"Not mergeable",followUpLabel:"Follow-up — {{status}}",selectedNode:"Selected node",selectedEdge:"Selected edge",activeSessions:"Active Sessions",ledger:"Ledger (mesh-wide)",queueTasks:"Queue tasks",keyWarning:"Key warning",healResult:"Heal result",healPreview:"Heal preview",noResultCode:"No result code returned.",health:"Health",legend:"Legend",checking:"Checking",heal:"Heal",loadingGraph:"Loading graph…",bootstrapBanner:"Awaiting live data — showing setup inventory until peer mesh_status probes succeed.",emptyGraph:"No live mesh graph is available for this coordinator yet.",fieldMachine:"Machine",fieldLocality:"Locality",fieldWorkspace:"Workspace",fieldHead:"HEAD",fieldDirtyAheadBehind:"Dirty/ahead/behind",fieldSessions:"Sessions",fieldUpstream:"Upstream",fieldSource:"Source",fieldTransport:"Transport",fieldMachineId:"Machine id",fieldDaemonId:"Daemon id",fieldFrom:"From",fieldTo:"To",fieldLabel:"Label",fieldCompleted:"Completed",fieldFailed:"Failed",fieldLaunched:"Launched",fieldRecentFailures:"Recent failures",meshConnecting:"mesh connecting...",connecting:"connecting...",providerUnknown:"provider unknown"}},Jx={login:{eyebrow:"Inicio de sesión en la nube",title:"Inicia sesión en ADHDev",subtitle:"Conecta tus máquinas, recibe notificaciones de aprobación y finalización, y mantén tus agentes de programación en marcha cuando estés lejos de tu escritorio.",continueWith:"Continuar con {{provider}}",connecting:"Conectando...",devDivider:"dev",devLogin:"Inicio de sesión dev (test_jwt_token)",providerNote:"GitHub y Google se usan solo para autenticación.",errorUnverifiedEmail:"Este proveedor de inicio de sesión no devolvió un correo verificado, por lo que no pudimos iniciar tu sesión de forma segura.",termsPrefix:"Al continuar, aceptas nuestros ",termsLink:"Términos de servicio",termsAnd:" y la ",privacyLink:"Política de privacidad",termsSuffix:"."},account:{title:"Cuenta",subtitle:"Perfil, plan y actividad",tabAccount:"Cuenta",tabBilling:"Facturación",tabActivity:"Actividad",profile:"Perfil",noName:"Sin nombre",displayName:"Nombre para mostrar",displayNameDesc:"Tu nombre mostrado en el panel y los espacios de equipo.",nicknamePlaceholder:"Apodo",save:"Guardar",saving:"...",cancel:"Cancelar",saved:"Guardado",edit:"Editar",failedToSave:"Error al guardar",userId:"ID de usuario",loadingProfile:"Cargando perfil...",planLimits:"Límites del plan",limitMachines:"Máquinas",limitP2P:"Conexiones P2P",limitWebhooks:"Webhooks",limitTurnRelay:"Relé TURN",enabled:"Activado",disabled:"Desactivado",frozen:"Congelado",session:"Sesión",logout:"Cerrar sesión",logoutConfirm:"¿Seguro que quieres cerrar sesión?",logoutDesc:"Cierra la sesión de tu cuenta de ADHDev en este dispositivo.",dangerZone:"Zona de peligro",dangerZoneDesc:"Elimina permanentemente tu cuenta y todos los datos asociados. Esta acción no se puede deshacer.",deleteAccount:"Eliminar cuenta",deleteWillRemove:"Esto eliminará permanentemente:",deleteItemProfile:"Tu perfil y credenciales de inicio de sesión",deleteItemKeys:"Todas las claves API y tokens de conexión",deleteItemWebhooks:"Webhooks e historial de entregas",deleteItemPush:"Suscripciones de notificaciones push",deleteItemSessions:"Sesiones compartidas y registros de auditoría",deleteTypeConfirm:"Escribe {{keyword}} para confirmar:",deleting:"Eliminando...",permanentlyDelete:"Eliminar permanentemente",failedToDeleteAccount:"Error al eliminar la cuenta",registeredMachines:"Máquinas registradas",machinesSummary:"{{count}} registradas · {{online}} en línea",machinesLimit:"(límite: {{limit}})",loadingMachines:"Cargando máquinas...",noMachinesRegistered:"No hay máquinas registradas",runSetupPrefix:"Ejecuta ",runSetupMiddle:" y luego inicia ",runSetupSuffix:" en una máquina para registrarla aquí.",removeMachineConfirm:"¿Quitar esta máquina? Deberá ejecutar `adhdev setup` de nuevo para reconectarse.",failedToDeleteMachine:"Error al eliminar la máquina",failedToUpdate:"Error al actualizar",rename:"Renombrar",online:"En línea",connecting:"Conectando",lastSeen:"Última conexión {{time}}",removeMachine:"Quitar máquina",never:"Nunca",justNow:"Justo ahora",minutesAgo:"hace {{minutes}} min",hoursAgo:"hace {{hours}} h",daysAgo:"hace {{days}} d"},billing:{title:"Billing",subtitle:"Manage your subscription and plan",currentPlan:"Plan actual:",statusTrial:"Prueba",statusActive:"Activo",statusPastDue:"Vencido",statusCanceled:"Cancelado",nextBilling:"Próximo cobro: {{date}}",trialEnds:"La prueba termina: {{date}}",accessUntil:"Acceso hasta: {{date}}",updatePayment:"Actualiza tu método de pago",managePayment:"Gestionar pagos y facturas",couldNotOpenPortal:"No se pudo abrir el portal de facturación",statMachines:"Máquinas",statTeam:"Equipo",statTurnPerDay:"min TURN/día",monthly:"Mensual",yearly:"Anual",savePercent:"Ahorra 17%",paddleLoading:"Paddle se está cargando, inténtalo de nuevo.",cancelConfirm:"¿Seguro que quieres cancelar tu suscripción? Conservarás el acceso hasta el final de tu período de facturación.",teamSeats:"Asientos del equipo",seatsUsed:"{{used}} / {{total}} asientos usados",pricePerMonth:"${{price}}/mes",cannotReduceSeats:"No se puede reducir por debajo de {{count}} asientos (en uso). Quita miembros primero.",removeSeat:"− Quitar asiento",addSeat:"+ Añadir asiento",cancelSubscription:"Cancelar suscripción",cancelRetainAccess:"Conservarás el acceso a las funciones de {{plan}} hasta el final de tu período de facturación actual.",cancelTeamDowngrade:" Todos los miembros del equipo pasarán a sus planes personales."},about:{title:"About",subtitle:"Cloud overview, supported surfaces, and plan-level capabilities",cloudEdition:"Cloud edition",heroTitle:"Control your local CLI agents from anywhere — web or mobile.",heroDesc:"ADHDev Cloud surfaces the agents running on your machines in your browser: send prompts, approve actions, orchestrate work across machines, and get notified on your phone — code flows P2P directly to your daemon, never through the server.",openDashboard:"Open Dashboard",viewMachines:"View Machines",docs:"Docs ↗",whyTitle:"Why ADHDev Cloud",whyDesc:"Core capabilities available when your machines are connected through the cloud control plane.",howTitle:"How it works",howDesc:"The cloud onboarding path from install to remote control.",repoMeshTitle:"Repo Mesh",repoMeshDesc:"Orchestrate agents across machines — cloud only.",meshCard1Title:"One coordinator, many agents",meshCard1Desc:"Enqueue tasks against a mission and let idle nodes claim work from a local-first, pull-based queue. Fan out across machines and providers — Claude Code on one, Codex on another — then converge the results from a single coordinator session.",meshCard2Title:"Same repo, many machines at once",meshCard2Desc:"Each node is a checkout or an isolated git worktree, so parallel agents never collide. The refinery converges every branch — validate, merge, push, clean up — with safe submodule handling. Runs over a direct daemon-to-daemon P2P channel; the server only signals and authorizes same-account peers.",worksWith:"Works with",worksWithDesc:"Supported CLI agents, IDEs, and AI extensions.",groupCli:"CLI Agents",groupIdes:"IDEs",groupExtensions:"AI Agents",pricingTitle:"Pricing",pricingDesc:"Current cloud plans and machine capacity by tier.",planPopular:"Popular",planPerMonth:"/mo",readyTitle:"Ready to connect a machine",readyDesc:"Jump into your dashboard, inspect your connected machines, or continue in the docs if you are still setting up.",dashboard:"Dashboard",machines:"Machines",discord:"Discord ↗",github:"GitHub ↗",features:{webControlTitle:"Web control of local CLI agents",webControlDesc:"Drive any local CLI agent — Claude Code, Codex, Gemini — from your browser: send prompts, approve actions, and steer sessions without touching the terminal.",chatRelayTitle:"Agent chat relay",chatRelayDesc:"Read and respond to agent conversations from anywhere, including mobile surfaces.",liveViewTitle:"Live session view",liveViewDesc:"Watch agent activity in real time; for IDE sessions, view and control the screen over P2P without switching windows.",mobileTitle:"Mobile-ready",mobileDesc:"Receive approvals and check progress while away from your development machine.",secureTitle:"Secure by default",secureDesc:"Chat, commands, and screenshots flow directly between your browser and your daemon over WebRTC — the cloud handles auth and signaling metadata only. Your code never routes through the server."},steps:{step1Title:"One-line Install",step1Desc:"Run a single command on any machine you want to drive. It installs the ADHDev daemon plus the adhdev CLI.",step2Title:"Sign In",step2Desc:"Sign in with GitHub or Google and the daemon pairs itself to your account — no token to copy.",step3Title:"Drive Your Agents from Anywhere",step3Desc:"The machine appears in your dashboard instantly. Launch and control Claude Code, Codex, Gemini, and other CLI agents from the web — IDE sessions too."},plans:{freeName:"Free",proName:"Pro",ultraName:"Ultra",freePer:"/mo",proPer:"/mo",ultraPer:"/mo",freeFeature1:"1 machine",freeFeature2:"Real-time chat relay",freeFeature3:"Web control for your local agents",freeFeature4:"Community support",proFeature1:"2 machines",proFeature2:"Unlimited AI agents",proFeature3:"P2P remote view",proFeature4:"7-day free trial",ultraFeature1:"5 machines — flat, not per-seat",ultraFeature2:"Everything in Pro",ultraFeature3:"Higher concurrency & usage limits",ultraFeature4:"Unlimited daily screenshot minutes"}},layout:{navDashboard:"Dashboard",navBurrows:"Burrows",navNotifications:"Notifications",navMesh:"Mesh",navMarketplace:"Marketplace",navTeam:"Team",navApi:"API",navWebhooks:"Webhooks",navAccount:"Account",navSettings:"Settings",navDocs:"Docs",navAbout:"About",adminSection:"Admin",adminOverview:"Overview",adminUsers:"Users",adminAuditLogs:"Audit Logs",adminSystem:"System",adminEntry:"Admin",footerPlanTitle:"Current plan: {{plan}} — manage or upgrade",expandSidebar:"Expand sidebar",collapseSidebar:"Collapse sidebar",collapse:"Collapse",logoutConfirm:"Are you sure you want to logout?",logout:"Logout",machineLimitBanner:"You've reached your Free plan limit of {{count}} machine{{plural}}. Upgrade to add more.",upgradeArrow:"Upgrade →"},settings:{title:"Settings",subtitle:"Appearance & preferences",quickLinksTitle:"Quick links",quickLinksDesc:"Open the pages that are easiest to need from mobile inbox.",linkNotificationsTitle:"Notifications",linkNotificationsSubtitle:"Push, browser alerts, and delivery settings",linkAccountTitle:"Account",linkAccountSubtitle:"Profile, billing, sessions, and delete account",linkAboutTitle:"About",linkAboutSubtitle:"Cloud overview, supported surfaces, and plans",linkDocsTitle:"Docs",linkDocsSubtitle:"Open product docs in a new tab",appearanceTitle:"Appearance"},planCard:{unlimited:"Unlimited",machineSingular:"{{count}} machine",machinePlural:"{{count}} machines",sharedSessionSingular:"{{count}} shared session",sharedSessionPlural:"{{count}} shared sessions",teamMemberSingular:"{{count}} team member",teamMemberPlural:"{{count}} team members",turnPerDay:"{{count}} TURN min/day",recommended:"Recommended",currentPlan:"Current Plan",contactUs:"Contact Us",freeForever:"Free Forever",startTrial:"Start 7-day free trial",upgradeTo:"Upgrade to {{name}}",noChargeCancel:"No charge for 7 days. Cancel anytime.",periodSeatMo:"seat/mo",periodMo:"mo",yearlyNote:"${{yearly}}/year — Save ${{saved}}",pricingCustom:"Custom"},activity:{filterPlaceholder:"Filtrar por acción, recurso u origen...",refresh:"Actualizar",loading:"Cargando...",noLogs:"Sin registros",noMatchingLogs:"No se encontraron registros coincidentes.",logsWillAppear:"Las acciones aparecerán aquí a medida que sucedan.",colAction:"Acción",colResource:"Recurso",colSource:"Origen",colTime:"Hora",logCount:"{{count}} registros",logCountFiltered:" (filtrado de {{total}})"},webhooks:{title:"Webhooks",subtitle:"Notificaciones de eventos en tiempo real",addWebhook:"+ Añadir webhook",eventDaemonConnect:"Daemon conectado",eventDaemonDisconnect:"Daemon desconectado",eventAgentStatus:"Cambio de estado del agente",eventApprovalRequired:"Aprobación requerida",failed:"Error",deleteConfirm:"¿Eliminar este webhook?",testFailed:"Error en la prueba",secretTitle:"Secreto del webhook",secretShownOncePrefix:"Se muestra ",secretShownOnce:"solo una vez",secretShownOnceSuffix:". Úsalo para verificar ",copy:"Copiar",done:"Listo",newWebhook:"Nuevo webhook",labelUrl:"URL",urlPlaceholder:"https://tu-servicio.com/webhook",labelEvents:"Eventos",allEvents:"Todos los eventos (*)",creating:"Creando...",create:"Crear",cancel:"Cancelar",loading:"Cargando...",noWebhooks:"Sin webhooks",noWebhooksDesc:"Recibe notificaciones en tiempo real sobre eventos.",setupFirst:"Configurar el primer webhook",off:"OFF",autoDisabled:"Autodesactivado",autoDisabledTitle:"Autodesactivado tras 10 fallos consecutivos",failuresWarning:"⚠ {{count}} fallos",failuresTitle:"{{count}} fallos consecutivos — se autodesactivará a los 10",all:"TODOS",history:"Historial",test:"Probar",delete:"Eliminar",deleting:"...",recentDeliveries:"Entregas recientes",refresh:"Actualizar",noDeliveries:"Aún no hay entregas. Usa 🧪 para enviar una prueba.",request:"SOLICITUD",response:"RESPUESTA",securityTitle:"Seguridad",securityVerifyPrefix:"Verifica ",securityVerifySuffix:" con tu secreto",securityHttps:"Usa solo endpoints HTTPS",securityAsync:"Devuelve 2xx de inmediato, procesa de forma asíncrona",securityAutoDisable:"Autodesactivado tras 10 fallos consecutivos"},apiKeys:{title:"Claves API",keyCount:"{{count}} claves",playground:"Área de pruebas",create:"+ Crear",scopeDaemonRead:"Lectura de daemon",scopeDaemonReadDesc:"Listar daemons y estado",scopeDaemonControl:"Control de daemon",scopeDaemonControlDesc:"Comandos, iniciar/detener, desconectar",scopeAgentRead:"Lectura de agente",scopeAgentReadDesc:"Estado e historial de chat",scopeAgentControl:"Control de agente",scopeAgentControlDesc:"Enviar, aprobar/rechazar",scopeTerminal:"Terminal",scopeTerminalDesc:"Ejecutar comandos",scopeWebhooks:"Webhooks",scopeWebhooksDesc:"Gestionar hooks y entregas",frozen:"Congelado",revokeConfirm:"¿Revocar esta clave API? Esto no se puede deshacer.",failedToLoad:"Error al cargar",failed:"Error",upgradePlan:"Mejora tu plan →",keyCreated:"¡Clave creada!",copyNow:"Copia ahora — se muestra solo una vez.",copied:"Copiado",copy:"Copiar",testKey:"Probar",dismiss:"Descartar",playgroundTitle:"Área de pruebas API",enterKeyToTest:"Introduce una clave API para probar.",open:"Abrir",createKeyTitle:"Crear clave API",labelName:"Nombre",namePlaceholder:"p. ej. Production Bot",permissions:"Permisos ({{count}})",createBtn:"Crear",cancel:"Cancelar",loading:"Cargando...",noKeys:"Sin claves API",noKeysDesc:"Crea una clave para integrarla con servicios externos.",createFirstKey:"Crear la primera clave",usedDate:"Usada {{date}}",neverUsed:"Nunca usada",revoke:"Revocar",usageLabel:"Uso:",apiReference:"Referencia API →"},auditLogs:{title:"Registros de auditoría",subtitle:"Eventos de seguridad e historial de API",refresh:"Actualizar",filterPlaceholder:"Filtrar por acción, recurso u origen...",loading:"Cargando...",noLogs:"Sin registros",noMatchingLogs:"No se encontraron registros coincidentes.",logsWillAppear:"Las acciones aparecerán aquí a medida que sucedan.",colAction:"Acción",colResource:"Recurso",colSource:"Origen",colTime:"Hora",logCount:"{{count}} registros",logCountFiltered:" (filtrado de {{total}})"},inviteModal:{title:"Invite Team Member",subtitle:"Send an invite link via email",manageSeats:"→ Manage seats in Billing",emailLabel:"Email Address",emailPlaceholder:"colleague@company.com",roleLabel:"Role",roleViewer:"Viewer",roleMember:"Member",roleAdmin:"Admin",roleViewerDesc:"Can view dashboards and chat history",roleMemberDesc:"Can control agents and send commands",roleAdminDesc:"Can manage members and settings",cancel:"Cancel",sending:"Sending...",sendInvite:"Send Invite",inviteSent:"Invite sent!",shareWith:"Share this link with",copied:"Copied!",copy:"Copy",done:"Done"},shareModal:{title:"Share Session",chatLabel:"Chat",chatDesc:"AI conversation only",remoteLabel:"Remote",remoteDesc:"Screenshot + desktop",permissionLabel:"Permission Level",authRequired:"Account required",expiresAfter:"Expires After",maxViewers:"Max Viewers",hide:"Hide",activeShares:"Active Shares",creating:"Creating...",createChatLink:"Create Chat Link",createRemoteLink:"Create Remote Link",expires:"expires",revoke:"Revoke",shareLinkCreated:"Share link created!",viewerMustLogin:"Viewer must be logged in to use this link",copy:"Copy",copied:"Copied!",expiresAt:"Expires:",done:"Done",failedToCreate:"Failed to create share link",expiry1h:"1 hour",expiry6h:"6 hours",expiry24h:"24 hours",expiry7d:"7 days",chatView:{label:"View Only",desc:"Read AI conversation in real-time"},chatControl:{label:"Control",desc:"Read + send messages + approve/reject actions"},remoteView:{label:"View Only",desc:"Watch screenshots + chat in real-time"},remoteControl:{label:"Control",desc:"Screenshots + send messages + approve/reject"},remoteFull:{label:"Full Access",desc:"Full remote control including desktop input"}},onboarding:{title:"Connect your first machine",subtitle:"Install ADHDev on a machine and sign in — it pairs itself and shows up here. Then drive every agent on it from this dashboard.",platformMac:"🍎🐧 macOS / Linux",platformWindows:"🪟 Windows",copyTitle:"Click to copy",copiedLabel:"✓ Copied",copyLabel:"📋 Copy",listeningLabel:"Listening for your daemon — keep this page open, it will appear automatically.",connectingLabel:"Connecting to ADHDev…",step1Title:"Install the daemon",step1Desc:"Run the command above on any machine you want to drive. It installs the daemon plus the adhdev CLI.",step2Title:"Sign in — the machine pairs itself",step2Desc:"The daemon links to this account automatically. No token to copy; it appears here the moment it connects.",step3Title:"Launch your first session",step3Desc:"Once a machine is online, start Claude Code, Codex, Cursor, and other agents straight from the dashboard.",readDocs:"📚 Read the documentation →"},legal:{navHome:"Home",navDashboard:"Dashboard",footerHome:"Home",footerTerms:"Terms",footerPrivacy:"Privacy",footerRefund:"Refund Policy",footerCopyright:"© 2026 RacoLab. All rights reserved."},authCallback:{authFailed:"Authentication Failed",backToLogin:"Back to Login",completing:"Completing authentication...",noTokenError:"No access token received"},cliAuth:{title:"ADHDev CLI Authentication",verifying:"Verifying...",authorizeAs:"Authorize CLI as {{name}}?",noCodeError:"No authentication code provided.",approve:"✓ Approve",signInFirst:"Please sign in first to authorize the CLI.",signIn:"Sign In →",failed:"Failed",successMessage:"CLI authentication complete!",returnToTerminal:"You can return to the terminal."},privacy:{title:"Privacy Policy",lastUpdated:"Last updated: March 23, 2026",intro:'This Privacy Policy describes how RacoLab ("we", "us", "our") collects, uses, and protects your information when you use the ADHDev service ("Service") at',s1Title:"1. Information We Collect",s1h1:"1.1 Account Information",s1p1:"When you create an account, we collect information provided by your authentication provider (GitHub or Google), including your name, email address, and profile picture.",s1h2:"1.2 IDE & Agent Data",s1p2:"When you connect your development environment to the Service, the local daemon may transmit:",s1l1:'IDE type and version (e.g., "Cursor 0.49.1")',s1l2:"Active AI agent information (name, status, current model)",s1l3:"Chat messages between you and AI agents",s1l4:"IDE screenshots (transmitted via P2P, not stored on our servers)",s1l5:"Workspace paths and open file names",s1l6:"Machine information (hostname, OS, memory usage)",s1h3:"1.3 Usage Data",s1p3:"We automatically collect usage information including API calls, feature usage patterns, and connection logs for service improvement and debugging purposes.",s1h4:"1.4 Payment Information",s1p4:"Payment processing is handled entirely by our Merchant of Record, Paddle (Paddle.com Market Limited). We do not directly collect or store credit card numbers, bank account details, or other financial information. Please refer to",s1p4PaddleLink:"Paddle's Privacy Policy",s1p4Suffix:"for their data handling practices.",s2Title:"2. How We Use Your Information",s2p1:"We use collected information to:",s2l1:"Provide and maintain the Service",s2l2:"Authenticate your identity and manage your account",s2l3:"Route commands and data between your dashboard and connected machines",s2l4:"Send notifications (browser and push) about agent status changes",s2l5:"Process billing and subscription management (via Paddle)",s2l6:"Detect and prevent abuse or unauthorized access",s2l7:"Improve the Service and develop new features",s2l8:"Respond to support requests",s3Title:"3. Data Storage & Security",s3h1:"3.1 Infrastructure",s3p1:"Our Service runs on Cloudflare's global network using Cloudflare Workers, Durable Objects, and D1 Database. Data is stored in Cloudflare's infrastructure and is subject to",s3p1CloudflareLink:"Cloudflare's Privacy Policy",s3h2:"3.2 P2P Data",s3p2:"IDE screenshots and real-time terminal data are transmitted directly between your browser and your machine via WebRTC peer-to-peer connections. This data does not pass through or get stored on our servers.",s3h3:"3.3 Security Measures",s3p3:"We implement the following security measures:",s3l1:"JWT-based authentication with short-lived access tokens and refresh token rotation",s3l2:"Encrypted WebSocket connections (WSS/TLS)",s3l3:"Per-connection tokens for daemon authentication",s3l4:"Rate limiting on all API endpoints",s3l5:"Audit logging for security-sensitive operations",s4Title:"4. Data Sharing",s4p1:"We do not sell your personal data to third parties. We may share data with:",s4l1:"Payment processing as Merchant of Record",s4l2:"Infrastructure provider (hosting, CDN, database)",s4l3Label:"Authentication providers",s4l3:"GitHub/Google for OAuth login",s4p2:"We may disclose data if required by law, legal process, or to protect our rights and the safety of our users.",s5Title:"5. Data Retention",s5p1:"We retain your account data for the duration of your active account. Chat messages and agent activity data are retained for up to 90 days for service functionality.",s5p2:"Upon account deletion, we will remove your personal data within 30 days. Some anonymized usage data may be retained for analytical purposes.",s6Title:"6. Your Rights",s6p1:"You have the right to:",s6l1Label:"Access",s6l1:"Request a copy of your personal data",s6l2Label:"Correction",s6l2:"Update or correct your personal information",s6l3Label:"Deletion",s6l3:"Request deletion of your account and associated data",s6l4Label:"Export",s6l4:"Download your data in a portable format",s6l5Label:"Object",s6l5:"Object to certain data processing activities",s6p2:"To exercise these rights, contact us at",s7Title:"7. Cookies",s7p1:"We use essential cookies only for authentication (session tokens) and user preferences (theme, notification settings). We do not use advertising or tracking cookies.",s8Title:"8. Children's Privacy",s8p1:"The Service is not intended for users under the age of 16. We do not knowingly collect personal information from children under 16.",s9Title:"9. International Data Transfers",s9p1:"Your data may be processed in various locations through Cloudflare's global network. By using the Service, you consent to the transfer and processing of your data in these locations.",s10Title:"10. Changes to This Policy",s10p1:"We may update this Privacy Policy from time to time. We will notify you of any material changes by email or through the Service. Your continued use after changes constitutes acceptance of the updated policy.",s11Title:"11. Contact",s11p1:"For questions about this Privacy Policy or data practices:",s11l1Prefix:"Email:",s11l2Prefix:"Website:"},terms:{title:"Terms of Service",lastUpdated:"Last updated: April 11, 2026",intro:'Welcome to ADHDev ("Service"), operated by RacoLab ("we", "us", "our"). By accessing or using our Service at',introSuffix:'you agree to be bound by these Terms of Service ("Terms"). If you do not agree, do not use the Service.',s1Title:"1. Service Description",s1p1:"ADHDev is a cloud developer tool that provides remote monitoring and control of AI coding agents (such as Cursor, VS Code, Antigravity, Claude Code, and others) through web and mobile dashboard surfaces. The Service includes a local daemon, remote dashboards, REST API access, and browser and push notifications.",s2Title:"2. Account Registration",s2p1:"You must create an account to use the Service. You are responsible for maintaining the confidentiality of your account credentials. You agree to provide accurate and complete information during registration and to keep your account information up to date.",s2p2:"You must be at least 16 years old to use the Service. By creating an account, you represent that you meet this age requirement.",s3Title:"3. Subscription Plans & Billing",s3p1:"The Service offers the following plans:",s3l1:"Limited features, 1 connected machine",s3l2:"2 connected machines, unlimited agents, P2P remote view, 7-day free trial",s3l3:"5 connected machines, everything in Pro plus higher concurrency and usage limits (flat price, not per-seat)",s3p2:"Paid subscriptions are billed in advance on a monthly or yearly basis. All payments are processed by our payment partner, Paddle (Paddle.com Market Limited), who acts as the Merchant of Record for all transactions.",s4Title:"4. Refund Policy",s4p1:"We offer a 14-day money-back guarantee for all paid plans. If you are not satisfied with the Service, you may request a full refund within 14 days of your initial purchase by contacting us at",s4p2:"Refunds for renewals are handled on a case-by-case basis. Paddle's refund policies also apply as they are the Merchant of Record.",s5Title:"5. Acceptable Use",s5p1:"You agree not to:",s5l1:"Use the Service for any unlawful purpose or in violation of any applicable laws",s5l2:"Attempt to gain unauthorized access to other users' accounts or data",s5l3:"Reverse-engineer, decompile, or attempt to extract the source code of the Service's server components",s5l4:"Use the Service to transmit malware, spam, or other harmful content",s5l5:"Resell or redistribute the Service without our written consent",s5l6:"Interfere with or disrupt the integrity or performance of the Service",s6Title:"6. Intellectual Property",s6p1:"The Service, including its original content, features, and functionality, is owned by RacoLab and is protected by applicable intellectual property laws. The local daemon component is available under an open-source license as specified in the project repository.",s6p2:"You retain ownership of all data and content you transmit through the Service.",s7Title:"7. Data & Privacy",s7p1:"Your use of the Service is also governed by our",s7PrivacyLink:"Privacy Policy",s7p1Suffix:"The Service processes IDE interactions, chat messages, and screenshots for the purpose of remote monitoring and control. We do not sell your data to third parties.",s8Title:"8. Service Availability",s8p1:"We strive to maintain high availability but do not guarantee uninterrupted access. The Service may be temporarily unavailable due to maintenance, updates, or circumstances beyond our control. We are not liable for any losses resulting from service interruptions.",s9Title:"9. Limitation of Liability",s9p1:"TO THE MAXIMUM EXTENT PERMITTED BY LAW, RacoLab SHALL NOT BE LIABLE FOR ANY INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES, OR ANY LOSS OF PROFITS OR REVENUES, WHETHER INCURRED DIRECTLY OR INDIRECTLY, ARISING OUT OF YOUR USE OF THE SERVICE.",s9p2:"Our total liability for any claim arising from the Service shall not exceed the amount you paid us in the 12 months preceding the claim.",s10Title:"10. Termination",s10p1:"We may suspend or terminate your access to the Service at any time for violations of these Terms or for any other reason at our sole discretion. You may cancel your account at any time through the Settings page. Upon cancellation, your data will be deleted within 30 days.",s11Title:"11. Changes to Terms",s11p1:"We reserve the right to modify these Terms at any time. We will notify you of material changes via email or through the Service. Your continued use after changes constitutes acceptance of the modified Terms.",s12Title:"12. Governing Law",s12p1:"These Terms shall be governed by and construed in accordance with the laws of the Republic of Korea, without regard to conflict of law provisions.",s13Title:"13. Contact",s13p1:"If you have any questions about these Terms, please contact us:",s13l1Prefix:"Email:",s13l2Prefix:"Website:"},refund:{title:"Refund Policy",lastUpdated:"Last updated: March 24, 2026",intro:"ADHDev is operated by RacoLab. All payments are processed by our Merchant of Record,",introSuffix:"who manages billing, invoicing, and refunds on our behalf.",s1Title:"1. 14-Day Money-Back Guarantee",s1p1:"We offer a 14-day money-back guarantee on all paid plans (Pro). If you are not satisfied with the Service for any reason, you may request a full refund within 14 days of your initial subscription purchase.",s1p2:"To request a refund, contact us at",s1p2Suffix:"with your account email and order details. We will process your request within 3 business days.",s2Title:"2. Renewal Refunds",s2p1:"Refunds for subscription renewals (monthly or yearly) are handled on a case-by-case basis. If you were charged for a renewal you did not intend, please contact us within 7 days of the charge at",s3Title:"3. Non-Refundable Cases",s3p1:"Refunds will not be issued for:",s3l1:"Requests made after the 14-day guarantee period for initial purchases",s3l2Prefix:"Accounts suspended or terminated due to violations of our",s3l2Link:"Terms of Service",s3l3:"Partial months of service already used beyond the refund window",s4Title:"4. How Refunds Are Processed",s4p1:"Approved refunds are processed through Paddle and returned to the original payment method. Depending on your bank or card issuer, refunds may take 5–10 business days to appear. Paddle's own",s4p1RefundLink:"refund terms",s4p1Suffix:"also apply.",s5Title:"5. Cancellation",s5p1Prefix:"You may cancel your subscription at any time from the",s5p1BillingLink:"Billing",s5p1Suffix:"page in your dashboard. Cancellation stops future charges. You retain access to your plan's features until the end of the current billing period. Cancellation alone does not trigger a refund.",s6Title:"6. Contact",s6p1:"For refund requests or billing questions:",s6l1Prefix:"Email:",s6l2Prefix:"Website:"},teamWorkspace:{title:"Team",subtitle:"Seat-based team management — $15/seat/mo, centralized billing",planRequired:"Team Plan Required",planDesc:`Team Workspaces are available on the Team plan ($15/seat/mo).
36
+ Manage seats, invite team members, and centrally manage billing for your organization.`,upgradeBtn:"Upgrade to Team →",seatsTitle:"Team Seats",seatsUsedOf:"{{used}} / {{total}} seats used",seatsAvailable:"{{count}} available",seatsFullMsg:"All seats are in use. Add more seats in",seatsBillingLink:"Billing",seatsBillingLinkSuffix:"to invite more members.",newWorkspace:"New Workspace",workspaceNamePlaceholder:"Workspace name...",createBtn:"Create",cancelBtn:"Cancel",noWorkspaceYet:"No team workspace yet",noWorkspaceDesc:"Create a workspace to start managing your team and sharing seats.",createWorkspace:"Create Workspace",membersTab:"Members ({{count}})",sessionsTab:"Sessions",settingsTab:"Settings",membersTitle:"Members ({{count}})",inviteBtn:"+ Invite",pendingInvites:"Pending Invites ({{count}})",pendingBadge:"Pending",removeBtn:"Remove",removeMemberConfirm:"Remove this member? They will lose their Team plan access.",removeSuccess:"Member removed",invitationSent:"Invitation sent!",joinedSuccess:"Successfully joined team workspace!",waitingApproval:"Waiting for {{name}} to approve your view request...",viewRequestSent:"View request sent to {{name}}. Waiting for approval...",viewDeclined:"{{name}} declined the view request",sessionRestricted:"Session viewing is restricted by organization policy (admin_only)",sessionTitle:"Team Sessions",noMembersOnline:"No team members online",selfBadge:"You",machineNoSessions:"Machine online, no active sessions",offline:"Offline",statusGenerating:"Generating...",statusApprovalNeeded:"Approval needed",statusStarting:"Starting...",statusStopped:"Stopped",statusError:"Error",statusDisconnected:"Disconnected",statusHidden:"Hidden",statusUnmonitored:"Unmonitored",statusIdle:"Idle",viewBtn:"View →",requestBtn:"Request →",policyOpen:"Open",policyRequest:"Request",policyAdminOnly:"Admin Only",settingsTitle:"Workspace Settings",sessionVisibilityTitle:"Session Visibility",sessionVisibilityDesc:"Control who can view team members' AI agent sessions",visibilityOpen:"Open",visibilityOpenDesc:"All members can view any session freely",visibilityRequest:"Request-based",visibilityRequestDesc:"Members must request access. Admins can always view.",visibilityAdminOnly:"Admin Only",visibilityAdminOnlyDesc:"Only administrators and the owner can view sessions.",dangerZone:"Danger Zone",dangerZoneDesc:"Irreversible actions",deleteWorkspace:"Delete Workspace",deleteWorkspaceConfirm:"Delete this Team Workspace? All members will lose their Team plan benefits.",leaveWorkspace:"Leave Workspace",leaveWorkspaceConfirm:"Are you sure you want to leave this workspace? Your plan may be downgraded."},sessionShare:{loading:"Loading session...",sessionNotFound:"Session Not Found",noLongerAvailable:"This session is no longer available",homeBtn:"← ADHDev Home",sharedSession:"Shared Session",host:"Host",mode:"Mode",permission:"Permission",auth:"Auth",authRequired:"Account required",viewers:"Viewers",joinChat:"Join Chat",joinSession:"Join Session",expires:"Expires: {{date}}",chatLabel:"Chat",remoteLabel:"Remote",waitingMessages:"Waiting for messages...",connecting:"Connecting... ({{state}})",sendMessageAs:"Send message as {{name}}...",sendAs:"Send as {{name}}...",ownerChat:"{{name}}'s Chat",ownerSession:"{{name}}'s Session",agentName:"{{name}}'s Agent",fullControlBadge:"Full Control Active",failedToJoin:"Failed to join session",sessionRevoked:"Session has been revoked by the host",sessionExpired:"Session has expired",authRequired2:"Authentication required for control share"},apiPlayground:{title:"API Playground",history:"History ({{count}})",apiRelayWarning:"Daemon API relay is opt-in. REST command/chat proxy routes stay disabled unless that daemon explicitly enables them with `adhdev daemon:api enable`.",authBearer:"Authorization: Bearer {{key}}",copyAsCurl:"cURL",copied:"Copied",targetDaemon:"Target Daemon",quickActions:"Quick Actions",requestBody:"Request Body (JSON)",recentRequests:"Recent Requests",clearHistory:"Clear",noDaemonsWarning:"No daemons connected. Start a daemon first or replace {daemonId} manually.",send:"▶ Send",sending:"⏳",close:"Close"}},Qx={openMenu:"Open menu",closeMenu:"Close menu"},Xx={loadingOlderMessages:"Loading older messages...",waitingForMessages:"Waiting for messages...",agentGenerating:"Agent generating...",jumpToTop:"Jump to top",jumpToOldestMessages:"Jump to oldest messages",top:"↑ Top",latest:"↓ Latest",jumpToLatestMessages:"Jump to latest messages",jumpToBottom:"Jump to bottom",showEarlierMessages:"↑ Show {{count}} earlier messages...",showEarlierMessagesHidden:"↑ Show {{count}} earlier messages... ({{total}} hidden)",loadOlderMessages:"↑ Load older messages",loadErrorRetry:"↻ {{error}}"},Zx={zoomOut:"Zoom Out",zoomIn:"Zoom In",resetZoom:"Reset Zoom",toggleFullscreen:"Toggle Fullscreen"},ey={mouse:"Mouse",touch:"Touch",connected:"Connected",ws:"WS",direct:"Direct",relay:"Relay",turnBlocked:"TURN blocked",turnUsage:"TURN {{used}}/{{budget}}m",typeAndEnter:"Type & Enter...",settings:"SETTINGS",zoom:"ZOOM:",fill:"FILL",fit:"FIT",directP2PTitle:"Direct P2P connection",turnRelayTitle:"TURN relay in use",dailyTurnTitle:"Daily TURN relay usage"},ty={title:"Session info",loading:"Loading…",refresh:"Refresh",close:"Close",failedToLoad:"Failed to load session info",notCoordinatorSession:"This isn't a mesh coordinator session, so no coordinator-specific prompt was injected. The agent runs with whatever defaults its CLI ships with.",stampedToNode:"This session is stamped to a mesh node that the coordinator no longer reports.",sectionSession:"Session",sectionLaunch:"Launch",sectionMeshNode:"Mesh node",sectionMeshCoordinator:"Mesh coordinator",sectionRuntime:"Runtime",rowSessionId:"Session ID",rowProvider:"Provider",rowTransport:"Transport",rowWorkspace:"Workspace",rowSpawnedAt:"Spawned at",rowProviderSessionId:"Provider session ID",rowMachine:"Machine",rowConnection:"Connection",rowWorkspaceGit:"Workspace git",rowCommand:"Command",rowWorkingDirectory:"Working directory",rowArgs:"Args",rowExtraArgs:"Extra args",rowExtraEnv:"Extra env",rowNodeId:"Node ID",rowRepoRoot:"Repo root",rowDaemonId:"Daemon ID",rowRole:"Role",rowMachineStatus:"Machine status",rowHealth:"Health",rowWorktree:"Worktree",rowLaunchReady:"Launch ready",rowGit:"Git",rowProviders:"Providers",rowProviderPriority:"Provider priority",rowMeshId:"Mesh ID",rowCoordinatorCli:"Coordinator CLI",rowStartedAt:"Started at",rowPromptInjection:"Prompt injection",rowMcpConfig:"MCP config",rowRuntimeId:"Runtime ID",rowLifecycle:"Lifecycle",rowSurface:"Surface",rowRecoveryState:"Recovery state",rowRestoredFromStorage:"Restored from storage",rowAttachedClients:"Attached clients"},sy={status:{schedulingNotReported:"Scheduling runtime not reported by this daemon (older build). Update the coordinator daemon to surface distribution, parallel caps, and per-node load.",schedulingTitle:"Scheduling",distributionTitle:"Distribution only governs how untargeted work is spread across eligible nodes. Per-node load, priority, and provider caps are below.",protocolTitle:"Protocol & provider versions",nodesRuntime:"Nodes — runtime",noNodesReporting:"No nodes reporting runtime yet."},overview:{missionCard:"Missions",ledgerCard:"Ledger",queueCard:"Queue",nodesCard:"Nodes",sessionsCard:"Active sessions",refineCard:"Refine jobs",recentActivity:"Recent activity",recentTasks:"Recent tasks",showFewer:"Show fewer",showMore:"+{{count}} more",noActiveMissions:"No active missions. The coordinator creates a mission for multi-task work.",missionDataUnavailable:"Mission data unavailable from this daemon — update the daemon to see missions.",completedHistory:"Completed / abandoned history",noQueueActivity:"No queue activity.",noNodes:"No nodes in this mesh yet.",noActiveSessions:"No active sessions.",noRefineJobs:"No refine jobs.",closeDetail:"Close detail",loadingGoal:"Loading…",showFullGoal:"Show full goal",statCompleted:"Completed",statAssigned:"Assigned",statPending:"Pending",statFailed:"Failed",statBlocked:"Blocked",statCancelled:"Cancelled",statWallClock:"Wall clock",statTotalRuntime:"Total runtime",statRetries:"Retries",statDispatched:"Dispatched",statStalled:"Stalled",statSessions:"Sessions",statCheckpoints:"Checkpoints",statActive:"Active",recentFailures:"{{count}} recent failures",activeCount:"{{count}} active",failedCount:"{{count}} failed",detailKickerMission:"Mission",detailKickerLedger:"Ledger entry",detailKickerQueue:"Queue task",detailKickerSession:"Session",detailLabelMissionId:"Mission id",detailLabelCreated:"Created",detailLabelUpdated:"Updated",detailLabelLastActivity:"Last task activity",detailLabelIncompleteEvidence:"Incomplete evidence",incompleteTaskCount_one:"{{count}} task",incompleteTaskCount_other:"{{count}} tasks",detailLabelEntryId:"Entry id",detailLabelWhen:"When",detailLabelNode:"Node",detailLabelSession:"Session",detailLabelProvider:"Provider",detailLabelPayload:"Payload",detailLabelTaskId:"Task id",detailLabelAutoLaunch:"Auto launch",detailLabelCancelReason:"Cancel reason",detailLabelRequeueReason:"Requeue reason",detailLabelRequeued:"requeued {{count}}",detailLabelSessionId:"Session id",detailLabelBranch:"Branch",detailLabelRole:"Role",detailLabelStarted:"Started",detailLabelWorkspace:"Workspace"}},ny={launchConfirm:{workspace:"Workspace",languageModel:"Language Model (Optional)",autoDetect:"Auto-detect or default",cliArgs:"CLI Arguments (Optional)",cliArgsPlaceholder:"e.g. --experimental",cancel:"Cancel",closeAria:"Close launch confirmation",launch:"Launch",launching:"Launching…"},confirmExternal:{dialogAria:"Confirm untrusted external provider",title:"Activate untrusted external provider?",description:"This manifest ships JavaScript that the daemon will execute. Treat as untrusted code — review the source before enabling.",proceedWarning:"Only proceed if you trust the source URL you added and have reviewed the manifest.",cancel:"Cancel",activate:"Activate"},workspace:{noWorkspace:"(no workspace — launch in home)",selectWorkspace:"📁 Select workspace…",customPath:"✏️ Custom path…",noWorkspacesSaved:"(no workspaces saved — add in Overview tab)",selectWorkspaceBtn:"Select workspace…",enterAbsolutePath:"Enter absolute path…",browseHint:"Browse to a folder before launching there.",absolutePathHint:"Enter an absolute path to launch there.",defaultWorkspace:"Default workspace",selectedWorkspace:"Selected workspace",noWorkspaceSelected:"No workspace selected. This launches in the home directory."},agentTab:{selectToLaunch:"Select {{label}} to Launch",launchSettings:"Launch Settings",noIdesDetected:"No IDEs detected.",scanSystem:"Scan System",noProviders:"No usable {{category}} providers available.",noProvidersHint:"Set a custom executable path in Providers if the binary is installed outside the default location.",targetModel:"Target Model",leaveEmptyDefault:"Leave empty for default",startupArguments:"Startup Arguments",optionalFlags:"Optional flags...",openSession:"Open Session",starting:"Starting...",configure:"Configure",select:"Select",launching:"⏳ Launching...",launchBtn:"▶ Launch",running:"Running ({{count}})",noRunning:"No {{plural}} running",launchingProcess:"Launching process...",waitingProcess:"Waiting for process and session to register...",startingBadge:"starting",chatView:"Chat view",terminalView:"Terminal view",localTerminal:"Local terminal:",copied:"Copied",copy:"Copy",openRemoteControl:"Open remote control",restart:"Restart",viewChat:"View chat",openInDashboard:"Open current view in dashboard",stop:"Stop",extensions:"Extensions",browseFolderTitle:"Select workspace",browseFolderDesc:"Choose a folder in a regular explorer-style dialog, then use it as the launch target.",browseFolderConfirm:"Use this folder",detailMode:"Mode",detailProvider:"Provider",detailResume:"Resume",detailArguments:"Arguments",detailModel:"Model",categoryIde:"IDE",categoryCliPlural:"CLIs",categoryAcp:"ACP Agent",categoryAcpPlural:"ACP agents"},providers:{filter:"Filter",sourceConfigTitle:"Provider source config",sourceConfigDesc:"Where the daemon looks for provider manifests. Affects resolution and reloads.",sourceMode:"Source mode",explicitProviderDir:"Explicit providerDir",providerDirPlaceholder:"Leave blank to use ~/.adhdev/providers",applying:"Applying…",applyReload:"Apply + Reload",userRoot:"User root:",upstreamRoot:"Upstream root:",providerRoots:"Provider roots:",loadingSettings:"Loading provider settings…",noProviders:'No providers installed yet. Open "Add provider" above to install one.',noFilteredProviders:"No {{filter}} providers installed.",refresh:"↻ Refresh",sources:"🌐 Sources",create:"✨ Create",advanced:"⚙ Advanced"},providerRow:{statusDetected:"Detected",statusNotDetected:"Not detected",statusEnabledUnchecked:"Enabled (unchecked)",statusDisabled:"Disabled",labelType:"Type:",labelVersion:"Version:",labelBinary:"Binary:",labelStatus:"Status:",labelDetails:"Details:",labelSource:"Source:",labelTrust:"Trust:",labelLinks:"Links:",labelDetection:"Detection:",labelVerification:"Verification:",saving:"saving…",disable:"Disable",enable:"Enable",detect:"Detect",resetCommand:"Reset command"},providerFix:{aiAgent:"AI Agent",scriptsToFix:"Scripts to Fix",all:"All",none:"None",additionalInstructions:"Additional Instructions",optional:"(optional)",agentOutput:"Agent Output",running:"● Running...",agentGenerating:"Agent is generating...",validateHint:"Run `adhdev provider verify` to validate",cancel:"Cancel",startFix:"🚀 Start Fix",cancelRunning:"⬛ Cancel",back:"← Back",close:"Close",footerHint:"AI agent will implement provider scripts",scriptsSelected_one:"{{count}} script selected",scriptsSelected_other:"{{count}} scripts selected",titlePrefix:"Auto-Fix: {{name}}",descCodex:"OpenAI o3/gpt-5.4",descClaude:"Anthropic Claude",descGemini:"Google Gemini"},providerClone:{title:"✨ Create User Provider",subtitle:"Clone an upstream IDE provider to customize",baseProvider:"Base Provider",providerTypeId:"Provider Type (ID)",typeIdPlaceholder:"my-cursor, custom-windsurf...",typeIdHint:"Lowercase, alphanumeric + hyphens only. Will be created at",displayName:"Display Name",displayNamePlaceholder:"My Custom IDE",cancel:"Cancel",creating:"⏳ Creating...",createProvider:"✨ Create Provider",createdTitle:"Provider Created!",createdDesc:"{{type}} has been created at",createdRunHint:"Run adhdev provider fix {{type}} or use Auto-Fix to implement scripts.",close:"Close"},connectedMachines:{noMachines:"No machines connected",defaultDescription:"Install ADHDev on a machine and sign in to connect it here.",startingUpgrade:"Starting upgrade...",machineDisconnected:"Machine disconnected.",tokenRevoked:"Token revoked. Restart ADHDev on that machine to reconnect.",failedToDisconnect:"Failed to disconnect",failedToRevokeToken:"Failed to revoke token",connectionLostUpgrade:"Connection lost during upgrade",disconnect:"Disconnect",remove:"Remove",disconnectTitle:"🔌 Disconnect Machine",removeTitle:"⚠️ Remove Machine",cancel:"Cancel",noIdesConnected:"No IDEs connected",upgrading:"Upgrading...",updated:"✓ Updated",updateNow:"↑ Update now",updateTo:"↑ Update to v{{version}}",cdpConnected:"CDP connected",cdpConnecting:"CDP connecting...",connecting:"connecting..."}},ry={theme:{helloHelp:"Hello! How can I help?",fixBug:"Fix the bug please",onIt:"On it! ✨",customEditorTitle:"🎨 Custom Theme Editor",darkMode:"🌙 Dark mode",lightMode:"☀️ Light mode",sectionAppBackground:"App Background",sectionAppText:"App Text",sectionBordersAccent:"Borders & Accent",sectionChatBubbles:"Chat Bubbles",sectionChatLayout:"Chat Layout",colorBackground:"Background",colorSurface:"Surface",colorCard:"Card",colorPrimary:"Primary",colorSecondary:"Secondary",colorMuted:"Muted",colorBorderSubtle:"Border subtle",colorBorderDefault:"Border default",colorAccent:"Accent",colorUserBubble:"User bubble",colorUserText:"User text",colorAgentBubble:"Agent bubble",colorAgentText:"Agent text",colorChatBg:"Chat BG",colorSendButton:"Send button",colorInputBorder:"Input border",labelBubbleRadius:"Bubble radius",resetToDefaults:"Reset to defaults",customLabel:"🎨 Custom"}},oy={chatHistory:"Historial de chat",startNewChat:"+ Iniciar nueva sesión de chat",creating:"⌛ Creando...",searchPlaceholder:"Buscar título o vista previa",filterWorkspace:"Filtrar por workspace",filterModel:"Filtrar por modelo",sortRecent:"Más recientes",sortOldest:"Más antiguos primero",sortMessages:"Más mensajes",resumeReadyOnly:"Solo reanudables",untitledSession:"Sesión sin título",noSavedPreview:"Aún no hay vista previa guardada",workspaceUnknown:"Workspace desconocido",selectedWorkspaceSuffix:" · workspace seleccionado",msgCount:"{{count}} mensajes",statusActive:"ACTIVA",statusMissingWorkspace:"FALTA WORKSPACE",statusResumeSelectedWorkspace:"REANUDAR EN WORKSPACE SELECCIONADO",statusResuming:"REANUDANDO...",statusResume:"REANUDAR",noMatchingHistory:"Ningún historial guardado coincide con estos filtros.",noRecentChats:"No se encontraron sesiones de chat recientes.",refreshHistory:"Actualizar historial",refreshing:"⌛ Actualizando..."},ay={nav:{home:"ADHDev Home",mesh:"Mesh",what:"What",agents:"Agents",pricing:"Pricing",install:"Install",github:"GitHub",docs:"Docs",getStarted:"Get started",toggleMenu:"Toggle menu"},hero:{badge:"The multi-vendor, multi-machine agent control plane",title:"Anyone can run ten agents. ADHDev lands the work on main.",subtitle:"Drive any local coding agent — Claude Code, Codex, Cursor — from your browser, then let the Refinery merge finished work back to main <em>unattended</em>: your repo's own gates, patch-equivalence checks, fast-forward only, no force-push. You talk to one coordinator; it runs parallel agents across your own machines asynchronously — no sessions to babysit. Code stays on your machine — P2P, end to end.",selectOs:"Select OS",osUnix:"macOS / Linux",osWindows:"Windows",copyInstall:"Copy install command: {{cmd}}",copied:"Copied",copy:"Copy",getStarted:"Get started",openSource:"Open source on GitHub",joinDiscord:"Join Discord",selfHost:"Self-host it yourself",demoDesktop:"ADHDev command center driving live agent sessions across multiple machines",demoPush:"ADHDev mobile push notification and one-tap approval"},mesh:{sectionTitle:"They parallelize. We land.",sectionSubtitle:"Spawning parallel agents is the easy part — every tool does it now. The hard part is what happens after: ten branches that still have to be verified and merged. The Refinery does that for you, unattended, so finished work arrives on main instead of in your review queue.",refineryHighlight:"The Refinery",refineryTitle:"Finished work lands on main — unattended",refineryDesc:"Anyone can spawn ten parallel agents. The Refinery validates each worktree against your repo's own gates (typecheck, tests, lint), verifies patch equivalence, publishes submodule commits, fast-forwards main, and cleans up — automatically. No force-push, ever. Anything ambiguous is kicked back for review instead of merged.",asyncHighlight:"Async orchestration",asyncTitle:"You talk to one place. It runs the rest.",asyncDesc:"You give work to one coordinator; it drives many workers across many machines on an event loop — reacting only when a completion, approval, or status event arrives. No polling, no window-per-agent to babysit. Unlike a desktop app where you watch each agent session, here the coordinator waits on events, so you don't have to sit synchronously in front of anything.",monoHighlight:"Monorepo-aware",monoTitle:"Safe even with git submodules",monoDesc:"Real production repos nest submodules — and that's exactly where naive auto-merge breaks. The Refinery is submodule-aware: it gates on submodule-commit reachability, judges patch equivalence, and bumps the pointer atomically. This project is itself a root + two-submodule monorepo, converged this way every day.",crossHighlight:"Cross-check",crossTitle:"Consensus over a single opinion",crossDesc:"Fan the same read-only investigation out to several machine × provider replicas and synthesize where they agree and diverge (MAGI). More trustworthy than one agent's take.",tryMesh:"Try Repo Mesh →",seePlans:"See plans",availableOn:"Available on Pro and above. Drive it from the <strong>Repo Mesh</strong> page once connected.",readGuide:"Read the guide"},compare:{sectionTitle:"Parallel agents are everywhere now. Where does the work actually land?",sectionSubtitle:"A fair question. Local CLIs spawn subagents; desktop orchestrators fan work across worktrees with a slick native UI. Both stop at the branch. Here's the honest line — including where each of them beats us — with no hand-waving.",colLocalCli:"Local CLI + subagents",colDesktop:"Desktop orchestrator",colAdhdev:"ADHDev Repo Mesh",rowLandsMain:"Lands finished work on main",rowLandsMainLocalCli:"You run the gates and merge by hand",rowLandsMainDesktop:"Parallelizes the work, then hands you the branches to review",rowLandsMainAdhdev:"The Refinery runs your repo's gates, checks patch equivalence, and fast-forwards main — unattended, no force-push",rowSubmodules:"Safe with git submodules",rowSubmodulesLocalCli:"No merge automation to be aware of them",rowSubmodulesDesktop:"Worktree parallelism, but the merge is yours to get right",rowSubmodulesAdhdev:"Submodule-aware convergence: reachability gate, patch-equivalence check, atomic pointer bump — dogfooded on this monorepo daily",rowAsync:"Talk to one place, async",rowAsyncLocalCli:"One session at a time, synchronously",rowAsyncDesktop:"You supervise each agent window yourself",rowAsyncAdhdev:"One coordinator drives every worker on an event loop — it waits on completion/approval events, you don't poll or babysit",rowMultiMachine:"Multiple physical machines",rowMultiMachineLocalCli:"One host's processes only",rowMultiMachineDesktop:"Bound to the one machine it runs on",rowMultiMachineAdhdev:"Remote daemons over P2P — dispatch across every machine you own (no SSH plumbing)",rowParallelBranch:"Parallel isolated-branch work",rowParallelBranchLocalCli:"Subagents share one working tree — concurrent writes collide",rowParallelBranchDesktop:"One git worktree per task — a core strength",rowParallelBranchAdhdev:"One git worktree per node — parallel across machines, not just cores",rowBrowser:"Drive it from a browser or phone",rowBrowserLocalCli:"You have to be at the terminal",rowBrowserDesktop:"Native desktop app — you're at that desk",rowBrowserAdhdev:"Web-first: control sessions and approve from any browser or phone",rowNativeApp:"Native desktop app",rowNativeAppLocalCli:"Terminal only",rowNativeAppDesktop:"Polished native window — genuinely nicer to sit in front of",rowNativeAppAdhdev:"We're web-first — a browser tab, not a native app",rowRestarts:"Survives restarts & context loss",rowRestartsLocalCli:"State lives in a session — close it and it's gone",rowRestartsDesktop:"State tied to the app process",rowRestartsAdhdev:"Missions persist to disk and resume after a coordinator or daemon restart — append-only, tamper-evident audit trail",rowCrossCheck:"Cross-check the answer",rowCrossCheckLocalCli:"One agent's take, no second opinion",rowCrossCheckDesktop:"Parallel work, single verdict",rowCrossCheckAdhdev:"MAGI fans the same read-only question to independent machine × provider agents and surfaces where they diverge",footnote:"For a single machine, a single branch, a one-shot task — a local CLI with subagents is lighter and works great, and a native desktop orchestrator is a nicer place to sit. Repo Mesh earns its keep when work fans out across machines and branches, needs to survive restarts, and should land on main automatically — controlled from wherever you are."},what:{sectionTitle:"Any agent, mixed freely",sectionSubtitle:"Vendor-neutral by design. Run Claude Code on the Mac, Codex on the Windows GPU box, Gemini for review passes — in the same mesh, under the same policies. Switch vendors without switching platforms.",cliHighlight:"CLI agents",cliTitle:"Drive any terminal agent from the web",cliDesc:"Claude Code, Codex CLI, Cursor CLI, Antigravity CLI, Hermes, Kimi, and OpenCode — attached on your machine through a PTY adapter with proper resume and reconnect, driven from your browser. Send prompts and provide visual context instantly (paste, drag & drop, or upload multiple images at once, up to 5 images / 10MB each). Aider, Gemini CLI, Goose, and other ACP agents connect over stdio.",uiHighlight:"One UI",uiTitle:"Same dashboard, any device",uiDesc:"Cloud-hosted at adhf.dev — drive every agent from a laptop or phone, whether you're at your desk or away from it.",ideHighlight:"IDE agents",ideTitle:"Also: attach to running editors",ideDesc:"Cursor, VS Code, VSCodium, Windsurf, Antigravity, Kiro, PearAI, Trae. Read live chat, send prompts, switch sessions, capture screenshots.",p2pHighlight:"Yours, end to end",p2pTitle:"P2P-first: your data stays yours",p2pDesc:"Chat, commands, and screenshots flow directly between your browser and your daemon over WebRTC. The cloud sees auth and signaling metadata, nothing else — your code never routes through the server."},oss:{sectionTitle:"Open source & self-hostable",sectionSubtitle:"The daemon and dashboard are AGPL-3.0 and available on GitHub. Run them yourself on any machine or server — no account required.",github:"GitHub",selfHostDocs:"Self-hosting docs"},agents:{sectionTitle:"Supported agents",sectionSubtitle:"{{ides}} built-in IDE integrations, {{clis}} built-in CLI agents, {{extensions}} IDE-resident extension agents, and {{acp}}+ ACP (stdio MCP) agents. Provider scripts live in <code>adhdev-providers/</code> — add your own under <code>~/.adhdev/providers/</code>.",tierTested:"Tested",tierTestedDesc:"validated against a real app + version",tierCommunity:"Community",tierCommunityDesc:"built-in and community-supported",groupIdes:"IDEs",hintIdes:"Attached via Chrome DevTools Protocol. Read chat, send prompts, switch sessions, screenshot.",groupCli:"CLI agents",hintCli:"Driven through a PTY adapter with resume and reconnect.",groupExtensions:"In-IDE extension agents",hintExtensions:"CDP webview attachment for agents that live inside another IDE.",acpFootnote:"Plus {{count}}+ ACP agents over stdio (Agent Client Protocol): Codex, Claude Agent, Gemini, Goose, Cline, OpenHands, and more."},pricing:{sectionTitle:"Simple pricing as your agents grow",sectionSubtitle:"Start free on one machine. Go Pro for two, or Ultra for five. No per-seat math, no enterprise sales call — just the plans below.",mostPopular:"Most popular",upgradeToPro:"Upgrade to Pro",footnote:"Simple, transparent pricing — the prices above are what you'll pay. Prefer to self-host? The daemon and dashboard are open source. Prices in USD.",plans:{free:{period:"forever",tagline:"Everything you need to drive one machine from anywhere.",cta:"Start free",features:{machine:"One machine, paired in a single command",p2p:"P2P chat, commands, screenshots, remote input",providers:"Every provider — CLI, IDE, and ACP agents",push:"Push notifications for approvals & completions",share:"One shared session link"}},pro:{period:"/mo",tagline:"Run agents across a couple of machines, with the reliability paid plans need.",cta:"Start 7-day Pro trial",features:{machines:"2 machines — run agents on both",p2p:"More concurrent P2P sessions",push:"Unlimited push notifications",turn:"TURN relay for restrictive networks",mesh:"Repo Mesh — orchestrate agents across machines",share:"More shared sessions"}},ultra:{period:"/mo",tagline:"Everything in Pro, scaled up — more machines and higher limits for heavy parallel work.",cta:"Go Ultra",features:{machines:"5 machines — flat price, not per-seat",everything:"Everything in Pro",p2p:"Highest concurrent P2P sessions",screenshots:"Unlimited daily screenshot minutes",webhooks:"More webhooks & API calls",share:"More shared sessions"}}}},install:{sectionTitle:"Three steps to a working dashboard",sectionSubtitle:"No configuration files. No API keys to wire up. ADHDev does not manage agent auth — each tool keeps its own login.",selectOs:"Select OS",osUnix:"macOS / Linux",osWindows:"Windows",copyInstall:"Copy install command: {{cmd}}",copied:"Copied",copy:"Copy",platformNote:"macOS and Windows are the validated install paths. Linux runs the same Unix script and is community-tested.",arrow:"→",steps:{step1:{title:"Install the daemon",desc:"One curl command installs the daemon plus the adhdev CLI — the launcher you run to pair machines and start the daemon (not to be confused with the CLI agents it drives, like Claude Code or Codex). Same binary powers cloud and standalone."},step2:{title:"Link a machine",desc:"Sign in once with GitHub or Google and the daemon pairs itself — no token to copy."},step3:{title:"Drive your agents",desc:"Launch Claude Code, Codex CLI, Cursor CLI, Antigravity CLI, Hermes, Kimi, and other agents from the dashboard. Read chat, send prompts, provide visual context (paste, drag & drop, or upload multiple images at once), approve actions, and switch sessions."}}},cta:{headline:"Stop juggling tabs. Drive every agent from one dashboard.",subtitle:"One curl command, one daemon, every agent you already use. Drive them all from the web — Cloud is live.",getStarted:"Get started →",github:"GitHub",discord:"Discord"},footer:{docs:"Docs",github:"GitHub",discord:"Discord",dashboard:"Dashboard",terms:"Terms",privacy:"Privacy",contact:"Contact",copyright:"© {{year}} RacoLab. All rights reserved."}},iy={chat:Hx,chatPane:Wx,chatInput:Ox,paneGroup:Ux,terminal:Gx,conversation:Kx,cliView:zx,launch:qx,standalone:Vx,meshGraph:Yx,cloud:Jx,app:Qx,chatList:Xx,screenshot:Zx,remote:ey,sessionInfo:ty,mesh:sy,machine:ny,settings:ry,historyModal:oy,landing:ay},za="lang",Ol="common",ly={en:{common:fg},ko:{common:Yg},ja:{common:gx},"zh-CN":{common:Fx},es:{common:iy}};function cy(){try{const e=localStorage.getItem(za);if(un(e))return e}catch{}return null}function mu(){const e=cy();return e||(typeof navigator<"u"?Eb(navigator.language):Qn)}function qa(e){typeof document>"u"||document.documentElement.setAttribute("lang",e)}let Ul=!1;function dy(){if(Ul)return wt;Ul=!0;const e=mu();return wt.use(Cm).init({resources:ly,lng:e,fallbackLng:Qn,supportedLngs:pu,ns:[Ol],defaultNS:Ol,interpolation:{escapeValue:!1},returnEmptyString:!1}),qa(e),wt}var uy=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function hy(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function Zt(e,t){if(hy(t==null?void 0:t.activeModal))return"waiting_approval";const n=String(e||"idle").trim().toLowerCase();return n==="waiting_approval"?"waiting_approval":n==="waiting_choice"?"waiting_choice":uy.has(n)?"generating":n==="error"?"error":n==="stopped"?"stopped":n==="starting"?"starting":n==="panel_hidden"?"panel_hidden":n==="not_monitored"?"not_monitored":n==="disconnected"?"disconnected":"idle"}function Va(e){return Zt(e)==="generating"}function Gl(e,t){return Zt(e,t)==="waiting_approval"}function ft(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function De(...e){for(const t of e){if(typeof t!="string")continue;const n=t.trim();if(n)return n}}function zt(...e){for(const t of e)if(typeof t=="number"&&Number.isFinite(t))return t}function _t(...e){for(const t of e)if(typeof t=="boolean")return t}function Jo(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function py(e,t){const n=typeof e=="string"?e.trim().replace(/[\\/]+$/,""):"",r=typeof t=="string"?t.trim():"";if(r){if(/^(?:[A-Za-z]:[\\/]|\/)/.test(r))return r;if(n)return`${n}/${r.replace(/^[\\/]+/,"")}`}}function Ri(e){switch(e){case"fresh":return 30;case"no_upstream":return 4;case"unchecked":case void 0:return 0;case"stale":return-10;case"unavailable":return-15;default:return 0}}function my(e,t){if(!Array.isArray(e))return;const n=e.map(r=>{const o=ft(r),a=De(o.path),i=De(o.commit),c=De(o.repoPath,o.repo_root)??py(t,a);if(!a||!i)return null;const u={path:a,commit:i,dirty:_t(o.dirty)??!1,outOfSync:_t(o.outOfSync,o.out_of_sync)??!1,lastCheckedAt:zt(o.lastCheckedAt,o.last_checked_at)??Date.now()};c&&(u.repoPath=c);const h=De(o.error);return h&&(u.error=h),u}).filter(r=>r!==null);return n.length>0?n:void 0}function fy(e){return _t(e.isGitRepo)!==void 0||!!De(e.branch,e.upstream,e.upstreamStatus,e.upstream_status,e.headCommit)||!!De(e.repoRoot,e.repo_root,e.workspace)||zt(e.ahead,e.behind,e.staged,e.modified,e.untracked,e.deleted,e.renamed,e.lastCheckedAt,e.last_checked_at)!==void 0||Array.isArray(e.submodules)&&e.submodules.length>0}function Or(e,t,n){const r=_t(e.isGitRepo);if(!Object.keys(e).length||!fy(e))return;const o=r??!0,a=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(j=>typeof j=="string"):[],i=zt(e.conflicts)??a.length,c=_t(e.hasConflicts)??i>0,u=De(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,h=my(e.submodules,u),d=De(e.upstreamStatus,e.upstream_status),m=zt(e.upstreamFetchedAt,e.upstream_fetched_at),f=De(e.upstreamFetchError,e.upstream_fetch_error),x=De(e.error),w=zt(e.staged)??0,p=zt(e.modified)??0,y=zt(e.untracked)??0,k=zt(e.deleted)??0,b=zt(e.renamed)??0;return{workspace:De(e.workspace,t.workspace)||"",repoRoot:u??null,isGitRepo:o,branch:De(e.branch)??null,headCommit:De(e.headCommit)??null,headMessage:De(e.headMessage)??null,upstream:De(e.upstream)??null,upstreamStatus:d??"unchecked",...m!==void 0?{upstreamFetchedAt:m}:{},...f?{upstreamFetchError:f}:{},ahead:zt(e.ahead)??0,behind:zt(e.behind)??0,staged:w,modified:p,untracked:y,deleted:k,renamed:b,dirty:_t(e.dirty,e.isDirty,e.is_dirty)??(w+p+y+k+b>0||c),hasConflicts:c,conflictFiles:a,stashCount:zt(e.stashCount,e.stash_count)??0,lastCheckedAt:(n==null?void 0:n.lastCheckedAt)??zt(e.lastCheckedAt,e.last_checked_at)??Date.now(),...h?{submodules:h}:{},...x?{error:x}:{}}}function by(e){if(!e)return Number.NEGATIVE_INFINITY;let t=0;return e.isGitRepo===!0&&(t+=50),e.isGitRepo===!1&&(t-=10),e.branch&&(t+=20),e.headCommit&&(t+=20),e.upstream&&(t+=10),t+=Ri(e.upstreamStatus),typeof e.ahead=="number"&&(t+=2),typeof e.behind=="number"&&(t+=2),Array.isArray(e.submodules)&&e.submodules.length>0&&(t+=4+e.submodules.length),e.error&&(t-=20),t}function gy(e,t){const n=ft(e.lastGit??e.last_git),r=ft(n.result),o=ft(n.status),a=ft(r.status),i=ft(e.lastProbe??e.last_probe),c=ft(i.git),u=ft(c.result),h=ft(c.status),d=ft(u.status),m=t==null?void 0:t.lastCheckedAt;let f=null;for(const x of[o,a,h,d]){const w=Or(x,e,{lastCheckedAt:m??Date.now()});if(!w)continue;const p=by(w);(!f||p>f.score)&&(f={git:w,score:p})}return f==null?void 0:f.git}function xy(e){const t=[De(e.workspace),De(e.providerType,e.provider),De(e.role),De(e.state,e.status),De(e.title),De(e.createdAt,e.created_at),De(e.startedAt,e.started_at)].filter(n=>!!n);if(t.length!==0)return`synthetic:${t.join("|")}`}function Ya(e){const t=ft(e),n=De(t.sessionId,t.session_id,t.id)??xy(t);return n?{sessionId:n,...De(t.providerType,t.provider)?{providerType:De(t.providerType,t.provider)}:{},...De(t.state,t.status)?{state:De(t.state,t.status)}:{},...De(t.chatStatus,t.chat_status)?{chatStatus:De(t.chatStatus,t.chat_status)}:{},...De(t.lifecycle)?{lifecycle:De(t.lifecycle)}:{},...De(t.surfaceKind,t.surface_kind)?{surfaceKind:De(t.surfaceKind,t.surface_kind)}:{},...De(t.recoveryState,t.recovery_state)?{recoveryState:De(t.recoveryState,t.recovery_state)}:{},...De(t.workspace)?{workspace:De(t.workspace)}:{},...De(t.title)?{title:De(t.title)}:{},...De(t.role)?{role:De(t.role)}:{},..._t(t.isSelfCoordinator,t.is_self_coordinator)!==void 0?{isSelfCoordinator:_t(t.isSelfCoordinator,t.is_self_coordinator)}:{},...De(t.statusNote,t.status_note)?{statusNote:De(t.statusNote,t.status_note)}:{},...De(t.createdAt,t.created_at)?{createdAt:De(t.createdAt,t.created_at)}:{},...De(t.startedAt,t.started_at)?{startedAt:De(t.startedAt,t.started_at)}:{},...De(t.lastActivityAt,t.last_activity_at)?{lastActivityAt:De(t.lastActivityAt,t.last_activity_at)}:{},..._t(t.isCached,t.is_cached)!==void 0?{isCached:_t(t.isCached,t.is_cached)}:{}}:null}function yy(e){const t=e&&typeof e=="object"?e:{};return De(t.id,t.nodeId,t.node_id)}function vy(e,t){if(!t)return!1;const n=t.trim();return n?yy(e)===n:!1}var wy=["daemon_","standalone_"];function Kl(e){const t=De(e);if(t){for(const n of wy)if(t.startsWith(n))return t.slice(n.length).trim()||void 0;return t}}function Ws(e,t){const n=Kl(e),r=Kl(t);return!n||!r?!1:n===r}var ky=["easy","medium","difficult","freeform"];function Et(e){return(typeof e=="string"?e.trim():"")||void 0}function ws(e,t){const n=Et(t);return n?`${e}:${n}`:void 0}function As(e,t,n){const r=ws(t,n),o=Et(n);r&&e.push(r),o&&e.push(o)}function hn(e){const t=[],n=new Set;for(const r of e)!r||n.has(r)||(n.add(r),t.push(r));return t}function fu(e){return Et(e.providerSessionId)||Et(e.sessionId)||Et(e.tabKey)||Et(e.routeId)}function Ao(e){return hn([Et(e.historySessionId),Et(e.providerSessionId),Et(e.sessionId)])}function Xn(e){const t=[];return As(t,"provider",e.providerSessionId),As(t,"session",e.sessionId),As(t,"tab",e.tabKey),As(t,"route",e.routeId),hn(t)}function Sy(e){const t=[];return Et(e.providerSessionId)?(As(t,"provider",e.providerSessionId),hn(t)):Et(e.sessionId)?(As(t,"session",e.sessionId),hn(t)):Et(e.tabKey)?(As(t,"tab",e.tabKey),hn(t)):Et(e.routeId)?(As(t,"route",e.routeId),hn(t)):[]}function bu(e){return ws("provider",e.providerSessionId)||ws("session",e.sessionId)||ws("tab",e.tabKey)||ws("route",e.routeId)||"unknown:"}function To(e){return Ao(e)[0]}function Io(e){const t=Et(e.sessionId),n=To(e);if(n&&!(t&&n===t))return n}function Cy(e){const t=Et(e.providerSessionId),n=Et(e.sessionId),r=Et(e.tabKey),o=Et(e.routeId),a=[ws("provider",t),ws("session",n),ws("tab",r),ws("route",o)].filter(u=>typeof u=="string"),i=Xn({providerSessionId:t,sessionId:n,tabKey:r,routeId:o}),c=bu({providerSessionId:t,sessionId:n,tabKey:r,routeId:o});return{providerSessionId:t,sessionId:n,tabKey:r,routeId:o,canonicalKey:c,targetKey:c,targetValue:fu({providerSessionId:t,sessionId:n,tabKey:r,routeId:o}),historySessionId:To({providerSessionId:t,sessionId:n}),runtimeSessionId:n,allKeys:a,lookupKeys:i}}function Ja(e,t){const n=Cy(e);return Sy(t).some(r=>n.lookupKeys.includes(r))}function gu(e){const t=String(e.daemonId||"").trim(),n=String(e.id||"").trim();return t&&n.startsWith(`${t}:`)?n.slice(t.length+1):n}function Qa(e){if(String(e.ownerDaemonId||"").trim())return!0;const t=e.settings;return t?!!t.meshNodeFor||!!t.meshNodeId||t.launchedByCoordinator===!0||t._remoteOwnedSession===!0:!1}function jy(e,t){const n=String(e.daemonId||"").trim(),r=String(e.id||"").trim(),o=gu(e);if(o&&t.has(o))return`mesh:${o}`;const a=String(e.ownerDaemonId||"").trim()||n;return a?o?`${a}:${o}`:a:r}function Qo(e,t){return t||e||"unknown"}function Ny(e,t){return e.ownerDaemonId&&(t==null?void 0:t[e.ownerDaemonId])||e.ownerMachineName||void 0||e.daemonId&&(t==null?void 0:t[e.daemonId])||void 0}function $t(e){return e?e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):"IDE"}function Ay(e){if(e<60)return`${Math.round(e)}s`;const t=Math.floor(e/60);if(t<60)return`${t}m`;const n=Math.floor(t/60),r=t%60;if(n<24)return r>0?`${n}h ${r}m`:`${n}h`;const o=Math.floor(n/24),a=n%24;return`${o}d ${a}h`}function Xo(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function xu(e,t){const n=typeof t=="string"?t.trim():"";if(n)return n;const r=typeof e=="string"?e.trim():"";if(!r)return"";const o=r.replace(/[\\/]+$/,""),a=o.split(/[\\/]/).filter(Boolean);return a[a.length-1]||o}function Ty(e){if(e.length>16&&/^[a-f0-9]+$/i.test(e))return`Machine-${e.substring(0,8)}`;if(e.includes("_")){const t=e.split("_"),n=t[t.length-1];return n.length>12?`Machine-${n.substring(0,8)}`:n}return e}function Iy(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function My(e){return Ty(e.trim().replace(/\.local$/i,""))}function Dy(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function yu(e,t={}){var o,a;const n=[e.hostname,(o=e.machine)==null?void 0:o.hostname,(a=e.system)==null?void 0:a.hostname].find(i=>typeof i=="string"&&i.trim().length>0&&!Iy(i));if(n&&n!=="Unknown")return My(n);const r=t.fallbackId||e.id;return r?`Machine-${r.substring(0,8)}`:t.fallbackLabel||"Machine"}function ts(e,t={}){return Dy(e)||yu(e,t)}function vu(e){return!e||!Array.isArray(e.items)?[]:e.items.map(t=>String((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim()).filter(Boolean)}function wu(e,t,n={}){const r=String(t).trim();if(!e||!Array.isArray(e.items)||!r)return"";const o=e.items.find(a=>String((a==null?void 0:a.id)||"").trim()===r);return o?String(n.preferShortValue?o.shortValue||o.value||"":o.value||o.shortValue||"").trim():""}function Js(e,t){return vu(e).join(" · ")}function ir(e){return e.transport==="pty"}function pn(e){return e.transport==="acp"}function Py(e,t){var n,r;return(n=t==null?void 0:t.providerLabels)!=null&&n[e]?t.providerLabels[e]:(r=t==null?void 0:t.providerLabels)!=null&&r[e==null?void 0:e.toLowerCase()]?t.providerLabels[e.toLowerCase()]:t!=null&&t.agentName&&t.agentName!==e?t.agentName:$t(e)}function zl(e,t,n){const r=(e||"").trim().toLowerCase();if(!r)return!0;const o=(t||"").trim().toLowerCase(),a=(n||"").trim().toLowerCase(),i=$t(n||"").trim().toLowerCase();return r===o||r===a||r===i}function Ly(e,t=[],n=[]){var u,h,d,m;const r=Zt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal});if(r==="waiting_approval")return"waiting_approval";if(r==="waiting_choice")return"waiting_choice";if(r==="generating")return"generating";const o=t.find(f=>Gl(f.status,{activeModal:f.activeModal})||Va(f.status));if(o)return Zt(o.status,{activeModal:o.activeModal});const a=n.find(f=>Gl(f.status,{activeModal:f.activeModal})||Va(f.status));if(a)return Zt(a.status,{activeModal:a.activeModal});if(r&&r!=="idle")return r;const i=Zt((u=t[0])==null?void 0:u.status,{activeModal:(h=t[0])==null?void 0:h.activeModal});if(i!=="idle")return i;const c=Zt((d=n[0])==null?void 0:d.status,{activeModal:(m=n[0])==null?void 0:m.activeModal});return c!=="idle"?c:"idle"}function Ry(e){return Zt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Ey(e){if(!Array.isArray(e)||e.length<=1)return e;const t=new Map,n=["generating","waiting_approval","waiting_choice","connected","idle","panel_hidden"];for(const r of e){const o=(r.name||r.id||"").toLowerCase().replace(/\s+/g,"-"),a=t.get(o),i=Zt(r.status);if(!a){t.set(o,{...r,status:i});continue}const c=n.indexOf(a.status||"idle"),u=n.indexOf(i||"idle");u>=0&&(c<0||u<c)&&t.set(o,{...r,status:i})}return Array.from(t.values())}function _y(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 $y(e){var n,r;const t=(r=(n=e==null?void 0:e.messages)==null?void 0:n.at)==null?void 0:r.call(n,-1);return t&&_y(t.receivedAt)||0}function By(e){return(e.recentLaunches||[]).reduce((n,r)=>Math.max(n,r.lastLaunchedAt||0),0)}function Xa(e){return Math.max(By(e),$y(e.activeChat))}function Fy(e,t,n,r,o,a){const i=t-e;if(i!==0)return i;const c=n.localeCompare(r);return c!==0?c:o.localeCompare(a)}function Ei(e,t){return Fy(Xa(e),Xa(t),ts(e,{fallbackId:e.id}),ts(t,{fallbackId:t.id}),e.id,t.id)}const ku="adhdev_notification_prefs",ql={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Hy(){try{const e=localStorage.getItem(ku);if(e){const t=JSON.parse(e);return{...ql,...t}}}catch{}return{...ql}}function Wy(e){try{localStorage.setItem(ku,JSON.stringify(e))}catch{}}let vs=Hy(),Ur=[];function Oy(){Ur.forEach(e=>e())}function Uy(e){vs={...vs,...e},Wy(vs),Oy()}function Gy(){const[,e]=l.useState(0);l.useEffect(()=>{const n=()=>e(r=>r+1);return Ur.push(n),()=>{Ur=Ur.filter(r=>r!==n)}},[]);const t=l.useCallback(n=>{Uy(n)},[]);return[{...vs},t]}function Zn(e){if(!vs.globalEnabled)return!1;switch(e){case"disconnect":return vs.disconnectAlert;case"completion":return vs.completionAlert;case"approval":return vs.approvalAlert;case"browser":return vs.browserNotifications;default:return!0}}const Ky={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Su(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function Cu(){return"Notification"in window&&Notification.permission==="granted"}let Es=null;function zy(e){return e!==!1}async function qy(){if(Es!==null)return Es;try{if(!("serviceWorker"in navigator)||!("PushManager"in window))return Es=!1,!1;const e=await navigator.serviceWorker.getRegistration();return e?(Es=!!await e.pushManager.getSubscription(),Es):(Es=!1,!1)}catch{return Es=!1,!1}}function Za(e,t,n){if(Cu())try{const r=new Notification(e,{body:t,icon:"/otter-logo.png",tag:n||`adhdev-${Date.now()}`,silent:!1});setTimeout(()=>r.close(),8e3),r.onclick=()=>{window.focus(),r.close()}}catch{}}function Vy(e,t={}){const n={...Ky,...t},r=l.useRef(new Map),o=l.useRef(0),[a,i]=l.useState(null);l.useEffect(()=>{let u=!1;return qy().then(h=>{u||i(h)}),()=>{u=!0}},[]);const c=l.useCallback((u,h,d)=>{const m=Date.now();m-o.current<n.throttleMs||(o.current=m,Za(u,h,d))},[n.throttleMs]);l.useEffect(()=>{var u;if(!(!n.enabled||!Cu())&&Zn("browser")&&!zy(a)){if(document.hasFocus()){for(const h of e)r.current.set(h.id,Zt(h.status,{activeModal:h.activeModal}));return}for(const h of e){const d=r.current.get(h.id),m=Zt(h.status,{activeModal:h.activeModal}),f=h.name||h.id;if(h.muted){r.current.set(h.id,m);continue}if(n.onApproval&&Zn("approval")&&m==="waiting_approval"&&d!=="waiting_approval"){const x=((u=h.activeModal)==null?void 0:u.message)||"Action requires your approval";c(`🔔 ${f} — Approval needed`,x.slice(0,120),`approval-${h.id}`)}n.onComplete&&Zn("completion")&&Va(d)&&m==="idle"&&c(`✅ ${f} — Task complete`,"Agent has finished generating",`complete-${h.id}`),n.onError&&m==="error"&&d!=="error"&&c(`⚠️ ${f} — Error`,"Agent encountered an error",`error-${h.id}`),r.current.set(h.id,m)}}},[e,n.enabled,n.onApproval,n.onComplete,n.onError,a,c])}const Yy=/^(run|approve|accept|yes|allow|always)/,Jy=/^(run|approve|accept|yes|allow|always|proceed|save)/,Qy=/^(reject|deny|delete|remove|abort|cancel|no)/;function _i(e){return e.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").replace(/\s*(Alt|Ctrl|Shift|Cmd|Enter|Return|Esc|Tab|Backspace)(\+\s*\w+)*/gi,"").trim()}function Xy(e){const t=_i(e).toLowerCase();return Yy.test(t)?"primary":Qy.test(t)?"danger":"default"}function Zy(e){return Jy.test(_i(e).toLowerCase())?"approve":"reject"}function ev(e){return e.map((t,n)=>({label:_i(t),variant:Xy(t),action:Zy(t),button:t,buttonIndex:n}))}function tv(e,t,n){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:n}function sv(e,t,n,r){return[{label:"Approve",variant:"primary",onClick:()=>{n(e,t,"approve").catch(o=>r==null?void 0:r("approve",o))}},{label:"Decline",variant:"danger",onClick:()=>{n(e,t,"reject").catch(o=>r==null?void 0:r("reject",o))}}]}class nv{constructor(){st(this,"dedupMap",new Map);st(this,"DEDUP_WINDOW_MS",5e3);st(this,"DEDUP_MAX_SIZE",50);st(this,"DEDUP_CLEANUP_AGE_MS",1e4);st(this,"toastCallbacks",[]);st(this,"statusEventCallbacks",[]);st(this,"resolveActionFn",null);st(this,"viewRequestRespondFn",null);st(this,"ides",[])}onToast(t){return this.toastCallbacks.push(t),()=>{this.toastCallbacks=this.toastCallbacks.filter(n=>n!==t)}}onStatusEvent(t){return this.statusEventCallbacks.push(t),()=>{this.statusEventCallbacks=this.statusEventCallbacks.filter(n=>n!==t)}}setResolveAction(t){this.resolveActionFn=t}setIdes(t){this.ides=t}setViewRequestRespond(t){this.viewRequestRespondFn=t}emitToast(t){for(const n of this.toastCallbacks)n(t)}showToast(t,n="info",r){const o=(r==null?void 0:r.id)||Date.now();this.emitToast({id:o,message:t,type:n,timestamp:o,duration:5e3,...r})}isDuplicate(t){const n=Date.now(),r=this.dedupMap.get(t)||0;if(n-r<this.DEDUP_WINDOW_MS)return!0;if(this.dedupMap.set(t,n),this.dedupMap.size>this.DEDUP_MAX_SIZE)for(const[o,a]of this.dedupMap)n-a>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(o);return!1}resolveOwningDaemon(t){if(t.daemonId){const o=this.ides.find(a=>a.id===t.daemonId&&a.type==="adhdev-daemon");if(o)return o}const n=t.targetSessionId&&this.findOwningSession(t.targetSessionId)||void 0;if(n){const o=n.daemonId;if(o){const a=this.ides.find(i=>i.id===o&&i.type==="adhdev-daemon");if(a)return a}}const r=this.ides.filter(o=>o.type==="adhdev-daemon");return r.length===1?r[0]:null}findOwningSession(t){for(const n of this.ides)if(n.id===t||n.sessionId===t||(Array.isArray(n.childSessions)?n.childSessions:[]).some(o=>(o==null?void 0:o.id)===t))return n;return null}resolveActionRouteTarget(t){if(t.targetSessionId){const n=this.findOwningSession(t.targetSessionId);return(n==null?void 0:n.id)||(n==null?void 0:n.daemonId)||null}return t.daemonId||null}resolveConversationKey(t){return t.targetSessionId?t.targetSessionId:t.daemonId?t.daemonId:null}isConversationEventMuted(t){const n=t.targetSessionId;if(!n)return!1;for(const r of this.ides){if(r.id===n||r.sessionId===n)return!!r.muted;const a=(Array.isArray(r.childSessions)?r.childSessions:[]).find(i=>(i==null?void 0:i.id)===n);if(a)return!!a.muted}return!1}handleRawEvent(t,n){var p;const r=this.resolveConversationKey(t),o=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),a=r||t.daemonId||"",i=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(o),c=`${a}:${t.event}:${i}`;if(this.isDuplicate(c))return;for(const y of this.statusEventCallbacks)y(t);const u=this.isConversationEventMuted(t),h=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,d=(h==null?void 0:h.type)||"";let m=$t(d);const f=this.resolveOwningDaemon(t);if(f){const y=ts(f,{fallbackId:f.id});y&&(m=!d||d==="adhdev-daemon"?y:`${y}/${m}`)}let x="",w="info";if(t.event==="agent:generating_completed"){if(x=t.duration?`✅ ${wt.t("event.taskCompletedWithDuration",{label:m,duration:t.duration})}`:`✅ ${wt.t("event.taskCompleted",{label:m})}`,w="success",!u)try{new Audio("data:audio/wav;base64,UklGRigAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQQAAAB/f39/").play().catch(()=>{})}catch{}}else if(t.event!=="agent:generating_started"){if(t.event==="agent:waiting_approval"){if(x=`⚡ ${wt.t("event.approvalNeeded",{label:m})}`,w="warning",u)x="";else if((p=t.modalButtons)!=null&&p.length&&this.resolveActionFn){const y=this.resolveActionRouteTarget(t);if(!y)return;const k=this.resolveActionFn,b=ev(t.modalButtons).map(v=>({label:v.label,variant:v.variant,onClick:()=>{k(y,"resolve_action",{action:v.action,button:v.button,buttonIndex:v.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),j=tv(m,t.modalMessage,x),S=Date.now();this.emitToast({id:S,message:j,type:w,timestamp:S,targetKey:r||y,actions:b,duration:15e3}),x=""}}else if(t.event==="monitor:no_progress"||t.event==="monitor:long_generating"){const y=t.elapsedSec?Math.round(t.elapsedSec/60):0;x=y?`⚠️ ${wt.t("event.noProgressWithDuration",{label:m,minutes:y})}`:`⚠️ ${wt.t("event.noProgress",{label:m})}`,w="warning",!u&&Zn("browser")&&!document.hasFocus()&&Za(`⚠️ ${wt.t("event.noProgressTitle",{label:m})}`,wt.t("event.noProgressBody",{duration:y?`${y}m`:""}),`no-progress-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const y=t.requesterName||wt.t("event.someoneRequester"),k=t.requestId,b=t.orgId;if(x=`👁️ ${wt.t("event.viewRequest",{requester:y})}`,w="warning",k&&b&&this.viewRequestRespondFn){const j=Date.now(),S=sv(b,k,this.viewRequestRespondFn,(v,g)=>console.error(`[EventManager] ${v} view request failed:`,g));this.emitToast({id:j,message:x,type:w,timestamp:j,actions:S,duration:3e4}),x=""}Zn("browser")&&!document.hasFocus()&&Za(`👁️ ${wt.t("event.viewRequestTitle")}`,wt.t("event.viewRequest",{requester:y}),`view-request-${k}`)}else if(t.event==="team:view_request_approved")x=`✅ ${wt.t("event.viewRequestApproved")}`,w="success";else if(t.event==="team:view_request_rejected"){const y=t.targetName||wt.t("event.someoneTarget");x=`❌ ${wt.t("event.viewRequestDeclined",{target:y})}`,w="warning"}}if(x&&!u){const y=Date.now();this.emitToast({id:y,message:x,type:w,timestamp:y,targetKey:r||t.daemonId,duration:5e3})}}}const pt=new nv,Vl=new Map;function no(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function mn(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Mo(e){return no(e)?no(e.result)?e.result:e:null}function rv(e){const t=Mo(e);return!t||!no(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function Sr(e){const t=Mo(e);return!t||!no(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function En(e){const t=Mo(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function Cr(e){const t=Mo(e);return!!t&&t.success===!1}function ov(e){var t,n;for(const r of e||[]){if(r.type==="toast"&&((t=r.toast)!=null&&t.message)){const o=r.toast.level==="warning"?"warning":r.toast.level==="success"?"success":"info";pt.showToast(r.toast.message,o);continue}if(r.type==="notification"&&((n=r.notification)!=null&&n.body)){const o=r.notification.level==="warning"?"warning":r.notification.level==="success"?"success":"info";pt.showToast(r.notification.body,o)}}}function av(e,t){return e&&mn(e.currentValue)?e.currentValue:t}function iv(e,t){const n=Object.keys(e).filter(o=>t[o]!==void 0);if(n.length===0)return e;const r={...e};for(const o of n)delete r[o];return r}function lv(e,t){return mn(t)?mn(e)?typeof e=="string"&&e.trim()==="":!0:!1}function cv(e,t){var a,i;if((t.now??Date.now())<t.localOverrideUntil){const c=t.localValues[e];if(mn(c))return c}const r=(a=t.controlValues)==null?void 0:a[e];if(mn(r))return r;const o=(i=t.defaultValues)==null?void 0:i[e];return mn(o)?o:void 0}function Gr(e,t){return e.options||t[e.id]||[]}const dv={antigravity:new Set(["new_session"]),"claude-cli":new Set(["compact","new_session","stop"]),"claude-code-vscode":new Set(["new_session"]),codex:new Set(["new_session"])};function uv(e,t,n){var r;return((r=dv[t])==null?void 0:r.has(n.id))===!0}function hv(e){if(e)switch(e){case"idle":return["idle"];case"generating":case"streaming":case"working":case"starting":case"no_progress":case"long_generating":return["busy","generating","starting"];case"waiting_approval":case"approval":return["approval"];case"waiting_choice":return["picker"];default:return}}function pv(e,t){const n=e.visibleWhenState;if(!n||n.length===0)return!0;const r=hv(t);return r?r.some(o=>n.includes(o)):!0}function $i(e,t){return(e||[]).filter(n=>n.placement==="bar"&&n.hidden!==!0&&!uv(t.hostIdeType,t.providerType,n)&&pv(n,t.currentStatus)).sort((n,r)=>(n.order??50)-(r.order??50))}function Zo(e,t){return{value:t}}function mv(e,t,n){var o;return n?((o=Gr(e,t).find(a=>a.value===n))==null?void 0:o.label)||n:""}const fv={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function bv({routeId:e,sessionId:t,hostIdeType:n,providerType:r,displayLabel:o,controls:a,controlValues:i,currentStatus:c,coordinatorHint:u}){const{sendCommand:h}=yt(),d=`${e}:${t||r}`,m=fv[r]||"#94a3b8",[f,x]=l.useState({}),w=l.useRef({}),p=l.useRef(i);w.current=f,p.current=i;const y=l.useRef(0),k={};for(const E of a||[])E.defaultValue!==void 0&&(k[E.id]=E.defaultValue);const b={...k,...i||{},...Date.now()<y.current?f:{}};l.useEffect(()=>{i&&Date.now()>y.current&&x(E=>iv(E,i))},[i]);const[j,S]=l.useState(Vl.get(d)||{}),[v,g]=l.useState(null),[N,C]=l.useState(null),A=l.useCallback(async(E,I={})=>{const $={...I,...t&&{targetSessionId:t},...u??{}};return await h(e,E,$)},[e,t,h,u]),T=l.useCallback(async(E,I={})=>{const $=t?{targetSessionId:t}:{agentType:r,...n?{ideType:n}:{}};return await A("invoke_provider_script",{...$,scriptName:E,...I})},[A,r,n,t]),M=l.useCallback((E,I,$)=>{const D=av($,I);x(U=>({...U,[E.id]:D})),ov($==null?void 0:$.effects)},[]),L=l.useCallback((E,I)=>{x($=>{const D={...$};return I===void 0?delete D[E.id]:D[E.id]=I,D}),y.current=0},[]);if(!a||a.length===0)return null;const P=$i(a,{hostIdeType:n,providerType:r,currentStatus:c});if(P.length===0)return null;const B=async E=>{if(v===E.id){g(null);return}if(Gr(E,j).length>0){g(E.id);return}if(E.dynamic&&E.listScript){C(E.id);try{const $=await T(E.listScript,{}),D=rv($);if(!D){const ae=En($);ae&&pt.showToast(ae,"warning");return}const U=D.options;S(ae=>{const z={...ae,[E.id]:U};return Vl.set(d,z),z});const Y=cv(E.id,{localOverrideUntil:y.current,localValues:w.current,controlValues:p.current,defaultValues:k});if(lv(Y,D.currentValue)){const ae=D.currentValue;x(z=>({...z,[E.id]:ae}))}g(E.id)}catch($){const D=$ instanceof Error?$.message:`Could not load ${E.label}`;pt.showToast(D,"warning")}finally{C(null)}}},K=async(E,I)=>{g(null);const $=(i==null?void 0:i[E.id])??k[E.id];x(D=>({...D,[E.id]:I})),y.current=Date.now()+5e3;try{if(!E.setScript)return;const D=await T(E.setScript,Zo(E,I)),U=Sr(D);if(U&&!U.ok||Cr(D))throw new Error((U==null?void 0:U.error)||En(D)||`Could not update ${E.label}`);M(E,I,U)}catch(D){L(E,$);const U=D instanceof Error?D.message:`Could not update ${E.label}`;pt.showToast(U,"warning")}},F=async E=>{const I=Gr(E,j).map(z=>z.value);if(I.length===0)return;const $=String(b[E.id]||""),U=(I.indexOf($)+1)%I.length,Y=I[U];if(typeof Y!="string")return;const ae=(i==null?void 0:i[E.id])??k[E.id];x(z=>({...z,[E.id]:Y})),y.current=Date.now()+5e3;try{if(!E.setScript)return;const z=await T(E.setScript,Zo(E,Y)),X=Sr(z);if(X&&!X.ok||Cr(z))throw new Error((X==null?void 0:X.error)||En(z)||`Could not update ${E.label}`);M(E,Y,X)}catch(z){L(E,ae);const X=z instanceof Error?z.message:`Could not update ${E.label}`;pt.showToast(X,"warning")}},R=async E=>{const $=!b[E.id],D=(i==null?void 0:i[E.id])??k[E.id];x(U=>({...U,[E.id]:$})),y.current=Date.now()+5e3;try{if(!E.setScript)return;const U=await T(E.setScript,Zo(E,$)),Y=Sr(U);if(Y&&!Y.ok||Cr(U))throw new Error((Y==null?void 0:Y.error)||En(U)||`Could not update ${E.label}`);M(E,$,Y)}catch(U){L(E,D);const Y=U instanceof Error?U.message:`Could not update ${E.label}`;pt.showToast(Y,"warning")}},Q=async E=>{if(!E.invokeScript)return;if(E.confirmMessage){const $=[E.confirmTitle,E.confirmMessage,E.confirmLabel].filter(U=>typeof U=="string"&&U.trim().length>0);if(!window.confirm($.join(`
37
+
38
+ `)))return}const I=(i==null?void 0:i[E.id])??k[E.id];try{const $=await T(E.invokeScript),D=Sr($);if(D&&!D.ok||Cr($))throw new Error((D==null?void 0:D.error)||En($)||`Could not run ${E.label}`);D&&M(E,I??!0,D)}catch($){L(E,I);const D=$ instanceof Error?$.message:`Could not run ${E.label}`;pt.showToast(D,"warning")}};return s.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-[11px] font-semibold tracking-[0.02em]",style:{borderColor:`${m}33`,background:`${m}12`,color:m},children:o}),P.map(E=>{const I=String(b[E.id]||""),$=mv(E,j,I),D=v===E.id,U=N===E.id,Y=Gr(E,j),ae="inline-flex h-7 max-w-full items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium transition-colors whitespace-nowrap";switch(E.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${ae} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:D?`${m}55`:"var(--border-default)",background:D?`${m}10`:"var(--surface-tertiary)",color:I?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void B(E),title:E.label,children:[E.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:E.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:U?"Loading…":$||E.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),D&&Y.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[var(--z-dropdown)]",onClick:()=>g(null)}),s.jsxs("div",{className:"absolute bottom-full left-0 z-[var(--z-dropdown)] mb-2 min-w-44 overflow-y-auto rounded-xl border border-border-subtle bg-[var(--surface-primary)] shadow-[0_-8px_24px_rgba(0,0,0,0.35)] max-h-[240px]",children:[s.jsx("div",{className:"border-b border-border-subtle px-3 py-2 text-[10px] font-semibold uppercase tracking-[0.08em] text-text-muted",children:E.label}),Y.map(z=>s.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-[12px] transition-colors",style:{background:z.value===I?`${m}14`:"transparent",color:z.value===I?"var(--text-primary)":"var(--text-secondary)",borderLeft:z.value===I?`2px solid ${m}`:"2px solid transparent"},title:z.description||z.label,onMouseEnter:X=>{X.currentTarget.style.background=`${m}10`},onMouseLeave:X=>{X.currentTarget.style.background=z.value===I?`${m}14`:"transparent"},onClick:()=>void K(E,z.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:z.label}),z.value===I&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},z.value))]})]})]},E.id);case"cycle":return s.jsxs("button",{type:"button",className:`${ae} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:I?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void F(E),title:`Click to cycle: ${Y.map(z=>z.label).join(" → ")}`,children:[E.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:E.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:$||E.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},E.id);case"toggle":return s.jsxs("button",{type:"button",className:`${ae} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:I?`${m}44`:"var(--border-default)",background:I?`${m}14`:"var(--surface-tertiary)",color:I?m:"var(--text-muted)"},onClick:()=>void R(E),"aria-pressed":!!I,children:[E.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:E.icon}),E.label]},E.id);case"action":return s.jsxs("button",{type:"button",className:`${ae} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void Q(E),children:[E.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:E.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:E.resultDisplay==="inline"&&I?`${E.label}: ${I}`:E.label})]},E.id);case"display":return s.jsxs("span",{className:"inline-flex h-7 items-center gap-1.5 rounded-full border px-3 text-[12px] font-medium whitespace-nowrap",style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:I?"var(--text-primary)":"var(--text-muted)"},children:[E.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:E.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:I?`${E.label}: ${I}`:E.label})]},E.id);default:return null}})]})})}function gv({isActive:e=!0,isCliTerminal:t=!1,routeId:n,sessionId:r,hostIdeType:o,providerType:a,displayLabel:i,controls:c,controlValues:u,currentStatus:h,coordinatorHint:d}){const{isVisible:m}=Li(),f=$i(c,{hostIdeType:o,providerType:a,currentStatus:h});return!e||t||f.length===0||!m?null:s.jsx("div",{className:"shrink-0 bg-[var(--surface-primary)] border-t border-border-subtle",children:s.jsx(bv,{routeId:n,sessionId:r,hostIdeType:o,providerType:a,displayLabel:i,controls:f,controlValues:u,currentStatus:h,coordinatorHint:d})})}const _n=5,ju=10*1024*1024;function xv({hasDraft:e,isBusy:t=!1}){return!e||t}function yv(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}async function vv(e){if(e.size>ju)return null;const t=await yv(e),n=t.indexOf(",");if(n<0)return null;const r=t.slice(n+1);return{mimeType:e.type||"image/png",data:r,name:e.name,previewUrl:t}}function wv(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}const Nu=l.memo(function({contextKey:t,panelLabel:n,isSending:r,isBusy:o=!1,statusMessage:a=null,inlineStatusMessage:i=null,onSend:c,onForceSend:u,canForceSend:h=!1,isActive:d=!0,showControlsToggle:m=!1,animateVisibility:f=!0,onControlsToggle:x,messageInput:w}){const{t:p}=Le("common"),y=l.useRef(null),k=l.useRef(null),[b,j]=l.useState(""),[S,v]=l.useState([]),[g,N]=l.useState(null),[C,A]=l.useState(!1),T=l.useRef(!1),{isVisible:M,toggleVisibility:L}=Li(),P=wv(w),B=!!b.trim()||S.length>0;l.useEffect(()=>{j(""),v([]),N(null)},[t]),l.useEffect(()=>{var D;d&&((D=y.current)==null||D.focus({preventScroll:!0}))},[t,d]),l.useEffect(()=>{const D=y.current;D&&(D.style.height="auto",D.style.height=`${Math.min(D.scrollHeight,160)}px`)},[b]);const K=l.useCallback(async D=>{N(null);const U=Array.from(D).filter(re=>re.type.startsWith("image/"));if(U.length===0)return;const Y=_n-S.length;if(Y<=0){N(`Max ${_n} images`);return}const ae=U.slice(0,Y);if(ae.filter(re=>re.size>ju).length>0){N("Image too large (max 10 MB)");return}const de=(await Promise.all(ae.map(vv))).filter(re=>re!==null);v(re=>[...re,...de])},[S.length]),F=l.useCallback(D=>{v(U=>U.filter((Y,ae)=>ae!==D))},[]),R=l.useCallback(async()=>{const D=b.trim();if(!D&&S.length===0||o||T.current)return;T.current=!0;const U=S.length>0?[...S]:void 0;try{await c(D,U)!==!1&&(j(""),v([]),N(null))}finally{T.current=!1}},[b,S,o,c]),Q=l.useCallback(async()=>{if(!h||!u)return;const D=b.trim();if(!D&&S.length===0||T.current)return;T.current=!0;const U=S.length>0?[...S]:void 0;try{await u(D,U)!==!1&&(j(""),v([]),N(null))}finally{T.current=!1}},[S,h,b,u]),E=l.useCallback(D=>{P&&(D.preventDefault(),A(!0))},[P]),I=l.useCallback(()=>A(!1),[]),$=l.useCallback(D=>{P&&(D.preventDefault(),A(!1),D.dataTransfer.files.length>0&&K(D.dataTransfer.files))},[P,K]);return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",f?"transition-all duration-200 ease-out":"",C?"ring-1 ring-inset ring-[var(--accent-primary)]":""].filter(Boolean).join(" "),style:{borderTop:d?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:d?200:0,opacity:d?1:0,transform:d?"translateY(0)":"translateY(10px)",padding:d?"10px 12px":"0 12px",pointerEvents:d?"auto":"none"},"aria-hidden":!d,onDragOver:E,onDragLeave:I,onDrop:$,children:[S.length>0&&s.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:S.map((D,U)=>s.jsxs("div",{className:"relative group w-14 h-14 rounded-lg overflow-hidden border border-border-subtle shrink-0",style:{background:"var(--surface-secondary)"},children:[s.jsx("img",{src:D.previewUrl,alt:D.name,className:"w-full h-full object-cover"}),s.jsx("button",{type:"button",onClick:()=>F(U),className:"absolute top-0.5 right-0.5 w-4 h-4 rounded-full bg-black/60 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity text-[10px] leading-none","aria-label":`Remove ${D.name}`,children:"✕"})]},U))}),s.jsxs("div",{className:"flex gap-2 items-center",title:d?`Send message to ${n}`:void 0,children:[m&&s.jsx("button",{type:"button",onClick:()=>{L(),x==null||x()},"aria-label":M?"Hide controls":"Show controls","aria-pressed":M,title:M?"Hide controls":"Show controls",className:"h-10 w-7 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center",children:s.jsxs("svg",{width:"12",height:"18",viewBox:"0 0 12 18",fill:"currentColor","aria-hidden":"true",children:[s.jsx("circle",{cx:"6",cy:"3",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"9",r:"1.2"}),s.jsx("circle",{cx:"6",cy:"15",r:"1.2"})]})}),P&&s.jsxs(s.Fragment,{children:[s.jsx("input",{ref:k,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:D=>{D.target.files&&K(D.target.files),D.target.value=""}}),s.jsx("button",{type:"button",onClick:()=>{var D;return(D=k.current)==null?void 0:D.click()},disabled:S.length>=_n,title:S.length>=_n?`Max ${_n} images`:p("chatInput.attachImage"),className:"h-10 w-8 shrink-0 rounded-full border border-border-subtle bg-bg-secondary text-text-muted hover:text-text-primary hover:bg-[var(--surface-tertiary)] transition-colors flex items-center justify-center disabled:opacity-40","aria-label":p("chatInput.attachImage"),children:s.jsx("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:s.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48"})})})]}),s.jsx("div",{className:"flex-1 relative",children:s.jsx("textarea",{ref:y,rows:1,placeholder:a||(P&&S.length>0?"Add a message (optional)...":p("chatInput.placeholder",{panel:n})),value:b,onChange:D=>j(D.target.value),onPaste:D=>{if(P&&D.clipboardData.files.length>0&&Array.from(D.clipboardData.files).some(oe=>oe.type.startsWith("image/"))){D.preventDefault(),K(D.clipboardData.files);return}const U=D.clipboardData.getData("text/plain"),Y=qm(U);if(Y===U)return;D.preventDefault();const ae=y.current,z=(ae==null?void 0:ae.selectionStart)??b.length,X=(ae==null?void 0:ae.selectionEnd)??b.length,de=b.slice(0,z)+Y+b.slice(X);j(de);const re=z+Y.length;requestAnimationFrame(()=>{ae==null||ae.setSelectionRange(re,re)})},onKeyDown:D=>{D.key==="Enter"&&(D.nativeEvent.isComposing||D.shiftKey||(D.preventDefault(),R()))},className:"w-full rounded-[20px] px-4 py-2 bg-bg-secondary text-sm text-text-primary resize-none leading-[1.4] block",style:{border:"1px solid var(--chat-input-border, var(--border-subtle))",minHeight:40,maxHeight:160,overflowY:"auto",whiteSpace:"pre-wrap"}})}),s.jsx("button",{onClick:()=>{R()},disabled:xv({hasDraft:B,isBusy:o}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${B&&!o?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:B&&!o?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,"aria-label":p("chatInput.sendMessage"),children:s.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",className:B?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})}),h&&s.jsx("button",{type:"button",onClick:()=>{Q()},disabled:!B,className:`h-10 px-3 rounded-full text-[11px] font-medium border border-border-subtle shrink-0 transition-colors ${B?"bg-bg-secondary text-text-primary hover:bg-[var(--surface-tertiary)]":"bg-bg-secondary text-text-muted cursor-default opacity-60"}`,"aria-label":"Force send message now",title:"Force send message now",children:"Force"})]}),(g||P&&C)&&s.jsx("div",{className:`pt-1.5 px-1 text-[11px] ${g?"text-red-400":"text-[var(--accent-primary)]"}`,children:g||p("chatInput.dropImage")}),i&&!g&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:i})]})}),kv=l.createContext(null);function Bi(){return l.useContext(kv)}function Sv(e){return gy(e,{lastCheckedAt:Date.now()})}function Cv(e){const t=Array.isArray(e==null?void 0:e.submodules)?e.submodules:[];let n=!1,r=!1;for(const o of t)o!=null&&o.outOfSync&&(r=!0),o!=null&&o.dirty&&(n=!0);return{dirty:n,outOfSync:r}}function jv(e){return e?(e.staged??0)>0||(e.modified??0)>0||(e.untracked??0)>0||(e.deleted??0)>0||(e.renamed??0)>0||e.hasConflicts===!0:!1}function ro(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=Cv(e);return t.outOfSync?"degraded":t.dirty||jv(e)?"dirty":"online"}function Nv(e,t){const n=t?ro(t):void 0;return!e||e==="unknown"?n:e}function Av(e){const t=Array.isArray(e.activeSessionDetails)?e.activeSessionDetails:Array.isArray(e.active_session_details)?e.active_session_details:Array.isArray(e.sessions)?e.sessions:null;if(t){const a=t.map(Ya).filter(i=>i!==null);if(a.length>0)return a}const n=ft(e.activeSession??e.active_session),r={...n,sessionId:De(n.sessionId,n.id,n.session_id,e.activeSessionId,e.active_session_id,e.sessionId,e.session_id)},o=Ya(r);return o?[o]:void 0}function Tv(e){const t=ft(e.connection);return Object.keys(t).length>0?t:void 0}function Iv(e){const t=e==null?void 0:e.source,n=e==null?void 0:e.transport;return{...e,perspective:(e==null?void 0:e.perspective)??"selected_coordinator",source:t&&t!=="not_reported"?t:"mesh_peer_status",state:"connected",transport:n&&n!=="unknown"?n:"direct",reported:!0,reason:"Live peer git snapshot reported by the selected coordinator."}}function Fi(e){var n;const t=e.git;return!!(t&&(t.isGitRepo===!0||t.isGitRepo===!1||t.branch||t.upstream||t.headCommit||typeof t.lastCheckedAt=="number"||(((n=t.submodules)==null?void 0:n.length)??0)>0))}function Yl(e){var r,o,a,i,c,u;let t=0;const n=e.git;return Fi(e)&&(t+=80,(n==null?void 0:n.isGitRepo)===!0&&(t+=20),(n==null?void 0:n.isGitRepo)===!1&&(t+=5),n!=null&&n.branch&&(t+=20),n!=null&&n.upstream&&(t+=12),n!=null&&n.headCommit&&(t+=12),t+=Ri(n==null?void 0:n.upstreamStatus),typeof(n==null?void 0:n.lastCheckedAt)=="number"&&(t+=6),t+=(((r=n==null?void 0:n.submodules)==null?void 0:r.length)??0)*6),(o=e.branchConvergence)!=null&&o.status&&(t+=12),(((a=e.connection)==null?void 0:a.state)==="connected"||((i=e.connection)==null?void 0:i.state)==="self")&&(t+=8),((c=e.connection)==null?void 0:c.transport)==="direct"&&(t+=4),((u=e.connection)==null?void 0:u.source)==="mesh_peer_status"&&(t+=4),e.health==="online"&&(t+=4),e.health==="dirty"&&(t+=3),e.health==="degraded"&&(t+=2),e.launchReady&&(t+=2),e.gitProbePending&&(t-=40),e.error&&(t-=10),t}function Mv(e,t){var w,p,y,k;const n=Yl(e),o=Yl(t)>n?t:e,a=o===t?e:t,i=o.git??a.git,c=(((w=o.providers)==null?void 0:w.length)??0)>0?o.providers:a.providers,u=(((p=o.activeSessions)==null?void 0:p.length)??0)>0?o.activeSessions:a.activeSessions,h=(((y=o.activeSessionDetails)==null?void 0:y.length)??0)>0?o.activeSessionDetails:a.activeSessionDetails,d=(((k=o.providerPriority)==null?void 0:k.length)??0)>0?o.providerPriority:a.providerPriority,m=o.connection??a.connection,f={...a,...o,machineLabel:o.machineLabel||a.machineLabel,workspace:o.workspace||a.workspace,...o.repoRoot||a.repoRoot?{repoRoot:o.repoRoot||a.repoRoot}:{},...o.daemonId||a.daemonId?{daemonId:o.daemonId||a.daemonId}:{},...o.machineId||a.machineId?{machineId:o.machineId||a.machineId}:{},...o.machineStatus||a.machineStatus?{machineStatus:o.machineStatus||a.machineStatus}:{},health:i&&(!o.health||o.health==="unknown")?ro(i):o.health,providers:c??[],activeSessions:u??[],...h&&h.length>0?{activeSessionDetails:h}:{},...d&&d.length>0?{providerPriority:d}:{},...m?{connection:m}:{},...i?{git:i}:{}},x=ft(o.branchConvergence);return Object.keys(x).length>0?Object.assign(f,{branchConvergence:x}):delete f.branchConvergence,i&&(delete f.gitProbePending,delete f.error),f}function Au(e){const t=ft(e),n=De(t.nodeId,t.id);if(!n)return null;const r=ft(t.cachedStatus),o=Sv(t),a=o?void 0:Or(ft(t.git),t)??Or(t,t),i=o??a,c=i?void 0:Or(ft(r.git),t),u=i??c,h=De(t.machineStatus,t.machine_status,r.machineStatus,r.machine_status),d=De(t.health),m=o?ro(u):Nv(d,i)||(u?ro(u):void 0)||De(r.health)||h||De(t.status)||"unknown",x=(o?void 0:De(t.error))??(i?void 0:De(r.error)),w=Av(t),p=Jo(t.activeSessions),y=(w==null?void 0:w.map(C=>C.sessionId))??[],k=Jo(t.providerPriority),b=_t(t.gitProbePending,t.git_probe_pending),j=i?void 0:b,S=Tv(t),v=ft(t.branchConvergence??t.branch_convergence),g=S==null?void 0:S.state,N=o&&(!(S!=null&&S.reported)||g==="unknown")?Iv(S):S;return{nodeId:n,machineLabel:De(t.machineLabel,t.machine_label,t.hostname,t.daemonId,t.daemon_id,t.machineId,t.machine_id,n)||n,workspace:De(t.workspace,u==null?void 0:u.workspace)||"",...De(t.repoRoot,t.repo_root,u==null?void 0:u.repoRoot)?{repoRoot:De(t.repoRoot,t.repo_root,u==null?void 0:u.repoRoot)}:{},...De(t.daemonId,t.daemon_id)?{daemonId:De(t.daemonId,t.daemon_id)}:{},...De(t.machineId,t.machine_id)?{machineId:De(t.machineId,t.machine_id)}:{},...h?{machineStatus:h}:{},..._t(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:_t(t.isLocalWorktree,t.is_local_worktree)}:{},...De(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:De(t.worktreeBranch,t.worktree_branch)}:{},...De(t.clonedFromNodeId,t.cloned_from_node_id)?{clonedFromNodeId:De(t.clonedFromNodeId,t.cloned_from_node_id)}:{},health:m,...u?{git:u}:{},...j!==void 0?{gitProbePending:j}:{},providers:Jo(t.providers),activeSessions:p.length>0?p:y,...w&&w.length>0?{activeSessionDetails:w}:{},...k.length>0?{providerPriority:k}:{},..._t(t.launchReady)!==void 0?{launchReady:_t(t.launchReady)}:o?{launchReady:!0}:{},...De(t.lastSeenAt,t.last_seen_at,r.lastSeenAt,r.last_seen_at)?{lastSeenAt:De(t.lastSeenAt,t.last_seen_at,r.lastSeenAt,r.last_seen_at)}:{},...De(t.updatedAt,t.updated_at,r.updatedAt,r.updated_at)?{updatedAt:De(t.updatedAt,t.updated_at,r.updatedAt,r.updated_at)}:{},...N?{connection:N}:{},...Object.keys(v).length>0?{branchConvergence:v}:{},...t.scheduling&&typeof t.scheduling=="object"?{scheduling:t.scheduling}:{},..._t(t.autoFastForwardEligible,t.auto_fast_forward_eligible)===!0?{autoFastForwardEligible:!0}:{},...t.worktreeBootstrap&&typeof t.worktreeBootstrap=="object"?{worktreeBootstrap:t.worktreeBootstrap}:{},...t.staleDaemonBuild&&typeof t.staleDaemonBuild=="object"?{staleDaemonBuild:t.staleDaemonBuild}:{},...t.providerVersions&&typeof t.providerVersions=="object"&&!Array.isArray(t.providerVersions)?{providerVersions:t.providerVersions}:{},...De(t.daemonBuildVersion,t.daemon_build_version)?{daemonBuildVersion:De(t.daemonBuildVersion,t.daemon_build_version)}:{},...x?{error:x}:{}}}function Jl(e){const t=new Map;for(const n of e){const r=t.get(n.sessionId);t.set(n.sessionId,r?{...r,...n}:n)}return[...t.values()]}function Tu(e,t){const n=Array.isArray(e.coordinatorSessions)?e.coordinatorSessions:Array.isArray(e.coordinator_sessions)?e.coordinator_sessions:[],r=n.map(Ya).filter(o=>o!==null);return r.length===0?t:t.map(o=>{const a=r.filter(c=>{const u=ft(n.find(f=>{const x=ft(f);return De(x.sessionId,x.session_id,x.id)===c.sessionId})),h=De(u.nodeId,u.node_id),d=De(u.daemonId,u.daemon_id),m=De(u.workspace);return h&&h===o.nodeId?!0:Ws(d,o.daemonId)?!m||!o.workspace||m===o.workspace:!!(m&&o.workspace&&m===o.workspace)});if(a.length===0)return o;const i=Jl([...o.activeSessionDetails??[],...a]);return{...o,activeSessionDetails:i,activeSessions:Jl([...o.activeSessionDetails??[],...a,...(o.activeSessions??[]).map(c=>({sessionId:c}))]).map(c=>c.sessionId)}})}function Dv(e){const t=ft(e);return Array.isArray(t.sessions)||Array.isArray(t.active_session_details)||De(t.daemon_id,t.machine_id,t.repo_root,t.worktree_branch,t.cloned_from_node_id)!==void 0||_t(t.is_local_worktree)!==void 0}function Iu(e){const t=new Map,n=[];for(const r of e){const o=Dv(r)?Au(r)??r:r;if(!(o!=null&&o.nodeId))continue;const a=t.get(o.nodeId);if(!a){t.set(o.nodeId,o),n.push(o);continue}const i=Mv(a,o);t.set(o.nodeId,i);const c=n.findIndex(u=>u.nodeId===o.nodeId);c>=0&&(n[c]=i)}return n}function Mu(e){const t=e??{},n=Iu(t.nodes??[]);return{...t,nodes:Tu(t,n)}}function Pv(e){var n;const t=e==null?void 0:e.git;return{nodeId:(e==null?void 0:e.nodeId)??null,chosenSource:t?"live_git":e!=null&&e.gitProbePending?"pending_git":"no_git",hasLiveGit:Fi(e??{git:void 0}),branch:(t==null?void 0:t.branch)??null,upstream:(t==null?void 0:t.upstream)??null,headCommit:(t==null?void 0:t.headCommit)??null,submoduleCount:((n=t==null?void 0:t.submodules)==null?void 0:n.length)??0,pendingGit:(e==null?void 0:e.gitProbePending)===!0,connection:e!=null&&e.connection?{state:e.connection.state,transport:e.connection.transport,source:e.connection.source}:null}}function Lv(e){const t=De(e.meshId,e.mesh_id,e.id),n=e.nodes,r=Array.isArray(n)?n.map(u=>Au(u)).filter(u=>u!==null):null;if(!t||!r)return null;const o=Tu(e,Iu(r)),a=De(e.meshName,e.mesh_name,e.name),i=De(e.repoIdentity,e.repo_identity),c=De(e.refreshedAt,e.refreshed_at,e.updatedAt,e.updated_at);return!a||!i||!c?null:{...e,meshId:t,meshName:a,repoIdentity:i,refreshedAt:c,nodes:o}}function Rv(e){var a;let t=0;const n=ft(e.sourceOfTruth),r=ft(n.directPeerTruth);De(n.currentStatus)==="live_git_and_session_probes"&&(t+=100),n.coordinatorOwnsLiveTruth===!0&&(t+=25),r.satisfied===!0&&(t+=15);for(const i of e.nodes){const c=i.git;if(!c){i.gitProbePending&&(t-=8);continue}t+=10,c.isGitRepo===!0&&(t+=5),c.isGitRepo===!1&&(t+=1),c.branch&&(t+=4),c.upstream&&(t+=3),c.headCommit&&(t+=3),t+=Ri(c.upstreamStatus),typeof c.ahead=="number"&&(t+=1),typeof c.behind=="number"&&(t+=1),typeof c.lastCheckedAt=="number"&&(t+=2),t+=(((a=c.submodules)==null?void 0:a.length)??0)*2}return t}function Ev(e){const t=e.refreshedAt;if(typeof t!="string"||t.length===0)return 0;const n=Date.parse(t);return Number.isFinite(n)?n:0}const _v=20;function Ql(e){let t=null;for(const n of e){const r=Lv(ft(n));if(!r)continue;const o=Rv(r),a=Ev(r);if(!t){t={status:r,score:o,refreshedAt:a};continue}(Math.abs(o-t.score)<=_v?a>t.refreshedAt||a===t.refreshedAt&&o>t.score:o>t.score)&&(t={status:r,score:o,refreshedAt:a})}return(t==null?void 0:t.status)??null}function Hi(e){const n=!!(e&&typeof e=="object"&&"result"in e)?e==null?void 0:e.result:e,r=Ql([n==null?void 0:n.status,n]);return r||Ql([e==null?void 0:e.status,e])}function $v(e){var r;if(!e)return null;const t=(r=e.coordinator)==null?void 0:r.meshId;if(typeof t=="string"&&t.trim())return t.trim();const n=e.settings||{};for(const o of["meshNodeFor","meshCoordinatorFor"]){const a=n[o];if(typeof a=="string"&&a.trim())return a.trim()}return null}function Bv(e){const t=(e==null?void 0:e.settings)||{};for(const n of["meshNodeId","nodeId"]){const r=t[n];if(typeof r=="string"&&r.trim())return r.trim()}return null}function Fv(e,t){var o;if(!t)return null;const n=Hi(e),r=(o=n==null?void 0:n.nodes)==null?void 0:o.find(a=>vy(a,t));return r?{nodeId:r.nodeId,workspace:r.workspace,repoRoot:r.repoRoot,daemonId:r.daemonId,role:r.role,machineStatus:r.machineStatus,health:r.health,isLocalWorktree:r.isLocalWorktree,worktreeBranch:r.worktreeBranch,launchReady:r.launchReady,providers:r.providers,providerPriority:r.providerPriority,git:r.git?{branch:r.git.branch,headCommit:r.git.headCommit,ahead:r.git.ahead,behind:r.git.behind,dirty:r.git.dirty,upstream:r.git.upstream}:void 0,connection:r.connection?{transport:r.connection.transport,state:r.connection.state,rttMs:r.connection.rttMs}:void 0}:null}const Hv={sm:"max-w-md",md:"max-w-lg",lg:"max-w-3xl"};function Du({open:e,onClose:t,size:n="md",title:r,footer:o,children:a,showClose:i=!0,closeOnBackdrop:c=!0,closeOnEsc:u=!0,ariaLabel:h,className:d,contentClassName:m}){l.useEffect(()=>{if(!e||!u)return;const p=y=>{y.key==="Escape"&&t()};return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[e,u,t]);const f=l.useCallback(p=>{c&&p.target===p.currentTarget&&t()},[c,t]);if(!e)return null;const x=r!=null||i,w=s.jsx("div",{className:Ht("fixed inset-0 flex items-center justify-center bg-black/60 p-4",d),style:{zIndex:"var(--z-modal-backdrop)"},onClick:f,children:s.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":r==null?h:void 0,className:Ht("relative flex max-h-[calc(100dvh-2rem)] w-full flex-col overflow-hidden","rounded-xl border border-border-default bg-surface-primary shadow-2xl",Hv[n],m),style:{zIndex:"var(--z-modal)"},onClick:p=>p.stopPropagation(),children:[x&&s.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-4 border-b border-border-default px-5 py-4",children:[s.jsx("div",{className:"min-w-0",children:typeof r=="string"||typeof r=="number"?s.jsx("h2",{className:"truncate text-lg font-bold text-text-primary",children:r}):r}),i&&s.jsx("button",{type:"button",onClick:t,className:"btn btn-ghost btn-sm h-8 w-8 shrink-0 p-0","aria-label":"Close dialog",children:s.jsx(At,{size:16})})]}),s.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-5 py-4",children:a}),o!=null&&s.jsx("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border-default px-5 py-4",children:o})]})});return typeof document>"u"?w:fn.createPortal(w,document.body)}function Xl(e){if(!e||!Number.isFinite(e))return"—";try{return`${new Date(e).toLocaleString()} (${e})`}catch{return String(e)}}function Zl(e){if(!e)return"";const t=Date.now()-e;if(t<0)return"";const n=Math.floor(t/1e3);if(n<60)return`${n}s ago`;const r=Math.floor(n/60);if(r<60)return`${r}m ago`;const o=Math.floor(r/60);return o<24?`${o}h ago`:`${Math.floor(o/24)}d ago`}function Wv({sessionId:e,daemonId:t,conv:n,onClose:r}){var g,N;const{t:o}=Le("common"),{sendCommand:a}=yt(),i=Bi(),[c,u]=l.useState(!0),[h,d]=l.useState(null),[m,f]=l.useState(null),[x,w]=l.useState(null),[p,y]=l.useState(null),k=l.useMemo(()=>$v(n),[n]),b=l.useMemo(()=>Bv(n),[n]),j=l.useCallback(async()=>{u(!0),f(null);try{const C=await a(t,"get_session_info",{targetSessionId:e}),A=C&&typeof C=="object"?C:{},T=A.result&&typeof A.result=="object"?A.result:A;T!=null&&T.success?d(T):(f((T==null?void 0:T.error)||o("sessionInfo.failedToLoad")),d(null))}catch(C){f((C==null?void 0:C.message)||String(C)),d(null)}finally{u(!1)}},[a,t,e]);l.useEffect(()=>{j()},[j]);const S=l.useCallback(async()=>{if(w(null),y(null),!(!k||!b||!(i!=null&&i.loadMeshStatus)))try{const C=await i.loadMeshStatus(t,k,{refresh:!1}),A=Fv(C,b);if(!A){y(o("sessionInfo.stampedToNode"));return}w(A)}catch(C){y((C==null?void 0:C.message)||"Failed to load mesh node info")}},[i,t,k,b]);l.useEffect(()=>{S()},[S]);const v=s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",onClick:()=>void j(),className:"px-3 py-1 text-sm rounded border border-border-default hover:bg-surface-secondary",children:o("sessionInfo.refresh")}),s.jsx("button",{type:"button",onClick:r,className:"px-3 py-1 text-sm rounded bg-accent text-white hover:opacity-90",children:o("sessionInfo.close")})]});return s.jsx(Du,{open:!0,onClose:r,title:o("sessionInfo.title"),size:"lg",footer:v,children:s.jsxs("div",{className:"text-sm space-y-4",children:[c&&s.jsx("div",{className:"text-text-secondary",children:o("sessionInfo.loading")}),m&&s.jsx("div",{className:"text-red-500",children:m}),(h==null?void 0:h.session)&&s.jsxs(on,{title:o("sessionInfo.sectionSession"),children:[s.jsx(nt,{k:o("sessionInfo.rowSessionId"),v:s.jsx(Mt,{children:h.session.sessionId})}),s.jsx(nt,{k:o("sessionInfo.rowProvider"),v:`${h.session.providerName||h.session.providerType} (${h.session.providerType})`}),h.session.transport&&s.jsx(nt,{k:o("sessionInfo.rowTransport"),v:h.session.transport}),h.session.workspace&&s.jsx(nt,{k:o("sessionInfo.rowWorkspace"),v:s.jsx(Mt,{children:h.session.workspace})}),s.jsx(nt,{k:o("sessionInfo.rowSpawnedAt"),v:s.jsxs(s.Fragment,{children:[Xl(h.session.spawnedAtMs),h.session.spawnedAtMs?s.jsx("span",{className:"text-text-secondary ml-2",children:Zl(h.session.spawnedAtMs)}):null]})}),h.session.providerSessionId&&s.jsx(nt,{k:o("sessionInfo.rowProviderSessionId"),v:s.jsx(Mt,{children:h.session.providerSessionId})}),!h.session.workspace&&(n==null?void 0:n.workspacePath)&&s.jsx(nt,{k:o("sessionInfo.rowWorkspace"),v:s.jsx(Mt,{children:n.workspacePath})}),(n==null?void 0:n.machineName)&&s.jsx(nt,{k:o("sessionInfo.rowMachine"),v:n.machineName}),(n==null?void 0:n.connectionState)&&s.jsx(nt,{k:o("sessionInfo.rowConnection"),v:n.connectionState}),(n==null?void 0:n.git)&&s.jsx(nt,{k:o("sessionInfo.rowWorkspaceGit"),v:s.jsxs("span",{children:[n.git.branch||"(detached)",n.git.ahead?` ↑${n.git.ahead}`:"",n.git.behind?` ↓${n.git.behind}`:"",n.git.dirty?" · dirty":" · clean"]})})]}),((g=h==null?void 0:h.session)==null?void 0:g.launch)&&s.jsxs(on,{title:o("sessionInfo.sectionLaunch"),children:[h.session.launch.command&&s.jsx(nt,{k:o("sessionInfo.rowCommand"),v:s.jsx(Mt,{children:h.session.launch.command})}),h.session.launch.cwd&&s.jsx(nt,{k:o("sessionInfo.rowWorkingDirectory"),v:s.jsx(Mt,{children:h.session.launch.cwd})}),Array.isArray(h.session.launch.args)&&h.session.launch.args.length>0&&s.jsx(nt,{k:o("sessionInfo.rowArgs"),v:s.jsx(Mt,{children:h.session.launch.args.join(" ")})}),Array.isArray(h.session.launch.extraArgs)&&h.session.launch.extraArgs.length>0&&s.jsx(nt,{k:o("sessionInfo.rowExtraArgs"),v:s.jsx(Mt,{children:h.session.launch.extraArgs.join(" ")})}),Array.isArray(h.session.launch.extraEnvKeys)&&h.session.launch.extraEnvKeys.length>0&&s.jsx(nt,{k:o("sessionInfo.rowExtraEnv"),v:s.jsx(Mt,{children:h.session.launch.extraEnvKeys.join(", ")})})]}),x&&s.jsxs(on,{title:o("sessionInfo.sectionMeshNode"),children:[x.nodeId&&s.jsx(nt,{k:o("sessionInfo.rowNodeId"),v:s.jsx(Mt,{children:x.nodeId})}),x.workspace&&s.jsx(nt,{k:o("sessionInfo.rowWorkspace"),v:s.jsx(Mt,{children:x.workspace})}),x.repoRoot&&x.repoRoot!==x.workspace&&s.jsx(nt,{k:o("sessionInfo.rowRepoRoot"),v:s.jsx(Mt,{children:x.repoRoot})}),x.daemonId&&s.jsx(nt,{k:o("sessionInfo.rowDaemonId"),v:s.jsx(Mt,{children:x.daemonId})}),x.role&&s.jsx(nt,{k:o("sessionInfo.rowRole"),v:x.role}),x.machineStatus&&s.jsx(nt,{k:o("sessionInfo.rowMachineStatus"),v:x.machineStatus}),x.health&&s.jsx(nt,{k:o("sessionInfo.rowHealth"),v:x.health}),x.isLocalWorktree&&s.jsx(nt,{k:o("sessionInfo.rowWorktree"),v:x.worktreeBranch?s.jsx(Mt,{children:x.worktreeBranch}):"yes"}),typeof x.launchReady=="boolean"&&s.jsx(nt,{k:o("sessionInfo.rowLaunchReady"),v:x.launchReady?"yes":"no"}),x.git&&s.jsx(nt,{k:o("sessionInfo.rowGit"),v:s.jsxs("span",{children:[x.git.branch||"(detached)",x.git.headCommit?` @ ${String(x.git.headCommit).slice(0,10)}`:"",x.git.ahead?` ↑${x.git.ahead}`:"",x.git.behind?` ↓${x.git.behind}`:"",x.git.dirty?" · dirty":" · clean",x.git.upstream?` · ${x.git.upstream}`:""]})}),x.connection&&s.jsx(nt,{k:"Connection",v:s.jsxs("span",{children:[x.connection.transport||"—",x.connection.state?` · ${x.connection.state}`:"",typeof x.connection.rttMs=="number"?` · ${x.connection.rttMs}ms RTT`:""]})}),Array.isArray(x.providers)&&x.providers.length>0&&s.jsx(nt,{k:o("sessionInfo.rowProviders"),v:s.jsx(Mt,{children:x.providers.join(", ")})}),Array.isArray(x.providerPriority)&&x.providerPriority.length>0&&s.jsx(nt,{k:o("sessionInfo.rowProviderPriority"),v:s.jsx(Mt,{children:x.providerPriority.join(" › ")})})]}),!x&&p&&(k||b)&&s.jsx(on,{title:o("sessionInfo.sectionMeshNode"),children:s.jsx("div",{className:"text-text-secondary italic",children:p})}),(h==null?void 0:h.coordinator)&&s.jsxs(on,{title:o("sessionInfo.sectionMeshCoordinator"),children:[s.jsx(nt,{k:o("sessionInfo.rowMeshId"),v:s.jsx(Mt,{children:h.coordinator.meshId})}),h.coordinator.cliType&&s.jsx(nt,{k:o("sessionInfo.rowCoordinatorCli"),v:h.coordinator.cliType}),s.jsx(nt,{k:o("sessionInfo.rowStartedAt"),v:s.jsxs(s.Fragment,{children:[Xl(h.coordinator.startedAt),h.coordinator.startedAt?s.jsx("span",{className:"text-text-secondary ml-2",children:Zl(h.coordinator.startedAt)}):null]})}),h.coordinator.injection&&s.jsx(nt,{k:o("sessionInfo.rowPromptInjection"),v:`${h.coordinator.injection.mode}${h.coordinator.injection.target?` → ${h.coordinator.injection.target}`:""}`}),h.coordinator.mcpConfigPath&&s.jsx(nt,{k:o("sessionInfo.rowMcpConfig"),v:s.jsx(Mt,{children:h.coordinator.mcpConfigPath})}),h.coordinator.extraSystemPrompt&&s.jsx(ei,{title:"Per-launch extra prompt",body:h.coordinator.extraSystemPrompt,defaultOpen:!0}),h.coordinator.systemPrompt&&s.jsx(ei,{title:"Final system prompt (click to expand)",body:h.coordinator.systemPrompt})]}),((N=h==null?void 0:h.session)==null?void 0:N.runtimeMetadata)!=null&&s.jsx(Ov,{meta:h.session.runtimeMetadata}),h&&!h.coordinator&&s.jsx("div",{className:"text-text-secondary italic",children:o("sessionInfo.notCoordinatorSession")})]})})}function on({title:e,children:t}){return s.jsxs("div",{children:[s.jsx("h3",{className:"text-xs uppercase tracking-wide text-text-secondary mb-1",children:e}),s.jsx("div",{className:"space-y-1",children:t})]})}function nt({k:e,v:t}){return s.jsxs("div",{className:"flex flex-col sm:flex-row gap-1 sm:gap-3",children:[s.jsx("div",{className:"w-full sm:w-36 sm:shrink-0 text-text-secondary font-medium sm:font-normal",children:e}),s.jsx("div",{className:"min-w-0 break-all",children:t})]})}function Mt({children:e}){return s.jsx("code",{className:"font-mono text-xs",children:e})}function Ov({meta:e}){const{t}=Le("common");if(!e||typeof e!="object")return null;const n=e,r=h=>typeof h=="string"&&h.trim()?h:null,o=r(n.runtimeId),a=r(n.lifecycle),i=r(n.surfaceKind),c=r(n.recoveryState),u=Array.isArray(n.attachedClients)?n.attachedClients.length:null;return s.jsxs(on,{title:t("sessionInfo.sectionRuntime"),children:[o&&s.jsx(nt,{k:t("sessionInfo.rowRuntimeId"),v:s.jsx(Mt,{children:o})}),a&&s.jsx(nt,{k:t("sessionInfo.rowLifecycle"),v:a}),i&&s.jsx(nt,{k:t("sessionInfo.rowSurface"),v:i}),c&&s.jsx(nt,{k:t("sessionInfo.rowRecoveryState"),v:c}),typeof n.restoredFromStorage=="boolean"&&s.jsx(nt,{k:t("sessionInfo.rowRestoredFromStorage"),v:n.restoredFromStorage?"yes":"no"}),u!=null&&s.jsx(nt,{k:t("sessionInfo.rowAttachedClients"),v:String(u)}),s.jsx(ei,{title:"Raw runtime metadata (click to expand)",body:Uv(e)})]})}function Uv(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function ei({title:e,body:t,defaultOpen:n=!1}){const[r,o]=l.useState(n);return s.jsxs("div",{className:"mt-2",children:[s.jsxs("button",{type:"button",onClick:()=>o(a=>!a),className:"text-xs uppercase tracking-wide text-text-secondary hover:text-text-primary",style:{pointerEvents:"auto"},children:[r?"▾":"▸"," ",e]}),r&&s.jsx("pre",{className:"mt-1 p-2 bg-[var(--surface-secondary)] border border-border-subtle rounded text-xs whitespace-pre-wrap overflow-x-auto max-h-96 overflow-y-auto",children:t})]})}function Gv({sessionId:e,daemonId:t,conv:n}){const[r,o]=l.useState(!1);return!e||!t?null:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",onClick:()=>o(!0),title:"Session info — launch args, mesh node, system prompt, …","aria-label":"Session info",className:"inline-flex items-center justify-center w-6 h-6 rounded-full text-text-secondary hover:text-text-primary hover:bg-surface-secondary text-sm leading-none",style:{pointerEvents:"auto"},children:"ⓘ"}),r&&s.jsx(Wv,{sessionId:e,daemonId:t,conv:n,onClose:()=>o(!1)})]})}const Kv=8e3;function zv({sessionId:e,daemonId:t,muted:n,sendDaemonCommand:r}){const{t:o}=Le("common"),[a,i]=l.useState(null),c=l.useRef(null);if(l.useEffect(()=>{a!==null&&n===a&&i(null)},[n,a]),l.useEffect(()=>()=>{c.current&&clearTimeout(c.current)},[]),!e||!t)return null;const u=a!==null?a:n,h=()=>{const d=!u;i(d),c.current&&clearTimeout(c.current),c.current=setTimeout(()=>i(null),Kv),r(t,"set_conversation_prefs",{sessionId:e,muted:d}).catch(m=>{console.warn("[conversation-prefs] toggle mute failed",m),i(null)})};return s.jsx("button",{type:"button",onClick:h,"aria-label":o(u?"conversation.unmuteThis":"conversation.muteThis"),"aria-pressed":u,title:o(u?"conversation.mutedTitle":"conversation.muteTitle"),className:`inline-flex items-center justify-center w-6 h-6 rounded-full leading-none transition-colors ${u?"bg-amber-500 text-white hover:bg-amber-600":"text-text-secondary hover:text-text-primary hover:bg-surface-secondary"}`,style:{pointerEvents:"auto"},children:u?s.jsx(Xd,{size:13}):s.jsx(Nn,{size:13})})}function Pu(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}function Lu(e,t){return t!=null&&t.hasLiveSnapshot?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function qv(e){const t=String(e.role||"").toLowerCase();if(t!=="user"&&t!=="assistant")return!1;const n=String(e.kind||"standard").toLowerCase();return n===""||n==="standard"}function ea(e){return qv(e)?String(e.role||"").toLowerCase():""}const Vv=4;function Yv(e,t){if(e.length===0)return[];for(let a=t.length-1;a>=0;a-=1)if(ea(t[a])==="assistant")return[];const n=t.some(a=>ea(a)==="user"),r=[];let o=!1;for(let a=e.length-1;a>=0&&r.length<Vv;a-=1){const i=e[a],c=ea(i);if(c){if(!o&&c==="assistant"){r.unshift(i),o=!0;continue}if(o&&c==="user"){n||r.unshift(i);break}}}return r}function Jv(e){return e.map((t,n)=>({message:t,index:n,ts:Pu(t)})).sort((t,n)=>t.ts-n.ts||t.index-n.index).map(t=>t.message)}function Qv(e){const{historyMessages:t,liveMessages:n,visibleLiveCount:r}=e,o=Math.max(0,n.length-r),a=o>0?n.slice(0,o):[],i=o>0?n.slice(-r):n,c=Yv(a,i),u=c.length>0?[...c,...i]:i,h=t.length===0?u:[...t,...u];return Jv(h)}const ct=e=>e.transport==="pty",Tn=(e,t)=>ct(e)&&e.mode||"chat",Ru=(e,t)=>ct(e)&&Tn(e)==="terminal",lt=e=>e.transport==="acp",Xv=180;function Ms(e){return e.streamSource!=="agent-stream"}function Ps(e){var t;return e.daemonId||((t=e.routeId)==null?void 0:t.split(":")[0])||e.routeId||""}function Do(e){var n;const t=typeof((n=e.settings)==null?void 0:n.meshCoordinatorDaemonId)=="string"?e.settings.meshCoordinatorDaemonId:void 0;return t?{meshCoordinatorDaemonId:t}:{}}function Eu(e){return e.machineName||""}function en(e){return Ps(e)}function bs(e){return e.agentType||""}function oo(e){return e.hostIdeType||""}function Wi(e){return e.displayPrimary||e.agentName||"Agent"}function _u(e){return e.title||e.displayPrimary||e.agentName||e.tabKey||e.routeId||"Session"}function Zv(e,t){const n=Lu(e,t);return[...n].reverse().find(r=>!(r!=null&&r._localId))||n[n.length-1]}function $u(e,t){const n=Zv(e,t),r=gn(n==null?void 0:n.content),o=gn(e.lastMessagePreview);return o&&e.lastMessageRole==="assistant"&&(n==null?void 0:n.role)==="user"?o:r||o||""}function ew(e,t=Xv){const n=gn(e);if(!n||t<=0)return"";const r=Array.from(n);return r.length<=t?n:`${r.slice(0,Math.max(0,t-1)).join("").trimEnd()}…`}function tw(e){return ew($u(e)||e.displaySecondary||"")}function Bu(e){return[e.displaySecondary,Eu(e)].filter(Boolean)}function yn(e){return e.agentName||$t(bs(e))}function sw(e){var t,n;if(!Ms(e)){const r=(n=(t=e.displaySecondary)==null?void 0:t.split("·")[0])==null?void 0:n.trim();if(r)return r}return $t(oo(e)||bs(e))}function Fu(e){return Ms(e)?e.sessionId:e.nativeSessionId}function ec(e){return Ms(e)?"native":e.tabKey}function nw(e){return e.sessionId}function rw(e,t){if(t)return Ms(e)||!t.childSessions?t:t.childSessions.find(n=>n.id===e.sessionId||n.providerType===e.agentType)||t}function ow(e,t){const n=bs(e),r=Ms(e),o=ct(e)||lt(e),a=r?o?yn(e)||(t==null?void 0:t.cliName)||$t(oo(e)||n):t!=null&&t.type?$t(t.type):$t(oo(e)||n):yn(e);return{isNativeConversation:r,isCli:ct(e),isAcp:lt(e),isCliTerminal:Ru(e),providerType:n,displayLabel:a,targetEntry:rw(e,t)}}function Os(e){if(!e)return{};const t=e.sessionId?{targetSessionId:e.sessionId}:{};return e.sessionId?t:ct(e)||lt(e)?{agentType:bs(e)}:e.streamSource==="agent-stream"?{agentType:bs(e)}:t}function Us(e){return e?en(e):""}function an(e,t){e(n=>[...n,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function Oi(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function tc(e){const t=e instanceof Error?e.message:String(e||""),n=t.toLowerCase();return n.includes("still processing the previous prompt")?"Message queued and will send after the current reply finishes.":n.includes("awaiting confirmation")?"Resolve the pending approval prompt before sending another message.":n.includes("not ready")?"Wait for the runtime to finish starting up before sending a message.":n.includes("not running")?"Runtime is not available right now.":t||"Unable to send message right now."}function Hu(){return"select_session"}function aw(){return"open_panel"}function iw({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function sc(e,t,n=2e3){return e?e.tabKey===t.tabKey&&e.message===t.message&&t.timestamp-e.timestamp<n:!1}function jr(e,t){return e?e.tabKey===t.tabKey&&e.message===t.message&&e.timestamp===t.timestamp?null:e:null}function er(e){return!e||typeof e!="object"?e:e.result&&typeof e.result=="object"?e.result:e}function Ui(e){return e instanceof Error?e.message:String(e||"")}function nc(e){const t=Ui(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function rc(e,t){const n=Ui(t);return n?n.toLowerCase().includes("button not found")?`⚠️ **${e}** failed — button not found`:`⚠️ **${e}** failed — ${n}`:`⚠️ **${e}** unavailable`}function oc(e,t,n,r={}){const o=Os(n);if(!t||t.length===0)return{message:e,...r.force?{force:!0}:{},...o};const a=t.map(i=>({type:"image",mimeType:i.mimeType,data:i.data,alt:i.name}));return e&&a.push({type:"text",text:e}),{message:e,input:{parts:a,textFallback:e},...r.force?{force:!0}:{},...o}}function Po({sendDaemonCommand:e,activeConv:t,setActionLogs:n,isStandalone:r}){const[o,a]=l.useState(!1),[i,c]=l.useState(!1),[u,h]=l.useState(null),d=l.useRef(!1),m=l.useRef(null);l.useEffect(()=>{h(null)},[t==null?void 0:t.tabKey]);const f=l.useCallback(async(k,b)=>{if(!t||d.current)return!1;const j=k.trim(),S=Oi(t);if(iw({hasMessage:!!j,blockedMessage:S,sendInFlight:d.current}))return S&&h(S),!1;const v=Date.now(),g={tabKey:t.tabKey,message:j,timestamp:v};if(sc(m.current,g))return h(null),!0;d.current=!0,c(!0),h(null),m.current=g;try{const N=Us(t);if(!N)return m.current=jr(m.current,g),h("Unable to send message right now."),!1;const C=await e(N,"send_chat",oc(j,b,t)),A=er(C);if(A!=null&&A.deduplicated)return h(null),!0;if((A==null?void 0:A.sent)===!1)throw new Error((A==null?void 0:A.error)||"Send failed");if((A==null?void 0:A.success)===!1)throw new Error((A==null?void 0:A.error)||"Send failed");return h(null),!0}catch(N){const C=Ui(N);return C.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",C):console.warn("Send blocked/failed",N),m.current=jr(m.current,g),h(tc(N)),!1}finally{d.current=!1,c(!1)}},[t,e]),x=l.useCallback(async(k,b)=>{if(!t||d.current)return!1;const j=k.trim();if(!j&&(!b||b.length===0))return!1;const S=Date.now(),v={tabKey:t.tabKey,message:`force:${j}`,timestamp:S};if(sc(m.current,v))return h(null),!0;d.current=!0,c(!0),h(null),m.current=v;try{const g=Us(t);if(!g)return m.current=jr(m.current,v),h("Unable to send message right now."),!1;const N=await e(g,"send_chat",oc(j,b,t,{force:!0})),C=er(N);if((C==null?void 0:C.success)===!1||(C==null?void 0:C.sent)===!1)throw new Error((C==null?void 0:C.error)||"Send failed");return h(null),!0}catch(g){return console.warn("Force send blocked/failed",g),m.current=jr(m.current,v),h(tc(g)),!1}finally{d.current=!1,c(!1)}},[t,e]),w=l.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(k){console.error("Relaunch failed",k)}},[t,e]),p=l.useCallback(async k=>{if(t)try{const j=(t.modalButtons||[]).indexOf(k),S=k.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),v=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(S),g=Us(t);if(!g)return;const N=await e(g,"resolve_action",{button:k,action:v?"approve":"reject",...j>=0&&{buttonIndex:j},...Os(t),...Do(t)}),C=er(N);C.success||n(A=>[...A,{routeId:t.tabKey,text:rc(k,C==null?void 0:C.error),timestamp:Date.now()}])}catch(b){nc(b)||console.error("[ModalButton] Error:",b),n(j=>[...j,{routeId:t.tabKey,text:nc(b)?rc(k,b):`❌ **${k}** error`,timestamp:Date.now()}])}},[t,e,n]),y=l.useCallback(async()=>{if(!(!t||o)){a(!0);try{await e(t.routeId,aw(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(k){console.error("Focus agent failed",k)}finally{a(!1)}}},[t,o,e]);return{isSendingChat:i,sendFeedbackMessage:u,isFocusingAgent:o,handleSendChat:f,handleForceSendChat:x,handleRelaunch:w,handleModalButton:p,handleFocusAgent:y}}const lw=10,cw=8e3,dw=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function uw(e){return e.replace(/(Authorization\s*:\s*Bearer\s+)[^\s'"`]+/gi,"$1[REDACTED:bearer]").replace(/(Bearer\s+)[A-Za-z0-9._~+\/-]{12,}=*/gi,"$1[REDACTED:bearer]").replace(/\b(?:gh[pousr]|github_pat)_[A-Za-z0-9_]{20,}\b/g,"[REDACTED:github-token]").replace(/\bsk-[A-Za-z0-9_-]{12,}\b/g,"[REDACTED:api-key]").replace(/\b(?:adk|adm)_[A-Za-z0-9_-]{12,}\b/g,"[REDACTED:adhdev-token]").replace(/((?:api[_-]?key|token|secret|password|passwd|client[_-]?secret)\s*[:=]\s*)[^\s,'"`}&]+/gi,"$1[REDACTED:secret]").replace(/([?&](?:api[_-]?key|token|secret|password|client_secret)=)[^&#\s]+/gi,"$1[REDACTED:secret]")}function ti(e,t="",n=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(dw.test(t)&&e.trim())return"[REDACTED:secret-field]";const r=uw(e);return r.length>8e3?`${r.slice(0,8e3)}…[truncated ${r.length-8e3} chars]`:r}if(typeof e!="object")return String(e);if(n>=6)return"[MaxDepth]";if(Array.isArray(e)){const r=e.slice(-20).map(o=>ti(o,t,n+1));return e.length>20?[{truncatedBefore:e.length-20},...r]:r}return Object.fromEntries(Object.entries(e).slice(0,80).map(([r,o])=>[r,ti(o,r,n+1)]))}function $n(e,t){return Array.isArray(e)?e.slice(-t):[]}function hw(e,t=Date.now()){const n=e&&t-e.firstAt<=cw,r=n?e.count+1:1;return r>=lw?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:r,firstAt:n?e.firstAt:t},shouldCollect:!1}}function Wu(e){var r,o;const{activeConv:t}=e,n={version:1,createdAt:new Date(e.now??Date.now()).toISOString(),url:e.locationHref??(typeof window<"u"?window.location.href:void 0),activeConversation:{routeId:t.routeId,tabKey:t.tabKey,sessionId:t.sessionId,providerSessionId:t.providerSessionId,transport:t.transport,agentName:t.agentName,agentType:t.agentType,hostIdeType:t.hostIdeType,status:t.status,connectionState:t.connectionState,title:t.title,workspaceName:t.workspaceName,displayPrimary:t.displayPrimary,displaySecondary:t.displaySecondary,streamSource:t.streamSource,lastMessageHash:t.lastMessageHash},messageCounts:{live:((r=e.chatTailState.liveMessages)==null?void 0:r.length)??t.messages.length,activeConversation:t.messages.length,visible:e.visibleMessages.length,history:((o=e.chatTailState.historyMessages)==null?void 0:o.length)||0,hiddenLive:e.ui.hiddenLiveCount},liveMessagesTail:$n(e.chatTailState.liveMessages??t.messages,10),activeConversationMessagesTail:$n(t.messages,10),visibleMessagesTail:$n(e.visibleMessages,5),historyMessagesTail:$n(e.chatTailState.historyMessages,5),actionLogsTail:$n(e.actionLogs.filter(a=>a.routeId===t.tabKey),20),controls:{visibleBarControlCount:e.visibleBarControlCount,definitions:e.controls||[],values:e.controlValues||{},visible:e.ui.controlsVisible},chatTail:{hasLiveSnapshot:!!e.chatTailState.hasLiveSnapshot,hasMoreHistory:!!e.chatTailState.hasMoreHistory,historyError:e.chatTailState.historyError||null},ui:e.ui,browser:typeof navigator<"u"?{userAgent:navigator.userAgent,language:navigator.language,online:navigator.onLine}:null};return ti(n)}function Ou(e,t={}){const n=e&&typeof e=="object"?e:{},r=t.locatorCopyStatus??(t.locatorCopied===!1?"failed":"copied"),o=r==="copied"?"locator copied":r==="manual"?"locator shown for manual copy":"locator copy failed";return n.delivery==="daemon_file"?`Chat debug signal sent${typeof n.bundleId=="string"&&n.bundleId.trim()?` (${n.bundleId})`:""}; saved on daemon, ${o}.`:`Chat debug signal sent; ${o}.`}async function Uu(e){var t;if(typeof navigator<"u"&&((t=navigator.clipboard)!=null&&t.writeText)&&typeof window<"u"&&window.isSecureContext)try{return await navigator.clipboard.writeText(e),"copied"}catch(n){console.warn("[chat-debug-bundle] clipboard API failed, trying execCommand fallback",n)}if(typeof document<"u"&&document.body){let n=null;try{if(n=document.createElement("textarea"),n.value=e,n.setAttribute("readonly","true"),n.style.cssText="position:fixed;left:-9999px;top:0",document.body.appendChild(n),n.focus(),n.select(),document.execCommand("copy"))return"copied"}catch{}finally{n==null||n.remove()}}if(typeof window<"u"&&typeof window.prompt=="function")try{return window.prompt("Copy ADHDev chat debug locator:",e),"manual"}catch{}return"failed"}function Gu(e){const t=e&&typeof e=="object"?e:{};if(t.delivery==="daemon_file"){const n=["# ADHDev Chat Debug Bundle saved on daemon","",`bundleId: ${String(t.bundleId||"")}`,`savedPath: ${String(t.savedPath||"")}`,`sizeBytes: ${String(t.sizeBytes||"")}`,`createdAt: ${String(t.createdAt||"")}`];return t.summary&&typeof t.summary=="object"&&n.push("","summary:",JSON.stringify(t.summary,null,2)),Array.isArray(t.warnings)&&t.warnings.length>0&&n.push("","warnings:",...t.warnings.map(r=>`- ${String(r)}`)),n.join(`
39
+ `)}return typeof t.text=="string"?t.text:t.bundle&&typeof t.bundle=="object"?`# ADHDev Chat Debug Bundle
40
+
41
+ \`\`\`json
42
+ ${JSON.stringify(t.bundle,null,2)}
43
+ \`\`\``:`# ADHDev Chat Debug Bundle
44
+
45
+ \`\`\`json
46
+ ${JSON.stringify(t,null,2)}
47
+ \`\`\``}function ta(e,t){return`${e}:${t}`}function pw(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function mw(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function sn(e,t){mw()&&console.debug(`[subscription-manager] ${e}`,t)}class fw{constructor(){st(this,"active",new Map);st(this,"retryTimers",new Map)}subscribe(t,n,r,o,a){var d,m;const i=ta(r.topic,r.key),c=this.active.get(i);let u=!0;if(c)c.handlers.add(o),(!pw(c.request,r)||c.daemonId!==n)&&(c.daemonId=n,c.request=r,u=((d=t.sendData)==null?void 0:d.call(t,n,r))??!1,!u&&(a!=null&&a.retryIntervalMs)?this.scheduleRetry(i,t,a.retryIntervalMs):u&&this.clearRetry(i),sn("subscribe_update",{daemonId:n,topic:r.topic,key:r.key,accepted:u})),c.lastUpdate&&o(c.lastUpdate);else{const f={daemonId:n,request:r,handlers:new Set([o])};this.active.set(i,f),sn("subscribe",{daemonId:n,topic:r.topic,key:r.key}),u=((m=t.sendData)==null?void 0:m.call(t,n,r))??!1,!u&&(a!=null&&a.retryIntervalMs)&&this.scheduleRetry(i,t,a.retryIntervalMs)}const h=()=>{var w;this.clearRetry(i);const f=this.active.get(i);if(!f||(f.handlers.delete(o),f.handlers.size>0))return;this.active.delete(i);const x={type:"unsubscribe",topic:r.topic,key:r.key};sn("unsubscribe",{daemonId:n,topic:r.topic,key:r.key}),(w=t.sendData)==null||w.call(t,n,x)};return h.initialSendAccepted=u,h}publish(t){const n=ta(t.topic,t.key),r=this.active.get(n);r&&(this.clearRetry(n),r.lastUpdate=t,bn.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.publish",topic:t.topic,payload:{key:t.key}}),r.handlers.forEach(o=>{o(t),bn.record({interactionId:typeof t.interactionId=="string"?t.interactionId:void 0,kind:"subscription.handler_invoked",topic:t.topic,payload:{key:t.key}})}))}updateParams(t,n,r){const o=ta(t,n),a=this.active.get(o);a&&(a.request={...a.request,params:{...a.request.params,...r}})}resubscribeAll(t){var n;sn("resubscribe_all",{count:this.active.size,subscriptions:Array.from(this.active.values()).map(r=>({daemonId:r.daemonId,topic:r.request.topic,key:r.request.key}))});for(const r of this.active.values())(n=t.sendData)==null||n.call(t,r.daemonId,r.request)}resubscribeForDaemon(t,n){var o;const r=Array.from(this.active.values()).filter(a=>a.daemonId===t);sn("resubscribe_daemon",{daemonId:t,count:r.length,subscriptions:r.map(a=>({topic:a.request.topic,key:a.request.key}))});for(const a of r)(o=n.sendData)==null||o.call(n,a.daemonId,a.request)}scheduleRetry(t,n,r){if(this.retryTimers.has(t))return;const o=setTimeout(()=>{var c;this.retryTimers.delete(t);const a=this.active.get(t);if(!a)return;const i=((c=n.sendData)==null?void 0:c.call(n,a.daemonId,a.request))??!1;sn("subscribe_retry",{id:t,accepted:i,topic:a.request.topic,key:a.request.key}),i||this.scheduleRetry(t,n,r)},r);this.retryTimers.set(t,o)}clearRetry(t){const n=this.retryTimers.get(t);n!==void 0&&(clearTimeout(n),this.retryTimers.delete(t))}}const ls=new fw;function bw(e,t){const n=new Map;for(const r of e||[])if((r.daemonId||r.id.includes(":")&&r.id.split(":")[0]||"")===t&&r.sessionId){n.set(r.sessionId,{parentSessionId:r.parentSessionId,providerSessionId:r.providerSessionId,workspace:r.workspace??null,sessionCapabilities:r.sessionCapabilities,cdpConnected:r.cdpConnected,activeChat:r.activeChat,controlValues:r.controlValues,providerControls:r.providerControls,summaryMetadata:r.summaryMetadata,runtimeWriteOwner:r.runtimeWriteOwner,runtimeAttachedClients:r.runtimeAttachedClients,cliName:r.cliName,type:r.type,mode:r.mode,status:r.status,lastMessagePreview:r.lastMessagePreview,lastMessageRole:r.lastMessageRole,lastMessageAt:r.lastMessageAt,lastMessageHash:r.lastMessageHash,completionMarker:r.completionMarker,seenCompletionMarker:r.seenCompletionMarker,settings:r.settings,activeInteractivePrompt:r.activeInteractivePrompt});for(const a of r.childSessions||[]){if(!(a!=null&&a.id))continue;const i=n.get(a.id)||{};n.set(a.id,{...i,...a})}}return n}function gw(e){const t=[],n=new Map;for(const r of e)if(r.parentId){const o=n.get(r.parentId)||[];o.push(r),n.set(r.parentId,o)}else t.push(r);return{topLevel:t,childrenByParent:n}}function sa(e,t){return t&&(t.startsWith(`${e}:`)?t:`${e}:${t}`)}function xw(){if(typeof window>"u")return!1;try{return!!(window.__ADHDEV_CONVERSATION_DEBUG__||window.localStorage.getItem("adhdev_conversation_debug")==="1")}catch{return!1}}function yw(e){xw()&&console.debug("[dashboard-conversations] statusPayloadToEntries",e.map(t=>({id:t.id,daemonId:t.daemonId,sessionId:t.sessionId,instanceId:t.instanceId,providerSessionId:t.providerSessionId,transport:t.transport,type:t.type})))}function ao(e,t){const n=[],{daemonId:r,existingDaemon:o,existingEntries:a,timestamp:i}=t,c=i||e.timestamp||Date.now(),u=e.sessions||[],{topLevel:h,childrenByParent:d}=gw(u),m=bw(a,r),f=e.machine?{...(o==null?void 0:o.machine)||{},...e.machine}:o==null?void 0:o.machine,x=h.filter(y=>y.kind==="workspace"&&y.transport==="cdp-page"),w=h.filter(y=>y.kind==="agent"&&y.transport==="pty"),p=h.filter(y=>y.kind==="agent"&&y.transport==="acp");n.push({...o||{},id:r,type:"adhdev-daemon",status:"online",timestamp:c,...e.version&&{version:e.version},...f&&{machine:f,platform:f.platform},...e.instanceId&&{instanceId:e.instanceId},...e.machineNickname!==void 0&&{machineNickname:e.machineNickname},...e.p2p&&{p2p:e.p2p},...e.workspaces&&{workspaces:e.workspaces},...e.defaultWorkspaceId!==void 0&&{defaultWorkspaceId:e.defaultWorkspaceId},...e.defaultWorkspacePath!==void 0&&{defaultWorkspacePath:e.defaultWorkspacePath},...e.terminalSizingMode!==void 0&&{terminalSizingMode:e.terminalSizingMode},...e.recentLaunches&&{recentLaunches:e.recentLaunches},...e.terminalBackend&&{terminalBackend:e.terminalBackend},...e.detectedIdes&&{detectedIdes:e.detectedIdes},...e.availableProviders&&{availableProviders:e.availableProviders},_sessionListAuthoritative:Array.isArray(e.sessions),cdpConnected:x.some(y=>!!y.cdpConnected)});for(const y of x){const k=m.get(y.id),b=zn(y,k),j=(d.get(y.id)||[]).map(S=>zn(S,m.get(S.id)));n.push({id:`${r}:ide:${y.id}`,sessionId:y.id,providerSessionId:y.providerSessionId??(k==null?void 0:k.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,status:b.cdpConnected?"online":"detected",daemonId:r,instanceId:sa(r,y.id),workspace:b.workspace,terminals:0,childSessions:j,agents:j.map(S=>({id:S.id,name:S.providerName||S.providerType,type:S.providerType,status:S.status})),activeChat:b.activeChat,...b.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:b.activeInteractivePrompt},chats:[],cdpConnected:b.cdpConnected,...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,muted:b.muted,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},...b.settings!==void 0&&{settings:b.settings},...b.messageInput!==void 0&&{messageInput:b.messageInput},timestamp:c})}for(const y of w){const k=m.get(y.id),b=zn(y,k);n.push({id:`${r}:cli:${y.id}`,sessionId:y.id,providerSessionId:y.providerSessionId??(k==null?void 0:k.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,agentType:b.providerType,status:b.status||"running",daemonId:r,instanceId:sa(r,y.id),cliName:b.providerName||b.providerType,mode:b.mode||(k==null?void 0:k.mode)||"terminal",workspace:b.workspace||"",...y.ownerDaemonId&&{ownerDaemonId:y.ownerDaemonId},...y.ownerMachineName&&{ownerMachineName:y.ownerMachineName},activeChat:b.activeChat,...b.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:b.activeInteractivePrompt},...b.resume!==void 0&&{resume:b.resume},...b.runtimeKey!==void 0&&{runtimeKey:b.runtimeKey},...b.runtimeDisplayName!==void 0&&{runtimeDisplayName:b.runtimeDisplayName},...b.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:b.runtimeWorkspaceLabel},...b.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:b.runtimeWriteOwner},...b.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:b.runtimeAttachedClients},...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,muted:b.muted,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},...b.settings!==void 0&&{settings:b.settings},...b.messageInput!==void 0&&{messageInput:b.messageInput},timestamp:c,_isCli:!0})}for(const y of p){const k=m.get(y.id),b=zn(y,k);n.push({id:`${r}:acp:${y.id}`,sessionId:y.id,providerSessionId:y.providerSessionId??(k==null?void 0:k.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,agentType:b.providerType,status:b.status||"running",daemonId:r,instanceId:sa(r,y.id),cliName:b.providerName||b.providerType,mode:"chat",workspace:b.workspace||"",...y.ownerDaemonId&&{ownerDaemonId:y.ownerDaemonId},...y.ownerMachineName&&{ownerMachineName:y.ownerMachineName},activeChat:b.activeChat,...b.activeInteractivePrompt!==void 0&&{activeInteractivePrompt:b.activeInteractivePrompt},...b.runtimeKey!==void 0&&{runtimeKey:b.runtimeKey},...b.runtimeDisplayName!==void 0&&{runtimeDisplayName:b.runtimeDisplayName},...b.runtimeWorkspaceLabel!==void 0&&{runtimeWorkspaceLabel:b.runtimeWorkspaceLabel},...b.runtimeWriteOwner!==void 0&&{runtimeWriteOwner:b.runtimeWriteOwner},...b.runtimeAttachedClients!==void 0&&{runtimeAttachedClients:b.runtimeAttachedClients},...b.lastMessagePreview!==void 0&&{lastMessagePreview:b.lastMessagePreview},...b.lastMessageRole!==void 0&&{lastMessageRole:b.lastMessageRole},...b.lastMessageAt!==void 0&&{lastMessageAt:b.lastMessageAt},...b.lastMessageHash!==void 0&&{lastMessageHash:b.lastMessageHash},lastUpdated:b.lastUpdated,unread:b.unread,lastSeenAt:b.lastSeenAt,inboxBucket:b.inboxBucket,completionMarker:b.completionMarker,seenCompletionMarker:b.seenCompletionMarker,surfaceHidden:b.surfaceHidden,muted:b.muted,...b.controlValues!==void 0&&{controlValues:b.controlValues},...b.providerControls!==void 0&&{providerControls:b.providerControls},...b.summaryMetadata!==void 0&&{summaryMetadata:b.summaryMetadata},...b.settings!==void 0&&{settings:b.settings},...b.messageInput!==void 0&&{messageInput:b.messageInput},timestamp:c,_isAcp:!0})}return yw(n),n}const vw=15e3,ww=15e3,kw=6e4,ac=12,Sw=8e3,Cw=4e3;function jw(e){const{force:t,hasSubscription:n,loadedAt:r,now:o,minFreshMs:a}=e;return t||r<=0?!0:n?!1:o-r>=a}const na=new Map,ra=new Map,Nr=new Set;function Nw(e){if(!e||typeof e!="object")return null;const t=e,n=t.status;if(n&&typeof n=="object")return n;const r=t.result;if(r&&typeof r=="object"&&"status"in r){const o=r.status;if(o&&typeof o=="object")return o}return t}function In(){const{sendCommand:e,sendData:t}=yt(),{injectEntries:n,getIdes:r}=or();return l.useCallback(async(o,a)=>{if(!o)return;const i=(a==null?void 0:a.minFreshMs)??kw;if(!jw({force:a==null?void 0:a.force,hasSubscription:Nr.has(o),loadedAt:ra.get(o)||0,now:Date.now(),minFreshMs:i}))return;const c=na.get(o);if(c)return c;const u=(async()=>{t&&!Nr.has(o)&&(ls.subscribe({sendData:t},o,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${o}`,params:{includeSessions:!0}},p=>{const y=r(),k=y.find(j=>j.id===o),b=ao(p.status,{daemonId:o,existingDaemon:k,existingEntries:y,timestamp:p.timestamp});b.length>0&&n(b),ra.set(o,Date.now())}).initialSendAccepted?Nr.add(o):Nr.delete(o));const h=await e(o,"get_status_metadata"),d=Nw(h);if(!d)return;const m=r(),f=m.find(w=>w.id===o),x=ao(d,{daemonId:o,existingDaemon:f,existingEntries:m,timestamp:d.timestamp||Date.now()});x.length>0&&n(x,{authoritativeDaemonIds:[o]}),ra.set(o,Date.now())})().finally(()=>{na.delete(o)});return na.set(o,u),u},[r,n,e,t])}const Aw=60,Tw=50;function Ku(e={}){return e.isCliLike?Tw:Aw}function Iw(e={}){return Ku(e)}const fr=60,Mw=1e3,Dw=750,ic=500,Lo=12e4,zu=new Set(["generating","waiting_approval","starting","streaming","working"]),lr=new Map;let qu=0;const si=new Set;function Pw(){qu+=1;for(const e of si)e()}function Lw(e){return si.add(e),()=>{si.delete(e)}}function lc(){return qu}function br(e,t,n){return`${e}::${t}::${n||t}`}function io(e=fr){return{liveMessages:[],hasLiveSnapshot:!1,cursor:Rw([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function Rw(e,t=fr){return{tailLimit:t}}function cc(e,t){const n=e[e.length-1];if(!n)return"empty:";let r="";try{r=JSON.stringify(n.content??"")}catch{r=String(n.content??"")}return["",e.length,String(n.id||""),String(n.index??""),String(n.receivedAt??n.timestamp??""),r].join("|")}function lo(e){if(typeof e=="string")return e;if(e==null)return"";if(Array.isArray(e))return e.map(lo).join(`
48
+ `);if(typeof e=="object"){const t=e;return lo(t.text??t.content??t.value??"")}return String(e)}function Gi(e){return lo(e.content).replace(/[─━═│┃┄┅┈┉┌┐└┘├┤┬┴┼╭╮╰╯╴╶╷╵\s]+/g,"").length===0}function Ew(e){return e.length===0||e.every(Gi)}function dc(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t],r=typeof(n==null?void 0:n.role)=="string"?n.role:"",o=typeof(n==null?void 0:n.kind)=="string"?n.kind:"";if(!(r==="system"||o==="system")&&!(o==="tool"||o==="thought"||o==="terminal"||o==="activity")&&!Gi(e[t]))return r}return""}function uc(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t],r=typeof(n==null?void 0:n.role)=="string"?n.role:"",o=typeof(n==null?void 0:n.kind)=="string"?n.kind:"";if(r==="system"||o==="system"||o==="tool"||o==="thought"||o==="terminal"||o==="activity"||Gi(e[t]))continue;if(r!=="assistant")return"";const a=e[t];return`${String(a.bubbleId??a.providerUnitKey??a.id??"")}#${lo(a.content).length}`}return""}function Vu(e,t){if(dc(t)!=="assistant")return!1;const n=Array.isArray(e.liveMessages)?e.liveMessages:[];return dc(n)!=="assistant"}function _w(e){return!!e&&typeof e=="object"&&e.selected==="native-history"}function $w(e,t,n){return _w(n)?Vu(e,t):!1}function Yu(e){const t=typeof e=="string"?e.toLowerCase():"";return t==="generating"||t==="no_progress"||t==="long_generating"||t==="streaming"||t==="working"||t==="starting"}function Ju(e){const t=typeof e=="string"?e.trim().toLowerCase():"";return zu.has(t)}function Qu(e,t){return Math.max(Math.max(0,t),Array.isArray(e.liveMessages)?e.liveMessages.length:0)}function Bw(e,t,n,r,o,a){const i=Ju(r)||Yu(r),c=a&&e.hasLiveSnapshot;if(!i&&!c)return!1;const u=i?Qu(e,t):Array.isArray(e.liveMessages)?e.liveMessages.length:0;if(u<=0)return!1;if(Ew(n))return!0;if(c&&!i&&Vu(e,n))return!1;if(o&&typeof o=="object"){const h=o.selected,d=o.fallbackReason;if(h==="native-history"||typeof d=="string"&&d!==""&&!d.startsWith("native_history_"))return!1}return n.length<u}function Fw(e,t,n,r){if(n.length!==0||Qu(e,t)<=0||e.hasLiveSnapshot&&e.liveMessages.length===0||!r||typeof r!="object")return!1;const a=r.selected,i=r.fallbackReason,c=r.nativeSource;return a==="native-history"?!1:c==="native-unavailable"?!0:typeof i=="string"&&i.startsWith("native_history_")}function Hw(e,t,n,r,o,a){return Bw(e,t,n,r,o,a)?"defer-busy-shrink":Fw(e,t,n,o)?"skip-transient-empty":"apply"}function Ww(e){if(Array.isArray(e.messages))return e.messages;const t=e.messagesTail;return Array.isArray(t)?t:[]}function hc(e,t){const n=e[t];return typeof n=="string"?n:""}class Ow{constructor(t){st(this,"manager");st(this,"sendData");st(this,"daemonId");st(this,"sessionId");st(this,"historySessionId");st(this,"subscriptionKey");st(this,"fallbackRecentCount");st(this,"snapshot");st(this,"transportSubscription",null);st(this,"listeners",new Set);st(this,"retainCount",0);st(this,"loadHistoryPromise",null);st(this,"pendingDisconnectTimer",null);st(this,"authoritativeRefreshPromise",null);st(this,"lastAuthoritativeRefreshAt",0);st(this,"now");st(this,"lastActiveStatusAt",0);this.manager=t.manager||ls,this.sendData=t.sendData,this.daemonId=t.daemonId,this.sessionId=t.sessionId,this.historySessionId=t.historySessionId,this.subscriptionKey=t.subscriptionKey,this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount??0),this.now=t.now??(()=>Date.now()),this.snapshot=io(Math.max(0,t.tailLimit??fr))}updateOptions(t){const n=this.sendData,r=this.daemonId,o=this.sessionId;if(t.manager&&(this.manager=t.manager),t.sendData&&(this.sendData=t.sendData),t.historySessionId&&(this.historySessionId=t.historySessionId),t.now&&(this.now=t.now),t.fallbackRecentCount!==void 0&&(this.fallbackRecentCount=Math.max(0,t.fallbackRecentCount)),t.tailLimit!==void 0){const a=Math.max(0,t.tailLimit);a!==this.snapshot.cursor.tailLimit&&(this.snapshot={...this.snapshot,cursor:{tailLimit:a}},this.transportSubscription&&(this.disconnect(),this.connect()))}this.retainCount>0&&(n!==this.sendData||r!==this.daemonId||o!==this.sessionId)&&(this.disconnect(),this.connect())}getSnapshot(){return this.snapshot}clearLiveSnapshot(){this.snapshot={...io(this.snapshot.cursor.tailLimit),hasLiveSnapshot:!0},this.emit()}subscribe(t){return this.listeners.add(t),t(this.snapshot),()=>{this.listeners.delete(t)}}retain(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.retainCount+=1,this.connect()}release(){this.retainCount=Math.max(0,this.retainCount-1),!(this.retainCount!==0||this.pendingDisconnectTimer)&&(this.pendingDisconnectTimer=setTimeout(()=>{this.pendingDisconnectTimer=null,this.retainCount===0&&this.disconnect()},0))}async loadHistoryPage(t){if(this.loadHistoryPromise)return this.loadHistoryPromise;this.snapshot={...this.snapshot,historyError:null},this.emit();const n=(async()=>{try{const r=this.snapshot.hasLiveSnapshot,o=r?this.snapshot.liveMessages.length:Math.max(this.snapshot.liveMessages.length,this.fallbackRecentCount),a=await t({offset:this.snapshot.historyOffset,excludeRecentCount:o}),i=Array.isArray(a.messages)?a.messages:[],c=!r&&i.length===0&&a.hasMore!==!0&&this.fallbackRecentCount>0,u=[...i,...this.snapshot.historyMessages],h=u.length>ic?u.slice(u.length-ic):u;this.snapshot={...this.snapshot,historyMessages:h,historyOffset:this.snapshot.historyOffset+i.length,hasMoreHistory:c?!0:a.hasMore===!0,historyError:null}}catch(r){this.snapshot={...this.snapshot,historyError:r instanceof Error?r.message:"Failed to load history"}}this.emit()})().finally(()=>{this.loadHistoryPromise=null});return this.loadHistoryPromise=n,n}refreshAuthoritativeTail(t,n={}){if(this.authoritativeRefreshPromise)return this.authoritativeRefreshPromise;const r=this.now();if(!n.force&&this.lastAuthoritativeRefreshAt>0&&r-this.lastAuthoritativeRefreshAt<Dw)return Promise.resolve();this.lastAuthoritativeRefreshAt=r;const o=(async()=>{try{const a=await t();a&&this.handleUpdate(a)}catch{}})().finally(()=>{this.authoritativeRefreshPromise=null});return this.authoritativeRefreshPromise=o,o}buildSubscribeRequest(){return{type:"subscribe",topic:"session.chat_tail",key:this.subscriptionKey,params:{targetSessionId:this.sessionId,...this.historySessionId?{historySessionId:this.historySessionId}:{},...this.snapshot.cursor.tailLimit>0?{tailLimit:this.snapshot.cursor.tailLimit}:{}}}}connect(){this.transportSubscription||!this.sendData||!this.daemonId||!this.sessionId||(this.transportSubscription=this.manager.subscribe({sendData:this.sendData},this.daemonId,this.buildSubscribeRequest(),t=>{this.handleUpdate(t)},{retryIntervalMs:Mw}))}disconnect(){var t;(t=this.transportSubscription)==null||t.call(this),this.transportSubscription=null}dispose(){this.pendingDisconnectTimer&&(clearTimeout(this.pendingDisconnectTimer),this.pendingDisconnectTimer=null),this.disconnect(),this.listeners.clear(),this.retainCount=0,this.loadHistoryPromise=null}emit(){this.listeners.forEach(t=>t(this.snapshot))}handleUpdate(t){if(t.error)return;const n=hc(t,"sessionId");if(n&&n!==this.sessionId)return;const r=hc(t,"historySessionId");if(r&&this.historySessionId&&r!==this.historySessionId)return;const o=Ww(t),a=t.messageSource,i=this.now(),c=this.lastActiveStatusAt>0&&i-this.lastActiveStatusAt<=Lo;(Ju(t.status)||Yu(t.status))&&(this.lastActiveStatusAt=i);const u=$w(this.snapshot,o,a);if(!u&&Hw(this.snapshot,this.fallbackRecentCount,o,t.status,a,c)!=="apply")return;const h={tailLimit:this.snapshot.cursor.tailLimit};!u&&cc(this.snapshot.liveMessages)===cc(o)&&uc(this.snapshot.liveMessages)===uc(o)&&this.snapshot.cursor.tailLimit===h.tailLimit||(this.snapshot={...this.snapshot,liveMessages:o,hasLiveSnapshot:!0,cursor:h,messageSource:a},this.emit())}}function Xu(e){const t=br(e.daemonId,e.sessionId,e.historySessionId),n=lr.get(t);if(n)return n.updateOptions(e),n;const r=new Ow(e);return lr.set(t,r),Pw(),r}function Uw(e,t,n){if(!e||!t)return;const r=`${e}::${t}::`,o=br(e,t,n);for(const[a,i]of lr.entries())(a===o||a.startsWith(r))&&i.clearLiveSnapshot()}function Zu(e){const t=en(e),n=e.sessionId||"";if(!t||!n)return;const r=Io(e),o=br(t,n,r||n),a=lr.get(o);if(!a)return;const i=a.getSnapshot();return i.hasLiveSnapshot?i:void 0}function Gw(e,t){return{...e,loadHistoryPage:t}}function Kw(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||(e.historySessionId||"").localeCompare(t.historySessionId||"")}function zw(e,t={}){const n=String(e.status||"").trim().toLowerCase();if(zu.has(n)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const r=t.now??Date.now(),o=Math.max(0,Number(t.recentActivityMs??Lo)),a=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return a>0?r-a<=o:Array.isArray(e.messages)&&e.messages.length>0}function qw(e=Lo){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Vw(e,t={}){const n=new Set,r=[];for(const o of e){if(!zw(o,t))continue;const a=en(o),i=o.sessionId||"";if(!a||!i)continue;const c=Io(o),u=br(a,i,c||i);n.has(u)||(n.add(u),r.push({daemonId:a,sessionId:i,historySessionId:c,subscriptionKey:`daemon:${a}:session:${i}`}))}return r.sort(Kw),{descriptors:r,signature:r.map(o=>`${o.subscriptionKey}|${o.historySessionId}`).join("||")}}function Yw(e,t){const{sendData:n,sendCommand:r,isConnected:o}=yt(),a=(t==null?void 0:t.enabled)!==!1,i=en(e),c=e.sessionId||"",u=Io(e),h=`daemon:${i}:session:${c}`,d=Math.max(0,(t==null?void 0:t.tailLimit)??fr),m=e.messages.length,f=l.useMemo(()=>!a||!i||!c?null:Xu({daemonId:i,sessionId:c,historySessionId:u,subscriptionKey:h,sendData:n,tailLimit:d,fallbackRecentCount:m}),[i,a,u,n,c,h,d]);l.useEffect(()=>{f==null||f.updateOptions({fallbackRecentCount:m})},[f,m]);const[x,w]=l.useState(()=>(f==null?void 0:f.getSnapshot())||io(d));l.useEffect(()=>{if(!f){w(io(d));return}f.retain(),w(f.getSnapshot());const k=f.subscribe(b=>{w(b)});return()=>{k(),f.release()}},[f,d]);const p=l.useCallback(async()=>{!f||!i||!c||await f.loadHistoryPage(async({offset:k,excludeRecentCount:b})=>{const j=e.agentType,S=await r(i,"chat_history",{agentType:j,offset:k,limit:30,targetSessionId:c,historySessionId:u,excludeRecentCount:b}),v=S&&typeof S=="object"&&"result"in S?S.result||{}:S||{};return{messages:Array.isArray(v.messages)?v.messages:[],hasMore:v.hasMore===!0}})},[e.agentType,f,i,u,r,c]),y=l.useCallback((k=!1)=>!f||!i||!c?Promise.resolve():f.refreshAuthoritativeTail(async()=>{const b=await r(i,"read_chat",{agentType:e.agentType,targetSessionId:c,historySessionId:u,...d>0?{tailLimit:d}:{}}),j=b&&typeof b=="object"&&"result"in b?b.result:b;if(!j||typeof j!="object"||j.success===!1)return null;const S=Array.isArray(j.messages)?j.messages:Array.isArray(j.messagesTail)?j.messagesTail:[];return{topic:"session.chat_tail",key:h,sessionId:c,historySessionId:u,seq:0,timestamp:0,messages:S,status:typeof j.status=="string"?j.status:"idle",...j.messageSource&&typeof j.messageSource=="object"?{messageSource:j.messageSource}:{}}},{force:k}),[e.agentType,f,i,u,r,c,h,d]);return l.useEffect(()=>{if(!f||!a||!i||!c)return;y(!0);const k=()=>{typeof document<"u"&&document.visibilityState==="visible"&&y()};typeof document<"u"&&document.addEventListener("visibilitychange",k);let b=o?o(i):!0;const j=setInterval(()=>{if(!o)return;const S=o(i);S&&!b&&y(),b=S},2e3);return()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",k),clearInterval(j)}},[f,i,a,c,u]),l.useMemo(()=>Gw(x,p),[p,x])}function Jw(e,t){const{sendData:n}=yt(),r=(t==null?void 0:t.enabled)!==!1,o=Math.max(0,(t==null?void 0:t.tailLimit)??fr),a=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??Lo)),i=qw(a),[c,u]=l.useState(0);l.useEffect(()=>{if(!r||e.length===0)return;const d=setInterval(()=>{u(m=>m+1)},i);return()=>{clearInterval(d)}},[e.length,r,i]);const h=l.useMemo(()=>Vw(e,{recentActivityMs:a}),[e,a,c]);l.useEffect(()=>{if(!r||!n||h.descriptors.length===0)return;const d=h.descriptors.map(m=>Xu({...m,sendData:n,tailLimit:o}));return d.forEach(m=>{m.retain()}),()=>{d.forEach(m=>m.release())}},[h.signature,r,n,o])}function Qw(e){const[t,n]=l.useState(0),r=l.useMemo(()=>{const i=[];for(const c of e){const u=en(c),h=c.sessionId||"";if(!u||!h)continue;const d=Io(c);i.push(br(u,h,d||h))}return i},[e]),o=r.join("|"),a=l.useSyncExternalStore(Lw,lc,lc);return l.useEffect(()=>{if(r.length===0)return;const i=[];for(const c of r){const u=lr.get(c);if(!u)continue;let h=!1;i.push(u.subscribe(()=>{if(!h){h=!0;return}n(d=>d+1)}))}return()=>{for(const c of i)c()}},[o,a]),t}function Xw(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function Zw(e){return Xw(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const Kr=new Map,ni=new Set;function pc(e,t){!e||Kr.get(e)===t||(t?Kr.set(e,!0):Kr.delete(e),ni.forEach(r=>r(e,t)))}function e0(e){return e?Kr.get(e)===!0:!1}function t0(e){return ni.add(e),()=>{ni.delete(e)}}function s0(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function n0(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function r0(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function eh(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function th(e){const t=typeof e.completionMarker=="string"?e.completionMarker.trim():"";return t||(e.lastMessageHash?e.lastMessageHash:e.lastMessageAt?String(e.lastMessageAt):e.lastUpdated?String(e.lastUpdated):"")}function o0(e){return eh(e)?!1:e.inboxBucket==="task_complete"&&th(e).length>0}function mc(e){return e.branch||"detached HEAD"}function a0(e){if(e.error)return`${mc(e)} · Git error: ${e.error}`;const t=[mc(e)];return e.changedFiles>0?t.push(s0(e.changedFiles,"file")+" changed"):e.dirty||t.push("clean"),e.ahead>0&&t.push(`ahead ${e.ahead}`),e.behind>0&&t.push(`behind ${e.behind}`),e.hasConflicts&&t.push("conflicts"),t.join(" · ")}function i0(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${a0(t)}`}function l0(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function c0(e,t={}){if(t.enabled===!1)return[];if(!r0(e))return[];const n=eh(e)?"working":o0(e)?"complete":null;if(!n)return[];const r=n==="complete"?th(e):"";return[{id:n==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${n0(r)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:i0(n,e.git),timestamp:l0(e,e.git),meta:{source:"git-system-bubble",phase:n,workspace:e.workspacePath,repoRoot:e.git.repoRoot,branch:e.git.branch,changedFiles:e.git.changedFiles,hasConflicts:e.git.hasConflicts}}]}const d0=60;function u0(e){return e.status==="no_progress"||e.status==="long_generating"?"Agent shows no progress.":e.status==="generating"||e.status==="streaming"?"Agent is generating.":e.status==="waiting_approval"&&(!e.modalButtons||e.modalButtons.length===0)?"Agent is waiting for approval. Approval controls will appear when available.":null}function ri({activeConv:e,ideEntry:t,handleSendChat:n,handleForceSendChat:r,isSendingChat:o=!1,sendFeedbackMessage:a=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:u,userName:h,scrollToBottomRequestNonce:d,isInputActive:m=!0,isVisible:f=!0}){var pe,G,O,Z,q,me,Te,_;const{t:x}=Le("common"),w=l.useRef(new Map),p=l.useRef(void 0),y=In(),{sendCommand:k}=yt(),{isVisible:b}=Li();mr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:u.length,isSendingChat:o});const j=Rt.useMemo(()=>An(e),[e.status,e.connectionState]);Rt.useEffect(()=>{const te=e.sessionId;if(te)return pc(te,j.isGenerating),()=>{pc(te,!1)}},[e.sessionId,j.isGenerating]);const S=l.useMemo(()=>ow(e,t),[e,t]),v=l.useMemo(()=>{var te;return $i((te=S.targetEntry)==null?void 0:te.providerControls,{hostIdeType:e.hostIdeType,providerType:S.providerType})},[e.hostIdeType,S.providerType,(pe=S.targetEntry)==null?void 0:pe.providerControls]),g=Ku({isCliLike:S.isCli||S.isAcp}),N=Iw({isCliLike:S.isCli||S.isAcp}),C=Yw(e,{enabled:f&&!!e.sessionId,tailLimit:N}),[A,T]=l.useState(g),[M,L]=l.useState(()=>Pl()),P=e.tabKey,B=C.historyMessages,K=C.hasMoreHistory,F=C.historyError,R=Lu(e,C),Q=su(R).length;l.useEffect(()=>{T(g)},[g,P]);const E=Math.max(0,R.length-A),I=Wi(e),$=en(e),D=Zw(e),U=Oi(e),Y=u0(e),ae=a||U,z=ae||Y,X=!!U,[de,re]=l.useState(!1);l.useEffect(()=>{const te=S.targetEntry;$&&(!te||te.providerControls===void 0||te.controlValues===void 0)&&y($,{minFreshMs:3e4}).catch(()=>{})},[$,S.isAcp,(G=S.targetEntry)==null?void 0:G.providerControls,(O=S.targetEntry)==null?void 0:O.controlValues,y]);const W=l.useCallback(async()=>{if(!de){if(R.length>A){T(te=>Math.min(R.length,te+d0));return}re(!0);try{await C.loadHistoryPage()}finally{re(!1)}}},[C,de,R.length,A]),{allMessages:oe,receivedAtMap:V}=l.useMemo(()=>{const te=Qv({historyMessages:B,liveMessages:R,visibleLiveCount:A}),ve=c0(e),ce=ve.length>0?[...te,...ve]:te,H={};return ce.forEach((fe,je)=>{const Ce=`${e.tabKey}:${to(fe)}`;let Be=Pu(fe)||w.current.get(Ce)||0;Be||(Be=Date.now(),w.current.set(Ce,Be)),H[to(fe)]=Be}),{allMessages:ce,receivedAtMap:H}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,E,B,R,A]),ie=l.useMemo(()=>u.filter(te=>te.routeId===e.tabKey).sort((te,ve)=>te.timestamp-ve.timestamp),[u,e.tabKey]),ke=l.useCallback(async()=>{var je,Ce;if(!$)return;const te=Wu({activeConv:e,visibleMessages:oe,actionLogs:u,controls:(je=S.targetEntry)==null?void 0:je.providerControls,controlValues:(Ce=S.targetEntry)==null?void 0:Ce.controlValues,visibleBarControlCount:v.length,chatTailState:{liveMessages:C.liveMessages,hasLiveSnapshot:C.hasLiveSnapshot,hasMoreHistory:K,historyError:F,historyMessages:B},ui:{controlsVisible:b,visibleLiveCount:A,activityVisible:M,activityCount:Q,hiddenLiveCount:E,isInputActive:m,isVisible:f}}),ve=await k($,"get_chat_debug_bundle",{agentType:S.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:te}),ce=er(ve),H=Gu(ce),fe=await Uu(H);fe==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),pt.showToast(Ou(ce,{locatorCopyStatus:fe}),fe==="failed"?"warning":"success")},[e,u,Q,oe,b,C.hasLiveSnapshot,C.liveMessages,S.providerType,(Z=S.targetEntry)==null?void 0:Z.controlValues,(q=S.targetEntry)==null?void 0:q.providerControls,$,K,E,B,m,f,F,k,M,v.length,A]);l.useEffect(()=>{const te=ve=>{ve.key===eu&&L(Pl())};return window.addEventListener("storage",te),()=>window.removeEventListener("storage",te)},[]);const xe=l.useCallback(()=>{const te=hw(p.current);p.current=te.state,te.shouldCollect&&ke().catch(ve=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",ve),pt.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[ke]),Se=l.useMemo(()=>{if(R.length===0){if(e.connectionState==="connecting"||e.connectionState==="new")return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-4",children:[s.jsx("div",{className:"connecting-logo-float",children:s.jsx("div",{style:{width:64,height:64,borderRadius:"50%",background:"radial-gradient(circle, rgba(96,165,250,0.12), transparent 70%)",display:"flex",alignItems:"center",justifyContent:"center",boxShadow:"0 0 40px rgba(96,165,250,0.08)"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",style:{width:40,height:40,borderRadius:"50%",opacity:.85}})})}),s.jsxs("div",{className:"flex flex-col items-center gap-1.5",children:[s.jsxs("div",{className:"text-[13px] text-blue-400 font-medium",children:[x("chatPane.connectingToMachine"),s.jsx("span",{className:"connecting-dots"})]}),s.jsx("div",{className:"text-[11px] opacity-35",children:x("chatPane.establishingP2P")})]})]});if((j.isGenerating||e.status==="streaming")&&re(!1),e.status==="not_monitored"&&D)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(ar,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:x("chatPane.agentNotMonitored")}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?`⌛ ${x("chatPane.switchingPanel")}`:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(xn,{size:14})," ",x("chatPane.openPanel",{label:I})]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:x("chatPane.clickToSwitchMonitoring")})]});if(e.status==="panel_hidden"&&D)return s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-3xl opacity-60",children:s.jsx(Yd,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:x("chatPane.agentPanelHidden")}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?`⌛ ${x("chatPane.openingPanel")}`:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(xn,{size:14})," ",x("chatPane.openPanel",{label:I})]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:x("chatPane.openPanelHint")})]});if(e.status==="idle"&&!de)return!K&&B.length===0?s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:x("chatPane.noMessagesYet")})]}):s.jsxs("div",{className:"text-center mt-16 flex flex-col items-center gap-3",children:[s.jsx("div",{className:"text-2xl opacity-40 animate-pulse",children:"💬"}),s.jsx("div",{className:"text-[13px] opacity-40",children:x("chatPane.loadingChat")})]})}},[e.connectionState,e.status,D,i,K,B.length,c,de,R.length,I,j.isGenerating]);return s.jsxs("div",{className:"flex-1 min-h-0 w-full flex flex-col relative",children:[s.jsx("div",{className:"chat-activity-toggle-bar",children:s.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[s.jsx(zv,{sessionId:e.sessionId,daemonId:e.daemonId,muted:!!((me=S.targetEntry)!=null&&me.muted),sendDaemonCommand:k}),s.jsx(Gv,{sessionId:e.sessionId,daemonId:e.daemonId,conv:e})]})}),s.jsx(fb,{messages:oe,actionLogs:ie,agentName:yn(e)||I||"Agent",userName:h,isCliMode:S.isCli||S.isAcp,isWorking:j.isGenerating,contextKey:e.tabKey,receivedAtMap:V,lastMessageHash:e.lastMessageHash,showActivityMessages:M,onLoadMore:W,isLoadingMore:de,hasMoreHistory:K,hiddenLiveCount:E,loadError:F??void 0,emptyState:Se,scrollToBottomRequestNonce:d,isVisible:f}),s.jsx(gv,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:S.providerType,displayLabel:S.displayLabel,controls:(Te=S.targetEntry)==null?void 0:Te.providerControls,controlValues:(_=S.targetEntry)==null?void 0:_.controlValues,currentStatus:e.status,coordinatorHint:Do(e),isActive:m,isCliTerminal:S.isCliTerminal}),!S.isCliTerminal&&s.jsx(Nu,{contextKey:e.tabKey,panelLabel:I,isSending:o,isBusy:X,statusMessage:z,inlineStatusMessage:ae,onSend:n,onForceSend:r,canForceSend:!!r&&j.isGenerating&&!X,isActive:m,showControlsToggle:v.length>0,onControlsToggle:xe,messageInput:e.messageInput})]})}let sh=gs;function nh(){return sh()}class h0{constructor(){st(this,"listeners",new Map)}send(t){}isConnected(){return!1}on(t,n){return this.listeners.has(t)||this.listeners.set(t,new Set),this.listeners.get(t).add(n),()=>{var r;(r=this.listeners.get(t))==null||r.delete(n)}}emit(t,...n){var r;(r=this.listeners.get(t))==null||r.forEach(o=>o(...n))}}let rh=new h0;class p0{sendPtyInput(t,n,r){return!1}retryConnection(t){}getState(t){return"disconnected"}sendData(t,n){return!1}get(t){}onScreenshot(t,n){return()=>{}}onRuntimeEvent(t,n,r){return()=>{}}requestRuntimeSnapshot(t,n,r){return Promise.resolve({success:!1,error:"Connection manager not configured; host app must inject requestRuntimeSnapshot"})}}let kt=new p0;function m0(e){e.dashboardWS&&(rh=e.dashboardWS),e.connectionManager&&(kt=e.connectionManager),e.useDaemonsHook&&(sh=e.useDaemonsHook)}const f0=.5,b0=1.25,ns="\x1B",fc={ArrowUp:"A",ArrowDown:"B",ArrowLeft:"D",ArrowRight:"C"};function g0(e){return 1+(e.shift?1:0)+(e.alt?2:0)+(e.ctrl?4:0)}function bc(e,t){let n=e;if(t.shift&&n.length===1&&(n=n.toUpperCase()),t.ctrl){const r=n.toUpperCase().charCodeAt(0);return String.fromCharCode(r&31)}return n}function x0(e,t){if(t in fc){const r=fc[t],o=g0(e);return o===1?`${ns}[${r}`:`${ns}[1;${o}${r}`}switch(t){case"Enter":return e.alt?`${ns}\r`:"\r";case"Escape":return e.alt?`${ns}${ns}`:ns;case"Backspace":{const r=e.ctrl?"\b":"";return e.alt?`${ns}${r}`:r}case"Tab":{const r=e.shift?`${ns}[Z`:" ";return e.alt&&!e.shift?`${ns} `:r}case"Space":{const r=bc(" ",e);return e.alt?`${ns}${r}`:r}}const n=bc(t,e);return e.alt?`${ns}${n}`:n}function xt(e){return Wi(e)}function vn(e){return Bu(e).join(" · ")}function oh(e){var t,n;return!!e.daemonId&&!!((t=e.coordinator)!=null&&t.meshId||typeof((n=e.settings)==null?void 0:n.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.trim().length>0)}function y0(e){var o,a,i;const t=[],n=typeof((o=e.settings)==null?void 0:o.meshNodeFor)=="string"&&e.settings.meshNodeFor.trim().length>0,r=!!((a=e.coordinator)!=null&&a.meshId)||typeof((i=e.settings)==null?void 0:i.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor.trim().length>0;return n&&t.push("Mesh node"),r&&t.push("Coordinator"),t}function v0(e){var i,c,u;const t=[],n=typeof((i=e.settings)==null?void 0:i.meshNodeFor)=="string"?e.settings.meshNodeFor.trim():"",r=typeof((c=e.coordinator)==null?void 0:c.meshId)=="string"?e.coordinator.meshId.trim():"",o=typeof((u=e.settings)==null?void 0:u.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor.trim():"",a=r||o;if(n&&t.push(`Mesh node: ${n}`),a&&t.push(`Coordinator: ${a}`),e.meshQueueStats){const{pending:h,assigned:d,completed:m,failed:f}=e.meshQueueStats;t.push(`Queue: ${h} pending, ${d} assigned, ${m} completed, ${f} failed`)}return t.join(" · ")}function ah(e,t){const n=$u(e,t);return n||(e.title?e.title:vn(e)||"No messages yet")}function ih(e,t){const{isReconnecting:n,isConnecting:r}=An(e);return n?"Reconnecting…":r?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function w0(e,t){const n=["Chat",...Bu(e)];return t!=null&&t.timestampLabel&&n.push(t.timestampLabel),n.filter(Boolean).join(" · ")}function Gs(e){return ih(e)||vn(e)}function k0(e,t){return`${xt(e)} · ${ah(e,t)}`}function S0(e){const t=oo(e),n=t?$t(t):yn(e);return`${xt(e)} — ${n||"Agent"}`}function C0(e){return yn(e)||"CLI"}function lh(e){return _u(e)}function ch(e){return e?`Remote · ${xt(e)||e.workspaceName||"Session"}`:"Remote"}const gc=[{kind:"regex",label:"section matches",hint:"regex against a screen section",make:e=>({section:e[0],matches:""})},{kind:"elapsed",label:"elapsed_ms",hint:"N ms since state entered",make:()=>({elapsed_ms:1e3})},{kind:"stable",label:"stable_ms",hint:"region unchanged for N ms",make:()=>({stable_ms:1e3,cursor_above:5})},{kind:"changed",label:"changed",hint:"region changed vs prev frame",make:()=>({cursor_above:3,changed:!0})},{kind:"all",label:"all (AND)",hint:"every child must match",make:()=>({all:[]})},{kind:"any",label:"any (OR)",hint:"some child must match",make:()=>({any:[]})},{kind:"not",label:"not",hint:"invert a condition",make:()=>({not:{matches:""}})}],j0=[{label:"active spinner (busy)",cond:{section:"body",matches:"(?:^|\\n)\\s*[·✢✳✶✽✷✸✹]\\s+\\w.*?(?:…|\\.\\.\\.)"}},{label:"completion marker (done)",cond:{section:"body",matches:"✻\\s+\\w+ed\\s+for\\s+(?:\\d+h\\s+)?(?:\\d+m\\s+)?\\d+s"}},{label:"approval prompt (❯ 1.)",cond:{section:"footer",matches:"(?:^|\\n)\\s*[❯›>]\\s*1\\.\\s*.+"}},{label:"picker (Select a …)",cond:{section:"modal",matches:"Select (?:a |an )?(?:model|mode|option)\\b"}},{label:"stable 1.2s (settled)",cond:{stable_ms:1200,cursor_above:5}}];function N0(e){return"all"in e?"all":"any"in e?"any":"not"in e?"not":"elapsed_ms"in e?"elapsed":"stable_ms"in e&&!("changed"in e)?"stable":"changed"in e?"changed":"regex"}function Ki({cond:e,path:t,sections:n,onChange:r,onRemove:o,onPreview:a,preview:i}){const c=N0(e),u=i[t],h=d=>{const m=gc.find(f=>f.kind===d);m&&r(m.make(n))};return s.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-1.5 space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("select",{value:c,onChange:d=>h(d.target.value),className:"bg-bg-secondary text-text-primary text-[10px] font-mono rounded border border-border-default px-1 py-0.5",children:gc.map(d=>s.jsx("option",{value:d.kind,children:d.label},d.kind))}),(c==="regex"||c==="stable"||c==="changed"||c==="elapsed")&&s.jsx("button",{type:"button",className:"text-[10px] text-accent-primary hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/20",onClick:()=>a(t,e),children:"test"}),u&&u!=="loading"&&s.jsx("span",{className:`text-[10px] font-mono px-1.5 py-0.5 rounded ${u.result?"text-status-online bg-status-online/20":"text-text-secondary bg-bg-glass"}`,children:u.result?"match ✓":"no match"}),u==="loading"&&s.jsx("span",{className:"text-[10px] text-text-muted",children:"testing…"}),o&&s.jsx("button",{type:"button",className:"ml-auto text-text-muted hover:text-status-error text-xs px-1",onClick:o,children:"×"})]}),c==="regex"&&s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsxs("select",{value:e.section??"",onChange:d=>r({...e,section:d.target.value||void 0}),className:"bg-bg-secondary text-accent-primary text-[10px] font-mono rounded border border-border-default px-1 py-0.5",children:[s.jsx("option",{value:"",children:"(whole screen)"}),n.map(d=>s.jsx("option",{value:d,children:d},d))]}),s.jsx("input",{value:e.matches??"",onChange:d=>r({...e,matches:d.target.value}),placeholder:"regex",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-primary text-[10px] font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),c==="elapsed"&&s.jsx(Ts,{label:"elapsed_ms",value:e.elapsed_ms,onChange:d=>r({elapsed_ms:d})}),c==="stable"&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ts,{label:"stable_ms",value:e.stable_ms,onChange:d=>r({...e,stable_ms:d})}),s.jsx(Ts,{label:"cursor_above",value:e.cursor_above??0,onChange:d=>r({...e,cursor_above:d||void 0})})]}),c==="changed"&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ts,{label:"cursor_above",value:e.cursor_above,onChange:d=>r({...e,cursor_above:d})}),s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-text-secondary",children:[s.jsx("input",{type:"checkbox",checked:!!e.changed,onChange:d=>r({...e,changed:d.target.checked}),className:"accent-[var(--accent-primary)]"}),"changed"]})]}),(c==="all"||c==="any")&&s.jsx(A0,{kind:c,cond:e,path:t,sections:n,onChange:r,onPreview:a,preview:i}),c==="not"&&s.jsx("div",{className:"pl-2 border-l border-border-default",children:s.jsx(Ki,{cond:e.not,path:`${t}.not`,sections:n,onChange:d=>r({not:d}),onPreview:a,preview:i})})]})}function A0({kind:e,cond:t,path:n,sections:r,onChange:o,onPreview:a,preview:i}){const c=(e==="all"?t.all:t.any)??[],u=h=>o(e==="all"?{all:h}:{any:h});return s.jsxs("div",{className:"pl-2 border-l border-border-default space-y-1",children:[c.map((h,d)=>s.jsx(Ki,{cond:h,path:`${n}.${e}[${d}]`,sections:r,onChange:m=>u(c.map((f,x)=>x===d?m:f)),onRemove:()=>u(c.filter((m,f)=>f!==d)),onPreview:a,preview:i},d)),s.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[s.jsx("button",{type:"button",className:"text-[10px] text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>u([...c,{section:r[0],matches:""}]),children:"+ condition"}),j0.map(h=>s.jsxs("button",{type:"button",className:"text-[10px] text-accent-primary/80 hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/20",onClick:()=>u([...c,JSON.parse(JSON.stringify(h.cond))]),title:"insert verified pattern",children:["+ ",h.label]},h.label))]})]})}function Ts({label:e,value:t,onChange:n}){return s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-text-secondary font-mono",children:[e,s.jsx("input",{type:"number",value:Number.isFinite(t)?t:0,onChange:r=>n(Number(r.target.value)),className:"w-20 bg-bg-secondary text-text-primary rounded border border-border-default px-1 py-0.5 outline-none focus:border-accent"})]})}function T0({sections:e,otherSectionIds:t,onChange:n,onTest:r,testResult:o}){const a=Object.keys(e),i=o&&o!=="loading"&&!("error"in o)?Object.fromEntries(o.sections.map(m=>[m.id,m])):{},c=(m,f)=>{if(!f||f===m||e[f])return;const x={};for(const[w,p]of Object.entries(e))x[w===m?f:w]=p;n(x)},u=(m,f)=>n({...e,[m]:f}),h=m=>{const f={...e};delete f[m],n(f)},d=()=>{let m="section",f=1;for(;e[m];)m=`section${f++}`;n({...e,[m]:{from_top:0}})};return s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-text-secondary text-[10px] uppercase tracking-widest font-semibold",children:"Sections"}),s.jsx("span",{className:"text-text-muted text-[10px]",children:"— how the screen is split; conditions match against these"}),s.jsx("button",{type:"button",className:"ml-auto text-[10px] text-accent-primary hover:text-accent-primary px-1.5 py-0.5 rounded border border-accent hover:bg-accent-primary/20",onClick:r,title:"Resolve all sections against the live session screen",children:o==="loading"?"testing…":"test on live screen"}),s.jsx("button",{type:"button",className:"text-[10px] text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:d,children:"+ section"})]}),o&&o!=="loading"&&"error"in o&&s.jsx("div",{className:"text-status-error bg-status-error/15 border border-status-error/40 rounded p-1.5 text-[10px] mb-1",children:o.error}),s.jsx("div",{className:"space-y-1.5",children:a.map(m=>{var p;const f=e[m],x=f.anchor!=null?"anchor":"positional",w=y=>{y==="anchor"?u(m,{anchor:f.anchor??"^",anchor_last:f.anchor_last,until:f.until}):u(m,{from_top:f.from_top??0,until:f.until})};return s.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-2 space-y-1.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{value:m,onChange:y=>c(m,y.target.value.trim()),className:"w-28 bg-bg-secondary text-accent-primary font-mono text-[11px] rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),s.jsxs("div",{className:"inline-flex rounded border border-border-default overflow-hidden text-[10px]",children:[s.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${x==="positional"?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>w("positional"),children:"positional"}),s.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${x==="anchor"?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>w("anchor"),children:"anchor"})]}),s.jsx("button",{type:"button",className:"ml-auto text-text-muted hover:text-status-error text-sm px-1",onClick:()=>h(m),children:"×"})]}),x==="positional"?s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx(Ts,{label:"from_top",value:typeof f.from_top=="number"?f.from_top:0,onChange:y=>u(m,{...f,from_top:y,from_bottom:void 0})}),s.jsx(Ts,{label:"from_bottom",value:typeof f.from_bottom=="number"?f.from_bottom:0,onChange:y=>u(m,{...f,from_bottom:y||void 0})}),s.jsx(xc,{def:f,otherIds:t(m),onChange:y=>u(m,y)})]}):s.jsxs("div",{className:"space-y-1",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"text-[10px] text-text-muted w-16",children:"anchor"}),s.jsx("input",{value:f.anchor??"",onChange:y=>u(m,{...f,anchor:y.target.value}),placeholder:"^regex locating section start",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-primary text-[10px] font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-text-secondary",children:[s.jsx("input",{type:"checkbox",checked:!!f.anchor_last,onChange:y=>u(m,{...f,anchor_last:y.target.checked||void 0}),className:"accent-[var(--accent-primary)]"}),"last"]})]}),s.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:s.jsx(xc,{def:f,otherIds:t(m),onChange:y=>u(m,y)})}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("span",{className:"text-[10px] text-text-muted w-16",children:"ctx next"}),s.jsx("input",{value:((p=f.anchor_context)==null?void 0:p.next)??"",onChange:y=>u(m,{...f,anchor_context:{...f.anchor_context,next:y.target.value||void 0}}),placeholder:"optional: line after anchor must match",spellCheck:!1,className:"flex-1 bg-bg-secondary text-text-secondary text-[10px] font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]})]}),i[m]&&s.jsxs("div",{className:"border-t border-border-subtle pt-1",children:[s.jsxs("div",{className:"text-[9px] text-text-muted mb-0.5",children:["captured lines ",i[m].fromLine,"–",i[m].toLine,i[m].text.trim()===""&&s.jsx("span",{className:"text-amber-400 ml-1",children:"(empty — check bounds)"})]}),s.jsx("pre",{className:"font-mono text-[10px] text-text-secondary whitespace-pre-wrap break-all bg-bg-secondary rounded border border-border-subtle px-2 py-1 max-h-28 overflow-y-auto",children:i[m].text||"(empty)"})]})]},m)})})]})}function xc({def:e,otherIds:t,onChange:n}){const r=e.until??"",o=r.startsWith("^");return s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-text-secondary",children:["until",s.jsxs("select",{value:o?"__regex__":r,onChange:a=>{const i=a.target.value;n(i===""?{...e,until:void 0}:i==="__regex__"?{...e,until:r.startsWith("^")?r:"^"}:{...e,until:i})},className:"bg-bg-secondary text-accent-primary rounded border border-border-default px-1 py-0.5",children:[s.jsx("option",{value:"",children:"(none)"}),t.map(a=>s.jsx("option",{value:a,children:a},a)),s.jsx("option",{value:"__regex__",children:"regex…"})]}),o&&s.jsx("input",{value:r,onChange:a=>n({...e,until:a.target.value}),spellCheck:!1,className:"w-40 bg-bg-secondary text-text-primary font-mono rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]})}function I0({model:e,onChange:t,onPreview:n,preview:r,onTestSections:o,sectionPreview:a}){const i=e.states.map(m=>m.id),c=Object.keys(e.sections??{}),u=l.useCallback(m=>t({...e,...m}),[e,t]),h=(m,f)=>u({states:e.states.map((x,w)=>w===m?{...x,...f}:x)}),d=(m,f)=>u({transitions:e.transitions.map((x,w)=>w===m?{...x,...f}:x)});return s.jsxs("div",{className:"space-y-3",children:[s.jsx(T0,{sections:e.sections??{},otherSectionIds:m=>c.filter(f=>f!==m),onChange:m=>u({sections:m}),onTest:()=>o(e.sections??{}),testResult:a}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-text-secondary text-[10px] uppercase tracking-widest font-semibold",children:"States"}),s.jsx("button",{type:"button",className:"text-[10px] text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>u({states:[...e.states,{id:`state${e.states.length}`,label:"New"}]}),children:"+ state"})]}),s.jsx("div",{className:"space-y-1.5",children:e.states.map((m,f)=>s.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-2 space-y-1",children:[s.jsxs("div",{className:"flex items-end gap-2 flex-wrap",children:[s.jsxs("label",{className:"flex flex-col gap-0.5",children:[s.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide",children:"id (used by transitions)"}),s.jsx("input",{value:m.id,onChange:x=>h(f,{id:x.target.value}),placeholder:"idle",className:"w-32 bg-bg-secondary text-accent-primary font-mono text-[11px] rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),s.jsxs("label",{className:"flex flex-col gap-0.5 flex-1",children:[s.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide",children:"label (shown in dashboard)"}),s.jsx("input",{value:m.label,onChange:x=>h(f,{label:x.target.value}),placeholder:"Ready",className:"w-full bg-bg-secondary text-text-primary text-[11px] rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"})]}),s.jsx("button",{type:"button",className:"text-text-muted hover:text-status-error text-sm px-1 pb-0.5",onClick:()=>u({states:e.states.filter((x,w)=>w!==f)}),children:"×"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-[10px] text-text-secondary flex-wrap",children:[s.jsxs("label",{className:"flex items-center gap-1",children:[s.jsx("input",{type:"radio",name:"initial",checked:!!m.initial,onChange:()=>u({states:e.states.map((x,w)=>({...x,initial:w===f}))}),className:"accent-[var(--accent-primary)]"}),"initial"]}),s.jsxs("label",{className:"flex items-center gap-1",children:[s.jsx("input",{type:"checkbox",checked:!!m.modal,onChange:x=>h(f,{modal:x.target.checked||void 0}),className:"accent-[var(--accent-primary)]"}),"modal"]}),s.jsxs("label",{className:"flex items-center gap-1",children:["status",s.jsxs("select",{value:m.status??"",onChange:x=>h(f,{status:x.target.value||void 0}),className:"bg-bg-secondary text-text-primary rounded border border-border-default px-1 py-0.5",children:[s.jsx("option",{value:"",children:"(auto)"}),s.jsx("option",{value:"idle",children:"idle"}),s.jsx("option",{value:"generating",children:"generating"}),s.jsx("option",{value:"approval",children:"approval"})]})]})]})]},f))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-text-secondary text-[10px] uppercase tracking-widest font-semibold",children:"Transitions"}),s.jsx("button",{type:"button",className:"text-[10px] text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>u({transitions:[...e.transitions,{from:i[0]??"",to:i[0]??""}]}),children:"+ transition"})]}),s.jsx("div",{className:"space-y-1.5",children:e.transitions.map((m,f)=>s.jsxs("div",{className:"border border-border-default/60 rounded bg-surface-secondary p-2 space-y-1.5",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"text-[10px] text-text-muted",children:"from"}),s.jsx(M0,{value:m.from,states:i,onChange:x=>d(f,{from:x})}),s.jsx("span",{className:"text-[10px] text-text-muted",children:"→"}),s.jsx("select",{value:m.to,onChange:x=>d(f,{to:x.target.value}),className:"bg-bg-secondary text-status-online font-mono text-[10px] rounded border border-border-default px-1 py-0.5",children:i.map(x=>s.jsx("option",{value:x,children:x},x))}),s.jsx("span",{className:"text-[10px] text-text-muted ml-1",children:"label"}),s.jsx("input",{value:m.label??"",onChange:x=>d(f,{label:x.target.value||void 0}),placeholder:"debug name only (optional)",title:"Display name shown in the debug history/transition table. Does not affect behaviour.",className:"flex-1 min-w-[120px] bg-bg-secondary text-text-secondary text-[10px] rounded border border-border-default px-1.5 py-0.5 outline-none focus:border-accent"}),s.jsx("button",{type:"button",className:"text-text-muted hover:text-status-error text-sm px-1",onClick:()=>u({transitions:e.transitions.filter((x,w)=>w!==f)}),children:"×"})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(Ts,{label:"min_hold_ms",value:m.min_hold_ms??0,onChange:x=>d(f,{min_hold_ms:x||void 0})}),s.jsx(Ts,{label:"priority",value:m.priority??0,onChange:x=>d(f,{priority:x||void 0})})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[s.jsx("span",{className:"text-[10px] text-text-muted",children:"when"}),!m.when&&s.jsx("button",{type:"button",className:"text-[10px] text-text-secondary hover:text-text-primary px-1.5 py-0.5 rounded border border-border-default hover:bg-bg-glass-hover",onClick:()=>d(f,{when:{section:c[0],matches:""}}),children:"+ guard condition"}),m.when&&s.jsx("button",{type:"button",className:"text-[10px] text-text-muted hover:text-status-error",onClick:()=>d(f,{when:void 0}),children:"remove guard"})]}),m.when&&s.jsx(Ki,{cond:m.when,path:`t${f}`,sections:c,onChange:x=>d(f,{when:x}),onPreview:n,preview:r})]})]},f))})]})]})}function M0({value:e,states:t,onChange:n}){const r=new Set(Array.isArray(e)?e:e==="*"?t:[e]),o=e==="*",a=i=>{const c=new Set(r);c.has(i)?c.delete(i):c.add(i);const u=t.filter(h=>c.has(h));n(u.length===1?u[0]:u)};return s.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.map(i=>s.jsx("button",{type:"button",onClick:()=>a(i),className:`font-mono text-[10px] px-1 py-0.5 rounded border ${o||r.has(i)?"text-accent-primary bg-accent-primary/20 border-accent":"text-text-muted border-border-default hover:border-border-default"}`,children:i},i))})}function Bn(e){const t=Date.now()-e;if(t<0)return"just now";if(t<2e3)return`${t}ms ago`;if(t<6e4)return`${(t/1e3).toFixed(1)}s ago`;const n=Math.floor(t/6e4);return n<60?`${n}m ago`:`${Math.floor(n/60)}h ago`}function yc(e){return e<=0?"":e<1e3?`${e}ms`:`${(e/1e3).toFixed(1)}s`}const D0={busy_hold_expired:"text-status-warning bg-status-warning/20 border border-status-warning/40",idle_hold_committed:"text-status-online bg-status-online/20 border border-status-online/40",completion_idle_after:"text-accent-primary bg-accent-primary/20 border border-accent",forced_completion:"text-orange-200 bg-orange-500/20 border border-orange-500/30",forceEmit:"text-purple-200 bg-purple-500/20 border border-purple-500/30",spec_reload:"text-purple-200 bg-purple-500/20 border border-purple-500/30",eval_match:"text-text-secondary bg-bg-glass border border-border-default"},P0={idle:"text-status-online bg-status-online/20 border border-status-online/40",busy:"text-yellow-100 bg-yellow-600/30 border border-yellow-500/40",generating:"text-yellow-100 bg-yellow-600/30 border border-yellow-500/40",approval:"text-orange-100 bg-orange-600/30 border border-orange-500/40",waiting_approval:"text-orange-100 bg-orange-600/30 border border-orange-500/40",picker:"text-accent-primary bg-accent-primary/20 border border-accent",signing_in:"text-accent-primary bg-accent-primary/20 border border-accent"};function oa(e){return P0[e]??"text-text-primary bg-bg-glass border border-border-default"}function Ar({children:e}){return s.jsx("div",{className:"text-text-secondary text-[10px] uppercase tracking-widest font-semibold mb-1.5 mt-0.5",children:e})}function Tr(){return s.jsx("div",{className:"border-t border-white/8 my-2"})}function dh({node:e,depth:t=0}){var o;const n=e.result?"text-status-online":"text-text-muted",r=e.result?"●":"○";return s.jsxs("div",{style:{marginLeft:t*10},className:"font-mono text-[10px] leading-relaxed",children:[s.jsxs("span",{className:n,children:[r," "]}),s.jsx("span",{className:"text-text-secondary",children:e.kind}),s.jsxs("span",{className:"text-text-muted",children:[" ",e.detail]}),e.remainingMs!=null&&e.remainingMs>0&&s.jsxs("span",{className:"text-status-warning",children:[" (",e.remainingMs,"ms left)"]}),(o=e.children)==null?void 0:o.map((a,i)=>s.jsx(dh,{node:a,depth:t+1},i))]})}function L0({t:e}){const[t,n]=l.useState(!1),r=e.fires?"text-status-online bg-status-online/20 border-status-online/40":e.holdSatisfied?"text-text-secondary bg-bg-glass border-border-default":"text-status-warning bg-status-warning/20 border-status-warning/40";return s.jsxs("div",{className:"border border-border-default rounded bg-surface-secondary overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center gap-2 px-2 py-1 hover:bg-bg-glass-hover text-left",onClick:()=>n(o=>!o),children:[s.jsx("span",{className:"text-[10px] text-text-muted w-3",children:e.cond?t?"▾":"▸":" "}),s.jsxs("span",{className:`font-mono text-[11px] px-1.5 py-0.5 rounded border ${r}`,children:["→ ",e.to]}),s.jsx("span",{className:"text-text-secondary font-mono text-[10px] truncate",children:e.label}),s.jsxs("span",{className:"ml-auto flex items-center gap-1.5 shrink-0",children:[e.fires&&s.jsx("span",{className:"text-status-online text-[10px] font-mono",children:"FIRES"}),!e.holdSatisfied&&s.jsxs("span",{className:"text-status-warning text-[10px] font-mono",children:["hold ",e.holdRemainingMs,"ms"]}),s.jsx("span",{className:`text-[10px] font-mono ${e.condResult?"text-status-online":"text-text-muted"}`,children:e.condResult?"cond✓":"cond✗"})]})]}),t&&e.cond&&s.jsx("div",{className:"px-3 pb-1.5 pt-0.5 bg-bg-secondary border-t border-border-default",children:s.jsx(dh,{node:e.cond})})]})}function R0({activeConv:e,onClose:t}){var ie,ke,xe,Se,pe;const{sendCommand:n}=yt(),[r,o]=l.useState(!0),[a,i]=l.useState(null),[c,u]=l.useState(null),[h,d]=l.useState(!1),[m,f]=l.useState(new Set(["footer"])),[x,w]=l.useState("Snapshot"),[p,y]=l.useState(!1),[k,b]=l.useState(null),[j,S]=l.useState(!1),[v,g]=l.useState(""),[N,C]=l.useState(!1),[A,T]=l.useState("idle"),[M,L]=l.useState(null),[P,B]=l.useState([]),[K,F]=l.useState({}),[R,Q]=l.useState(null),[E,I]=l.useState(!1),$=e.daemonId||((ie=e.routeId)==null?void 0:ie.split(":")[0])||e.routeId||"",D=e.sessionId||"",U=l.useCallback(async()=>{o(!0),u(null);try{const G=await n($,"get_spec_debug",{targetSessionId:D}),O=G&&typeof G=="object"?G:{},Z=O.result&&typeof O.result=="object"?O.result:O;Z!=null&&Z.success?i(Z):(u((Z==null?void 0:Z.error)||"Failed to load spec debug"),i(null))}catch(G){u((G==null?void 0:G.message)||String(G)),i(null)}finally{o(!1)}},[n,$,D]);l.useEffect(()=>{U()},[U]),l.useEffect(()=>{if(!E)return;const G=setInterval(()=>{U()},1e3);return()=>clearInterval(G)},[E,U]),l.useEffect(()=>{const G=O=>{O.key==="Escape"&&!p&&t()};return window.addEventListener("keydown",G),()=>window.removeEventListener("keydown",G)},[t,p]);const Y=l.useCallback(async G=>{try{const O=await n($,"validate_spec",{content:JSON.stringify(G)}),Z=O&&typeof O=="object"?O:{},q=Z.result&&typeof Z.result=="object"?Z.result:Z;B(q!=null&&q.valid?[]:(q==null?void 0:q.errors)??["validation failed"])}catch(O){B([(O==null?void 0:O.message)||String(O)])}},[n,$]),ae=l.useCallback(async()=>{L(null),T("idle"),F({});try{const G=await n($,"get_spec_source",{targetSessionId:D}),O=G&&typeof G=="object"?G:{},Z=O.result&&typeof O.result=="object"?O.result:O;if(!(Z!=null&&Z.success)||typeof Z.content!="string"){L((Z==null?void 0:Z.error)||"Failed to load spec source");return}g(Z.content);let q=null;try{q=JSON.parse(Z.content)}catch{}q&&q.$schema==="adhdev:cli/spec@4"?(b(q),S(!1),Y(q)):(b(null),S(!0)),C(!1),y(!0)}catch(G){L((G==null?void 0:G.message)||String(G))}},[n,$,D,Y]),z=l.useCallback(G=>{b(G),g(JSON.stringify(G,null,2)),C(!0),T("idle"),Y(G)},[Y]),X=l.useCallback(async(G,O)=>{F(Z=>({...Z,[G]:"loading"}));try{const Z=await n($,"eval_condition_preview",{targetSessionId:D,condition:O}),q=Z&&typeof Z=="object"?Z:{},me=q.result&&typeof q.result=="object"?q.result:q;!(me!=null&&me.success)||!me.result?F(Te=>({...Te,[G]:{result:!1,detail:me==null?void 0:me.error}})):F(Te=>({...Te,[G]:{result:me.result.result,detail:me.result.detail}}))}catch(Z){F(q=>({...q,[G]:{result:!1,detail:Z==null?void 0:Z.message}}))}},[n,$,D]),de=l.useCallback(async G=>{Q("loading");try{const O=await n($,"resolve_section_preview",{targetSessionId:D,sections:G}),Z=O&&typeof O=="object"?O:{},q=Z.result&&typeof Z.result=="object"?Z.result:Z;!(q!=null&&q.success)||!Array.isArray(q.sections)?Q({error:(q==null?void 0:q.error)||"resolve failed"}):Q({sections:q.sections,screenLineCount:q.screenLineCount??0})}catch(O){Q({error:(O==null?void 0:O.message)||String(O)})}},[n,$,D]),re=l.useCallback(async()=>{var Z,q;const G=(Z=a==null?void 0:a.snapshot)==null?void 0:Z.specPath;if(!G){L("No spec path on this session");return}if(!j&&P.length>0){L("Fix validation errors before saving");return}const O=!j&&k?JSON.stringify(k,null,2):v;T("saving"),L(null);try{const me=await n($,"write_spec_source",{specPath:G,content:O}),Te=me&&typeof me=="object"?me:{},_=Te.result&&typeof Te.result=="object"?Te.result:Te;if(!(_!=null&&_.success)){T("error"),L(((q=_==null?void 0:_.validationErrors)==null?void 0:q.join(`
49
+ `))||(_==null?void 0:_.error)||"Save failed");return}T("saved"),C(!1),setTimeout(()=>{U()},400),setTimeout(()=>T("idle"),1500)}catch(me){T("error"),L((me==null?void 0:me.message)||String(me))}},[n,$,(ke=a==null?void 0:a.snapshot)==null?void 0:ke.specPath,v,k,j,P,U]),W=a==null?void 0:a.snapshot,oe=async()=>{var _,te,ve;let G=a;G||(await U(),G=a);const O=G==null?void 0:G.snapshot,Z=[];if(Z.push("# Spec Debug Snapshot"),Z.push(`Generated: ${new Date().toISOString()}`),Z.push(`Session: ${(G==null?void 0:G.sessionId)??""} (${(G==null?void 0:G.providerType)??""})`),Z.push(`Spec: ${(O==null?void 0:O.spec_id)??""} (${(O==null?void 0:O.specPath)??""})`),Z.push(`Provider: ${(O==null?void 0:O.name)??""} (${(O==null?void 0:O.cliType)??""})`),Z.push(`Working dir: ${(O==null?void 0:O.workingDir)??""}`),Z.push(`Spawned: ${O!=null&&O.spawnedAtMs?new Date(O.spawnedAtMs).toISOString():""}`),Z.push(""),Z.push("## Current State"),Z.push(`State: ${((_=O==null?void 0:O.current_state)==null?void 0:_.id)??"none"} (${((te=O==null?void 0:O.current_state)==null?void 0:te.label)??""})`),Z.push(`Status: ${(O==null?void 0:O.status)??""}`),Z.push(`Idle hold pending: ${(O==null?void 0:O.idleHoldPending)??!1}`),Z.push(`Exited: ${(O==null?void 0:O.exited)??!1}`),Z.push(`Last busy: ${O!=null&&O.lastBusyAt?Bn(O.lastBusyAt):""}`),Z.push(`Cursor: ${(O==null?void 0:O.cursorPosition)!=null?`(${O.cursorPosition.row},${O.cursorPosition.col})`:"n/a"}`),(ve=O==null?void 0:O.completionIdleDebounce)!=null&&ve.active){const ce=O.completionIdleDebounce;Z.push(`completion_idle_after: age=${ce.ageMs}ms hold=${ce.holdMs}ms force=${ce.forceAfterMs}ms remaining=${Math.max(0,ce.holdMs-ce.ageMs)}ms`)}if(Z.push(""),Z.push("## Modal"),O!=null&&O.current_modal){const ce=O.current_modal.buttons.map(H=>H.label).join(" / ");Z.push(`${O.current_modal.title??""} [${ce}]`)}else Z.push("none");Z.push(""),Z.push("## State History (last 20)");const q=O!=null&&O.stateHistory?[...O.stateHistory].reverse().slice(0,20):[];for(const ce of q){const H=ce.reason!=null?typeof ce.reason=="string"?ce.reason:JSON.stringify(ce.reason):"",fe=ce.debounceKind!=null?typeof ce.debounceKind=="string"?ce.debounceKind:JSON.stringify(ce.debounceKind):"",je=ce.matchedStateId!=null?String(ce.matchedStateId):"",Ce=(ce.matchedRules??[]).map(Be=>typeof Be=="string"?Be:JSON.stringify(Be)).join(", ");Z.push(`- ${ce.stateId} @ ${new Date(ce.at).toISOString()} held ${ce.durationMs}ms | reason: ${H} | debounce: ${fe} | eval→${je} | rules: ${Ce}`)}if(Z.push(""),Z.push("## Sections"),O!=null&&O.sections)for(const[ce,H]of Object.entries(O.sections)){const fe=H.split(`
50
+ `).slice(0,3).join(`
51
+ `);Z.push(`${ce}: ${fe}`)}Z.push(""),Z.push("## Last Assistant Message");const Te=[...(O==null?void 0:O.messages)??(O==null?void 0:O.committedMessages)??[]].reverse().find(ce=>ce.role==="assistant");Z.push(Te?Te.content.slice(0,400):""),Z.push(""),Z.push("## Screen (first 50 lines)"),Z.push(O!=null&&O.screen?O.screen.split(`
52
+ `).slice(0,50).join(`
53
+ `):"");try{await navigator.clipboard.writeText(Z.join(`
54
+ `)),w("Copied!"),setTimeout(()=>w("Snapshot"),1500)}catch(ce){console.error("[SpecDebugPanel] clipboard write failed",ce)}},V=G=>{f(O=>{const Z=new Set(O);return Z.has(G)?Z.delete(G):Z.add(G),Z})};return s.jsx("div",{role:"dialog","aria-modal":"true","aria-label":"Spec debug",className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center bg-black/60 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] px-0 sm:items-center sm:p-4",onClick:t,style:{pointerEvents:"auto"},children:s.jsxs("div",{className:"bg-bg-secondary text-text-primary border border-border-default rounded-t-xl sm:rounded-lg shadow-2xl max-w-2xl w-full max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[88vh] flex flex-col",onClick:G=>G.stopPropagation(),children:[s.jsxs("div",{className:"flex items-center justify-between border-b border-border-default px-4 py-2.5 shrink-0 gap-2 min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 overflow-hidden",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary shrink-0",children:"Spec Debug"}),W&&s.jsx("span",{className:"text-[11px] text-text-secondary font-mono bg-surface-secondary px-1.5 py-0.5 rounded truncate",children:W.spec_id})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[(W==null?void 0:W.specPath)&&s.jsx("button",{type:"button",className:`text-[11px] transition-colors px-2 py-1 rounded border ${p?"text-accent-primary bg-accent-primary/20 border-accent":"text-text-secondary hover:text-text-primary hover:bg-bg-glass-hover border-transparent hover:border-border-default"}`,onClick:()=>{p?y(!1):ae()},disabled:r,children:p?"Close Editor":"Edit Spec"}),s.jsx("button",{type:"button",className:"text-[11px] text-text-secondary hover:text-text-primary transition-colors px-2 py-1 rounded hover:bg-bg-glass-hover border border-transparent hover:border-border-default",onClick:()=>{oe()},disabled:r,children:x}),s.jsx("button",{type:"button",className:"text-[11px] text-text-secondary hover:text-text-primary transition-colors px-2 py-1 rounded hover:bg-bg-glass-hover border border-transparent hover:border-border-default",onClick:()=>{U()},disabled:r,children:r?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"text-text-secondary hover:text-text-primary transition-colors text-xl leading-none w-7 h-7 flex items-center justify-center rounded hover:bg-bg-glass-hover",onClick:t,"aria-label":"Close",children:"×"})]})]}),p&&s.jsxs("div",{className:"flex-1 flex flex-col min-h-0 px-4 py-3 gap-2",children:[s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.jsxs("div",{className:"inline-flex rounded border border-border-default overflow-hidden text-[10px]",children:[s.jsx("button",{type:"button",className:`px-2 py-0.5 ${j?"text-text-secondary hover:bg-bg-glass-hover":"bg-accent-primary/20 text-accent-primary"}`,onClick:()=>{if(j)try{const G=JSON.parse(v);b(G),Y(G)}catch{return}S(!1)},disabled:!k&&j,children:"Form"}),s.jsx("button",{type:"button",className:`px-2 py-0.5 ${j?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>{k&&g(JSON.stringify(k,null,2)),S(!0)},children:"JSON"})]}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate flex-1",title:W==null?void 0:W.specPath,children:((W==null?void 0:W.specPath)??"").split("/").slice(-3).join("/")}),N&&s.jsx("span",{className:"text-status-warning text-[10px]",children:"unsaved"}),!j&&P.length>0&&s.jsxs("span",{className:"text-status-error text-[10px]",children:[P.length," error",P.length>1?"s":""]}),s.jsx("button",{type:"button",className:`text-[11px] px-2.5 py-1 rounded border transition-colors ${A==="saving"||!j&&P.length>0?"text-text-muted border-border-default cursor-not-allowed":"text-status-online bg-status-online/20 border-status-online/40 hover:bg-status-online/20"}`,onClick:()=>{re()},disabled:A==="saving"||!j&&P.length>0,children:A==="saving"?"Saving…":A==="saved"?"Saved ✓ (reloading)":"Save & Apply"})]}),M&&s.jsx("pre",{className:"text-status-error bg-status-error/20 border border-status-error/40 rounded p-2 text-[10px] whitespace-pre-wrap shrink-0 max-h-28 overflow-y-auto",children:M}),!j&&P.length>0&&s.jsx("div",{className:"text-status-error bg-status-error/20 border border-status-error/40 rounded p-1.5 text-[10px] shrink-0 max-h-24 overflow-y-auto space-y-0.5",children:P.map((G,O)=>s.jsx("div",{className:"font-mono",children:G},O))}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:j||!k?s.jsx("textarea",{value:v,onChange:G=>{g(G.target.value),C(!0),T("idle")},spellCheck:!1,className:"w-full h-full min-h-[300px] font-mono text-[11px] leading-relaxed bg-bg-secondary text-text-primary border border-border-default rounded p-3 resize-none outline-none focus:border-accent"}):s.jsx(I0,{model:k,onChange:z,onPreview:X,preview:K,onTestSections:de,sectionPreview:R})}),s.jsx("div",{className:"text-[10px] text-text-muted shrink-0",children:j?"Raw JSON — validated on save.":'Build the FSM; from/to are constrained to existing states. "test" evaluates a condition against the live screen. Save hot-reloads the session.'})]}),!p&&s.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))] space-y-3 text-[12px]",children:[c&&s.jsx("div",{className:"text-status-error bg-status-error/20 border border-status-error/40 rounded p-2",children:c}),r&&!a&&s.jsx("div",{className:"text-text-muted text-center py-6",children:"Loading…"}),a&&!a.isSpecProvider&&s.jsxs("div",{className:"text-text-muted text-center py-6",children:["Not a spec-driven provider (",a.providerType||"unknown",")."]}),W&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 text-[11px] bg-surface-secondary rounded-md px-3 py-2 border border-border-default",children:[W.name&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"Provider"}),s.jsxs("span",{className:"font-mono text-text-primary",children:[W.name," ",s.jsxs("span",{className:"text-text-muted",children:["(",W.cliType,")"]})]})]}),W.workingDir&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"Dir"}),s.jsx("span",{className:"font-mono text-text-secondary truncate",title:W.workingDir,children:W.workingDir})]}),W.spawnedAtMs?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"Spawned"}),s.jsx("span",{className:"text-text-secondary",children:Bn(W.spawnedAtMs)})]}):null,W.providerSessionId&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"Session"}),s.jsx("span",{className:"font-mono text-text-muted text-[10px] truncate",title:W.providerSessionId,children:W.providerSessionId})]})]}),s.jsxs("div",{className:"flex items-center gap-2 flex-wrap bg-surface-secondary rounded-md px-3 py-2 border border-border-default",children:[s.jsx("span",{className:`font-semibold font-mono text-[12px] px-2 py-0.5 rounded ${W.current_state?oa(W.current_state.id):"text-text-muted"}`,children:W.current_state?W.current_state.id:"none"}),((xe=W.current_state)==null?void 0:xe.label)&&W.current_state.label!==W.current_state.id&&s.jsx("span",{className:"text-text-secondary text-[11px]",children:W.current_state.label}),W.status&&W.status!==((Se=W.current_state)==null?void 0:Se.id)&&s.jsxs("span",{className:"text-text-muted text-[11px]",children:["engine: ",s.jsx("span",{className:`font-mono ${oa(W.status)} px-1 py-0.5 rounded text-[10px]`,children:W.status})]}),W.idleHoldPending&&s.jsx("span",{className:"text-yellow-200 text-[10px] bg-yellow-600/25 border border-yellow-500/35 px-1.5 py-0.5 rounded font-mono",children:"idle hold pending"}),W.exited&&s.jsx("span",{className:"text-status-error text-[10px] bg-status-error/20 border border-status-error/40 px-1.5 py-0.5 rounded font-mono",children:"exited"}),W.cursorPosition!=null&&s.jsxs("span",{className:"text-text-muted text-[11px] font-mono",children:["cursor: ",s.jsxs("span",{className:"text-text-secondary",children:[W.cursorPosition.row,",",W.cursorPosition.col]})]}),W.lastBusyAt>0&&s.jsxs("span",{className:"text-text-muted text-[11px] ml-auto",children:["last busy: ",s.jsx("span",{className:"text-text-secondary",children:Bn(W.lastBusyAt)})]})]}),((pe=W.completionIdleDebounce)==null?void 0:pe.active)&&s.jsxs("div",{className:"flex items-center gap-2 text-[11px] bg-accent-primary/20 border border-accent rounded-md px-3 py-1.5 font-mono",children:[s.jsx("span",{className:"text-accent-primary",children:"completion_idle_after"}),s.jsxs("span",{className:"text-text-secondary",children:["age: ",s.jsxs("span",{className:"text-accent-primary",children:[W.completionIdleDebounce.ageMs,"ms"]})]}),s.jsx("span",{className:"text-text-muted",children:"/"}),s.jsxs("span",{className:"text-text-secondary",children:["hold: ",s.jsxs("span",{className:"text-text-secondary",children:[W.completionIdleDebounce.holdMs,"ms"]})]}),s.jsxs("span",{className:"text-text-secondary",children:["force: ",s.jsxs("span",{className:"text-text-secondary",children:[W.completionIdleDebounce.forceAfterMs,"ms"]})]}),s.jsx("span",{className:"text-text-muted ml-auto",children:W.completionIdleDebounce.ageMs<W.completionIdleDebounce.holdMs?s.jsxs("span",{className:"text-status-warning",children:["hold remaining: ",W.completionIdleDebounce.holdMs-W.completionIdleDebounce.ageMs,"ms"]}):W.completionIdleDebounce.ageMs<W.completionIdleDebounce.forceAfterMs?s.jsxs("span",{className:"text-orange-300",children:["force in: ",W.completionIdleDebounce.forceAfterMs-W.completionIdleDebounce.ageMs,"ms"]}):s.jsx("span",{className:"text-status-error",children:"overdue"})})]}),W.current_modal&&s.jsxs("div",{className:"bg-orange-900/30 border border-orange-600/40 rounded-md p-2.5",children:[s.jsx("span",{className:"text-orange-200 font-semibold",children:"Modal: "}),s.jsx("span",{className:"text-text-secondary",children:W.current_modal.title||""}),W.current_modal.buttons.length>0&&s.jsxs("span",{className:"text-text-secondary ml-2",children:["[",W.current_modal.buttons.map(G=>G.label).join(" / "),"]"]})]}),W.fsm&&s.jsxs(s.Fragment,{children:[s.jsx(Tr,{}),s.jsxs("div",{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[s.jsxs(Ar,{children:["FSM — outgoing from ",s.jsx("span",{className:"text-accent-primary font-mono normal-case",children:W.fsm.currentState})," (held ",yc(W.fsm.stateAgeMs),")"]}),s.jsxs("label",{className:"ml-auto flex items-center gap-1 text-[10px] text-text-muted cursor-pointer select-none mb-1.5",children:[s.jsx("input",{type:"checkbox",checked:E,onChange:G=>I(G.target.checked),className:"accent-[var(--accent-primary)]"}),"live"]})]}),s.jsxs("div",{className:"space-y-1",children:[W.fsm.transitions.length===0&&s.jsx("div",{className:"text-text-muted text-[11px] italic px-1",children:"no outgoing transitions (terminal state)"}),W.fsm.transitions.map((G,O)=>s.jsx(L0,{t:G},O))]})]})]}),s.jsx(Tr,{}),W.sections&&Object.keys(W.sections).length>0&&s.jsxs("div",{children:[s.jsx(Ar,{children:"Sections"}),s.jsx("div",{className:"space-y-1",children:Object.entries(W.sections).map(([G,O])=>{var Te;const Z=m.has(G),q=O.split(`
55
+ `),me=((Te=q[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:()=>V(G),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:G}),!Z&&s.jsx("span",{className:"text-text-secondary truncate font-mono text-[11px]",children:me}),s.jsxs("span",{className:"ml-auto text-text-muted text-[10px] shrink-0",children:[q.length,"L"]})]}),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:O||"(empty)"})]},G)})})]}),s.jsx(Tr,{}),W.stateHistory&&W.stateHistory.length>0&&s.jsxs("div",{children:[s.jsxs(Ar,{children:["State History (",W.stateHistory.length,")"]}),s.jsx("div",{className:"space-y-px",children:[...W.stateHistory].reverse().slice(0,20).map((G,O)=>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 ${oa(G.stateId)}`,children:G.stateId}),s.jsx("span",{className:"text-text-secondary text-[11px] shrink-0 tabular-nums",children:Bn(G.at)}),G.durationMs>0&&s.jsxs("span",{className:"text-text-muted text-[11px]",children:["held ",s.jsx("span",{className:"text-text-secondary",children:yc(G.durationMs)})]}),G.reason&&s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded font-mono shrink-0 ${D0[String(G.reason)]??"text-text-secondary bg-bg-glass border border-border-default"}`,children:String(G.reason)}),G.debounceKind&&String(G.debounceKind)!=="none"&&s.jsxs("span",{className:"text-text-muted text-[10px] font-mono",children:["debounce:",String(G.debounceKind)]}),G.matchedStateId&&String(G.matchedStateId)!==G.stateId&&s.jsxs("span",{className:"text-text-muted text-[10px] font-mono",children:["eval→",s.jsx("span",{className:"text-text-secondary",children:String(G.matchedStateId)})]})]}),G.matchedRules&&G.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:[G.matchedRules.slice(0,3).map((Z,q)=>s.jsx("span",{className:"font-mono text-[10px] text-accent-primary bg-accent-primary/20 border border-accent px-1.5 py-0.5 rounded break-all",children:typeof Z=="string"?Z:JSON.stringify(Z)},q)),G.matchedRules.length>3&&s.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",G.matchedRules.length-3," more"]})]})]},O))})]}),s.jsx(Tr,{}),(()=>{const G=W.messages??W.committedMessages??[];if(G.length===0)return null;const O=G.filter(me=>me.role==="user").length,Z=G.filter(me=>me.role==="assistant").length,q=[...G].reverse().find(me=>me.role==="assistant");return s.jsxs("div",{children:[s.jsxs(Ar,{children:["Transcript (",G.length," — ",O,"u / ",Z,"a)"]}),q&&s.jsxs("div",{className:"bg-surface-secondary border border-border-default rounded-md p-2.5 text-[11px]",children:[s.jsxs("div",{className:"text-text-muted mb-1 text-[10px]",children:["Last assistant ",q.receivedAt?Bn(q.receivedAt):""]}),s.jsxs("div",{className:"text-text-secondary font-mono whitespace-pre-wrap line-clamp-4 break-all",children:[q.content.slice(0,400),q.content.length>400?"…":""]})]})]})})(),W.specPath&&s.jsx("div",{className:"text-[10px] text-text-muted font-mono truncate border-t border-border-default pt-2 mt-1",title:W.specPath,children:W.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(G=>!G),children:[s.jsx("span",{className:"text-text-muted",children:h?"▾":"▸"}),s.jsxs("span",{children:["Raw screen (",W.screen?W.screen.split(`
56
+ `).length:0," lines)"]})]}),h&&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:W.screen||"(empty)"})]})]})]})]})})}function E0({activeConv:e,clearToken:t=0,terminalRef:n,handleSendChat:r,isSendingChat:o=!1,sendFeedbackMessage:a=null,isVisible:i=!0,isInputActive:c=!0}){var et;const{t:u}=Le("common");gs();const{sendPtyInput:h}=yt(),[d,m]=l.useState(!1),f=l.useRef(!1);f.current=d;const[x,w]=l.useState("Runtime terminal unavailable"),[p,y]=l.useState(!1),[k,b]=l.useState(null),[j,S]=l.useState(!1),[v,g]=l.useState(!1),[N,C]=l.useState(1),[A,T]=l.useState(!1),[M,L]=l.useState(!1),[P,B]=l.useState(!1),[K,F]=l.useState(!1),[R,Q]=l.useState(!1),[E,I]=l.useState({width:0,height:0}),[$,D]=l.useState({width:0,height:0}),[U,Y]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[ae,z]=l.useState(null),X=l.useRef(null),de=l.useRef(null),re=l.useRef(!1),W=l.useRef(!1),oe=l.useRef(i),V=l.useRef(0),ie=l.useRef(!1),ke=l.useRef(""),xe=l.useRef(null),Se=l.useRef(!1),pe=l.useRef(!1),G=l.useRef(null),O=l.useRef(null),Z=l.useRef(null),q=32*1024,me=()=>{var se,be,we,ze;return((be=(se=X.current)==null?void 0:se.ownerDocument)==null?void 0:be.defaultView)||((ze=(we=de.current)==null?void 0:we.ownerDocument)==null?void 0:ze.defaultView)||window},Te=se=>{const be=me();return{ownerWindow:be,frameId:be.requestAnimationFrame(se)}},_=()=>{const se=G.current;if(se){try{se.ownerWindow.cancelAnimationFrame(se.frameId)}catch{}G.current=null}},te=()=>{const se=O.current;if(se){try{se.ownerWindow.clearTimeout(se.timeoutId)}catch{}O.current=null}},ve=()=>{const se=Z.current;if(se){try{se.ownerWindow.clearTimeout(se.timeoutId)}catch{}Z.current=null}},ce=()=>{i&&G.current===null&&(G.current=Te(()=>{J()}))},H=e.tabKey,fe=e.sessionId||"",je=e.daemonId||((et=e.routeId)==null?void 0:et.split(":")[0])||e.routeId||"",Ce=Oi(e),Be=d?a||Ce:x,Xe=f0,dt=b0,it=.05,he=()=>{const se=$.width,be=$.height;if(!Number.isFinite(E.width)||E.width<=0||!Number.isFinite(E.height)||E.height<=0||!Number.isFinite(se)||se<=0||!Number.isFinite(be)||be<=0)return 1;const we=E.width/se,ze=E.height/be;return Number(Math.min(dt,Math.max(Xe,Math.min(we,ze))).toFixed(2))},$e=he(),Fe=re.current&&N>$e,Ie=Number.isFinite($.width)&&$.width>0?Math.max(E.width,Math.round($.width*N)):E.width,ye=Number.isFinite($.height)&&$.height>0?Math.max(E.height,Math.round($.height*N)):E.height,Oe=()=>{Te(()=>{const se=de.current;se&&(se.scrollLeft=0,se.scrollTop=se.scrollHeight-se.clientHeight)})},ut=()=>{var se,be;V.current=0,ie.current=!1,ke.current="",xe.current=null,Se.current=!1,pe.current=!1,re.current||(W.current=!1,C(1)),G.current!==null&&_(),m(!1),w("Runtime terminal unavailable"),ve(),te(),b(null),z(null),T(!1),y(!1),S(!1),g(!1),(be=(se=n.current)==null?void 0:se.reset)==null||be.call(se)},at=()=>{var se,be;V.current=0,ie.current=!1,ke.current="",xe.current=null,Se.current=!1,pe.current=!1,G.current!==null&&_(),m(!0),w(""),ve(),te(),b(null),z(null),T(!1),y(!1),S(!1),g(!1),(be=(se=n.current)==null?void 0:se.reset)==null||be.call(se)},ht=()=>{pe.current&&(pe.current=!1,Te(()=>{var se,be;(be=(se=n.current)==null?void 0:se.scrollToTop)==null||be.call(se)}))},J=()=>{if(G.current=null,!i)return;const se=ke.current;if(!se)return;const be=se.slice(0,q);ke.current=se.slice(be.length);const we=n.current;if(!we){ke.current=be+ke.current,ce();return}we.write(be,()=>{if(ke.current.length>0){ce();return}ht()})},ee=se=>{se&&(ke.current+=se,ce())},le=(se,be=0,we,ze,We={})=>{var qe,Ye,Tt,Wt;const tt=!!We.force;!tt&&be>0&&V.current>=be||!tt&&be===0&&ie.current||(V.current=be,be>0&&S(!0),m(!0),w(""),typeof we=="number"&&typeof ze=="number"&&we>0&&ze>0&&((Ye=(qe=n.current)==null?void 0:qe.resize)==null||Ye.call(qe,we,ze)),ke.current="",(Wt=(Tt=n.current)==null?void 0:Tt.reset)==null||Wt.call(Tt),se?ee(se):ht())};l.useEffect(()=>{ut()},[fe]),l.useEffect(()=>{var be;if(!fe)return;const se=((be=kt.onRuntimeEvent)==null?void 0:be.call(kt,fe,we=>{if(!(!we||we.sessionId!==fe)){if(we.type==="runtime_snapshot"){if(!i){xe.current={text:we.text||"",seq:we.seq||0,cols:we.cols,rows:we.rows,force:!!we.force};return}le(we.text||"",we.seq||0,we.cols,we.rows,{force:!!we.force});return}if(we.type==="session_output"){ie.current=!0,typeof we.seq=="number"&&(V.current=Math.max(V.current,we.seq),we.seq>0&&S(!0)),f.current||m(!0),f.current||w(""),typeof we.data=="string"&&ee(we.data);return}if(we.type==="session_cleared"){if(!i){Se.current=!0,ke.current="",xe.current=null;return}at();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()=>{se()}},[je,fe,n,i]);const ue=async(se={})=>{var be;if(!je||!fe)return{success:!1,error:"daemonId and sessionId are required"};se.preserveStatus||w(se.loadingMessage||"Loading runtime terminal...");try{const we=await((be=kt.requestRuntimeSnapshot)==null?void 0:be.call(kt,je,fe,{sinceSeq:se.sinceSeq,force:se.force}));return we&&we.success===!1?(se.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 se.preserveStatus||(m(!1),w(`Runtime terminal unavailable: ${ze}`)),{success:!1,error:ze}}},ge=async se=>{var tt,qe;const be=((tt=X.current)==null?void 0:tt.ownerDocument)||document,we=be.defaultView||window,ze=(qe=we.navigator)==null?void 0:qe.clipboard;if(ze!=null&&ze.writeText&&we.isSecureContext)try{return await ze.writeText(se),!0}catch{}let We=null;try{return We=be.createElement("textarea"),We.value=se,We.setAttribute("readonly","true"),We.style.position="fixed",We.style.left="-9999px",We.style.top="0",be.body.appendChild(We),We.focus(),We.select(),be.execCommand("copy")}catch{return!1}finally{We==null||We.remove()}},Ae=se=>{te(),z(se);const be=me();O.current={ownerWindow:be,timeoutId:be.setTimeout(()=>{O.current=null,z(we=>we===se?null:we)},2200)}},Pe=se=>{ve(),b(se);const be=me();Z.current={ownerWindow:be,timeoutId:be.setTimeout(()=>{Z.current=null,b(we=>we===se?null:we)},2200)}},Ne=async()=>{var We,tt,qe,Ye;const se=((tt=(We=n.current)==null?void 0:We.getSelection)==null?void 0:tt.call(We))||"",be=((Ye=(qe=n.current)==null?void 0:qe.getVisibleText)==null?void 0:Ye.call(qe))||"",we=se.trimEnd()||be.trimEnd();if(!we){Ae("Nothing to copy");return}if(!await ge(we)){Ae("Copy failed");return}Ae(se.trimEnd()?"Copied selection":"Copied visible terminal")},He=se=>{if(!d||!i)return;((h==null?void 0:h(je,fe,se))??!1)||Ae("Terminal input failed")},Ke=se=>{He(x0({ctrl:M,alt:P,shift:K},se)),L(!1),B(!1),F(!1)},Ze=async()=>{if(p)return;y(!0),b("Loading older terminal output..."),pe.current=!0;const se=await ue({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:d});if(y(!1),(se==null?void 0:se.success)===!1){pe.current=!1,b(`Older terminal output unavailable: ${se.error}`);return}g(!0),Pe("Older terminal output loaded"),Te(()=>{var be;(be=n.current)==null||be.bumpResize()})};l.useEffect(()=>{var be,we;if(!fe)return;je&&((be=kt.getState)==null?void 0:be.call(kt,je))==="connected"&&ue();const se=(we=kt.onStateChange)==null?void 0:we.call(kt,(ze,We)=>{ze!==je||We!=="connected"||ue()});return()=>{se==null||se()}},[je,fe,n]),l.useEffect(()=>{t&&ut()},[t,H,n]),l.useEffect(()=>{var ze,We;const se=X.current,be=(We=(ze=se==null?void 0:se.ownerDocument)==null?void 0:ze.defaultView)==null?void 0:We.ResizeObserver;if(!se||!be)return;const we=new be(tt=>{const qe=tt[0];if(!qe)return;const{width:Ye,height:Tt}=qe.contentRect;I(Wt=>{const ss=Math.round(Ye),Me=Math.round(Tt);return Wt.width===ss&&Wt.height===Me?Wt:{width:ss,height:Me}})});return we.observe(se),()=>we.disconnect()},[]),l.useEffect(()=>{if(re.current)return;const se=he();!Number.isFinite(se)||se<=0||C(be=>W.current?se<be-it?se:be:(W.current=!0,se))},[$.height,$.width,E.height,E.width]),l.useEffect(()=>{Fe&&Oe()},[Fe,ye,Ie]),l.useEffect(()=>{var we;const se=oe.current;if(oe.current=i,!i)return;se||g(!1),Se.current&&(Se.current=!1,at());const be=xe.current;be&&(xe.current=null,le(be.text,be.seq,be.cols,be.rows,{force:!!be.force})),je&&fe&&((we=kt.getState)==null?void 0:we.call(kt,je))==="connected"&&ue(),ke.current&&G.current===null&&ce(),Te(()=>{var ze;(ze=n.current)==null||ze.bumpResize()})},[je,i,fe]),l.useEffect(()=>()=>{G.current!==null&&_(),te(),ve()},[]),l.useEffect(()=>{const se=ze=>{var tt;const We=ze.detail;We!=null&&We.sessionId&&We.sessionId!==fe||d&&((tt=n.current)==null||tt.bumpResize())},be=me(),we=be===window?[window]:[window,be];for(const ze of we)ze.addEventListener("adhdev:fit-cli-terminal",se);return()=>{for(const ze of we)ze.removeEventListener("adhdev:fit-cli-terminal",se)}},[d,fe,n]);const Ue=d&&j&&!v&&(U.atTop||!U.canScroll)||p||!!k;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{ref:X,className:"flex-1 min-h-0 p-2 bg-[#0f1117] relative",children:[Ue&&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:!fe||p,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:u(p?"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:[ae&&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:ae}),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:()=>Q(se=>!se),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:()=>{Ne()},disabled:!d,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:u("terminal.copy")}),s.jsxs("div",{className:"relative",children:[s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>T(se=>!se),disabled:!d,"aria-label":u(A?"terminal.closeControlKeys":"terminal.openControlKeys"),"aria-expanded":A,"aria-controls":"terminal-control-keys-popover",title:"Open mobile-friendly terminal control keys",children:"Keys"}),A&&s.jsxs("div",{id:"terminal-control-keys-popover",role:"dialog","aria-label":u("terminal.openControlKeys"),className:"absolute right-0 top-10 w-72 rounded-2xl border border-white/10 bg-[#0b0d12]/95 p-3 text-white/85 shadow-2xl shadow-black/40 backdrop-blur-md",children:[s.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-[0.14em] text-white/45",children:"Terminal keys"}),s.jsx("button",{type:"button",className:"rounded-full px-2 py-0.5 text-[11px] text-white/55 transition-colors hover:bg-white/10 hover:text-white/85",onClick:()=>T(!1),"aria-label":u("terminal.closeControlKeys"),children:"×"})]}),s.jsx("div",{className:"mb-2 grid grid-cols-3 gap-1.5",children:[["Ctrl",M,L],["Alt",P,B],["Shift",K,F]].map(([se,be,we])=>s.jsx("button",{type:"button","aria-pressed":be,className:`h-9 rounded-lg border text-[12px] font-semibold transition-colors ${be?"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:se},se))}),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:()=>Ke("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:()=>Ke("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:()=>Ke("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:()=>Ke("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:()=>Ke("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:()=>Ke("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:()=>Ke("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:()=>He(""),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:()=>Ke("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:()=>Ke("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:()=>{re.current=!0,C(se=>{const be=Math.max($e,Number((se-.1).toFixed(2)));return be>$e&&Oe(),be})},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:()=>{re.current=!0,C(se=>{const be=Math.min(dt,Number((se+.1).toFixed(2)));return be>$e&&Oe(),be})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:de,className:Fe?"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:Ie>0?`${Ie}px`:"100%",height:ye>0?`${ye}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(au,{ref:n,readOnly:!d||!i,sizingMode:"measured",onViewportMetrics:D,onScrollMetrics:Y,onInput:se=>{!d||(h==null||h(je,fe,se))}})})})}),!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:x})]}),s.jsx(Nu,{contextKey:e.tabKey,panelLabel:xt(e),isSending:o,isBusy:!!Ce,statusMessage:Be,inlineStatusMessage:Be,onSend:async se=>Ce?!1:r(se),isActive:c&&i,showControlsToggle:!1,animateVisibility:!1}),R&&s.jsx(R0,{activeConv:e,onClose:()=>Q(!1)})]})}const _0=5e3,$0=12e3;function B0(e){return e==="disconnected"||e==="reconnecting"}function F0({wsStatus:e,showReconnected:t,loginUrl:n,onReconnect:r,reconnectDelayMs:o=_0,reconnectActionDelayMs:a=$0}){const{t:i}=Le(),c=B0(e),[u,h]=l.useState(()=>!c||o<=0),[d,m]=l.useState(()=>!c||a<=0),f=l.useRef(!1);l.useEffect(()=>{if(!c){h(!1);return}if(f.current=!1,o<=0){f.current=!0,h(!0);return}h(!1);const g=setTimeout(()=>{f.current=!0,h(!0)},o);return()=>clearTimeout(g)},[o,c]),l.useEffect(()=>{if(!c){m(!1);return}if(a<=0){m(!0);return}m(!1);const g=setTimeout(()=>{m(!0)},a);return()=>clearTimeout(g)},[a,c]);const x=c?u:e==="offline"||e==="auth_failed",w=!!(r&&e!=="auth_failed"&&(!c||d)),p=l.useMemo(()=>!t||e!=="connected"?!1:o<=0||f.current,[o,t,e]),y=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)"},j={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},S="fixed left-1/2 top-4 z-[var(--z-toast)] flex items-center justify-center pointer-events-none",v={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[x&&s.jsx("div",{className:S,style:v,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[y],border:b[y],color:j[y]},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")})]})}),p&&s.jsx("div",{className:S,style:v,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 uh({mode:e,onChange:t,compact:n=!1}){const{t:r}=Le("common"),o=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:o}):s.jsx(Zs,{size:o})})}const Bs="New session",H0="A connected machine is ready. Start a new session with any installed provider — CLI, ACP, or IDE.";function W0(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 O0(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 U0(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 co({git:e,className:t="",compact:n=!1}){const r=W0(e),o=O0(e);if(!r||!o)return null;const a=[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 ${U0(o)} ${t}`.trim(),title:a.join(" · ")||r,"data-git-tone":o,children:[s.jsx("span",{"aria-hidden":"true",children:"⑂"}),s.jsx("span",{className:"truncate",children:r})]})}function G0({wsStatus:e,isConnected:t,daemonCount:n,p2pStates:r={}}){if(e!=="connected")return{tone:"disconnected",titleKey:"connection.disconnected",subtitleKey:null};const o=Object.values(r),a=o.filter(c=>c==="connected").length,i=o.filter(c=>c==="connecting"||c==="new"||c==="checking").length;return n>0&&i>0&&a===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 vc({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function wc({notification:e,shortcutIndex:t,onOpen:n,onMarkRead:r,onMarkUnread:o,onDelete:a}){const{t:i}=Le(),c=jo(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:h=>{h.stopPropagation(),r()},children:i("notification.markRead")}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:h=>{h.stopPropagation(),o()},children:i("notification.markUnread")}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:h=>{h.stopPropagation(),a()},children:i("notification.delete")})]})]})}function K0({activeConv:e,wsStatus:t,isConnected:n,conversations:r,onOpenHistory:o,onOpenRemote:a,onStopCli:i,activeCliViewMode:c,onSetCliViewMode:u,onHideConversation:h,hiddenConversations:d=[],onShowConversation:m,onShowAllHidden:f,onResetPanelsToMain:x,inboxOpen:w,onInboxOpenChange:p,hiddenOpen:y,onHiddenOpenChange:k,onOpenNewSession:b,onOpenDashboardGuide:j,guideNudgeVisible:S=!1,actionShortcuts:v,notifications:g,notificationUnreadCount:N,onOpenNotification:C,onMarkNotificationRead:A,onMarkNotificationUnread:T,onDeleteNotification:M,onOpenGitDialog:L,onOpenMeshGraph:P}){var Z;const{t:B}=Le(),{ides:K,p2pStates:F={}}=gs(),R=!!e&&ct(e)&&!lt(e),Q=!!e&&lt(e),E=!!(e!=null&&e.daemonId)&&!!((Z=e==null?void 0:e.coordinator)!=null&&Z.meshId),I=c||(e?Ru(e)?"terminal":"chat":null),[$,D]=l.useState(!1),[U,Y]=l.useState(!1),ae=l.useRef(null),z=l.useRef(null),X=l.useRef(null),de=K.filter(q=>q.type==="adhdev-daemon"),re=G0({wsStatus:t,isConnected:n,daemonCount:de.length,p2pStates:F}),W=B(re.titleKey),oe=re.subtitleKey?B(re.subtitleKey):null,V=re.tone==="connected"?"#22c55e":re.tone==="limited"?"#eab308":"#ef4444",ie=re.tone==="connected"?"0 0 4px #22c55e80":re.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",ke=l.useMemo(()=>g.filter(q=>!q.readAt),[g]),xe=l.useMemo(()=>g.filter(q=>!!q.readAt),[g]),Se=l.useMemo(()=>ke.slice(0,9),[ke]),pe=N;l.useEffect(()=>{if(!w)return;const q=me=>{var Te;(Te=z.current)!=null&&Te.contains(me.target)||p(!1)};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[w,p]),l.useEffect(()=>{if(!y)return;const q=me=>{var Te;(Te=X.current)!=null&&Te.contains(me.target)||k(!1)};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[y,k]),l.useEffect(()=>{if(!y&&!w)return;const q=me=>{if(!me.altKey)return;const Te=me.code.match(/^Digit([1-9])$/);if(!Te)return;const _=Number(Te[1])-1,te=y?d[_]:void 0,ve=w?Se[_]:void 0;if(!(!te&&!ve)){if(me.preventDefault(),me.stopPropagation(),te){m==null||m(te),k(!1);return}ve&&(C(ve),p(!1))}};return window.addEventListener("keydown",q,!0),()=>window.removeEventListener("keydown",q,!0)},[d,y,w,Se,k,p,C,m]),l.useEffect(()=>{const q=d.length;if(ae.current===null){ae.current=q;return}q>ae.current&&Y(!0),ae.current=q},[d.length]);const G=()=>Y(!1),O=q=>{if(!q)return;const me=r.find(Te=>Te.tabKey===q);me&&(h==null||h(me))};return s.jsxs("div",{className:"dashboard-header",children:[s.jsx("div",{className:"flex items-center gap-3",children:s.jsx("div",{className:"header-title-block",children:s.jsxs("div",{className:"header-title-row",children:[s.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[s.jsx(Zs,{size:18}),s.jsx("span",{className:"header-title-desktop",children:B("dashboard.header.title")}),s.jsx("span",{className:"header-title-mobile",children:e?xt(e):B("dashboard.header.title")}),s.jsx("span",{title:W,"aria-label":W,className:"header-title-status-dot",style:{background:V,boxShadow:ie}}),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:V,boxShadow:ie}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[oe&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",oe]}),b&&s.jsx("button",{type:"button",onClick:b,className:"btn btn-secondary btn-sm ml-2",title:`${Bs}${v!=null&&v.openNewSession?` (${v.openNewSession})`:""}`,"aria-label":Bs,children:s.jsx(Mi,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[j&&s.jsxs("button",{type:"button",onClick:j,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:B("dashboard.header.guide"),"aria-label":B("dashboard.header.guideOpen"),children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),S&&s.jsx("span",{children:B("dashboard.header.guideShort")})]}),e&&(R||Q||!lt(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:vn(e)||xt(e),children:xt(e)}),L&&e.git&&e.daemonId&&e.workspacePath?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:B("dashboard.header.openGitStatus"),onClick:()=>L(e.daemonId,e.workspacePath),children:s.jsx(co,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(co,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),E&&P&&s.jsxs("button",{type:"button",onClick:()=>P(e),className:"btn btn-secondary btn-sm dashboard-header-mesh-button",title:B("dashboard.header.openMeshGraph"),children:[s.jsx(es,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:B("dashboard.header.meshGraph")})]}),(R||Q)&&i&&s.jsxs(s.Fragment,{children:[R&&u&&I&&s.jsx(uh,{mode:I,onChange:u,compact:!0}),s.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:B(Q?"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:()=>o(e),className:"btn btn-secondary btn-sm",title:B("dashboard.header.chatHistory"),children:s.jsx(Ai,{size:14})}),!R&&!lt(e)&&s.jsx("button",{onClick:a,className:"btn btn-secondary btn-sm",title:B("dashboard.header.remoteControl"),children:s.jsx(us,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:z,children:[s.jsxs("div",{className:`dashboard-header-hidden${$?" is-drop-target":""}${U?" hidden-spawn-flash":""}`,onAnimationEnd:G,ref:X,onDragEnter:q=>{q.dataTransfer.types.includes("text/tab-key")&&(q.preventDefault(),D(!0))},onDragOver:q=>{q.dataTransfer.types.includes("text/tab-key")&&(q.preventDefault(),q.dataTransfer.dropEffect="move",D(!0))},onDragLeave:q=>{q.currentTarget.contains(q.relatedTarget)||D(!1)},onDrop:q=>{const me=q.dataTransfer.getData("text/tab-key");q.preventDefault(),D(!1),O(me)},children:[s.jsxs("button",{type:"button",onClick:()=>k(!y),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`${B("dashboard.hidden.title")}${v!=null&&v.toggleHiddenTabs?` (${v.toggleHiddenTabs})`:""}. ${B("dashboard.hidden.dragHint")}`,children:[s.jsx(Ti,{size:16}),d.length>0&&s.jsx("span",{className:`dashboard-header-hidden-badge${U?" hidden-badge-pop":""}`,children:d.length})]}),y&&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:B("dashboard.hidden.title")}),s.jsx(vc,{value:v==null?void 0:v.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[x&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:x,children:B("dashboard.hidden.resetPanels")}),d.length>0&&f&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{f(),k(!1)},children:B("dashboard.hidden.restoreAll")})]})]}),e&&h&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>h(e),children:[s.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[s.jsx("span",{className:"dashboard-header-hidden-current-label",children:B("dashboard.hidden.hideCurrentTab")}),s.jsx(vc,{value:v==null?void 0:v.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(q=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{m==null||m(q),k(!1)},children:[s.jsxs("span",{className:"dashboard-header-inbox-item-title",children:[q.status==="generating"&&s.jsx("span",{className:"tab-spinner dashboard-header-inbox-item-spinner","aria-label":B("dashboard.header.generating")}),xt(q)]}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[d.indexOf(q)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",d.indexOf(q)+1]}):null,vn(q)]})]},q.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:B("dashboard.hidden.empty")})]})]}),s.jsxs("button",{type:"button",onClick:()=>p(!w),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:B("dashboard.header.activityInbox"),children:[s.jsx(Nn,{size:16}),pe>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:pe})]}),w&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[ke.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:B("dashboard.inbox.unread")}),ke.map(q=>s.jsx(wc,{notification:q,shortcutIndex:Se.indexOf(q)>=0?Se.indexOf(q)+1:void 0,onOpen:()=>C(q),onMarkRead:()=>A(q.id),onMarkUnread:()=>T(q.id),onDelete:()=>M(q.id)},q.id))]}),xe.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:B("dashboard.inbox.read")}),xe.map(q=>s.jsx(wc,{notification:q,onOpen:()=>C(q),onMarkRead:()=>A(q.id),onMarkUnread:()=>T(q.id),onDelete:()=>M(q.id)},q.id))]}),g.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:B("dashboard.inbox.empty")})]})]})]})]})}function Ft(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function z0(e,t){return String(e||"")!==String(t||"")}function q0(e,t={}){const n=String(t.textQuery||"").trim().toLowerCase(),r=String(t.workspaceQuery||"").trim().toLowerCase(),o=String(t.modelQuery||"").trim().toLowerCase(),a=!!t.resumableOnly;return!n&&!r&&!o&&!a?e:e.filter(i=>!(a&&!i.canResume||n&&![i.title,i.preview].map(u=>String(u||"").toLowerCase()).join(`
57
+ `).includes(n)||r&&!String(i.workspace||"").toLowerCase().includes(r)||o&&!vu(i.summaryMetadata).map(u=>u.toLowerCase()).join(`
58
+ `).includes(o)))}function V0(e,t="recent"){const n=e.slice();return n.sort((r,o)=>{if(t==="oldest")return(Number(r.lastMessageAt)||0)-(Number(o.lastMessageAt)||0);if(t==="messages"){const a=(Number(o.messageCount)||0)-(Number(r.messageCount)||0);if(a!==0)return a}return(Number(o.lastMessageAt)||0)-(Number(r.lastMessageAt)||0)}),n}function hh(e,t={}){return V0(q0(e,t),t.sortMode||"recent")}function oi(e,t){return typeof e=="function"?e(t??!1?"launch.resumeSavedHistory":"launch.startFresh"):e?"Resume saved history":"Start fresh"}function ph(e,t){return typeof e=="function"?e(t??!1?"launch.resumingSavedHistory":"launch.startingFresh"):e?"Resuming saved history…":"Starting fresh…"}function Y0(e){return e?e("launch.startFresh"):"Start fresh"}function J0(e){return e?e("launch.hostedRuntimeRecoveryDescription"):"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function Q0(e){return e?e("launch.openSavedHistory"):"Open saved history"}function X0(e){return e?e("launch.savedHistoryTitle"):"Saved History"}function zi(e){return e?e("launch.savedHistoryHelper"):"Use saved history when you want continuity in the same provider conversation."}function Z0(e){return e?e("launch.savedHistoryEmpty"):"No saved history found yet."}function ek(e){return e?e("launch.refreshSavedHistory"):"Refresh saved history"}function tk(e){return e?e("launch.refreshingSavedHistory"):"Refreshing saved history…"}function uo(e,t,n){if(typeof e=="function"){const a=t,i=n;return a==="start-fresh"?e("launch.startFreshWith",{label:i}):e("launch.restart",{label:i})}const r=e,o=t;return r==="start-fresh"?`Start fresh with ${o}?`:`Restart ${o}?`}function ho(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 po(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartFresh":"launch.confirmRestart"):e==="start-fresh"?"Start fresh":"Restart"}function mo(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartingFresh":"launch.confirmRestarting"):e==="start-fresh"?"Starting fresh…":"Restarting…"}function mh(e,t){return typeof e=="function"?e("launch.resumeWith",{label:t}):`Resume saved history with ${e}?`}function fh(e){return e?e("launch.resumeReview"):"Review or change the target workspace before resuming saved history."}function sk(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 bh({activeConv:e,ides:t,isCreatingChat:n,isRefreshingHistory:r,savedSessions:o=[],isSavedSessionsLoading:a=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:u,onSavedHistoryFiltersChange:h,onClose:d,onNewChat:m,onSwitchSession:f,onRefreshHistory:x,onResumeSavedSession:w}){var L;const{t:p}=Le("common"),y=t.find(P=>P.id===e.routeId),k=(y==null?void 0:y.chats)||[],b=(L=y==null?void 0:y.activeChat)==null?void 0:L.id,j=ct(e)&&!lt(e),[S,v]=l.useState(()=>Ft()),g=c||S,N=String(u||"").trim(),C=P=>{if(h){h(P);return}v(P)},A=l.useMemo(()=>o.map(P=>{const B=String(P.workspace||"").trim();return P.canResume||B||!N?P:{...P,workspace:N,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[N,o]),T=l.useMemo(()=>hh(A,{textQuery:g.textQuery,workspaceQuery:g.workspaceQuery,modelQuery:g.modelQuery,resumableOnly:g.resumableOnly,sortMode:g.sortMode}),[A,g.modelQuery,g.resumableOnly,g.sortMode,g.textQuery,g.workspaceQuery]),M=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:j?X0(p):p("historyModal.chatHistory")}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:S0(e)}),j&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:zi(p)})]}),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:[!j&&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:p(n?"historyModal.creating":"historyModal.startNewChat")}),j?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:g.textQuery,onChange:P=>C({...g,textQuery:P.target.value}),placeholder:p("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:g.workspaceQuery,onChange:P=>C({...g,workspaceQuery:P.target.value}),placeholder:p("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:g.modelQuery,onChange:P=>C({...g,modelQuery:P.target.value}),placeholder:p("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:g.sortMode,onChange:P=>C({...g,sortMode:P.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:p("historyModal.sortRecent")}),s.jsx("option",{value:"oldest",children:p("historyModal.sortOldest")}),s.jsx("option",{value:"messages",children:p("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:g.resumableOnly,onChange:P=>C({...g,resumableOnly:P.target.checked})}),p("historyModal.resumeReadyOnly")]})]}),T.map(P=>{const B=e.providerSessionId===P.providerSessionId,K=B||!P.canResume||!!i,F=P.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{K||!w||w(P)},disabled:K,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${B?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${K?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${B?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:P.title||p("historyModal.untitledSession")}),s.jsx("div",{className:"text-[11px] text-text-muted font-mono truncate",children:P.providerSessionId})]}),s.jsx("div",{className:"text-[11px] text-text-muted shrink-0",children:sk(P.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:P.preview||p("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:[P.workspace||p("historyModal.workspaceUnknown"),F?p("historyModal.selectedWorkspaceSuffix"):"",Js(P.summaryMetadata)?` · ${Js(P.summaryMetadata)}`:"",P.messageCount>0?` · ${p("historyModal.msgCount",{count:P.messageCount})}`:""]}),s.jsx("div",{className:"shrink-0",children:B?p("historyModal.statusActive"):P.canResume?F?p("historyModal.statusResumeSelectedWorkspace"):i===P.providerSessionId?p("historyModal.statusResuming"):p("historyModal.statusResume"):p("historyModal.statusMissingWorkspace")})]})]},P.id)})]}):k.map(P=>s.jsxs("div",{onClick:()=>{f(e.routeId,P.id),d()},className:`p-4 rounded-xl mb-2 cursor-pointer border transition-all ${b===P.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===P.id?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:P.title||p("historyModal.untitledSession")}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[P.id.substring(0,12),"..."]}),b===P.id&&s.jsx("span",{className:"text-[10px] bg-accent text-white px-2 py-0.5 rounded-[10px] font-extrabold",children:p("historyModal.statusActive")})]})]},P.id)),(j&&!a&&T.length===0||!j&&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(Hf,{size:32})}),s.jsx("div",{className:"text-[13px]",children:j?o.length>0?p("historyModal.noMatchingHistory"):Z0(p):p("historyModal.noRecentChats")})]}),j&&a&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:tk(p)})})]}),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:x,disabled:r||a,className:"btn btn-secondary btn-sm rounded-[10px]",children:r||a?p("historyModal.refreshing"):s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Co,{size:13})," ",j?ek(p):p("historyModal.refreshHistory")]})})})]})]});return typeof document>"u"?M:fn.createPortal(M,document.body)}const kc={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 gh({toasts:e,onDismiss:t,onClickToast:n}){const{t:r}=Le();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(o=>{const a=kc[o.type]||kc.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=o.actions)!=null&&i.length||n&&n(o)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${a.accent}, color-mix(in srgb, ${a.accent} 55%, transparent))`}}),s.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),t(o.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:a.chipBg,color:a.chipText,border:`1px solid color-mix(in srgb, ${a.accent} 22%, transparent)`},children:r(a.labelKey)})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:o.message}),o.actions&&o.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:o.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(o.id)},children:i.label},c))})]})]},o.id)})})}const nk=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function rk(e){const t=e.workspace||"";if(!t)return"";const n=t.split(/[/\\]/).filter(Boolean);return n.length>0?n[n.length-1]:t}function ok(e,t){return xh(e)||t}function xh(e){var o,a,i;const t=(a=(o=e.summaryMetadata)==null?void 0:o.items)==null?void 0:a.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 ak(e){return xh(e)||void 0}function ik(e){return e.sessionId||e.instanceId||e.agentType}function yh(e=[]){const t={};for(const n of e)n.type==="adhdev-daemon"&&(t[n.id]=ts(n,{fallbackId:n.id}));return t}function vh(e,t={}){var r;const n=e.daemonId||((r=e.id)==null?void 0:r.split(":")[0])||e.id;return{machineName:Ny(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[n]||t.defaultConnectionState||"new":t.defaultConnectionState}}function qi(e,t={}){return lk(e,vh(e,t))}function lk(e,t={}){var f,x,w,p,y,k,b,j,S;const n=[],r=t.machineName,o=t.connectionState,a=rk(e),i=e.workspace||"",c=Py(e.type,{agentName:e.cliName}),u=ct(e)||lt(e)?c:$t(e.type),h=ok(e,u),d=Array.isArray(e.childSessions)?e.childSessions.map(v=>{var g,N,C;return{sessionId:v.id,instanceId:v.id,providerSessionId:v.providerSessionId,activeChatId:(g=v.activeChat)==null?void 0:g.id,transport:v.transport,sessionCapabilities:v.capabilities,agentType:v.providerType,agentName:v.providerName||$t(v.providerType),model:ak(v),status:v.status,title:v.title,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,messages:((N=v.activeChat)==null?void 0:N.messages)||[],activeModal:((C=v.activeChat)==null?void 0:C.activeModal)||void 0,unread:v.unread,lastSeenAt:v.lastSeenAt,lastUpdated:v.lastUpdated,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,surfaceHidden:v.surfaceHidden,muted:v.muted,git:v.git,settings:v.settings,coordinator:v.coordinator,messageInput:v.messageInput}}):[],m=nk(e);if(m){const v=e.sessionId||e.instanceId,g=(f=e.settings)==null?void 0:f.meshCoordinatorFor,N=((x=e.settings)==null?void 0:x.meshNodeFor)||!((w=e.settings)!=null&&w.meshCoordinatorFor)&&((p=e.settings)==null?void 0:p.launchedByCoordinator),C=g?" (Coordinator)":N?" (Mesh Node)":"",A=c+C,T=(y=e.activeChat)==null?void 0:y.activeModal,M=T&&Array.isArray(T.buttons)&&T.buttons.length>0,L=Ly(e.activeChat,[{status:e.status,activeModal:(k=e.activeChat)==null?void 0:k.activeModal}],e.agents||[]),P=e.activeChat||{title:"",messages:[]};let B=P.title&&String(P.title).trim()?String(P.title).trim():"";const K=(b=e.activeChat)==null?void 0:b.id,F=e.chats;if(K&&Array.isArray(F)&&F.length>0){const Y=F.find(ae=>ae.id===K||ae.id&&String(ae.id)===String(K));Y!=null&&Y.title&&String(Y.title).trim()&&(B=String(Y.title).trim())}const R=(ct(e)||lt(e),e.type),Q=(ct(e)||lt(e))&&zl(B,A,R)?"":B,E=P.messages||[],I=typeof K=="string"?K.trim():"",$=(ct(e)||lt(e))&&I===String(e.type||"").trim(),D=I&&!$?I:e.providerSessionId,U=e.coordinator||(typeof((j=e.settings)==null?void 0:j.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:v,providerSessionId:e.providerSessionId,historySessionId:D,nativeSessionId:v,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:ct(e)&&e.mode||"chat",agentName:A,agentType:R,status:L,title:Q,messages:E,resume:e.resume,hostIdeType:!ct(e)&&!lt(e)?e.type:void 0,workspaceName:a,workspacePath:i,git:e.git,displayPrimary:a||Q||(ct(e)?e.mode==="chat"?A:`Terminal${C}`:A),displaySecondary:h,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:M?T.buttons:void 0,modalMessage:M?T.message:void 0,streamSource:"native",tabKey:Qo(v,e.id),machineName:r,connectionState:o,settings:e.settings,coordinator:U,messageInput:e.messageInput})}if(m&&(ct(e)||lt(e)))return n;for(const v of d){const g=v.activeModal&&Array.isArray(v.activeModal.buttons)&&v.activeModal.buttons.length>0,N=Ry(v),C=ik(v),A=`${e.id}:${C}`,T=v.title&&String(v.title).trim()||"",M=zl(T,v.agentName,v.agentType)?"":T,L=v.messages||[];if(!(v.transport==="cdp-webview"||!!v.sessionId||!!v.providerSessionId||L.length>0||g||!!M||!["idle","panel_hidden","disconnected","not_monitored"].includes(N)))continue;const B=v.coordinator||(typeof((S=v.settings)==null?void 0:S.meshCoordinatorFor)=="string"&&v.settings.meshCoordinatorFor?{meshId:v.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:v.sessionId||v.instanceId,providerSessionId:v.providerSessionId,historySessionId:v.activeChatId||v.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:v.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:v.sessionCapabilities,mode:"chat",agentName:v.agentName,agentType:v.agentType,status:N,title:M,messages:L,hostIdeType:e.type,workspaceName:a,workspacePath:i,git:v.git||e.git,displayPrimary:a||M||v.agentName||u,displaySecondary:v.model&&v.model.trim()?v.model.trim():`${u} · ${v.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:v.lastMessagePreview,lastMessageRole:v.lastMessageRole,lastMessageAt:v.lastMessageAt,lastMessageHash:v.lastMessageHash,lastUpdated:v.lastUpdated||e.lastUpdated,inboxBucket:v.inboxBucket,completionMarker:v.completionMarker,modalButtons:g?v.activeModal.buttons:void 0,modalMessage:g?v.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Qo(v.sessionId||v.instanceId,A),machineName:r,connectionState:o,settings:v.settings,coordinator:B,messageInput:v.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:a,workspacePath:i,git:e.git,displayPrimary:a||u,displaySecondary:h,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Qo(e.sessionId||e.instanceId,e.id),connectionState:o,settings:e.settings,messageInput:e.messageInput}),n}function wh(e){return String(e.type||e.id||"").trim()}function fo(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function ck(e,t){const n=(t||"").trim();if(!n)return[];const r=(e||[]).find(o=>o.type===n);return fo(r==null?void 0:r.modelOptions)}function dk(e,t){const n=(t||"").trim();if(!n)return[];const r=(e||[]).find(o=>o.type===n);return fo(r==null?void 0:r.thinkingLevelOptions)}function kh(e){const t=new Map;for(const n of e||[])n!=null&&n.type&&t.set(n.type,{models:fo(n.modelOptions),thinking:fo(n.thinkingLevelOptions)});return t}function uk(e){var t;return e.category!=="cli"||!wh(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 o of e||[]){if(!uk(o))continue;const a=wh(o);if(!a||t.has(a))continue;t.add(a);const i=String(o.displayName||o.name||a),c=o.detectedPath||((r=o.lastDetection)==null?void 0:r.path)||null;n.push({type:a,label:i,icon:o.icon,statusLabel:c?`Detected at ${c}`:"Detected on this machine",detectedPath:c,...Array.isArray(o.modelOptions)&&o.modelOptions.length?{modelOptions:o.modelOptions}:{},...Array.isArray(o.thinkingLevelOptions)&&o.thinkingLevelOptions.length?{thinkingLevelOptions:o.thinkingLevelOptions}:{}})}return n}function kn(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],n=new Set,r=[];for(const o of t){const a=typeof o=="string"?o.trim():"";!a||n.has(a)||(n.add(a),r.push(a))}return r}function cr(e){return e.map(t=>t.type)}function hk(e,t){const n=kn(e),r=t.trim();return!r||n.includes(r)?n:[...n,r]}function pk(e,t){return kn(e).filter(n=>n!==t)}function Sc(e,t,n){const r=kn(e),o=r.indexOf(t);if(o<0)return r;const a=r.filter(c=>c!==t);if(n==="top")return[t,...a];if(n==="bottom")return[...a,t];const i=n==="up"?Math.max(0,o-1):Math.min(a.length,o+1);return a.splice(i,0,t),a}function Cc({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 mk({value:e,availableProviders:t,onChange:n,disabled:r=!1,saveButton:o}){const[a,i]=l.useState(""),c=l.useMemo(()=>new Map(t.map(f=>[f.type,f])),[t]),u=l.useMemo(()=>kn(e),[e]),h=u.filter(f=>!c.has(f)).length,d=t.filter(f=>!u.includes(f.type)),m=()=>{a&&(n(hk(u,a)),i(""))};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:u.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."}):u.map((f,x)=>{const w=c.get(f),p=!!w;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 ${p?"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:["#",x+1]}),(w==null?void 0:w.icon)&&s.jsx("span",{"aria-hidden":"true",children:w.icon}),s.jsx("span",{className:`font-mono text-[12px] ${p?"text-text-primary":"text-text-muted"}`,children:f}),p?s.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:"available"}):s.jsx("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:"not on this machine"})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:w?`${w.label} · ${w.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||x===0,title:"Move up",onClick:()=>n(Sc(u,f,"up")),children:s.jsx(Cc,{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||x===u.length-1,title:"Move down",onClick:()=>n(Sc(u,f,"down")),children:s.jsx(Cc,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:r,onClick:()=>n(pk(u,f)),children:"Remove"})]})]},f)})}),s.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[s.jsxs("label",{className:"flex-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:"Add available CLI provider"}),s.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:a,onChange:f=>i(f.target.value),disabled:r||d.length===0,children:[s.jsx("option",{value:"",children:d.length?"Select provider…":"No additional detected CLI providers"}),d.map(f=>s.jsxs("option",{value:f.type,children:[f.label," (",f.type,")"]},f.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:r||!a,onClick:m,children:"Add provider"}),o]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Launches use this order, top to bottom.",h>0?` ${h} provider${h===1?"":"s"} not detected here — kept in order, skipped until available.`:""]})]})}function fk(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 Sh(e,t){const n=fk(e);return{daemonId:n.daemonId,payload:{...t,...n.targetSessionId&&!t.targetSessionId?{targetSessionId:n.targetSessionId}:{}}}}const Ch=[{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:"🏄"}],jh=[{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:"◆"}],Nh=[{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:"🟠"}],bk=Ch,gk=jh,xk=Nh;function yk({icon:e,title:t,subtitle:n,badge:r,actions:o,className:a}){return s.jsxs("div",{className:Ht("dashboard-header",a),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})]}),o&&s.jsx("div",{className:"flex gap-2",children:o})]})}function gr({icon:e,title:t,subtitle:n,badge:r,actions:o,widthClassName:a="max-w-6xl",contentClassName:i,children:c}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(yk,{icon:e,title:t,subtitle:n,badge:r,actions:o}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Ht("mx-auto flex w-full flex-col gap-4",a,i),children:c})})]})}const ai="adhdev:themechange";function vk(){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"?vk():e}function Ah(e){typeof document>"u"||(document.documentElement.setAttribute("data-theme",e),document.documentElement.style.colorScheme=e)}function zr(e,t){typeof window>"u"||window.dispatchEvent(new CustomEvent(ai,{detail:{preference:e,theme:t}}))}function wk(){const e=ln(),t=cn(e);Ah(t),zr(e,t)}function Ls(){const[e,t]=l.useState(ln),[n,r]=l.useState(()=>cn(ln()));l.useEffect(()=>{Ah(n)},[n]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=u=>{if(e==="system"){const h=u.matches?"light":"dark";r(h),zr("system",h)}};return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[e]),l.useEffect(()=>{const i=u=>{const h=u.detail||{},d=h.preference,m=h.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 h=ln(),d=cn(h);t(h),r(d)};return window.addEventListener(ai,i),window.addEventListener("storage",c),()=>{window.removeEventListener(ai,i),window.removeEventListener("storage",c)}},[]);const o=l.useCallback(i=>{const c=cn(i);t(i),r(c);try{localStorage.setItem("theme",i)}catch{}zr(i,c)},[]),a=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 zr(c,u),c})},[]);return{theme:n,preference:e,setPreference:o,cycleTheme:a,isDark:n==="dark"}}const jc={dark:"Dark",light:"Light",system:"System"};function kk({collapsed:e}){const{preference:t,cycleTheme:n}=Ls(),r=t==="dark"?s.jsx(Of,{size:16}):t==="light"?s.jsx(Wf,{size:16}):s.jsx(Uf,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:n,title:`Theme: ${jc[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:r}),!e&&s.jsx("span",{className:"text-xs",children:jc[t]})]})}const ii="adhdev:langchange";function Sk(){const e=wt.language;return un(e)?e:mu()}function Ck(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(ii,{detail:{language:e}}))}function jk(){const[e,t]=l.useState(Sk);l.useEffect(()=>{const r=i=>{un(i)&&t(i)},o=i=>{const c=i.detail||{};un(c.language)&&t(c.language)},a=i=>{if(i.key!==za)return;const c=i.newValue;un(c)&&c!==wt.language&&(wt.changeLanguage(c),qa(c))};return wt.on("languageChanged",r),window.addEventListener(ii,o),window.addEventListener("storage",a),()=>{wt.off("languageChanged",r),window.removeEventListener(ii,o),window.removeEventListener("storage",a)}},[]);const n=l.useCallback(r=>{if(un(r)){t(r);try{localStorage.setItem(za,r)}catch{}wt.changeLanguage(r),qa(r),Ck(r)}},[]);return{language:e,setLanguage:n}}function Nk({collapsed:e}){const{language:t,setLanguage:n}=jk(),{t:r}=Le("common"),o=Yo.find(i=>i.code===t)??Yo[0],a=r("language.select",{defaultValue:"Select language"});return s.jsxs("div",{className:`nav-item relative cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,title:`${r("language.label",{defaultValue:"Language"})}: ${o.label}`,children:[s.jsx("span",{className:"nav-icon",children:s.jsx(Xf,{size:16})}),!e&&s.jsx("span",{className:"text-xs",children:o.label}),s.jsx("select",{"aria-label":a,value:t,onChange:i=>n(i.target.value),className:"absolute inset-0 w-full h-full opacity-0 cursor-pointer",children:Yo.map(i=>s.jsx("option",{value:i.code,children:i.label},i.code))})]})}function aa(e,t){return e?typeof e=="function"?e(t):e:null}function Ak({children:e,brand:t,navItems:n,sidebarSections:r=[],footerItems:o=[],footerInfo:a,footerActions:i,preMainContent:c,collapsedStorageKey:u="sidebar-collapsed"}){const{t:h}=Le("common"),[d,m]=l.useState(!1),[f,x]=l.useState(()=>{try{return localStorage.getItem(u)==="1"}catch{return!1}}),w=()=>m(!0),p=()=>m(!1),y=()=>{x(S=>{const v=!S;try{localStorage.setItem(u,v?"1":"0")}catch{}return v})},k=l.useMemo(()=>({collapsed:f,mobileMenuOpen:d,openMobileMenu:w,closeMobileMenu:p,toggleCollapsed:y}),[f,d]),b=S=>`nav-item${S.active?" active":""} cursor-pointer ${f?"justify-center py-2.5 px-0":""}${S.className?` ${S.className}`:""}`,j=S=>s.jsxs("div",{className:b(S),id:`nav-${S.id}`,onClick:()=>{S.onSelect(),p()},title:f?S.title??(typeof S.label=="string"?S.label:void 0):S.title,children:[s.jsx("span",{className:"nav-icon",children:S.icon}),!f&&S.label]},S.id);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":h("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":h("app.closeMenu"),onClick:p,onKeyDown:S=>S.key==="Escape"&&p()}),s.jsxs("aside",{className:`sidebar ${d?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${f?"justify-center gap-0":""}`,children:aa(t,k)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":h("app.closeMenu"),onClick:p,children:s.jsx(At,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:n.map(j)}),r.map(S=>s.jsxs("div",{className:S.className??"border-t border-border-subtle pt-2 mt-2",children:[!f&&S.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:S.title}):null,S.items.map(j)]},S.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[o.map(j),aa(a,k),s.jsx(kk,{collapsed:f}),s.jsx(Nk,{collapsed:f}),aa(i,k)]})]}),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:o,collapsible:a,defaultOpen:i=!0,badge:c,children:u}){const[h,d]=l.useState(i),m=a?h:!0,f=(e||n)&&s.jsxs("div",{className:Ht("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})]}),a&&s.jsx("span",{className:Ht("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:Ht("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]",o),style:r?{borderLeftColor:r}:void 0,children:[a&&f?s.jsx("button",{type:"button",className:"w-full bg-transparent border-none p-0 text-left cursor-pointer",onClick:()=>d(x=>!x),"aria-expanded":m,children:f}):f,m&&u]})}function Ro({icon:e,title:t,description:n,action:r,className:o}){return s.jsxs("div",{className:Ht("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",o),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 Tk={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"},Ik={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Gt({variant:e,children:t,onDismiss:n,className:r}){return s.jsxs("div",{className:Ht("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",Tk[e],r),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:Ik[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:Ht("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:Ht("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 Mk={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:o,...a},i){return s.jsx("button",{ref:i,type:r??"button",className:Ht("btn",Mk[t],n==="sm"&&"btn-sm",o),...a})}),Dk=l.forwardRef(function({options:t,children:n,className:r,...o},a){return s.jsx("select",{ref:a,className:Ht("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),...o,children:n??(t==null?void 0:t.map(i=>s.jsx("option",{value:i.value,disabled:i.disabled,children:i.label},i.value)))})}),Pk={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"},Lk={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function Rk({status:e,label:t,className:n}){const r=t||e;return s.jsxs("span",{className:Ht("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",Pk[e],n),children:[s.jsx("span",{className:Ht("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",Lk[e])}),r]})}function Fs({label:e,description:t,checked:n,disabled:r,onChange:o,extra:a}){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:[a,s.jsxs("button",{type:"button",role:"switch","aria-checked":n,"aria-disabled":r,disabled:r,onClick:()=>o(!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 Ek({onPrefChange:e}){const[t,n]=Gy(),[r,o]=l.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);l.useEffect(()=>{const i=()=>{if(typeof window>"u"||!("Notification"in window)){o("unsupported");return}o(Notification.permission)};return i(),window.addEventListener("focus",i),document.addEventListener("visibilitychange",i),()=>{window.removeEventListener("focus",i),document.removeEventListener("visibilitychange",i)}},[]);const a=(i,c)=>{n({[i]:c}),e==null||e(i,c)};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})," Notifications"]}),description:"Master toggle for all alerts",checked:t.globalEnabled,onChange:i=>a("globalEnabled",i)}),t.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),t.globalEnabled&&s.jsx(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(us,{size:15})," Browser Notifications"]}),description:"Desktop alerts when tab is inactive",checked:t.browserNotifications,onChange:i=>a("browserNotifications",i)}),t.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:"Browser alerts only fire while this dashboard tab stays open in the background. If you close it, standalone cannot deliver hosted push notifications for you."}),r==="default"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-status-warning",children:[s.jsx("span",{children:"This browser has not granted notification permission yet. Allow it to receive local browser alerts."}),s.jsx("button",{onClick:()=>{Su().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:"Allow notifications"})]}),r==="denied"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive standalone desktop alerts."}),r==="unsupported"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device."})]}),t.globalEnabled&&t.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Zd,{size:15})," Completion Alerts"]}),description:"Notify when agent finishes a task",checked:t.completionAlert,onChange:i=>a("completionAlert",i)}),s.jsx(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Gf,{size:15})," Approval Alerts"]}),description:"Notify when agent needs approval",checked:t.approvalAlert,onChange:i=>a("approvalAlert",i)}),s.jsx(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ar,{size:15})," Connection Alerts"]}),description:"Alert when a daemon disconnects",checked:t.disconnectAlert,onChange:i=>a("disconnectAlert",i)})]}),!t.globalEnabled&&s.jsx("p",{className:"text-[11px] text-text-muted italic",children:"All notifications are disabled. Enable the master toggle to configure individual alerts."})]})}function li(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 o=n.match(/(?:^|\.)(\d+)$/);r=o?Number(o[1]):null}return{base:[Number(t[1]),Number(t[2]),Number(t[3])],prereleaseNumber:r,isPrerelease:n!==null}}function bo(e){var t;return((t=li(e))==null?void 0:t.base)??null}function _k(e,t){const n=bo(e),r=bo(t);if(!n||!r)return e.localeCompare(t);for(let o=0;o<3;o+=1){if(n[o]<r[o])return-1;if(n[o]>r[o])return 1}return 0}function $k(e,t){const n=li(e),r=li(t);if(!n||!r)return e!==t;for(let o=0;o<3;o+=1){if(n.base[o]<r.base[o])return!0;if(n.base[o]>r.base[o])return!1}return n.isPrerelease&&r.isPrerelease?n.prereleaseNumber===null||r.prereleaseNumber===null?!1:n.prereleaseNumber<r.prereleaseNumber:!1}function Vi(e,t){const n=e.version||null;return e.versionMismatch===!0?!0:!n||!t?!1:$k(n,t)}function tr(e,t){if(e.versionUpdateRequired===!0)return!0;const n=e.version||null;if(!n||!t||n===t||_k(n,t)>=0)return!1;const r=bo(n),o=bo(t);return!r||!o?!1:r[0]!==o[0]||r[1]!==o[1]}function Bk(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function ia(e,t){return e instanceof Error?e.message:t}function Fk({ides:e,emptyMessage:t,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:o}){const{t:a}=Le("common"),i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?s.jsx(Ro,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:a("machine.connectedMachines.noMachines"),description:t||a("machine.connectedMachines.defaultDescription")}):s.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>s.jsx(Wk,{ide:c,allIdes:e,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:o},c.id))})}function Nc({title:e,message:t,confirmLabel:n,confirmColor:r,onConfirm:o,onCancel:a}){const{t:i}=Le("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:a,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:a,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:o,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 Hk(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),r=[...bk,...gk,...xk].find(o=>o.id===t||t.includes(o.id)||o.id.includes(t));return r?{icon:r.icon,name:r.name}:{icon:"📝",name:e}}function Wk({ide:e,allIdes:t,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:o}){var K,F;const{t:a}=Le("common"),[i,c]=l.useState("idle"),[u,h]=l.useState(""),[d,m]=l.useState(null),[f,x]=l.useState("idle"),[w,p]=l.useState(""),y=e.version||null,k=((K=e.machine)==null?void 0:K.platform)||((F=e.system)==null?void 0:F.platform)||"",b=ts(e,{fallbackId:e.id}),j=k==="win32"?"🪟":k==="darwin"?"🍎":"🐧",S=t.filter(R=>R.daemonId===e.id&&R.transport==="cdp-page"),v=t.filter(R=>R.daemonId===e.id&&R.transport==="pty"),g=t.filter(R=>R.daemonId===e.id&&R.transport==="acp"),N=e.p2p,C=async()=>{if(n){c("upgrading"),h(a("machine.connectedMachines.startingUpgrade"));try{const R=Bk(await n(e.id,"daemon_upgrade",{}));R.alreadyLatest?(c("done"),h(`Already on v${R.version||"latest"}.`)):R.upgraded||R.success?(c("done"),h(`Upgrade to v${R.version||"latest"} started. Daemon is restarting...`)):(c("error"),h(R.error||"Upgrade failed"))}catch(R){c("error"),h(ia(R,"Connection lost during upgrade"))}}},A=async()=>{if(m(null),!!r){x("loading");try{await r(e.id),x("done"),p(a("machine.connectedMachines.machineDisconnected"))}catch(R){x("error"),p(ia(R,a("machine.connectedMachines.failedToDisconnect")))}}},T=async()=>{if(m(null),!!o){x("loading");try{await o(e.id),x("done"),p(a("machine.connectedMachines.tokenRevoked"))}catch(R){x("error"),p(ia(R,a("machine.connectedMachines.failedToRevokeToken")))}}},M="0.9.82",L=Vi(e,M),P=tr(e,M),B=S.length+v.length+g.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:j}),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),"…"]}),y&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${L?"":"bg-bg-secondary"}`,style:L?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",y,!L&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[n&&L&&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${M}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," ",a("machine.connectedMachines.upgrading")]}):i==="done"?a("machine.connectedMachines.updated"):P?a("machine.connectedMachines.updateNow"):a("machine.connectedMachines.updateTo",{version:M})}),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:a("machine.connectedMachines.disconnect")}),o&&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:a("machine.connectedMachines.remove")}),s.jsx(Rk,{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"?a("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&&B>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),B>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[S.map(R=>{const Q=Hk(R.type),E=R.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:Q.icon}),s.jsx("span",{children:Q.name}),E!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${E?"bg-status-online":"animate-pulse"}`,style:E?void 0:{background:"var(--status-warning)"},title:a(E?"machine.connectedMachines.cdpConnected":"machine.connectedMachines.cdpConnecting")})]},R.id)}),v.map(R=>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:R.cliName||"CLI"})]},R.id)),g.map(R=>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:R.cliName||"ACP"})]},R.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:a("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(Nc,{title:a("machine.connectedMachines.disconnectTitle"),message:`Disconnect "${b}" from ADHDev?
59
+
60
+ This will close the server connection. The daemon process will continue running on the machine and will automatically reconnect.
61
+
62
+ Use this if you want to temporarily stop remote control.`,confirmLabel:a("machine.connectedMachines.disconnect"),confirmColor:"amber",onConfirm:A,onCancel:()=>m(null)}),d==="revoke"&&s.jsx(Nc,{title:a("machine.connectedMachines.removeTitle"),message:`Remove "${b}" from your dashboard?
63
+
64
+ This will:
65
+ • Immediately disconnect the machine
66
+ • Delete the machine registration
67
+ • Require restarting ADHDev on that machine
68
+
69
+ Use this if you want to permanently remove a machine.`,confirmLabel:a("machine.connectedMachines.remove"),confirmColor:"red",onConfirm:T,onCancel:()=>m(null)})]})}const Ok=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli","gemini-cli"];function Uk({daemonId:e,knownCliTypes:t=Ok}){const{sendCommand:n}=yt(),[r,o]=l.useState({}),[a,i]=l.useState({}),[c,u]=l.useState(!0),[h,d]=l.useState(null),[m,f]=l.useState(null),[x,w]=l.useState(""),p=l.useCallback(async()=>{if(e){u(!0),f(null);try{const b=await n(e,"list_coordinator_prompts",{}),j=b!=null&&b.result&&typeof b.result=="object"?b.result:b;if(!(j!=null&&j.success)){f((j==null?void 0:j.error)||"Failed to load");return}const S=j.entries||{};w(j.dir||"");const v={};for(const g of t)v[g]=S[g]||{override:"",append:""};for(const g of Object.keys(S))v[g]||(v[g]=S[g]);o(v),i(JSON.parse(JSON.stringify(v)))}catch(b){f((b==null?void 0:b.message)||String(b))}finally{u(!1)}}},[n,e,t]);l.useEffect(()=>{p()},[p]);const y=l.useCallback(async(b,j)=>{var S;if(e){d(`${b}:${j}`),f(null);try{const v=((S=r[b])==null?void 0:S[j])||"",g=await n(e,"write_coordinator_prompt",{key:b,kind:j,content:v}),N=g!=null&&g.result&&typeof g.result=="object"?g.result:g;if(!(N!=null&&N.success)){f((N==null?void 0:N.error)||"Save failed");return}i(C=>({...C,[b]:{...C[b]||{override:"",append:""},[j]:v}}))}catch(v){f((v==null?void 0:v.message)||String(v))}finally{d(null)}}},[n,e,r]),k=l.useMemo(()=>(b,j)=>{var S,v;return(((S=r[b])==null?void 0:S[j])||"")!==(((v=a[b])==null?void 0:v[j])||"")},[r,a]);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:x||"~/.adhdev/coordinator-prompts/"})]}),s.jsxs("p",{className:"mt-1",children:[s.jsx("strong",{children:"Override"})," replaces the daemon's built-in base prompt for that CLI."," ",s.jsx("strong",{children:"Append"})," stacks after whichever base wins. Leave a field empty + Save to remove it (reset to default). Supports placeholders: ","{{meshName}}",", ","{{repo}}",", ","{{nodes}}",", ","{{rules}}",", etc."]})]}),m&&s.jsx("div",{className:"text-[12px] text-status-error bg-status-error/10 border border-status-error/40 rounded px-3 py-2",children:m}),c&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"Loading…"}),s.jsx("div",{className:"flex flex-col gap-6",children:Object.entries(r).map(([b,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:b}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:"Override"}),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:S=>o(v=>({...v,[b]:{...v[b],override:S.target.value}})),placeholder:"(empty — use daemon default base prompt)",disabled:h===`${b}:override`}),s.jsx("div",{className:"mt-1 mb-3 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void y(b,"override"),disabled:h===`${b}:override`||!k(b,"override"),children:h===`${b}:override`?"Saving…":k(b,"override")?"Save override":"Saved"})}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:"Append"}),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:S=>o(v=>({...v,[b]:{...v[b],append:S.target.value}})),placeholder:"(empty — nothing appended at this layer)",disabled:h===`${b}:append`}),s.jsx("div",{className:"mt-1 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void y(b,"append"),disabled:h===`${b}:append`||!k(b,"append"),children:h===`${b}:append`?"Saving…":k(b,"append")?"Save append":"Saved"})})]},b))})]}):s.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const Gk=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function Kk(){const{preference:e,setPreference:t}=Ls();return s.jsx("div",{className:"flex gap-2",children:Gk.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 zk(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 qk(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function la(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Ac(e){const{r:t,g:n,b:r}=qk(e);return .2126*la(t)+.7152*la(n)+.0722*la(r)}function Tc(e,t){const n=Ac(e),r=Ac(t),o=Math.max(n,r),a=Math.min(n,r);return(o+.05)/(a+.05)}function Th(e){const t=zk(e);if(!t)return"#111827";const n="#111827",r="#ffffff";return Tc(t,n)>=Tc(t,r)?n:r}const ci={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},di={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},Vk=[{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"}}}],Ih="adhdev-chat-theme",Mh="adhdev-chat-theme-custom";function qr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Ih)||"ember"}catch{return"ember"}}function as(e){try{const t=localStorage.getItem(Mh);if(t){const n=JSON.parse(t);return{...e==="dark"?ci:di,...n[e]}}}catch{}return e==="dark"?ci:di}function Ir(e,t){try{localStorage.setItem(Mh,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),o=parseInt(e.slice(5,7),16);return`rgba(${n}, ${r}, ${o}, ${t})`}function go(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),o=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${n.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}${o.toString(16).padStart(2,"0")}`}const Yk={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 o;const n=(o=Yk[e])==null?void 0:o[t];if(!n)return;const r=document.documentElement;r.style.setProperty("--accent-primary",n),r.style.setProperty("--accent-primary-light",go(n,24)),r.style.setProperty("--accent-on-primary",Th(n)),r.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${n}, ${go(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 Ks(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",go(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Th(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${go(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 Yi(){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 Jk(e){try{localStorage.setItem(Ih,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=zs()?"dark":"light";Ks(as(t))}else Yi(),sr(e,zs()?"dark":"light")}function Qk(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=qr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=zs()?"dark":"light";Ks(as(t))}else Yi(),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 Bt({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 Xk({dark:e,onColorsChange:t}){const{t:n}=Le("common"),r=e?"dark":"light",[o,a]=l.useState(()=>as(r));l.useEffect(()=>{a(as(r))},[r]);const i=l.useCallback((c,u)=>{a(h=>{const d={...h,[c]:u},f=as(r==="dark"?"light":"dark");return r==="dark"?Ir(d,f):Ir(f,d),Ks(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(Bt,{label:n("settings.theme.colorBackground"),value:o.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(Bt,{label:n("settings.theme.colorSurface"),value:o.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(Bt,{label:n("settings.theme.colorCard"),value:o.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(Fn,{title:n("settings.theme.sectionAppText"),children:[s.jsx(Bt,{label:n("settings.theme.colorPrimary"),value:o.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(Bt,{label:n("settings.theme.colorSecondary"),value:o.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(Bt,{label:n("settings.theme.colorMuted"),value:o.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(Fn,{title:n("settings.theme.sectionBordersAccent"),children:[s.jsx(Bt,{label:n("settings.theme.colorBorderSubtle"),value:o.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(Bt,{label:n("settings.theme.colorBorderDefault"),value:o.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(Bt,{label:n("settings.theme.colorAccent"),value:o.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Fn,{title:n("settings.theme.sectionChatBubbles"),children:[s.jsx(Bt,{label:n("settings.theme.colorUserBubble"),value:o.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(Bt,{label:n("settings.theme.colorUserText"),value:o.userText,onChange:c=>i("userText",c)}),s.jsx(Bt,{label:n("settings.theme.colorAgentBubble"),value:o.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(Bt,{label:n("settings.theme.colorAgentText"),value:o.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(Fn,{title:n("settings.theme.sectionChatLayout"),children:[s.jsx(Bt,{label:n("settings.theme.colorChatBg"),value:o.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(Bt,{label:n("settings.theme.colorSendButton"),value:o.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(Bt,{label:n("settings.theme.colorInputBorder"),value:o.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:o.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:[o.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const c=e?ci:di,h=as(e?"light":"dark");e?Ir(c,h):Ir(h,c),a(c),Ks(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 Zk(){const{t:e}=Le("common"),[t,n]=l.useState(qr),[r,o]=l.useState(!0),[a,i]=l.useState(()=>as("dark"));l.useEffect(()=>{o(zs());const h=new MutationObserver(()=>{const f=zs();o(f);const x=qr();x==="custom"?Ks(as(f?"dark":"light")):sr(x,f?"dark":"light")});h.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const d=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const f=zs();o(f);const x=qr();x==="custom"?Ks(as(f?"dark":"light")):sr(x,f?"dark":"light")};return d.addEventListener("change",m),()=>{h.disconnect(),d.removeEventListener("change",m)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?Ks(as(r?"dark":"light")):(Yi(),sr(t,r?"dark":"light"))},[t,r]),l.useEffect(()=>{i(as(r?"dark":"light"))},[r]);const c=h=>{n(h),Jk(h)},u=[...Vk,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText},light:{userBubble:a.userBubble,assistantBubble:a.assistantBubble,assistantBorder:`1px solid ${a.accentColor}22`,containerBg:a.containerBg,textColor:a.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:u.map(h=>{const d=t===h.id,m=r?h.preview.dark:h.preview.light,f=h.id==="honey"||h.id==="ember"?"#1a1a1a":h.id==="custom"?a.userText:"#fff";return s.jsxs("button",{onClick:()=>c(h.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:h.id==="custom"?e("settings.theme.customLabel"):h.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:h.description})]})]})]},h.id)})}),t==="custom"&&s.jsx(Xk,{dark:r,onColorsChange:h=>i(h)})]})}const Ji="adhdev_mobileDashboardMode_v1",ui="adhdev:mobile-dashboard-mode-change";function Qi(){try{return localStorage.getItem(Ji)==="workspace"?"workspace":"chat"}catch{return"chat"}}function eS(e){if(typeof window>"u")return()=>{};const t=o=>{e(o??Qi())},n=o=>{const a=o.detail;t(a)},r=o=>{o.key&&o.key!==Ji||t()};return window.addEventListener(ui,n),window.addEventListener("storage",r),()=>{window.removeEventListener(ui,n),window.removeEventListener("storage",r)}}function tS(e){try{localStorage.setItem(Ji,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(ui,{detail:e}))}function sS(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(Qi()==="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),tS(n?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const nS="Choose a preset or create a fully custom theme. Custom themes control the entire app — backgrounds, text, borders, and chat bubbles.",rS="Choose whether the dashboard opens like a chat app on phones or keeps the full workspace layout.";function oS({themeDescription:e=nS,mobileDescription:t=rS,fontsSlot:n}){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:"Mode"}),s.jsx(Kk,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:"Theme"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:e}),s.jsx(Zk,{})]}),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:"Mobile"}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:t}),s.jsx(sS,{})]})]})}const ca=new Map,Ic=new Map;function aS(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 iS(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 Dh(){const{sendCommand:e}=yt(),{injectEntries:t,getIdes:n}=or();return l.useCallback(async(r,o)=>{if(!r)return;const a=(o==null?void 0:o.minFreshMs)??ww,i=Ic.get(r)||0;if(!(o!=null&&o.force)&&i>0&&Date.now()-i<a)return;const c=ca.get(r);if(c)return c;const u=(async()=>{const h=await e(r,"get_machine_runtime_stats"),d=aS(h);if(!d)return;const m=n().find(x=>x.id===r),f=iS(m,r,d.machine,d.timestamp||Date.now());t([f]),Ic.set(r,Date.now())})().finally(()=>{ca.delete(r)});return ca.set(r,u),u},[n,t,e])}function lS(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 cS(e,t){const{sendData:n}=yt(),{injectEntries:r,getIdes:o}=or(),a=Array.from(new Set(e.filter(Boolean))).join("|");l.useEffect(()=>{if(!(t!=null&&t.enabled)||!n)return;const i=a?a.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=o().find(x=>x.id===u),f=lS(m,u,d);r([f])}));return()=>{c.forEach(u=>u())}},[a,o,r,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,n])}function dS(e,t){const{sendData:n}=yt(),[r,o]=l.useState(null),[a,i]=l.useState(!1);return l.useEffect(()=>{if(!e){o(null),i(!1);return}if(!(t!=null&&t.enabled)||!n){i(!1);return}o(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}:{}}},h=>{c&&(clearTimeout(c),c=null),o(h.diagnostics),i(!1)});return u.initialSendAccepted?c=setTimeout(()=>{i(!1)},Cw):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:a,applyDiagnostics:o}}function uS(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Ph(e){const{sendData:t}=yt(),[n,r]=l.useState({});return l.useEffect(()=>{const o=uS(e);if(!o||!e.sessionId||!t){r({});return}const a=ls.subscribe({sendData:t},o,{type:"subscribe",topic:"session.modal",key:`daemon:${o}: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 a.initialSendAccepted||r({}),()=>{a()}},[e.daemonId,e.routeId,e.sessionId,t]),n}function hS(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function pS(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 mS(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 o=`HTTP ${r.status}`;try{const a=await r.json();typeof(a==null?void 0:a.error)=="string"&&(o=a.error)}catch{}throw new Error(o)}}async function fS({promptSession:e,response:t,useP2PCommand:n,sendCommand:r,fetchImpl:o=fetch}){if(n){const a=await r(e.routeId,"interactive_prompt_response",{targetSessionId:e.sessionId,sessionId:e.sessionId,response:t});if(!hS(a))throw new Error(pS(a));return}await mS(e.sessionId,t,o)}function Lh(e){const{ides:t,isP2PActive:n,p2pStates:r}=gs(),{sendCommand:o}=yt(),[a,i]=l.useState(null),[c,u]=l.useState(!1),[h,d]=l.useState(null),m=l.useRef(!1),f=l.useMemo(()=>Tb(t,e),[t,e]),x=!!f,w=l.useMemo(()=>f?f.prompt.promptId===a?null:f:null,[a,f]),p=l.useCallback(async b=>{if(!w||m.current)return;m.current=!0;const j=lu(w.prompt,b);u(!0),d(null);try{const S=(r==null?void 0:r[w.daemonId])==="connected"||n===!0;await fS({promptSession:w,response:j,useP2PCommand:S,sendCommand:o}),i(w.prompt.promptId)}catch(S){throw d(S instanceof Error?S.message:String(S)),S}finally{u(!1),m.current=!1}},[n,r,w,o]),y=l.useCallback(()=>{w&&i(w.prompt.promptId)},[w]),k=l.useCallback(()=>{i(null),d(null)},[]);return{promptSession:w,hasActivePrompt:x,responseError:h,isSubmitting:c,submit:p,cancel:y,reopen:k}}function Rh(e){return e instanceof Error?e.message:String(e||"")}function bS(e){const t=Rh(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 gS(e){const t=Rh(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function Eh({conversation:e,mode:t,ides:n,sendDaemonCommand:r,setCliViewModeOverrides:o}){if(!e||!ct(e)||lt(e))return;const a=Tn(e);if(a===t)return;const i=e.sessionId;i&&o(c=>({...c,[i]:t}));try{await r(Ps(e)||e.routeId,"set_cli_view_mode",{targetSessionId:e.sessionId,cliType:bs(e),mode:t})}catch(c){const u=gS(c);i&&!u&&o(h=>{const d={...h};return a===yS(n,i)?delete d[i]:d[i]=a,d}),bS(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 Mc(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 xS(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let n=!1;const r=e.map(o=>{const a=Mc(o,t),i=Array.isArray(o.childSessions)?o.childSessions.map(u=>Mc(u,t)):o.childSessions,c=i!==o.childSessions;return a!==o||c?(n=!0,{...a,...c?{childSessions:i}:{}}):o});return n?r:e}function yS(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 vS({visibleConversations:e,clearedTabs:t,setClearedTabs:n,setActionLogs:r,isConversationMuted:o}){l.useEffect(()=>{Su()},[]);const a=l.useMemo(()=>e.map(i=>({id:i.tabKey,name:lh(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:o?o(i):!1})),[e,o]);return Vy(a),l.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{n(u=>{const h=Date.now(),d={};for(const[m,f]of Object.entries(u))h-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 h=u.filter(d=>d.timestamp>c).slice(-100);return h.length===u.length?u:h})},6e4);return()=>clearInterval(i)},[r]),null}function Dc(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 qs(e){const t=[...e.messages].reverse().find(o=>!(o!=null&&o._localId))||e.messages[e.messages.length-1],n=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,r=Dc(t==null?void 0:t.receivedAt)||Dc(t==null?void 0:t.timestamp)||0;return Math.max(n,r)}function hi(e,t=0){return qs(e)||e.lastUpdated||t||0}function _h(e){return qs(e)||e.lastUpdated||0}function $h(e,t,n=_h){const r=n(t)-n(e);if(r!==0)return r;const o=(e.machineName||"").localeCompare(t.machineName||"");if(o!==0)return o;const a=e.displayPrimary.localeCompare(t.displayPrimary);if(a!==0)return a;const i=e.displaySecondary.localeCompare(t.displaySecondary);return i!==0?i:e.tabKey.localeCompare(t.tabKey)}function pi(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 wS(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!pi(e)&&!e.title.trim()}function kS(e){return e.length===0?null:[...e].sort((t,n)=>{const r=Number(pi(n))-Number(pi(t));if(r!==0)return r;const o=n.messages.length-t.messages.length;return o!==0?o:$h(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,o=n.filter(i=>i.streamSource==="agent-stream"),a=kS(o);return r?a&&wS(r)?a:r:a||n[0]||null}function SS(e){const t=e.filter(o=>o.type!=="adhdev-daemon"),n=new Set;for(const o of t){if(!Qa(o))continue;const a=gu(o);a&&n.add(a)}const r=new Map;for(const o of t){const a=jy(o,n),i=r.get(a);if(!i){r.set(a,o);continue}const c=m=>(m.workspace?1:0)+(m.activeChat?1:0)+(m.lastMessagePreview?1:0),u=c(i),h=c(o),d=h>u||h===u&&(o.timestamp||0)>(i.timestamp||0)?o:i;r.set(a,CS(d,d===o?i:o))}return Array.from(r.values())}function CS(e,t){const n=Qa(t),r=Qa(e);if(!n&&!r)return e;const o=r?n?void 0:t:e,a=r?e:n?t:void 0,i=o&&String(o.daemonId||"").trim()||String(e.ownerDaemonId||"").trim()||String(t.ownerDaemonId||"").trim()||void 0,c=String(e.ownerMachineName||"").trim()||String(t.ownerMachineName||"").trim()||void 0,u=a==null?void 0:a.settings;return{...e,...i&&{ownerDaemonId:i},...c&&!e.ownerMachineName&&{ownerMachineName:c},...u&&!r&&{settings:{...u,...e.settings??{}}}}}function da(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 jS(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 Pc(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],n=t[t.length-1],r=n?jS(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 NS(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||""),Pc(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||""),Pc(n.activeChat)].join(":"))].join("|")}function AS(e,t){const n=Date.now();return e.map(r=>{const o=t[r.tabKey];return o&&n-o<5e3?{...r,messages:[],title:""}:r})}function TS(e,t){const n=new Map;for(const r of e){const o=t.get(r.routeId)||r;for(const a of Xn({routeId:r.routeId}))n.set(a,o);for(const a of Xn({providerSessionId:r.providerSessionId,sessionId:r.sessionId}))n.set(a,r.streamSource==="native"?o:r);for(const a of Xn({tabKey:r.tabKey}))n.set(a,r)}return n}function IS(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function MS(e){const t=IS(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 DS({ides:e,connectionStates:t,clearedTabs:n}){const r=l.useMemo(()=>SS(e),[e]),o=l.useMemo(()=>uu(e),[e]),a=l.useMemo(()=>yh(e),[e]),i=l.useRef([]),c=l.useRef([]),u=l.useRef([]),h=l.useRef(new Map),d=l.useRef(new Map),m=l.useMemo(()=>{const S=new Map,v=[];for(const A of r){const{connectionState:T="new",machineName:M}=vh(A,{machineNames:a,connectionStates:t,defaultConnectionState:"new"}),L=NS(A),P=h.current.get(A.id);if(P&&P.ide===A&&P.sourceSignature===L&&P.connectionState===T&&P.machineName===M){S.set(A.id,P),v.push(...P.conversations);continue}const B=qi(A,{machineNames:a,connectionStates:t,defaultConnectionState:"new"}),K={ide:A,sourceSignature:L,connectionState:T,machineName:M,conversations:B};S.set(A.id,K),v.push(...B)}h.current=S;const g=new Map,N=A=>{const T=MS(A),M=d.current.get(A.tabKey);if(M&&M.signature===T)return g.set(A.tabKey,M),M.timestamp;const L={signature:T,timestamp:_h(A)||(M==null?void 0:M.timestamp)||0};return g.set(A.tabKey,L),L.timestamp},C=[...v].sort((A,T)=>$h(A,T,N));return d.current=g,C},[r,t,a]),f=l.useMemo(()=>{const S=AS(m,n);return da(i.current,S)?i.current:(i.current=S,S)},[m,n]),x=l.useMemo(()=>{const S=new Map,v=Array.from(new Set(f.map(g=>g.routeId)));for(const g of v){const N=cs(f,g);N&&S.set(g,N)}return S},[f]),w=l.useMemo(()=>{const S=new Map;for(const v of f){const g=x.get(v.routeId),N=v.streamSource==="native"&&g?g:v;for(const C of Xn({providerSessionId:v.providerSessionId,sessionId:v.sessionId,tabKey:v.tabKey}))S.set(C,N)}return S},[f,x]),p=l.useMemo(()=>TS(f,x),[f,x]),y=l.useCallback(S=>{if(S)return w.get(S)},[w]),k=l.useCallback(S=>{if(S)return p.get(S)},[p]),b=l.useMemo(()=>{const S=f.filter(v=>!Ds(v,o).surfaceHidden);return da(c.current,S)?c.current:(c.current=S,S)},[f,o]),j=l.useMemo(()=>{const S=b.map(v=>v.tabKey);return da(u.current,S)?u.current:(u.current=S,S)},[b]);return{chatIdes:r,conversations:f,visibleConversations:b,visibleTabKeys:j,resolveConversationBySessionId:y,resolveConversationByTarget:k}}function PS({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:n,setSearchParams:r}){const o=l.useMemo(()=>{var c;return e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),a=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:o,requestedMobileTabKey:a,consumeRequestedActiveTab:i}}function LS({ides:e,sendDaemonCommand:t,setToasts:n,resolveConversationByTarget:r}){l.useEffect(()=>{pt.setIdes(e)},[e]),l.useEffect(()=>{pt.setResolveAction((o,a,i)=>{t(o,a,i).catch(()=>{})})},[t]),l.useEffect(()=>{const o=pt.onToast(a=>{n(c=>c.some(h=>h.message===a.message&&a.timestamp-h.timestamp<3e3)?c:[...c.slice(-4),{id:a.id,message:a.message,type:a.type,timestamp:a.timestamp,targetKey:a.targetKey,actions:a.actions}]);const i=a.duration||5e3;setTimeout(()=>n(c=>c.filter(u=>u.id!==a.id)),i)});return()=>{o()}},[n]),l.useEffect(()=>{const o=rh.on("status_event",a=>{pt.handleRawEvent(a,"ws")});return()=>{o()}},[]),l.useEffect(()=>{var a;const o=i=>{var p;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,h=r(u),d=(h==null?void 0:h.routeId)||c.daemonId;if(!d)return;const m=Number(c.buttonIndex),f=c.button||((p=h==null?void 0:h.modalButtons)==null?void 0:p[m])||"Approve",x=String(f).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),w=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(x);t(d,"resolve_action",{action:w?"approve":"reject",button:f,...Number.isFinite(m)&&{buttonIndex:m},...(h==null?void 0:h.sessionId)&&{targetSessionId:h.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(y=>console.error("[SW Action] approval failed:",y))};return(a=navigator.serviceWorker)==null||a.addEventListener("message",o),()=>{var i;return(i=navigator.serviceWorker)==null?void 0:i.removeEventListener("message",o)}},[r,t])}const RS="adhdev_dashboardLayout_v1",ES="adhdev_dashboardDockview_v1",_S="adhdev_dashboardDockviewHiddenRestore_v1",Hn={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Xi(e,t){try{const n=localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}}function $S(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Bh(e){return`${RS}:${e}`}function BS(e){const t=Bh(e);return Xi(t,null)}function FS(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=Bh(e);if(n){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Fh(e){return`${ES}:${e}`}function HS(e){const t=Fh(e);return Xi(t,null)}function WS(e,t){try{const n=Fh(e);if(!t){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Hh(e){return`${_S}:${e}`}function OS(e){const t=Hh(e);return Xi(t,{})}function US(e,t){try{const n=Hh(e);if(Object.keys(t).length===0){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function GS(){return{groupAssignments:[...Hn.groupAssignments],focusedGroup:Hn.focusedGroup,groupActiveTabIds:{...Hn.groupActiveTabIds},groupTabOrders:{...Hn.groupTabOrders},groupSizes:[...Hn.groupSizes]}}function KS(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):t.length===0}function zS(){const[e]=l.useState(()=>$S(typeof window<"u"?window.innerWidth:1280)),[t,n]=l.useState(()=>new Map),[r,o]=l.useState(0),[a,i]=l.useState({}),[c,u]=l.useState({}),[h,d]=l.useState([]),[m,f]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[x,w]=l.useState(!1),p=l.useCallback(()=>{if(x)return;const A=BS(e)??GS();n(new Map(A.groupAssignments)),o(A.focusedGroup),i(A.groupActiveTabIds),u(A.groupTabOrders),d(A.groupSizes),w(!0)},[x,e]);l.useEffect(()=>{x&&FS(e,{groupAssignments:[...t.entries()],focusedGroup:r,groupActiveTabIds:a,groupTabOrders:c,groupSizes:h})},[x,e,t,r,a,c,h]),l.useEffect(()=>{const A=window.matchMedia("(max-width: 767px)"),T=M=>f(M.matches);return A.addEventListener("change",T),()=>A.removeEventListener("change",T)},[]);const y=l.useCallback(A=>{n(A)},[]),k=l.useCallback(A=>{o(A)},[]),b=l.useCallback(A=>{i(A)},[]),j=l.useCallback(A=>{u(A)},[]),S=l.useCallback(A=>{d(A)},[]),v=l.useCallback(A=>{k(A)},[k]),g=l.useCallback((A,T)=>{i(M=>(M[A]??null)===(T??null)?M:{...M,[A]:T})},[]),N=l.useCallback((A,T)=>{u(M=>{const L=M[A];return KS(L,T)?M:{...M,[A]:T}})},[]),C=l.useCallback((A,T)=>{const M=T.get(A)??0;return g(M,A),v(M),M},[v,g]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:y,focusedGroup:r,updateFocusedGroup:k,focusGroup:v,groupActiveTabIds:a,updateGroupActiveTabIds:b,setGroupActiveTab:g,groupTabOrders:c,updateGroupTabOrders:j,setGroupTabOrder:N,groupSizes:h,updateGroupSizes:S,isMobile:m,hasHydratedStoredLayout:x,hydrateStoredLayout:p,focusConversationTab:C}}function qS(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0],r=Ao(t);return typeof(n==null?void 0:n.id)=="string"&&r.includes(n.id)}function VS({urlActiveTab:e,conversations:t,resolveConversationBySessionId:n,normalizedGroupAssignments:r,hasHydratedStoredLayout:o,hydrateStoredLayout:a,focusConversationTab:i,setSearchParams:c,historyModalOpen:u,activeConv:h,isRefreshingHistory:d,ides:m,handleRefreshHistory:f}){const x=l.useRef(!1),w=l.useRef(!1),p=l.useRef(null),y=l.useRef(!1);l.useEffect(()=>{if(!e||x.current||t.length===0)return;if(!o){a();return}const k=n(e);k&&(i(k.tabKey,r),x.current=!0,w.current=!0,p.current!=null&&(window.clearTimeout(p.current),p.current=null),c(b=>{const j=new URLSearchParams(b);return j.delete("activeTab"),j},{replace:!0}))},[e,t,n,r,o,a,i,c]),l.useEffect(()=>{if(!(w.current||o)&&t.length!==0){if(!e){a(),w.current=!0;return}if(x.current){w.current=!0;return}if(p.current==null)return p.current=window.setTimeout(()=>{p.current=null,!(w.current||o)&&(a(),w.current=!0)},1500),()=>{p.current!=null&&(window.clearTimeout(p.current),p.current=null)}}},[e,t.length,o,a]),l.useEffect(()=>{if(!u){y.current=!1;return}if(!h||y.current||d)return;const k=m.find(b=>b.id===h.routeId);k&&(!k.chats||k.chats.length===0||qS(k.chats,h))&&(y.current=!0,f())},[u,h,d,m,f])}function ua(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=Ao(t);return typeof(n==null?void 0:n.id)=="string"&&r.includes(n.id)}function Wh({sendDaemonCommand:e,activeConv:t,chats:n,updateRouteChats:r,setToasts:o,setClearedTabs:a}){const[i,c]=l.useState(!1),[u,h]=l.useState(!1),d=l.useCallback(async w=>{try{await e("standalone","launch_ide",{ideType:w,enableCdp:!0})}catch(p){console.error("Launch failed",p)}},[e]),m=l.useCallback(async(w,p)=>{try{const y=w||(t==null?void 0:t.daemonId)||"",k=await e(y,"switch_chat",{id:p,sessionId:p,...Os(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"?an(o,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?an(o,`⚠️ Switch error: ${b}`):an(o,"⚠️ Session switch failed")}catch(y){console.error("Switch failed",y),an(o,`❌ Switch failed: ${y.message||"connection error"}`)}},[t,e,o]),f=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const w=Us(t);await e(w,"new_chat",{...Os(t)}),Uw(w,t.sessionId,Ao(t)[0]),a(p=>({...p,[t.tabKey]:Date.now()}))}catch(w){console.error("New chat failed",w)}finally{c(!1)}}},[t,i,e,a]),x=l.useCallback(async()=>{var w,p;if(!(!t||u)){h(!0);try{const y=Us(t),k=async()=>e(y,"list_chats",{forceExpand:!0,...Os(t)});let b=await k(),j=(b==null?void 0:b.chats)||((w=b==null?void 0:b.result)==null?void 0:w.chats);ua(j,t)&&(await new Promise(S=>setTimeout(S,450)),b=await k(),j=(b==null?void 0:b.chats)||((p=b==null?void 0:b.result)==null?void 0:p.chats)),b!=null&&b.success&&Array.isArray(j)&&(r(t.routeId,j),ua(j,t)&&!ua(n,t)&&an(o,"⚠️ History dialog did not fully open — try once more"))}catch(y){console.error("Refresh history failed",y)}finally{h(!1)}}},[t,n,u,e,r,o]);return{isCreatingChat:i,isRefreshingHistory:u,handleLaunchIde:d,handleSwitchSession:m,handleNewChat:f,handleRefreshHistory:x}}function YS(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 JS(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function Lc(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(o=>t[Number(o)]===e[Number(o)])}function Mr(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 o={};r.forEach((i,c)=>{o[i]=c}),r.length===0&&(o[0]=0);const a=new Map;for(const[i,c]of e){if(!n.has(i)||c<=0)continue;const u=o[c];typeof u=="number"&&u>0&&a.set(i,u)}return{assignments:a,groupCount:Math.max(1,r.length),mapping:o,usedGroups:r}}function Rc(e,t){const n={};for(const[r,o]of Object.entries(e)){const a=t[Number(r)];typeof a=="number"&&(n[a]=o)}return n}function QS(e,t,n){if(t.length===0)return 0;if(typeof n[e]=="number")return n[e];const r=[...t].reverse().find(o=>o<e)??t[0];return n[r]??0}function XS(e,t,n){if(t.length<=1)return[];const r=t.map(i=>e[i]).filter(i=>Number.isFinite(i)),o=r.length===t.length?r:Array(n).fill(100/n),a=o.reduce((i,c)=>i+c,0);return a>0?o.map(i=>i/a*100):Array(n).fill(100/n)}function Ec(e,t){const n={};for(const[r,o]of Object.entries(e)){const a=Number(r);n[a>=t?a+1:a]=o}return n}function _c(e){return Array(e).fill(100/e)}function ZS({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:n,updateGroupActiveTabIds:r,updateGroupTabOrders:o,groupSizes:a,updateGroupSizes:i,isMobile:c,visibleConversations:u,visibleTabKeys:h}){const d=l.useRef(null),m=l.useMemo(()=>Mr(e,h),[e,h]),f=m.assignments,x=l.useMemo(()=>c?1:m.groupCount,[m.groupCount,c]),w=x>1,p=l.useCallback((v,g)=>{t(N=>{const C=new Map(Mr(N,h).assignments);return g===0?C.delete(v):C.set(v,g),C}),r(N=>({...N,[g]:v})),n(g)},[t,h,r,n]),y=l.useCallback(v=>{t(g=>{const N=Mr(g,h).assignments,C=new Map;for(const[A,T]of N)T!==v&&(T>v?C.set(A,T-1):C.set(A,T));return C}),i(g=>{if(g.length<=1)return[];const N=[...g];N.splice(v,1);const C=N.reduce((A,T)=>A+T,0);return C>0?N.map(A=>A/C*100):[]}),n(0)},[t,h,i,n]),k=l.useCallback((v,g)=>{g.preventDefault();const N=d.current;if(!N)return;const C=g.clientX,A=N.offsetWidth,T=a.length===x?[...a]:_c(x),M=P=>{const K=(P.clientX-C)/A*100,F=[...T];F[v]=Math.max(15,T[v]+K),F[v+1]=Math.max(15,T[v+1]-K),i(F)},L=()=>{document.removeEventListener("mousemove",M),document.removeEventListener("mouseup",L),document.body.style.cursor="",document.body.style.userSelect=""};document.body.style.cursor="col-resize",document.body.style.userSelect="none",document.addEventListener("mousemove",M),document.addEventListener("mouseup",L)},[a,x,i]),b=l.useCallback((v,g,N)=>{if(x>=4)return;const C=N==="left"?g:g+1;t(A=>{const T=Mr(A,h).assignments,M=new Map;for(const L of u){const P=T.get(L.tabKey)??0,B=P>=C?P+1:P;B>0&&M.set(L.tabKey,B)}return C>0&&M.set(v,C),M}),i(A=>{const T=A.length===x?[...A]:_c(x),M=T[g]??100/x,L=Math.max(15,M/2),P=Math.max(15,M/2),B=[...T];B[g]=L,B.splice(C,0,P);const K=B.reduce((F,R)=>F+R,0);return B.map(F=>F/K*100)}),r(A=>{const T=Ec(A,C);return T[C]=v,T}),o(A=>{const T=Ec(A,C);return T[C]=[v],T}),n(C)},[x,t,h,u,i,r,o,n]);l.useEffect(()=>{YS(e,f)||t(f)},[e,f,t]),l.useEffect(()=>{const{mapping:v,usedGroups:g}=m;r(N=>{const C=Rc(N,v);return Lc(N,C)?N:C}),o(N=>{const C=Rc(N,v);return Lc(N,C)?N:C}),n(N=>{const C=c?0:QS(N,g,v);return N===C?N:C}),i(N=>{const C=c?[]:XS(N,g,m.groupCount);return JS(N,C)?N:C})},[m,c,r,o,n,i]);const j=l.useMemo(()=>{const v=Array.from({length:x},()=>[]);for(const g of u){const N=f.get(g.tabKey)??0,C=Math.min(N,x-1);v[C].push(g)}return v},[u,f,x]),S=l.useCallback(()=>{t(new Map),n(0)},[t,n]);return{containerRef:d,normalizedGroupAssignments:f,numGroups:x,isSplitMode:w,groupedConvs:j,moveTabToGroup:p,closeGroup:y,handleResizeStart:k,splitTabRelative:b,clearAllSplits:S}}function ha(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 eC(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 Dr(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Zi(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},n=ha(t.channel)||ha(e.updateChannel)||ha(e.releaseChannel)||void 0,r=eC(t.npmTag)||(n==="preview"?"next":n==="stable"?"latest":void 0),o=Dr(t.targetVersion)||Dr(e.serverVersion)||void 0,a=Dr(t.minVersion)||void 0,i=Dr(t.updateCommand)||(n?`adhdev update --channel ${n}`:void 0);return{...n?{channel:n}:{},...r?{npmTag:r}:{},...o?{targetVersion:o}:{},...a?{minVersion:a}:{},...i?{updateCommand:i}:{}}}function dn(e,t=null){return Zi(e).targetVersion||t}function Oh(e){return Zi(e).channel||null}function Uh(e){const t=Zi(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 tC({ides:e,sendDaemonCommand:t}){const n="0.9.82",r=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:Vi(m,dn(m,n))).sort((m,f)=>Number(tr(f,dn(f,n)))-Number(tr(m,dn(m,n)))),[n,e]),o=l.useMemo(()=>r.some(m=>tr(m,dn(m,n))),[n,r]),a=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,h]=l.useState({}),d=l.useCallback(async m=>{var x,w;const f=e.find(p=>p.id===m);if(f){h(p=>({...p,[m]:"upgrading"}));try{const p=await t(m,"daemon_upgrade",Uh(f));(x=p==null?void 0:p.result)!=null&&x.upgraded||(w=p==null?void 0:p.result)!=null&&w.success?h(y=>({...y,[m]:"done"})):h(y=>({...y,[m]:"error"}))}catch{h(p=>({...p,[m]:"error"}))}}},[e,t]);return{versionMismatchDaemons:r,hasRequiredVersionDaemons:o,targetVersion:a,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:u,handleBannerUpgrade:d}}const Gh=80;function Vr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function sC(e){return{...e,createdAt:Vr(e.createdAt),updatedAt:Vr(e.updatedAt,e.createdAt),lastEventAt:Vr(e.lastEventAt,e.updatedAt||e.createdAt)}}function nC(e){const t=bu(e);return t==="unknown:"?e.id:t}function rC(e){return[e.type,fu(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function oC(e,t=Gh){const n=new Map;for(const r of e){if(r.deletedAt)continue;const o=nC(r),a=n.get(o);if(!a){n.set(o,r);continue}(r.updatedAt>a.updatedAt||r.updatedAt===a.updatedAt&&r.createdAt>a.createdAt)&&n.set(o,r)}return Array.from(n.values()).sort((r,o)=>{const a=o.updatedAt-r.updatedAt;return a!==0?a:o.createdAt-r.createdAt}).slice(0,Math.max(0,t))}function aC(e,t){const n=Date.now(),r=[];for(const o of e){const a=o.sessionId?t.get(o.sessionId):void 0;if(a!=null&&a.surfaceHidden||a!=null&&a.muted)continue;const i=No(o,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const u=Vr(o.lastMessageAt||(a==null?void 0:a.lastUpdated)||o.lastUpdated,n),h=rC({type:c,sessionId:o.sessionId,providerSessionId:o.providerSessionId,tabKey:o.tabKey,lastMessageHash:o.lastMessageHash,lastMessageAt:o.lastMessageAt,lastUpdated:(a==null?void 0:a.lastUpdated)||o.lastUpdated});r.push(sC({id:h,dedupKey:h,type:c,routeId:o.routeId,machineId:o.daemonId||o.routeId,sessionId:o.sessionId,providerSessionId:o.providerSessionId,tabKey:o.tabKey,title:_u(o),preview:tw(o),createdAt:u,updatedAt:u,lastEventAt:u}))}return oC(r)}function iC(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function lC(e){const{conversations:t,liveSessionInboxState:n,maxItems:r=Gh}=e,o=l.useMemo(()=>aC(t,n).slice(0,Math.max(0,r)),[t,n,r]),a=l.useMemo(()=>iC(o),[o]);return{notifications:o,unreadCount:a}}function cC({notifications:e,sendDaemonCommand:t}){const n=l.useCallback(a=>{const i=e.find(u=>u.id===a),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(a=>{const i=e.find(c=>c.id===a);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_notification_unread",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]),o=l.useCallback(a=>{const i=e.find(c=>c.id===a);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:o}}function el(...e){const t=new Set,n=[],r=o=>{const a=typeof o=="string"?o.trim():"";if(!a)return;const i=a.toLowerCase();t.has(i)||(t.add(i),n.push(a))};for(const o of e){if(Array.isArray(o)){for(const a of o)r(a);continue}r(o)}return n}function dC(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(),o=(n[2]||"").replace(/[\\/]+/g,"\\");return o?`${r}:\\${o}`:`${r}:\\`}return null}function tl(e,t=[]){if(e==="win32"){for(const n of t){if(typeof n!="string")continue;const r=dC(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 uC(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 hC(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function sl(e,t,n){const r=await e(t,"file_list_browse",{path:n}),o=hC(r);if(!(o!=null&&o.success))throw new Error((o==null?void 0:o.error)||(r==null?void 0:r.error)||"Could not browse folder");const a=typeof(o==null?void 0:o.path)=="string"?o.path:n,i=a.includes("\\")?"\\":"/",c=(h,d)=>/^[A-Za-z]:\\?$/.test(h)?`${h.replace(/\\?$/,"\\")}${d}`:h==="/"||h==="\\"?`${i}${d}`:`${h.replace(/[\\/]+$/,"")}${i}${d}`,u=Array.isArray(o==null?void 0:o.files)?o.files.filter(h=>(h==null?void 0:h.type)==="directory"&&typeof(h==null?void 0:h.name)=="string").map(h=>({name:h.name,path:typeof(h==null?void 0:h.path)=="string"&&h.path.trim()?h.path:c(a,h.name)})).sort((h,d)=>h.name.localeCompare(d.name)):[];return{path:a,directories:u}}function $c(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,(o,a)=>r[a]||"")}function Kh(e,t={}){const n=e==null?void 0:e.mcpConfig;if((n==null?void 0:n.mode)!=="manual")return null;const o=$c(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"}).trim();return!o.includes(`
70
+ `)&&!o.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:$c(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"})}}function pC(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 zh(e){return To(e)||e.tabKey||e.routeId||null}function qh(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():"",o=e.conversations.find(a=>{if(r&&a.routeId!==r)return!1;const i=[a.providerSessionId,a.sessionId,a.nativeSessionId,a.tabKey].map(c=>typeof c=="string"?c.trim():"").filter(Boolean);return!!(t&&i.includes(t)||n&&i.includes(n)||r&&a.routeId===r)});if(o!=null&&o.tabKey)return o.tabKey;if(r){const a=cs(e.conversations,r)||e.conversations.find(i=>i.routeId===r);if(a!=null&&a.tabKey)return a.tabKey}return t||n||r||null}function Ns(e){return String(e||"").trim()}function Vh(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function xo(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function mC(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function fC(e,t){const n=Ns(e.providerSessionId),r=Ns(e.targetSessionId),o=t.find(a=>{const i=[a.providerSessionId,a.sessionId,a.nativeSessionId,a.tabKey,a.routeId].map(Ns).filter(Boolean);return!!(n&&i.includes(n)||r&&i.includes(r))});return o?o.tabKey:r||n||null}function bC(e,t,n){if(t.event!=="agent:generating_completed")return null;const r=Vh(t.daemonId);if(r&&r!==e.machineId)return null;const o=Ns(t.providerType);if(e.providerType&&o!==e.providerType)return null;const a=Ns(e.resumeSessionId),i=Ns(e.launchedSessionId),c=Ns(t.providerSessionId),u=Ns(t.targetSessionId);if(a&&a!==c&&a!==u||i&&i!==c&&i!==u)return null;const h=xo(e.workspacePath);if(h){const d=xo(t.workspaceName);if(d&&!mC(d,h))return null}return fC(t,n)}function Bc(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function gC({ides:e,conversations:t,onOpenSession:n}){const[r,o]=l.useState(null),a=l.useRef(null),i=l.useCallback(()=>{a.current=null,o(null)},[]),c=l.useCallback(u=>{a.current=u,o(u)},[]);return l.useEffect(()=>{if(!r)return;const u=xo(r.workspacePath),h=e.find(m=>{var y,k,b,j;if(!m||m.type==="adhdev-daemon"||Vh(m.daemonId||m.id)!==r.machineId||(ir(m)?"cli":pn(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 S=String(r.launchedSessionId||"");return[m.providerSessionId,m.sessionId,m.instanceId,m.id].map(g=>String(g||"")).filter(Boolean).includes(S)}if(u){const S=xo(m.workspace||m.runtimeWorkspaceLabel);return S?S===u:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((j=(b=(k=(y=m.activeChat)==null?void 0:y.messages)==null?void 0:k.at)==null?void 0:b.call(k,-1))==null?void 0:j.timestamp)||0)>=r.startedAt-5e3});if(!h)return;const d=qh({entrySessionId:h.sessionId,entryInstanceId:h.instanceId,entryRouteId:h.id,conversations:t});d&&(i(),n(d))},[i,t,e,n,r]),l.useEffect(()=>pt.onStatusEvent(u=>{const h=a.current;if(!h)return;const d=bC(h,u,t);d&&(i(),n(d))}),[i,t,n]),l.useEffect(()=>{if(!r)return;const u=window.setTimeout(()=>{o(h=>!h||h.startedAt!==r.startedAt?h:(a.current=null,null))},45e3);return()=>window.clearTimeout(u)},[r]),{trackPendingLaunch:c}}function xC({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:n,activeConv:r,ides:o,setCliViewModeOverrides:a}){const i=Bi(),{launchCli:c}=ko(),u=l.useCallback(async(y,k)=>sl(e,y,k),[e]),h=l.useCallback(async(y,k)=>{if(!k.trim())return{ok:!1,error:"Choose a workspace path first."};try{const b=await e(y,"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(y,k,b)=>{var j;try{const S={ideType:k,enableCdp:!0};(j=b==null?void 0:b.workspacePath)!=null&&j.trim()&&(S.workspace=b.workspacePath.trim());const v=await e(y,"launch_ide",S);return!(v!=null&&v.success)&&(v==null?void 0:v.success)!==void 0?{ok:!1,error:(v==null?void 0:v.error)||"Could not launch IDE"}:(t({machineId:y,kind:"ide",providerType:k,workspacePath:(b==null?void 0:b.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(S){return{ok:!1,error:S instanceof Error?S.message:"Could not launch IDE"}}},[e,t]),m=l.useCallback(async(y,k,b,j)=>{var v,g,N,C;const S=Date.now();try{const A={cliType:b};(v=j==null?void 0:j.workspacePath)!=null&&v.trim()?A.dir=j.workspacePath.trim():j!=null&&j.workspaceId&&(A.workspaceId=j.workspaceId),(g=j==null?void 0:j.resumeSessionId)!=null&&g.trim()&&(A.resumeSessionId=j.resumeSessionId.trim()),Array.isArray(j==null?void 0:j.cliArgs)&&j.cliArgs.length>0&&(A.cliArgs=j.cliArgs),(N=j==null?void 0:j.initialModel)!=null&&N.trim()&&(A.initialModel=j.initialModel.trim()),(C=j==null?void 0:j.initialThinkingLevel)!=null&&C.trim()&&(A.initialThinkingLevel=j.initialThinkingLevel.trim());const T=await c(y,A),M=(T==null?void 0:T.result)||T,L=(M==null?void 0:M.sessionId)||(M==null?void 0:M.id);return T!=null&&T.success&&L?(t({machineId:y,kind:k,providerType:b,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,launchedSessionId:L,startedAt:S}),{ok:!0}):T!=null&&T.success?(t({machineId:y,kind:k,providerType:b,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,startedAt:S}),{ok:!0}):{ok:!1,error:(T==null?void 0:T.error)||(M==null?void 0:M.error)||`Could not launch ${k.toUpperCase()} session`}}catch(A){return Bc(A)?(t({machineId:y,kind:k,providerType:b,workspacePath:(j==null?void 0:j.workspacePath)||null,resumeSessionId:(j==null?void 0:j.resumeSessionId)||null,startedAt:S}),{ok:!0}):{ok:!1,error:A instanceof Error?A.message:`Could not launch ${k.toUpperCase()} session`}}},[c,e,t]),f=l.useCallback(async y=>{var k;if(i!=null&&i.listMeshes)return i.listMeshes(y);if(!y)return[];try{const b=await e(y,"list_meshes",{}),j=(b==null?void 0:b.result)??b;if((j==null?void 0:j.success)===!1)throw new Error((j==null?void 0:j.error)||"Could not load meshes");return(Array.isArray(j==null?void 0:j.meshes)?j.meshes:Array.isArray((k=j==null?void 0:j.result)==null?void 0:k.meshes)?j.result.meshes:[]).map(v=>{var g;return{id:String((v==null?void 0:v.id)||""),name:String((v==null?void 0:v.name)||(v==null?void 0:v.id)||"Untitled mesh"),repoIdentity:(v==null?void 0:v.repoIdentity)||(v==null?void 0:v.repo_identity)||null,workspace:Array.isArray(v==null?void 0:v.nodes)&&v.nodes.length>0?String(((g=v.nodes[0])==null?void 0:g.workspace)||""):null,nodesCount:Array.isArray(v==null?void 0:v.nodes)?v.nodes.length:void 0,status:(v==null?void 0:v.status)||null}}).filter(v=>v.id)}catch(b){throw console.error("List meshes failed",b),b}},[i,e]),x=l.useCallback(async(y,k,b,j)=>{var v,g;if(!k.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(y,k,b,j);const S=Date.now();try{const N={meshId:k.trim()};b.trim()&&(N.cliType=b.trim());const C=(v=j==null?void 0:j.initialModel)==null?void 0:v.trim(),A=(g=j==null?void 0:j.initialThinkingLevel)==null?void 0:g.trim();C&&(N.initialModel=C),A&&(N.initialThinkingLevel=A);const T=await e(y,"launch_mesh_coordinator",N),M=(T==null?void 0:T.result)??T;if((M==null?void 0:M.success)===!1||(T==null?void 0:T.success)===!1){const P=String((M==null?void 0:M.code)||(T==null?void 0:T.code)||""),B=pC((M==null?void 0:M.meshCoordinatorSetup)||(M==null?void 0:M.manualSetup)||(T==null?void 0:T.meshCoordinatorSetup)||(T==null?void 0:T.manualSetup));return{ok:!1,error:(M==null?void 0:M.error)||(T==null?void 0:T.error)||"Could not launch mesh coordinator",code:P||void 0,manualSetup:B}}const L=(M==null?void 0:M.sessionId)||(M==null?void 0:M.id);return L?n(L):t({machineId:y,kind:"cli",providerType:(M==null?void 0:M.cliType)||b.trim()||void 0,workspacePath:(M==null?void 0:M.workspace)||null,startedAt:S}),{ok:!0}}catch(N){return Bc(N)?(t({machineId:y,kind:"cli",providerType:b.trim()||void 0,startedAt:S}),{ok:!0}):{ok:!1,error:N instanceof Error?N.message:"Could not launch mesh coordinator"}}},[i,n,e,t]),w=l.useCallback(async(y,k)=>{if(!y||!k)return[];try{const b=await e(y,"list_saved_sessions",{providerType:k,kind:"cli",limit:30}),j=(b==null?void 0:b.result)??b;return Array.isArray(j==null?void 0:j.sessions)?j.sessions:[]}catch(b){return console.error("List saved sessions failed",b),[]}},[e]),p=l.useCallback(async y=>{await Eh({conversation:r,mode:y,ides:o,sendDaemonCommand:e,setCliViewModeOverrides:a})},[r,o,e,a]);return{handleBrowseMachineDirectory:u,handleSaveMachineWorkspace:h,handleLaunchMachineIde:d,handleLaunchMachineProvider:m,handleListMachineMeshes:f,handleLaunchMeshCoordinator:x,handleListMachineSavedSessions:w,setActiveCliViewMode:p}}function yC(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 vC(e,t,n=Date.now()){return!e||!yC(t)?null:{tabKey:e,nonce:n}}function wC({isMobile:e,conversations:t,visibleConversations:n,groupActiveTabIds:r,focusedGroup:o,groupedConvs:a,setSearchParams:i}){const[c,u]=l.useState(null),[h,d]=l.useState(null),m=l.useMemo(()=>{var y,k;if(!e){if(c){const b=t.find(j=>j.tabKey===c);if(b)return b}return n[0]}const p=r[o];if(p){const b=t.find(j=>j.tabKey===p);if(b)return b}return((y=a[o])==null?void 0:y[0])||((k=a[0])==null?void 0:k[0])},[t,c,o,r,a,e,n]),f=l.useCallback(p=>{u(p)},[]),x=l.useCallback(p=>{u(p.tabKey),i(y=>{const k=new URLSearchParams(y),b=nw(p);return b?k.set("activeTab",b):k.delete("activeTab"),k},{replace:!0})},[i]),w=l.useCallback((p,y)=>{const k=vC(p,y);k&&d(k)},[]);return{activeConv:m,openDesktopConversation:x,requestScrollToBottom:w,scrollToBottomRequest:h,setDesktopActiveTab:f}}function kC(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 SC(e){const t=String(e.liveState.completionMarker||""),n=String(e.liveState.seenCompletionMarker||""),r=String(e.liveState.inboxBucket||"idle"),o=!!e.liveState.unread,a=[e.tabKey,e.historySessionId||"",t,n,r,o?"1":"0"].join(":");return{shouldMarkSeen:!!(r==="task_complete"&&o&&(!t||t!==n)),autoReadKey:a,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function CC({activeConv:e,isMobile:t,liveSessionInboxState:n,sendDaemonCommand:r}){const o=l.useRef(null),a=l.useRef(null),i=l.useRef(null),c=l.useRef(null),u=l.useRef(null);l.useEffect(()=>{const h=()=>{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),a.current=null};if(t){h(),o.current=null;return}if(!(e!=null&&e.sessionId)){h(),o.current=null;return}const d=Ds(e,n),m=SC({tabKey:e.tabKey,historySessionId:To(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:qs(e),liveState:d}),f=m.autoReadKey,x=kC({autoReadKey:f,shouldMarkSeen:m.shouldMarkSeen,completedKey:o.current,pendingKey:a.current});if(!m.shouldMarkSeen){x.shouldCancelPending&&h(),o.current=f;return}if(!x.shouldSchedule)return;x.shouldCancelPending&&h();const w=()=>{if(document.visibilityState!=="visible"||o.current===f)return;o.current=f,a.current=null,i.current=null,c.current=null,u.current&&(document.removeEventListener("visibilitychange",u.current),u.current=null);const y=m.readAt;r(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:y,completionMarker:m.completionMarker}).catch(()=>{})};if(a.current=x.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(w,1500);const y=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};u.current=y,document.addEventListener("visibilitychange",y);return}const p=()=>{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=p,document.addEventListener("visibilitychange",p)},[e,t,n,r]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),u.current&&document.removeEventListener("visibilitychange",u.current)},[])}function pa(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 jC({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:n,ides:r,sendDaemonCommand:o,updateRouteChats:a,setToasts:i,setClearedTabs:c,setSearchParams:u}){var Q;const{launchCli:h}=ko(),[d,m]=l.useState(!1),[f,x]=l.useState([]),[w,p]=l.useState(()=>Ft()),[y,k]=l.useState(!1),[b,j]=l.useState(null),S=l.useRef(null),v=l.useMemo(()=>n||t||e,[e,n,t]),g=!!v&&ct(v)&&!lt(v),N=l.useMemo(()=>{if(!v||!g)return null;const E=v.daemonId||v.routeId||"",I=bs(v),$=pa(v);return`${E}:${I}:${v.providerSessionId||""}:${$}`},[v,g]),C=l.useMemo(()=>!v||!g?"":pa(v),[v,g]),{isCreatingChat:A,isRefreshingHistory:T,handleSwitchSession:M,handleNewChat:L,handleRefreshHistory:P}=Wh({sendDaemonCommand:o,activeConv:v,chats:(Q=r.find(E=>E.id===(v==null?void 0:v.routeId)))==null?void 0:Q.chats,updateRouteChats:a,setToasts:i,setClearedTabs:c}),B=l.useCallback(()=>{m(!0)},[]),K=l.useCallback(()=>{m(!1)},[]),F=l.useCallback(async()=>{if(!(!v||!g||y)){k(!0);try{const E=v.daemonId||v.routeId,I=bs(v),$=pa(v),D=await o(E,"list_saved_sessions",{agentType:I,providerType:I,kind:"cli",limit:50,...v.providerSessionId?{providerSessionId:v.providerSessionId}:{},...$?{workspace:$}:{}}),U=(D==null?void 0:D.result)??D;x(Array.isArray(U==null?void 0:U.sessions)?U.sessions:[])}catch(E){console.error("Refresh saved sessions failed",E),x([])}finally{k(!1)}}},[v,y,g,o]);l.useEffect(()=>{if(!d){S.current=null;return}if(!g){S.current=null,x([]),k(!1);return}!N||y||S.current!==N&&(S.current=N,F())},[F,d,y,g,N]);const R=l.useCallback(async E=>{if(!v||!g||!E.providerSessionId||!E.workspace)return;const I=v.daemonId||v.routeId,$=bs(v);try{j(E.providerSessionId);const D=await h(I,{cliType:$,dir:E.workspace,resumeSessionId:E.providerSessionId,initialModel:wu(E.summaryMetadata,"model",{preferShortValue:!0})||void 0}),U=(D==null?void 0:D.result)??D,Y=typeof(U==null?void 0:U.sessionId)=="string"?U.sessionId:typeof(U==null?void 0:U.id)=="string"?U.id:"";Y&&u(ae=>{const z=new URLSearchParams(ae);return z.set("activeTab",Y),z},{replace:!0}),K()}catch(D){console.error("Resume saved session failed",D)}finally{j(null)}},[K,v,g,o,u]);return{historyModalOpen:d,openHistoryModal:B,closeHistoryModal:K,historyTargetConv:v,isSavedSessionHistoryTarget:g,isHistoryCreatingChat:A,isHistoryRefreshingHistory:T,handleHistorySwitchSession:M,handleHistoryNewChat:L,handleHistoryRefresh:P,savedHistorySessions:f,savedHistoryFilters:w,setSavedHistoryFilters:p,missingWorkspaceResumePath:C,isSavedHistoryLoading:y,resumingSavedHistorySessionId:b,handleRefreshSavedHistory:F,handleResumeSavedHistorySession:R}}function NC({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:o,conversations:a,ides:i,resolveConversationByTarget:c}){const[u,h]=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]),x=l.useMemo(()=>{const k=u==null?void 0:u.routeId;if(!k)return null;const b=u!=null&&u.tabKey?a.find(j=>j.tabKey===u.tabKey):o?a.find(j=>j.tabKey===o):null;return(b==null?void 0:b.routeId)===k?b:cs(a,k)},[a,u,o]),w=l.useMemo(()=>{if(x)return i.find(k=>k.id===x.routeId)},[i,x]);l.useEffect(()=>{f&&(h({routeId:f.routeId,tabKey:ec(f)}),m(f),n({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,n,f]);const p=l.useCallback(k=>{k&&(h({routeId:k.routeId,tabKey:ec(k)}),m(k))},[]),y=l.useCallback(()=>{h(null),m(null)},[]);return{remoteDialogConv:x,remoteDialogIdeEntry:w,remoteDialogActiveConv:d,setRemoteDialogActiveConv:m,openRemoteDialog:p,closeRemoteDialog:y}}function AC({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:o,conversations:a,ides:i,resolveConversationByTarget:c,activeConv:u,sendDaemonCommand:h}){const{remoteDialogConv:d,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:x,openRemoteDialog:w,closeRemoteDialog:p}=NC({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:o,conversations:a,ides:i,resolveConversationByTarget:c}),[y,k]=l.useState(!1),[b,j]=l.useState(null),S=l.useCallback(async N=>{const C=N||u;!C||!ct(C)&&!lt(C)||(j(C),k(!0))},[u]),v=l.useCallback(()=>{k(!1),j(null)},[]),g=l.useCallback(async N=>{const C=b||u;if(!C||!ct(C)&&!lt(C)){v();return}k(!1);try{const A=bs(C),T=C.routeId||C.daemonId||"";await h(T,"stop_cli",{cliType:A,targetSessionId:C.sessionId,mode:N,...Do(C)})}catch(A){console.error("Stop CLI failed:",A)}finally{j(null)}},[u,v,b,h]);return{remoteDialogConv:d,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:x,openRemoteDialog:w,closeRemoteDialog:p,cliStopDialogOpen:y,cliStopTargetConv:b,requestCliStop:S,cancelCliStop:v,confirmCliStop:g}}function ma(e,t=!0){return(e??!0)&&t}const nl=l.memo(function({activeConv:t,clearToken:n,isCliTerminal:r,ideEntry:o,terminalRef:a,handleModalButton:i,handleRelaunch:c,handleSendChat:u,handleForceSendChat:h,isSendingChat:d,sendFeedbackMessage:m=null,handleFocusAgent:f,isFocusingAgent:x,actionLogs:w,userName:p,scrollToBottomRequestNonce:y,isInputActive:k=!0,isVisible:b=!0}){const j=r,S=!r,v=ma(b,j),g=ma(b,S),N=ma(b),C=Ph(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(hu,{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:j?"visible":"hidden",pointerEvents:j?"auto":"none"},children:s.jsx(E0,{activeConv:A,clearToken:n,terminalRef:a,handleSendChat:u,isSendingChat:d,sendFeedbackMessage:m,isVisible:v,isInputActive:k&&v})}),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(ri,{activeConv:A,ideEntry:o,handleSendChat:u,isSendingChat:d,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:x,actionLogs:w,userName:p,scrollToBottomRequestNonce:y,isInputActive:k&&g,isVisible:g})})]}):s.jsx(ri,{activeConv:A,ideEntry:o,handleSendChat:u,handleForceSendChat:h,isSendingChat:d,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:x,actionLogs:w,userName:p,scrollToBottomRequestNonce:y,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 TC({conversation:e,className:t="",onOpenNativeConversation:n,onOpenMachine:r,interactive:o=!0,meshOnly:a=!1}){var j,S,v;const i=pr(),c=Ps(e),u=a?null:Eu(e),h=!a&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),d=!a&&e.streamSource==="agent-stream"&&!!e.agentName,m=!a&&!d&&(e.transport==="pty"||e.transport==="acp"),f=yn(e),x=sw(e),w=(j=e.settings)==null?void 0:j.meshNodeFor,p=e.meshQueueStats,y=((S=e.coordinator)==null?void 0:S.meshId)||((v=e.settings)==null?void 0:v.meshCoordinatorFor),k=l.useCallback(()=>{if(r){r();return}c&&i("/dashboard",{state:{openMachineId:c}})},[c,i,r]),b=l.useCallback(()=>{if(n){n();return}const g=zh(e);g&&i(dr(g))},[e,i,n]);return!h&&!d&&!m&&!u&&!w&&!p?null:s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[h&&(o?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:b,title:x,children:[s.jsx(us,{size:12}),s.jsx("span",{children:x})]}):s.jsxs("span",{className:"conversation-meta-chip",title:x,children:[s.jsx(us,{size:12}),s.jsx("span",{children:x})]})),d&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[s.jsx(ar,{size:12}),s.jsx("span",{children:f})]}),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:f,children:[s.jsx(ar,{size:12}),s.jsx("span",{children:f})]}),u&&(o?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:k,title:u,children:[s.jsx(Is,{size:12}),s.jsx("span",{children:u})]}):s.jsxs("span",{className:"conversation-meta-chip",title:u,children:[s.jsx(Is,{size:12}),s.jsx("span",{children:u})]})),w&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(Is,{size:12}),s.jsx("span",{children:"Mesh Node"})]}),y&&p&&s.jsxs("span",{className:`conversation-meta-chip ${p.pending>0?"is-active":""}`,style:p.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${p.pending} pending, ${p.assigned} assigned, ${p.completed} completed, ${p.failed} failed`,children:[s.jsx(Rf,{size:12}),s.jsxs("span",{children:[p.pending," Pending"]})]})]})}function IC({selectedConversation:e,isAcp:t,isStandalone:n,selectedIdeEntry:r,actionLogs:o,userName:a,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:u,onBack:h,onOpenNativeConversation:d,onOpenMachine:m,onOpenHistory:f,onOpenRemote:x,onOpenMeshGraph:w,onStopCli:p,cliViewMode:y,onSetCliViewMode:k,handleSendChat:b,handleForceSendChat:j,handleFocusAgent:S,handleModalButton:v,handleRelaunch:g}){var L,P;const N=l.useRef(null),C=ct(e)&&!t,A=C&&y==="terminal",T=!!e.daemonId&&!!((L=e.coordinator)!=null&&L.meshId||(P=e.settings)!=null&&P.meshCoordinatorFor),M=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 ${M} 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:h,type:"button","aria-label":"Back",children:s.jsx(ji,{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(TC,{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&&y&&s.jsx(uh,{mode:y,onChange:k,compact:!0}),C&&p&&s.jsx("button",{onClick:()=>{p(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(At,{size:14})}),T&&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(Ai,{size:14})}),!t&&!C&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>x(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(nl,{activeConv:e,clearToken:0,isCliTerminal:A,ideEntry:r,terminalRef:N,handleModalButton:v,handleRelaunch:g,handleSendChat:b,handleForceSendChat:j,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:S,isFocusingAgent:u,actionLogs:o,userName:a})})]})}const fa={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 MC(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Yh(){const[e,t]=l.useState("unix"),[n,r]=l.useState("powershell"),[o,a]=l.useState(!1),i=e==="unix"?"unix":n;l.useEffect(()=>{t(MC())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(fa[i].cmd).catch(()=>{}),a(!0),setTimeout(()=>a(!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:fa[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:fa[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:o?"✓":"📋"})]}),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 Jh({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:o,icon:a})=>{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(a,{size:15})}),s.jsx("span",{children:o})]},r)})})})}function Pr({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 Wn({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 DC({conversation:e,onCancel:t,onConfirm:n}){const{t:r}=Le(),o=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:o})}),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:o,onRequestStopCli:a,onOpenMeshGraph:i,onCollectChatDebugBundle:c,isMuted:u,onToggleMute:h}){const{t:d}=Le(),m=t==="needs_attention"||t==="task_complete",f=t==="working",x=t==="earlier",w=t==="task_complete",{isReconnecting:p,isConnecting:y}=An(e.conversation),k=xt(e.conversation),b=vn(e.conversation),j=ih(e.conversation,{requiresAction:t==="needs_attention"}),S=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%)]":x?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",v=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":x?"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",g=x?"text-text-secondary":"text-text-primary",N=x?"text-text-muted":"text-text-secondary",C=x?"text-text-secondary opacity-80":"text-text-muted",A=x?"text-text-muted opacity-80":"text-text-muted",T=!f&&!w,M=oh(e.conversation),L="text-[color:var(--status-warning)]",P=B=>{if(!c)return;B.preventDefault(),B.stopPropagation();const K=c==null?void 0:c(e.conversation);Promise.resolve(K).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] ${S}`,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 ${v}`,style:m?{color:"var(--accent-on-primary)"}:void 0,children:n(k)}),M&&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:B=>{B.preventDefault(),B.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:P,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 ${g}`,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(co,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),p?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${L} animate-pulse`,children:d("mobileInbox.reconnectingItem")})]}):y?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")})]}):j==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:L,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:[T&&s.jsx("span",{className:`mr-0.5 text-[11px] font-medium shrink-0 ${A}`,children:du(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")}),h&&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:B=>{B.preventDefault(),B.stopPropagation(),h()},"aria-label":u?d("mobileInbox.unmute",{title:k}):d("mobileInbox.mute",{title:k}),title:d(u?"mobileInbox.mutedTitle":"mobileInbox.muteNotifications"),children:u?s.jsx(Xd,{size:13}):s.jsx(Nn,{size:13})}),o&&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:B=>{B.preventDefault(),B.stopPropagation(),o()},"aria-label":d("mobileInbox.hideConversationAria",{title:k}),title:d("mobileInbox.hideConversationTitle"),children:s.jsx(Ti,{size:13})}),a&&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:B=>{B.preventDefault(),B.stopPropagation(),a()},"aria-label":d("mobileInbox.stopSessionAria",{title:k}),title:d("mobileInbox.stopSessionTitle"),children:s.jsx(At,{size:13})})]})]})},e.conversation.tabKey)}function Fc({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 PC({section:e,attentionItems:t,unreadItems:n,workingItems:r,completedItems:o,hiddenConversations:a,machineCards:i,getAvatarText:c,actionLogs:u,sendDaemonCommand:h,onOpenConversation:d,onShowAllHidden:m,onHideConversation:f,onOpenMeshGraph:x,onStopCli:w,onOpenNewSession:p,onOpenMachine:y,onOpenSettings:k,onSectionChange:b,wsStatus:j="connected",isStandalone:S=!1,onCollectChatDebugBundle:v,isConversationMuted:g,onToggleMuteConversation:N}){const{t:C}=Le(),[A,T]=l.useState(null),M=j==="disconnected"||j==="reconnecting"||j==="offline"||j==="auth_failed",L=i.length>0,P=t.length>0||n.length>0||r.length>0||o.length>0,B=C(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),K=S?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",F=S?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",R=l.useCallback(async I=>{const $=Us(I);if(!$)return;const D=Array.isArray(I.messages)?I.messages:[],U=Wu({activeConv:I,visibleMessages:D,actionLogs:u,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:D.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),Y=await h($,"get_chat_debug_bundle",{...Os(I),delivery:"daemon_file",frontendSnapshot:U}),ae=er(Y),z=Gu(ae),X=await Uu(z);X==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),pt.showToast(Ou(ae,{locatorCopyStatus:X}),X==="failed"?"warning":"success")},[u,h]),Q=v||R,E=l.useCallback(()=>{A&&(f==null||f(A),T(null))},[A,f]);return s.jsxs("div",{className:"flex h-full w-full min-w-0 flex-1 flex-col overflow-hidden bg-bg-primary",children:[s.jsx("div",{className:`z-10 shrink-0 bg-bg-primary ${K}`,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:B}),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(So,{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:M?s.jsx(Wn,{icon:s.jsx(Fc,{}),title:C(j==="offline"?"mobileInbox.networkOffline":j==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:C(j==="offline"?"mobileInbox.waitingForNetwork":j==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):i.length===0?s.jsx(Wn,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:C(S?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:C(S?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!S&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(Yh,{})})}):s.jsx(nn,{children:i.map((I,$)=>s.jsxs("button",{className:`flex items-start gap-3.5 px-4 py-3.5 w-full text-left transition-colors active:scale-[0.995] ${$>0?"border-t border-border-subtle/70":""}`,onClick:()=>y(I.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(I.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:I.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:I.unread>0?s.jsx("span",{className:"text-accent-primary",children:C("mobileInbox.newCount",{count:I.unread})}):I.total>0?C("mobileInbox.chatCount",{count:I.total}):C("mobileInbox.idle")})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:I.subtitle}),I.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[C("mobileInbox.chatCount",{count:I.total}),I.unread>0?C("mobileInbox.unreadSuffix",{count:I.unread}):""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:C("mobileInbox.noActiveChats")})]})]},I.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(Pr,{title:C("mobileInbox.needsAttention"),className:"mb-0"}),s.jsx(nn,{children:t.map((I,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Lr,{item:I,type:"needs_attention",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>T(I.conversation):void 0,onRequestStopCli:w?()=>w(I.conversation):void 0,onOpenMeshGraph:x,onCollectChatDebugBundle:Q,isMuted:g==null?void 0:g(I.conversation),onToggleMute:N?()=>N(I.conversation):void 0})},I.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(Pr,{title:C("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),s.jsx(nn,{children:n.map((I,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Lr,{item:I,type:"task_complete",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>T(I.conversation):void 0,onRequestStopCli:w?()=>w(I.conversation):void 0,onOpenMeshGraph:x,onCollectChatDebugBundle:Q,isMuted:g==null?void 0:g(I.conversation),onToggleMute:N?()=>N(I.conversation):void 0})},I.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(Pr,{title:C("mobileInbox.workingNow"),className:"mb-0 mt-2"}),s.jsx(nn,{children:r.map((I,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Lr,{item:I,type:"working",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>T(I.conversation):void 0,onRequestStopCli:w?()=>w(I.conversation):void 0,onOpenMeshGraph:x,onCollectChatDebugBundle:Q,isMuted:g==null?void 0:g(I.conversation),onToggleMute:N?()=>N(I.conversation):void 0})},I.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[o.length>0&&s.jsx(Pr,{title:C("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),o.length>0?s.jsx(nn,{children:o.map((I,$)=>s.jsx("div",{className:$>0?"border-t border-border-subtle/70":"",children:s.jsx(Lr,{item:I,type:"earlier",getAvatarText:c,onOpenConversation:d,onRequestHideConversation:f?()=>T(I.conversation):void 0,onRequestStopCli:w?()=>w(I.conversation):void 0,onOpenMeshGraph:x,onCollectChatDebugBundle:Q,isMuted:g==null?void 0:g(I.conversation),onToggleMute:N?()=>N(I.conversation):void 0})},I.conversation.tabKey))}):P?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:C("mobileInbox.allCaughtUp")}):M?s.jsx(Wn,{icon:s.jsx(Fc,{size:28}),title:C("mobileInbox.connecting"),subtitle:C("mobileInbox.connectingSubtitle")}):L?s.jsx(Wn,{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:H0,children:p&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:p,"aria-label":Bs,title:Bs,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:Bs})]})}):s.jsx(Wn,{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"&&a.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:a.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"&&p&&P&&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:p,"aria-label":Bs,title:Bs,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(DC,{conversation:A,onCancel:()=>T(null),onConfirm:E}),s.jsx(Jh,{section:e,onSectionChange:b})]})}function LC(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 Qh(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=LC(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:r?`Updated ${r}`:"",preview:(e.preview||"").trim()}}function rl({title:e,description:t,currentPath:n,directories:r,busy:o=!1,error:a="",confirmLabel:i="Use this folder",onClose:c,onNavigate:u,onConfirm:h}){const[d,m]=l.useState(n);l.useEffect(()=>{m(n)},[n]);const f=uC(n),x=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:()=>{!f||o||u(f)},disabled:!f||o,children:[s.jsx(ji,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:"Current folder"}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:d,onChange:w=>m(w.target.value),onKeyDown:w=>{w.key!=="Enter"||!x||o||(w.preventDefault(),u(x))},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:()=>{!x||o||u(x)},disabled:!x||o,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:o?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):a?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:a}):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(w=>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(w.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:w.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:w.path})]})]},w.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:()=>h(x||n),disabled:!x&&!n||o,children:i})]})]})})}function Xh({title:e,description:t,details:n,workspaceOptions:r,selectedWorkspaceKey:o,onWorkspaceChange:a,confirmLabel:i,busyLabel:c,busy:u=!1,showArgsInput:h,argsValue:d,onArgsChange:m,showModelInput:f,modelValue:x,onModelChange:w,historyProviderNode:p,onConfirm:y,onCancel:k}){const{t:b}=Le("common"),j=i??b("machine.launchConfirm.launch"),S=c??b("machine.launchConfirm.launching"),v=r==null?void 0:r.find(g=>g.key===o);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&&a&&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:o||"",onChange:g=>a(g.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(g=>s.jsx("option",{value:g.key,children:g.label},g.key))}),(v==null?void 0:v.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:v.description})]}),p,n.map(g=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:g.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:g.value})]},`${g.label}:${g.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:x||"",onChange:g=>w(g.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})]}),h&&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:g=>m(g.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:y,disabled:u,children:[s.jsx(Qd,{size:14}),u?S:j]})]})]})})}function Hc(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function Zh(e){const{machine:t,currentWorkspacePath:n,currentWorkspaceId:r,includeHome:o=!0}=e,a=[];o&&a.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const u of t.workspaces||[])a.push({key:`saved:${u.id}`,label:`${u.id===t.defaultWorkspaceId?"⭐ ":""}${Hc(u.path,u.label)}`,description:u.path,workspaceId:u.id,workspacePath:u.path});const i=(n==null?void 0:n.trim())||"",c=i?(t.workspaces||[]).find(u=>u.path===i):null;if(i&&!c&&a.push({key:`custom:${i}`,label:Hc(i),description:i,workspaceId:null,workspacePath:i}),r){const u=`saved:${r}`;if(a.some(h=>h.key===u))return{options:a,selectedKey:u}}return c?{options:a,selectedKey:`saved:${c.id}`}:i?{options:a,selectedKey:`custom:${i}`}:{options:a,selectedKey:"__home__"}}function RC(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function EC(e){return[RC(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function _C(e){return e.lastLaunchedAt?jo(e.lastLaunchedAt):""}function ep(e){return{metaText:EC(e),updatedLabel:_C(e)}}function ba(e,t,n){return e?"ide":t>0?"cli":n>0?"acp":null}function $C({selectedMachineEntry:e,cliProviders:t,acpProviders:n,machineAction:r,onBrowseDirectory:o,onListSavedSessions:a}){var he,$e,Fe,Ie;const i=In(),[c,u]=l.useState(!1),h=(((he=e.detectedIdes)==null?void 0:he.length)||0)>0,d=l.useMemo(()=>(e.workspaces||[]).map(ye=>({id:ye.id,path:ye.path,label:ye.label})),[e]),m=e.defaultWorkspaceId||null,[f,x]=l.useState(m||(($e=d[0])==null?void 0:$e.id)||""),[w,p]=l.useState(""),[y,k]=l.useState(""),[b,j]=l.useState([]),[S,v]=l.useState(!1),[g,N]=l.useState(""),[C,A]=l.useState(!1),[T,M]=l.useState(ba(h,t.length,n.length)),L=l.useRef(null),[P,B]=l.useState(null),K=l.useRef("__home__"),[F,R]=l.useState("__home__"),[Q,E]=l.useState(""),[I,$]=l.useState(""),[D,U]=l.useState(""),[Y,ae]=l.useState([]),[z,X]=l.useState(()=>Ft().textQuery),[de,re]=l.useState(()=>Ft().workspaceQuery),[W,oe]=l.useState(()=>Ft().modelQuery),[V,ie]=l.useState(()=>Ft().resumableOnly),[ke,xe]=l.useState(()=>Ft().sortMode),[Se,pe]=l.useState(!1),[G,O]=l.useState(!1),Z=l.useRef(null),q=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const me=f==="__custom__"?w.trim():((Fe=d.find(ye=>ye.id===f))==null?void 0:Fe.path)||"",Te=f==="__custom__"&&!!me&&r.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(r.message),_=f!=="__custom__"&&((Ie=d.find(ye=>ye.id===f))==null?void 0:Ie.path)||"",te=l.useMemo(()=>(e.recentLaunches||[]).map(ye=>ye.workspace),[e]),ve=l.useCallback(async ye=>{v(!0),N("");try{const Oe=await o(ye);k(Oe.path),p(Oe.path),j(Oe.directories)}catch(Oe){N(Oe instanceof Error?Oe.message:"Could not load folder")}finally{v(!1)}},[o]),ce=l.useCallback(()=>{var Oe;x("__custom__"),A(!0);const ye=tl(e.platform,el(w.trim(),_,te,e.defaultWorkspacePath,(Oe=d.find(ut=>ut.id===m))==null?void 0:Oe.path,d.map(ut=>ut.path)));ve(ye)},[w,m,ve,te,_,e.platform,d]),H=l.useCallback(ye=>{if(ye!=null&&ye.workspaceId){x(ye.workspaceId),p("");return}if(ye!=null&&ye.workspacePath){x("__custom__"),p(ye.workspacePath);return}x(""),p("")},[]),fe=l.useCallback(ye=>{if(x(ye),ye==="__custom__"){ce();return}p("")},[ce]),je=l.useCallback(ye=>{x("__custom__"),p(ye)},[]),Ce=l.useCallback((ye,Oe)=>{L.current=Oe,K.current=ye.selectedWorkspaceKey||"__home__",R(ye.selectedWorkspaceKey||"__home__"),E(ye.initialArgs||""),$(ye.initialModel||""),U(""),ae([]);const ut=ye.providerType?`${e.id}:${ye.providerType}`:null;if(z0(q.current,ut)){const at=Ft();X(at.textQuery),re(at.workspaceQuery),oe(at.modelQuery),ie(at.resumableOnly),xe(at.sortMode)}q.current=ut,B(ye),ye.providerType&&a&&(pe(!0),a(ye.providerType).then(at=>ae(at||[])).catch(at=>console.warn("Failed to load saved sessions",at)).finally(()=>pe(!1)))},[a,e.id]),Be=l.useMemo(()=>hh(Y,{textQuery:z,workspaceQuery:de,modelQuery:W,resumableOnly:V,sortMode:ke}),[W,V,Y,ke,z,de]);l.useEffect(()=>{D&&(Be.some(ye=>ye.providerSessionId===D)||U(""))},[Be,D]);const Xe=l.useCallback(()=>{L.current&&(O(!0),L.current().finally(()=>{L.current=null,O(!1),B(null)}))},[]),dt=l.useCallback(()=>{L.current=null,B(null)},[]),it=l.useCallback(ye=>{K.current=ye,R(ye)},[]);return l.useEffect(()=>{var ye;Z.current!==e.id&&(Z.current=e.id,x(m||((ye=d[0])==null?void 0:ye.id)||"__custom__"),p(""),k(""),j([]),N(""),A(!1),X(Ft().textQuery),re(Ft().workspaceQuery),oe(Ft().modelQuery),ie(Ft().resumableOnly),xe(Ft().sortMode),q.current=null,M(ba(h,t.length,n.length)))},[n.length,t.length,m,h,e.id,d]),l.useEffect(()=>{var ye;f!=="__custom__"&&(f&&d.some(Oe=>Oe.id===f)||x(m||((ye=d[0])==null?void 0:ye.id)||"__custom__"))},[m,f,d]),l.useEffect(()=>{T==="ide"&&h||T==="cli"&&t.length>0||T==="acp"&&n.length>0||M(ba(h,t.length,n.length))},[T,n.length,t.length,h]),{showAllRecent:c,setShowAllRecent:u,hasIdeOptions:h,workspaceRows:d,defaultWorkspaceId:m,workspaceChoice:f,customWorkspacePath:w,browseCurrentPath:y,browseDirectories:b,browseBusy:S,browseError:g,browseDialogOpen:C,activeLauncherKind:T,launchConfirm:P,launchConfirmWorkspaceKeyRef:K,launchConfirmWorkspaceKey:F,launchConfirmArgs:Q,launchConfirmModel:I,launchConfirmResumeId:D,launchConfirmSavedSessions:Y,launchConfirmTextFilter:z,launchConfirmWorkspaceFilter:de,launchConfirmModelFilter:W,launchConfirmResumableOnly:V,launchConfirmSortMode:ke,filteredLaunchConfirmSavedSessions:Be,launchConfirmSessionsLoading:Se,launchConfirmBusy:G,resolvedWorkspacePath:me,canCreateMissingWorkspace:Te,openBrowseDialog:ce,loadBrowsePath:ve,handleWorkspaceChoiceChange:fe,chooseCustomWorkspacePath:je,setCustomWorkspacePath:p,setBrowseDialogOpen:A,setActiveLauncherKind:M,openLaunchConfirm:Ce,handleConfirmLaunch:Xe,closeLaunchConfirm:dt,setWorkspaceSelectionFromOption:H,setLaunchConfirmWorkspaceKeyAndSync:it,setLaunchConfirmArgs:E,setLaunchConfirmModel:$,setLaunchConfirmResumeId:U,setLaunchConfirmTextFilter:X,setLaunchConfirmWorkspaceFilter:re,setLaunchConfirmModelFilter:oe,setLaunchConfirmResumableOnly:ie,setLaunchConfirmSortMode:xe}}function BC({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:n,cliProviders:r,acpProviders:o,selectedMachineNeedsUpgrade:a,appVersion:i,machineAction:c,isStandalone:u,section:h,showBottomNav:d,onBack:m,onSectionChange:f,onOpenConversation:x,onOpenRecent:w,onOpenMachineDetails:p,onMachineUpgrade:y,onLaunchDetectedIde:k,onAddWorkspace:b,onBrowseDirectory:j,onLaunchWorkspaceProvider:S,onListSavedSessions:v}){const{t:g}=Le("common"),N=R=>R==="ide"?"IDE":R==="cli"?"CLI":"ACP",C=n.slice(0,4),A=t.slice(0,3),T=$C({selectedMachineEntry:e,cliProviders:r,acpProviders:o,machineAction:c,onBrowseDirectory:j,onListSavedSessions:v}),M=l.useMemo(()=>C.map(R=>{const{metaText:Q,updatedLabel:E}=ep(R);return{key:`recent-launch:${R.id}`,primary:R.label,secondary:Q,updatedLabel:E,onClick:()=>{const{options:I,selectedKey:$}=Zh({machine:{workspaces:T.workspaceRows,defaultWorkspaceId:T.defaultWorkspaceId},currentWorkspacePath:R.workspace});T.openLaunchConfirm({title:R.kind==="ide"?uo(g,"restart-ide",R.label):R.providerSessionId?mh(g,R.label):uo(g,"start-fresh",R.label),description:R.kind==="ide"?ho(g,"restart-ide"):R.providerSessionId?fh(g):ho(g,"start-fresh"),confirmLabel:R.kind==="ide"?po(g,"restart-ide"):R.providerSessionId?oi(g,!0):po(g,"start-fresh"),busyLabel:R.kind==="ide"?mo(g,"restart-ide"):R.providerSessionId?ph(g,!0):mo(g,"start-fresh"),workspaceOptions:I,selectedWorkspaceKey:$,details:[{label:"Mode",value:N(R.kind)},...R.providerType?[{label:"Provider",value:R.providerType}]:[]]},async()=>{const D=I.find(U=>U.key===T.launchConfirmWorkspaceKeyRef.current);T.setWorkspaceSelectionFromOption(D),await w({...R,workspace:(D==null?void 0:D.workspacePath)??null})})}}}),[T,w,C,g]),L=l.useMemo(()=>A.map(R=>({key:`recent-chat:${R.conversation.tabKey}`,primary:xt(R.conversation),secondary:w0(R.conversation,{timestampLabel:R.timestamp?du(R.timestamp):null}),unread:R.unread,onClick:()=>x(R.conversation)})),[x,A]),P=T.showAllRecent?M:M.slice(0,4),B=M.length>0,K=L.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(ji,{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:[K&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Current Chats"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:L.map(R=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${R.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:R.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:R.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:R.secondary})]},R.key))})]}),B&&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:P.map(R=>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:R.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:R.primary}),R.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:R.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:R.secondary})]},R.key))}),M.length>4&&s.jsx("div",{className:"flex justify-center px-4 pt-2",children:s.jsx("button",{type:"button",className:"min-h-[34px] px-3.5 rounded-full border border-border-default/80 bg-surface-primary/90 text-text-secondary text-xs font-bold",onClick:()=>T.setShowAllRecent(R=>!R),children:T.showAllRecent?"Show fewer":`Show ${M.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:[a&&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:y,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:p,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),T.browseDialogOpen&&s.jsx(rl,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:T.browseCurrentPath,directories:T.browseDirectories,busy:T.browseBusy,error:T.browseError,confirmLabel:"Use this folder",onClose:()=>T.setBrowseDialogOpen(!1),onNavigate:R=>{T.loadBrowsePath(R)},onConfirm:R=>{T.chooseCustomWorkspacePath(R),T.setBrowseDialogOpen(!1)}}),T.launchConfirm&&s.jsx(Xh,{title:T.launchConfirm.title,description:T.launchConfirm.description,details:T.launchConfirm.details,workspaceOptions:T.launchConfirm.workspaceOptions,selectedWorkspaceKey:T.launchConfirmWorkspaceKey,onWorkspaceChange:T.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:T.launchConfirm.providerType?oi(g,!!T.launchConfirmResumeId):T.launchConfirm.confirmLabel,busyLabel:T.launchConfirm.providerType?void 0:T.launchConfirm.busyLabel,busy:T.launchConfirmBusy,showArgsInput:T.launchConfirm.showArgsInput,argsValue:T.launchConfirmArgs,onArgsChange:T.setLaunchConfirmArgs,showModelInput:T.launchConfirm.showModelInput,modelValue:T.launchConfirmModel,onModelChange:T.setLaunchConfirmModel,historyProviderNode:T.launchConfirm.providerType&&(T.launchConfirmSessionsLoading||T.launchConfirmSavedSessions.length>0)&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsxs("div",{className:"flex items-center justify-between mb-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Resume saved history"}),T.launchConfirmSessionsLoading&&s.jsx("div",{className:"text-[10px] text-text-secondary font-medium",children:"Loading..."})]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2",children:zi(g)}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:T.launchConfirmTextFilter,onChange:R=>T.setLaunchConfirmTextFilter(R.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:T.launchConfirmWorkspaceFilter,onChange:R=>T.setLaunchConfirmWorkspaceFilter(R.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:T.launchConfirmModelFilter,onChange:R=>T.setLaunchConfirmModelFilter(R.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),s.jsxs("select",{value:T.launchConfirmSortMode,onChange:R=>T.setLaunchConfirmSortMode(R.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"recent",children:"Most recent"}),s.jsx("option",{value:"oldest",children:"Oldest first"}),s.jsx("option",{value:"messages",children:"Most messages"})]})]}),s.jsxs("label",{className:"mb-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:T.launchConfirmResumableOnly,onChange:R=>T.setLaunchConfirmResumableOnly(R.target.checked),disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:T.launchConfirmResumeId,onChange:R=>T.setLaunchConfirmResumeId(R.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:T.launchConfirmBusy||T.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:Y0(g)}),T.filteredLaunchConfirmSavedSessions.map(R=>s.jsxs("option",{value:R.providerSessionId,disabled:!R.canResume,children:[R.title||R.providerSessionId," ",R.canResume?"":"(workspace missing)"]},R.providerSessionId))]}),!T.launchConfirmSessionsLoading&&T.launchConfirmSavedSessions.length>0&&T.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),T.launchConfirmResumeId&&(()=>{const R=T.filteredLaunchConfirmSavedSessions.find(E=>E.providerSessionId===T.launchConfirmResumeId);if(!R)return null;const Q=Qh(R);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:Q.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:Q.providerSessionId}),s.jsx("div",{className:"mt-1",children:Q.metaLine}),Q.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:Q.updatedLabel}),Q.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:Q.preview})]})})()]}),onConfirm:T.handleConfirmLaunch,onCancel:T.closeLaunchConfirm}),d&&s.jsx(Jh,{section:h,onSectionChange:f})]})}const Wc=8e3;function FC(e){const t=e&&typeof e=="object"&&"result"in e?e.result:e,n=t&&typeof t=="object",r=n&&t.success===!1,o=n&&t.mirrorStale===!0;return!r&&!o?{confirmed:!0}:{confirmed:!1,reason:r&&typeof t.error=="string"?t.error:o?"the coordinator did not confirm the change":"command was rejected"}}function tp(e,t,n){const r=l.useRef(new Map),[,o]=l.useState(0),a=l.useCallback(()=>o(x=>x+1),[]);l.useEffect(()=>{const x=r.current;if(x.size===0)return;const w=Date.now();let p=!1;for(const[y,k]of x){const b=e.get(y),j=k.muted===void 0||(b?b.muted===k.muted:!1),S=k.hidden===void 0||(b?b.surfaceHidden===k.hidden:!1),v=w-k.at>Wc;(j&&S||v)&&(x.delete(y),p=!0)}p&&a()},[e,a]),l.useEffect(()=>{if(r.current.size===0)return;const x=setInterval(()=>{const w=r.current,p=Date.now();let y=!1;for(const[k,b]of w)p-b.at>Wc&&(w.delete(k),y=!0);y&&a(),w.size===0&&clearInterval(x)},1e3);return()=>clearInterval(x)});const i=l.useCallback((x,w)=>{const p=r.current.get(x);r.current.set(x,{...p,...w,at:Date.now()}),a()},[a]),c=l.useCallback(x=>{const w=x.sessionId,p=w?r.current.get(w):void 0;return(p==null?void 0:p.muted)!==void 0?p.muted:Ds(x,e).muted},[e]),u=l.useCallback(x=>{const w=x.sessionId,p=w?r.current.get(w):void 0;return(p==null?void 0:p.hidden)!==void 0?p.hidden:Ds(x,e).surfaceHidden},[e]),h=l.useCallback((x,w)=>{const p=Ps(x),y=x.sessionId;!p||!y||(i(y,w),t(p,"set_conversation_prefs",{sessionId:y,...w,...Do(x)}).then(k=>{const b=FC(k);b.confirmed||(console.warn("[conversation-prefs] set_conversation_prefs not confirmed",b.reason),r.current.delete(y),a(),n==null||n(`Couldn't update conversation — ${b.reason}`))}).catch(k=>{console.warn("[conversation-prefs] set_conversation_prefs failed",k),r.current.delete(y),a();const b=k instanceof Error?k.message:String(k??"the daemon is unreachable");n==null||n(`Couldn't update conversation — ${b}`)}))},[t,i,a,n]),d=l.useCallback(x=>{h(x,{muted:!c(x)})},[h,c]),m=l.useCallback((x,w)=>{h(x,{hidden:w})},[h]),f=l.useCallback(x=>{h(x,{hidden:!u(x)})},[h,u]);return{isMuted:c,isHidden:u,toggleMute:d,setHidden:m,toggleHidden:f}}function Yr(e){return[...e].sort((t,n)=>{const r=n.timestamp-t.timestamp;return r!==0?r:t.conversation.tabKey.localeCompare(n.conversation.tabKey)})}function HC(e,t=[]){const n=new Map(e.map(o=>[o.conversation.tabKey,o])),r=t.map(o=>n.get(o)).filter(o=>!!o);return r.length===e.length?r:Yr(e)}function WC(e){var r,o,a;const t=((r=e.p2p)==null?void 0:r.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":!(!!((o=e.p2p)!=null&&o.available)||!!((a=e.p2p)!=null&&a.state))&&e.status&&e.status!=="offline"?"Connected":"Offline"}function OC(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 o=ir(r)?"cli":pn(r)?"acp":"ide",a=Js(r.summaryMetadata);return{id:`${o}:${r.type}:${r.workspace||""}`,label:((i=r.activeChat)==null?void 0:i.title)||(ir(r)?r.cliName||r.type:pn(r)&&r.cliName||r.type),kind:o,providerType:r.type,providerSessionId:r.providerSessionId,subtitle:pn(r)?a||r.workspace||void 0:r.workspace||void 0,workspace:r.workspace||void 0,timestamp:r.lastMessageAt||0}}).sort((r,o)=>o.timestamp-r.timestamp).map(({timestamp:r,...o})=>o)}function UC(e,t){const n=new Map;for(const r of t){const o=Ps(r.conversation),a=n.get(o);a?a.push(r):n.set(o,[r])}return e.map(r=>{const o=n.get(r.id)||[],a=[...o].sort((m,f)=>f.timestamp-m.timestamp)[0]||null,i=(a==null?void 0:a.conversation)||null,c=Xa(r),u=o.filter(m=>m.unread||m.requiresAction).length,h=WC(r),d=[r.platform||"machine",h].filter(Boolean);return{id:r.id,label:ts(r,{fallbackId:r.id}),subtitle:d.join(" · "),unread:u,total:o.length,latestConversation:i,latestTimestamp:(a==null?void 0:a.timestamp)||0,fallbackActivityAt:c,preview:i?k0(i,Zu(i)):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((r,o)=>{const a=r.latestTimestamp||r.fallbackActivityAt||0,i=o.latestTimestamp||o.fallbackActivityAt||0;return i!==a?i-a:r.label.localeCompare(o.label)})}function GC(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 KC({conversations:e,machineEntries:t,items:n,selectedConversation:r,selectedTabKey:o,screen:a,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:u,onRequestedActiveTabConsumed:h,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:x,setSelectedTabKey:w,setScreen:p,setSelectedMachineId:y,setSection:k,setMachineBackTarget:b,resetMachineAction:j}){const S=l.useRef(null),v=l.useCallback(g=>{if(!(g!=null&&g.sessionId))return;const N=Ds(g,i),C=Math.max(Date.now(),qs(g),N.lastUpdated||0);Rr("mark_read:start",{tabKey:g.tabKey,sessionId:g.sessionId,displayPrimary:xt(g),inboxBucket:N.inboxBucket,unread:N.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:qs(g),readAt:C}),c(Ps(g)||g.routeId,"mark_session_seen",{sessionId:g.sessionId,providerSessionId:g.providerSessionId,seenAt:C,completionMarker:N.completionMarker}).then(A=>{Rr("mark_read:result",{tabKey:g.tabKey,sessionId:g.sessionId,result:A})}).catch(A=>{Rr("mark_read:error",{tabKey:g.tabKey,sessionId:g.sessionId,error:A instanceof Error?A.message:String(A)})})},[i,c]);return l.useEffect(()=>{var N;if(!r){GC(a)&&p("inbox"),w(((N=e[0])==null?void 0:N.tabKey)||null),S.current=null;return}if(a!=="chat"){S.current=null;return}const g=`${r.tabKey}:${r.sessionId||""}`;S.current!==g&&(S.current=g,v(r))},[e,v,a,r,p,w]),l.useEffect(()=>{if(!u)return;const g=e.find(N=>N.tabKey===u);g&&(w(g.tabKey),p("chat"),h==null||h())},[e,h,u,p,w]),l.useEffect(()=>{if(!d)return;const g=t.find(N=>N.id===d);g&&(y(g.id),j(),k("machines"),b("inbox"),p("machine"),m==null||m())},[t,m,d,j,b,p,k,y]),l.useEffect(()=>{f&&(k(f),p("inbox"),x==null||x())},[x,f,p,k]),l.useEffect(()=>{const g=n.filter(N=>N.inboxBucket==="task_complete"||N.unread);g.length!==0&&Rr("inbox_state",{screen:a,selectedTabKey:o,items:g.map(N=>{const C=Ds(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:qs(N.conversation)}})})},[n,i,a,o]),{markConversationRead:v}}function zC(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Oc(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function qC(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function VC({sendDaemonCommand:e,navigate:t,ides:n,conversations:r}){const{launchCli:o}=ko(),[a,i]=l.useState("idle"),[c,u]=l.useState(""),[h,d]=l.useState(null),m=l.useCallback(()=>{i("idle"),u(""),d(null)},[]),f=l.useCallback(async(j,S,v)=>{var g;try{i("loading"),u(`Launching ${S}…`);const N={ideType:S,enableCdp:!0};(g=v==null?void 0:v.workspacePath)!=null&&g.trim()&&(N.workspace=v.workspacePath.trim()),await e(j,"launch_ide",N),i("done"),u(`${S} launch requested`)}catch(N){i("error"),u(N instanceof Error?N.message:"Launch IDE failed"),console.error("Launch IDE failed",N)}},[e]),x=l.useCallback(async(j,S,v)=>{if(S.trim())try{i("loading"),u(v!=null&&v.createIfMissing?"Creating folder…":"Saving workspace…");const g=await e(j,"workspace_add",{path:S.trim(),createIfMissing:(v==null?void 0:v.createIfMissing)===!0});if(g!=null&&g.success){i("done"),u(v!=null&&v.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),u((g==null?void 0:g.error)||"Could not save workspace")}catch(g){i("error"),u(g instanceof Error?g.message:"Could not save workspace")}},[e]),w=l.useCallback(async j=>{var S,v,g,N,C,A;try{i("loading"),u("Starting daemon upgrade…");const T=await e(j,"daemon_upgrade",{});if((S=T==null?void 0:T.result)!=null&&S.alreadyLatest){i("done"),u(`Already on v${((v=T==null?void 0:T.result)==null?void 0:v.version)||"latest"}.`);return}if((g=T==null?void 0:T.result)!=null&&g.upgraded||(N=T==null?void 0:T.result)!=null&&N.success){i("done"),u(`Upgrade to v${((C=T==null?void 0:T.result)==null?void 0:C.version)||"latest"} started. Daemon is restarting…`);return}i("error"),u(((A=T==null?void 0:T.result)==null?void 0:A.error)||"Upgrade failed")}catch(T){i("error"),u(T instanceof Error?T.message:"Upgrade failed")}},[e]),p=l.useCallback(async(j,S,v,g)=>{var A,T,M;const N=Date.now(),C={machineId:j,kind:S,providerType:v,workspaceId:(g==null?void 0:g.workspaceId)||null,workspacePath:(g==null?void 0:g.workspacePath)||null,resumeSessionId:(g==null?void 0:g.resumeSessionId)||null,startedAt:N};try{i("loading"),u(`Launching ${v}…`),d(C);const L={cliType:v};(A=g==null?void 0:g.workspacePath)!=null&&A.trim()?L.dir=g.workspacePath.trim():g!=null&&g.workspaceId&&(L.workspaceId=g.workspaceId),g!=null&&g.resumeSessionId&&(L.resumeSessionId=g.resumeSessionId),(T=g==null?void 0:g.args)!=null&&T.trim()&&(L.cliArgs=g.args.trim().split(/\s+/).filter(Boolean)),(M=g==null?void 0:g.model)!=null&&M.trim()&&(L.initialModel=g.model.trim());const P=await o(j,L),B=(P==null?void 0:P.result)||P,K=(B==null?void 0:B.sessionId)||(B==null?void 0:B.id);if(P!=null&&P.success&&K){d(null),i("done"),u(`${v} launched`),t(dr(K));return}if(P!=null&&P.success){i("loading"),u(`${v} launch requested — waiting for session…`);return}d(null),i("error"),u((P==null?void 0:P.error)||(B==null?void 0:B.error)||`Could not launch ${S.toUpperCase()} workspace`)}catch(L){if(qC(L)){i("loading"),u(`${v} launch requested — waiting for session…`);return}d(null),i("error"),u(L instanceof Error?L.message:`Could not launch ${S.toUpperCase()} workspace`)}},[t,e]),y=l.useCallback(async(j,S)=>{try{const v=await e(j,"list_saved_sessions",{providerType:S,kind:"cli",limit:30}),g=(v==null?void 0:v.result)??v;return Array.isArray(g==null?void 0:g.sessions)?g.sessions:[]}catch(v){return console.error("Failed to list saved sessions on mobile:",v),[]}},[e]),k=l.useCallback(async(j,S)=>sl(e,j,S),[e]);l.useEffect(()=>{if(!h)return;const j=Oc(h.workspacePath),S=n.find(g=>{var L,P,B,K;if(!g||g.type==="adhdev-daemon"||zC(g.daemonId||g.id)!==h.machineId||(g.transport==="acp"?"acp":g.transport==="pty"?"cli":null)!==h.kind||String(g.agentType||g.type||"")!==h.providerType)return!1;const T=String(g.providerSessionId||"");if(h.resumeSessionId&&T)return T===h.resumeSessionId;if(j){const F=Oc(g.workspace||g.runtimeWorkspaceLabel);return F?F===j:!1}return Number(g.lastUpdated||g._lastUpdate||g.timestamp||((K=(B=(P=(L=g.activeChat)==null?void 0:L.messages)==null?void 0:P.at)==null?void 0:B.call(P,-1))==null?void 0:K.timestamp)||0)>=h.startedAt-5e3});if(!S)return;const v=qh({entrySessionId:S.sessionId,entryInstanceId:S.instanceId,entryRouteId:S.id,conversations:r});v&&(d(null),i("done"),u(`${h.providerType} launched`),t(dr(v)))},[r,n,t,h]),l.useEffect(()=>{if(!h)return;const j=window.setTimeout(()=>{d(S=>!S||S.startedAt!==h.startedAt?S:(i("error"),u("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(j)},[h]);const b=l.useCallback(async(j,S)=>{if(S.kind==="ide"&&S.providerType){await f(j,S.providerType,{workspacePath:S.workspace||null});return}(S.kind==="cli"||S.kind==="acp")&&S.providerType&&await p(j,S.kind,S.providerType,{workspacePath:S.workspace||null,resumeSessionId:S.providerSessionId||null})},[f,p]);return{machineAction:{state:a,message:c},resetMachineAction:m,handleLaunchDetectedIde:f,handleAddWorkspace:x,handleMachineUpgrade:w,handleLaunchWorkspaceProvider:p,handleListSavedSessions:y,handleBrowseDirectory:k,handleOpenRecent:b}}function YC({conversations:e,selectedConversation:t,machineBackTarget:n,markConversationRead:r,resetMachineAction:o,setSelectedTabKey:a,setScreen:i,setSelectedMachineId:c,setSection:u,setMachineBackTarget:h}){const d=l.useCallback(k=>{a(k.tabKey),i("chat"),r(k)},[r,i,a]),m=l.useCallback(k=>{const b=e.find(j=>j.routeId===k.routeId&&j.streamSource==="native");b&&(a(b.tabKey),i("chat"),r(b))},[e,r,i,a]),f=l.useCallback(()=>{r(t),i("inbox")},[r,t,i]),x=l.useCallback((k,b="inbox")=>{c(k),o(),u("machines"),h(b),i("machine")},[o,h,i,u,c]),w=l.useCallback(k=>{const b=Ps(k);b&&x(b,"chat")},[x]),p=l.useCallback(()=>{o(),i(n)},[n,o,i]),y=l.useCallback(k=>{u(k),i("inbox")},[i,u]);return{openConversation:d,openNativeConversation:m,backFromConversation:f,openMachine:x,openConversationMachine:w,backFromMachine:p,changeMachineSection:y}}function Sn(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function JC(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function QC({conversations:e,hiddenConversations:t,ides:n,actionLogs:r,sendDaemonCommand:o,setActionLogs:a,isStandalone:i,userName:c,requestedActiveTabKey:u,onRequestedActiveTabConsumed:h,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:x,onOpenHistory:w,onOpenRemote:p,onStopCli:y,wsStatus:k,isConnected:b,onShowAllHiddenConversations:j,onHideConversation:S,onOpenMeshGraph:v,onOpenNewSession:g,liveSessionInboxState:N,setCliViewModeOverrides:C}){const[A,T]=l.useState(()=>{var H;return((H=e[0])==null?void 0:H.tabKey)||null}),[M,L]=l.useState(()=>e[0]?"chat":"inbox"),[P,B]=l.useState("chats"),[K,F]=l.useState(null),[R,Q]=l.useState("inbox"),E=l.useRef([]),I=pr(),$="0.9.82",D=l.useMemo(()=>e.find(H=>H.tabKey===A)||e[0]||null,[e,A]),U=l.useMemo(()=>D?n.find(H=>H.id===D.routeId):void 0,[n,D]),Y=l.useMemo(()=>!D||lt(D)||!ct(D)?null:Tn(D),[D]),ae=l.useMemo(()=>n.filter(H=>H.type==="adhdev-daemon").sort(Ei),[n]),z=l.useMemo(()=>ae.find(H=>H.id===K)||null,[ae,K]),X=Po({sendDaemonCommand:o,activeConv:D||void 0,setActionLogs:a,isStandalone:i}),de=VC({sendDaemonCommand:o,navigate:I,ides:n,conversations:e}),re=Qw(e),W=l.useMemo(()=>e.map(H=>{const fe=M==="chat"&&(D==null?void 0:D.tabKey)===H.tabKey,je=No(H,N,{hideOpenTaskCompleteUnread:!0,isOpenConversation:fe}),Ce=qs(H),Be=Zu(H),Xe=ah(H,Be);return{conversation:H,timestamp:Ce,preview:Xe,unread:je.unread,requiresAction:je.requiresAction,isWorking:je.isWorking,inboxBucket:je.inboxBucket}}),[e,N,M,D,re]),{markConversationRead:oe}=KC({conversations:e,machineEntries:ae,items:W,selectedConversation:D,selectedTabKey:A,screen:M,liveSessionInboxState:N,sendDaemonCommand:o,requestedActiveTabKey:u,onRequestedActiveTabConsumed:h,requestedMachineId:d,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:x,setSelectedTabKey:T,setScreen:L,setSelectedMachineId:F,setSection:B,setMachineBackTarget:Q,resetMachineAction:de.resetMachineAction}),V=YC({conversations:e,selectedConversation:D,machineBackTarget:R,markConversationRead:oe,resetMachineAction:de.resetMachineAction,setSelectedTabKey:T,setScreen:L,setSelectedMachineId:F,setSection:B,setMachineBackTarget:Q}),{isMuted:ie,toggleMute:ke}=tp(N,o),xe=l.useMemo(()=>Yr(W.filter(H=>H.requiresAction&&!ie(H.conversation))),[W,ie]),Se=l.useMemo(()=>Yr(W.filter(H=>H.unread&&!H.requiresAction&&!ie(H.conversation))),[W,ie]),pe=l.useMemo(()=>HC(W.filter(H=>!H.unread&&!H.requiresAction&&H.isWorking),E.current),[W]);l.useEffect(()=>{E.current=pe.map(H=>H.conversation.tabKey)},[pe]);const G=l.useMemo(()=>Yr(W.filter(H=>!H.unread&&!H.requiresAction&&!H.isWorking)),[W]),O=l.useMemo(()=>z?W.filter(H=>Ps(H.conversation)===z.id):[],[W,z]),Z=l.useMemo(()=>OC(z,n),[n,z]),q=(z==null?void 0:z.version)||null,me=!!z&&!!q&&!0&&q!==$,Te=l.useMemo(()=>(z==null?void 0:z.availableProviders)||[],[z]),_=l.useMemo(()=>Te.filter(H=>Sn(H,"cli")).map(H=>({type:H.type,displayName:H.displayName||H.type,icon:H.icon})),[Te]),te=l.useMemo(()=>Te.filter(H=>Sn(H,"acp")).map(H=>({type:H.type,displayName:H.displayName||H.type,icon:H.icon})),[Te]),ve=l.useMemo(()=>UC(ae,W),[W,ae]),ce=l.useCallback(async H=>{z&&await de.handleOpenRecent(z.id,H)},[de,z]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:M==="chat"&&D?s.jsx(IC,{selectedConversation:D,isAcp:lt(D),isStandalone:i,selectedIdeEntry:U,actionLogs:r,userName:c,isSendingChat:X.isSendingChat,sendFeedbackMessage:X.sendFeedbackMessage,isFocusingAgent:X.isFocusingAgent,handleModalButton:X.handleModalButton,handleRelaunch:X.handleRelaunch,onBack:V.backFromConversation,onOpenNativeConversation:V.openNativeConversation,onOpenMachine:V.openConversationMachine,onOpenHistory:w,onOpenRemote:p,onOpenMeshGraph:v,onStopCli:y,cliViewMode:Y,onSetCliViewMode:async H=>{await Eh({conversation:D,mode:H,ides:n,sendDaemonCommand:o,setCliViewModeOverrides:C})},handleSendChat:X.handleSendChat,handleForceSendChat:X.handleForceSendChat,handleFocusAgent:X.handleFocusAgent}):M==="machine"&&z?s.jsx(BC,{selectedMachineEntry:z,selectedMachineConversations:O,selectedMachineRecentLaunches:Z,cliProviders:_,acpProviders:te,selectedMachineNeedsUpgrade:me,appVersion:$,machineAction:de.machineAction,isStandalone:i,section:P,showBottomNav:R==="inbox",onBack:V.backFromMachine,onSectionChange:V.changeMachineSection,onOpenConversation:V.openConversation,onOpenRecent:ce,onOpenMachineDetails:()=>I(`/machines/${z.id}`),onMachineUpgrade:()=>de.handleMachineUpgrade(z.id),onLaunchDetectedIde:(H,fe)=>de.handleLaunchDetectedIde(z.id,H,fe),onAddWorkspace:(H,fe)=>de.handleAddWorkspace(z.id,H,fe),onBrowseDirectory:H=>de.handleBrowseDirectory(z.id,H),onLaunchWorkspaceProvider:(H,fe,je)=>de.handleLaunchWorkspaceProvider(z.id,H,fe,je),onListSavedSessions:H=>de.handleListSavedSessions(z.id,H)}):s.jsx(PC,{section:P,attentionItems:xe,unreadItems:Se,workingItems:pe,completedItems:G,hiddenConversations:t,machineCards:ve,getAvatarText:JC,actionLogs:r,sendDaemonCommand:o,onOpenConversation:V.openConversation,onShowAllHidden:j,onHideConversation:S,onOpenMeshGraph:v,onStopCli:y,onOpenNewSession:g,onOpenMachine:V.openMachine,onOpenSettings:()=>I("/settings"),onSectionChange:B,wsStatus:k,isConnected:b,isStandalone:i,isConversationMuted:ie,onToggleMuteConversation:ke})})}function ga(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function XC({conversations:e,numGroups:t,onMoveTab:n,onReceiveTab:r,onOwnTabDrop:o,onClearPreviewOrder:a}){const i=l.useRef(0),[c,u]=l.useState(!1),[h,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(y=>{y.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,u(!0))},[]),x=l.useCallback(y=>{if(!y.dataTransfer.types.includes("text/tab-key"))return;if(y.preventDefault(),!ga(t,n)){d("merge");return}const k=y.currentTarget.getBoundingClientRect(),b=y.clientX-k.left,j=k.width/3;b<j?d("split-left"):b>j*2?d("split-right"):d("merge")},[t,n]),w=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,u(!1),d(null))},[]),p=l.useCallback(y=>{i.current=0,u(!1);const k=y.dataTransfer.getData("text/tab-key"),b=k?e.some(S=>S.tabKey===k):!1,j=h;if(d(null),a(),!!k){if(y.preventDefault(),j==="split-left"&&ga(t,n)){n==null||n(k,"split-left");return}if(j==="split-right"&&ga(t,n)){n==null||n(k,"split-right");return}if(b){o(k);return}r==null||r(k)}},[e,h,t,n,r,o,a]);return{dragOver:c,dropAction:h,resetDragState:m,handleDragEnter:f,handleDragOver:x,handleDragLeave:w,handleDrop:p}}function ZC(e,t){const n=new Set(t.map(a=>a.tabKey)),r=e.filter(a=>n.has(a)),o=t.filter(a=>!e.includes(a.tabKey)).map(a=>a.tabKey);return[...r,...o]}function e1({conversations:e,initialActiveTabId:t,initialTabOrder:n,onActiveTabChange:r,onTabOrderChange:o}){const[a,i]=l.useState(t??null),[c,u]=l.useState(n??[]),[h,d]=l.useState(null),m=l.useRef(null),f=l.useRef(null),x=l.useRef(r),w=l.useRef(o);l.useEffect(()=>{x.current=r},[r]),l.useEffect(()=>{w.current=o},[o]),l.useEffect(()=>{t&&t!==a&&i(t)},[t,a]),l.useEffect(()=>{u(N=>{const C=ZC(N,e);return C.length===N.length&&C.every((A,T)=>A===N[T])?N:C})},[e]);const p=l.useMemo(()=>{const N=h??c;if(N.length===0)return e;const C=new Map(N.map((A,T)=>[A,T]));return[...e].sort((A,T)=>{const M=C.get(A.tabKey)??999,L=C.get(T.tabKey)??999;return M-L})},[e,h,c]);l.useEffect(()=>{var C,A;if(p.length===0){a!==null&&(i(null),(C=x.current)==null||C.call(x,null));return}if(a&&p.some(T=>T.tabKey===a))return;const N=p[0].tabKey;N!==a&&(i(N),(A=x.current)==null||A.call(x,N))},[p,a]);const y=l.useMemo(()=>p.find(N=>N.tabKey===a),[p,a]),k=l.useCallback(N=>{var C;i(N),(C=x.current)==null||C.call(x,N)},[]),b=l.useCallback((N,C,A)=>{u(T=>{var B;const M=T.filter(K=>K!==N),L=M.indexOf(C);if(L<0)return T;const P=A==="left"?L:L+1;return M.splice(P,0,N),(B=w.current)==null||B.call(w,M),M}),d(null)},[]),j=l.useCallback((N,C,A)=>{const M=(c.length>0?c:e.map(B=>B.tabKey)).filter(B=>B!==N),L=M.indexOf(C);if(L<0)return;const P=A==="left"?L:L+1;M.splice(P,0,N),m.current=M,d(M)},[c,e]),S=l.useCallback(()=>{var C;const N=m.current;N&&(u(N),(C=w.current)==null||C.call(w,N))},[]),v=l.useCallback(()=>{m.current=null,d(null)},[]),g=l.useCallback(N=>{u(C=>{var T;const A=C.filter(M=>M!==N);return A.push(N),(T=w.current)==null||T.call(w,A),A})},[]);return{activeTabId:a,activeConv:y,sortedConversations:p,previewOrderRef:m,draggingTabRef:f,selectTab:k,handleTabReorder:b,updatePreviewOrder:j,commitPreviewOrder:S,clearPreviewOrder:v,moveTabToEnd:g,setDraggingTabKey:N=>{f.current=N}}}function t1({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 ol({conversationsCount:e,isSplitMode:t,isStandalone:n,hasRegisteredMachines:r=!1,suppressGuide:o=!1,onOpenNewSession:a}){const{t:i}=Le("common");if(o)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&&!!a,h=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:h}),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:a,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:i("paneGroup.newSession"),"aria-label":i("paneGroup.newSession"),children:[s.jsx(Mi,{size:14}),s.jsx("span",{children:i("paneGroup.newSession")})]})}),c&&s.jsx(Yh,{}),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 sp="adhdev-tab-shortcuts";function np(){try{return JSON.parse(localStorage.getItem(sp)||"{}")}catch{return{}}}function rp({enabled:e=!0,sortedTabKeys:t,onFocus:n,onSelectTab:r}){const o=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[a,i]=l.useState(()=>np()),[c,u]=l.useState(null),h=l.useCallback(m=>{const f=[];return m.metaKey&&f.push(o?"⌘":"Meta"),m.ctrlKey&&f.push("Ctrl"),m.altKey&&f.push(o?"⌥":"Alt"),m.shiftKey&&f.push(o?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(f.push(m.key.length===1?m.key.toUpperCase():m.key),f.join("+"))},[o]),d=l.useCallback(m=>{i(m);try{localStorage.setItem(sp,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 x=h(f);if(!x)return;const w={...a};for(const[p,y]of Object.entries(w))y===x&&delete w[p];w[c]=x,d(w),u(null)};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[e,c,a,d,h]),l.useEffect(()=>{if(!e)return;const m=f=>{if(!(!f.ctrlKey&&!f.metaKey&&!f.altKey)){for(const[x,w]of Object.entries(a))if(t.includes(x)&&h(f)===w){f.preventDefault(),n(),r(x);return}}};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[e,a,t,n,r,h]),{isMac:o,tabShortcuts:a,shortcutListening:c,setShortcutListening:u,saveShortcuts:d}}const xa=e=>{e.preventDefault()},s1=l.memo(function({conv:t,isActive:n,isDraggedTab:r,isTaskCompleteUnread:o,shortcut:a,conversationKeys:i,draggingTabRef:c,onFocus:u,onSelectTab:h,onConversationActivated:d,onPreviewReorder:m,onReorderTab:f,onCommitPreviewOrder:x,onClearPreviewOrder:w,onDragStateReset:p,onDragTabKeyChange:y,onReceiveTab:k,onOpenContextMenu:b,longPressTimer:j,isGroupActive:S}){const v=An(t),g=v.isGenerating?"agent-tab-generating":v.isWaiting?"agent-tab-waiting":"",N=v.isReconnecting,C=y0(t),A=v0(t),T=oh(t),M=l.useCallback(I=>{c.current=t.tabKey,y(t.tabKey),I.dataTransfer.setData("text/tab-key",t.tabKey),I.dataTransfer.effectAllowed="move"},[t.tabKey,c,y]),L=l.useCallback(()=>{c.current=null,y(null),x(),w(),p()},[c,y,x,w,p]),P=l.useCallback(I=>{const $=c.current;if(!(!$||$===t.tabKey)&&I.dataTransfer.types.includes("text/tab-key")){I.preventDefault(),I.stopPropagation();const D=I.currentTarget.getBoundingClientRect(),U=I.clientX<D.left+D.width/2?"left":"right";m($,t.tabKey,U)}},[t.tabKey,c,m]),B=l.useCallback(I=>{I.preventDefault(),I.stopPropagation();const $=I.dataTransfer.getData("text/tab-key");if($&&$!==t.tabKey){const D=I.currentTarget.getBoundingClientRect(),U=I.clientX<D.left+D.width/2?"left":"right";i.includes($)?f($,t.tabKey,U):k&&k($)}w()},[t.tabKey,i,f,k,w]),K=l.useCallback(I=>{I.stopPropagation(),u(),h(t.tabKey),d(t)},[t,d,u,h]),F=l.useCallback(I=>{I.preventDefault(),b(I.clientX,I.clientY,t.tabKey)},[t.tabKey,b]),R=l.useCallback(I=>{const $=I.touches[0];j.current=setTimeout(()=>{b($.clientX,$.clientY,t.tabKey)},600)},[t.tabKey,j,b]),Q=l.useCallback(()=>{j.current&&clearTimeout(j.current)},[j]),E=["adhdev-dockview-tab",g,n&&"is-active",S&&"is-group-active",N&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:E,draggable:!0,onDragStart:M,onDragEnd:L,onDragOver:P,onDrop:B,onClick:K,onContextMenu:F,onTouchStart:R,onTouchEnd:Q,onTouchMove:Q,style:{position:"relative",cursor:"pointer",opacity:r?.4:void 0},children:[T&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-badge pointer-events-none absolute top-0.5 right-0.5 text-text-muted",title:"Mesh chat","aria-label":"Mesh chat",children:s.jsx(es,{size:11})}),o&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:v.isGenerating?s.jsx("div",{className:"tab-spinner"}):v.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):N?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):v.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)}):v.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(co,{git:t.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),a&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${a}`,children:a})]})},(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 n1({conversations:e,activeTabId:t,groupIndex:n,unreadTabKeys:r,draggingTabRef:o,onFocus:a,onSelectTab:i,onConversationActivated:c,onPreviewReorder:u,onReorderTab:h,onCommitPreviewOrder:d,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:x,onReceiveTab:w,onHideTab:p,isGroupActive:y,allowTabShortcuts:k=!0}){const[b,j]=l.useState(null),S=l.useRef(null),v=l.useRef(null),g=l.useMemo(()=>e.map(P=>P.tabKey),[e]);mr("PaneGroupTabBar",{groupIndex:n,activeTabId:t,tabCount:e.length,ctxMenuTab:(b==null?void 0:b.tabKey)||null});const{isMac:N,tabShortcuts:C,shortcutListening:A,setShortcutListening:T,saveShortcuts:M}=rp({enabled:k,sortedTabKeys:e.map(P=>P.tabKey),onFocus:a,onSelectTab:i});l.useEffect(()=>{if(!b)return;const P=B=>{const K=document.querySelector("[data-pane-context-menu]");K&&K.contains(B.target)||j(null)};return window.addEventListener("mousedown",P,!0),()=>window.removeEventListener("mousedown",P,!0)},[b]),l.useEffect(()=>{const P=v.current;if(!P)return;const B=K=>{Math.abs(K.deltaY)<=Math.abs(K.deltaX)||(K.preventDefault(),P.scrollLeft+=K.deltaY)};return P.addEventListener("wheel",B,{passive:!1}),()=>P.removeEventListener("wheel",B)},[]);const L=l.useCallback((P,B,K)=>{j({x:P,y:B,tabKey:K})},[]);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(P=>s.jsx(s1,{conv:P,isActive:t===P.tabKey,isDraggedTab:o.current===P.tabKey,isTaskCompleteUnread:r.has(P.tabKey),shortcut:k?C[P.tabKey]:void 0,conversationKeys:g,draggingTabRef:o,onFocus:a,onSelectTab:i,onConversationActivated:c,onPreviewReorder:u,onReorderTab:h,onCommitPreviewOrder:d,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:x,onReceiveTab:w,onOpenContextMenu:L,longPressTimer:S,isGroupActive:y},P.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:"No tabs in this group"})]})}),b&&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:b.x,top:b.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:xa,onClick:P=>{P.stopPropagation(),T(b.tabKey),j(null)},children:["⌨ ",C[b.tabKey]?`Change shortcut (${C[b.tabKey]})`:"Set shortcut"]}),C[b.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:xa,onClick:()=>{const P={...C};delete P[b.tabKey],M(P),j(null)},children:"✕ Remove shortcut"})]}),p&&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:xa,onClick:()=>{p(b.tabKey),j(null)},children:"🚫 Hide from Dashboard"})]})]}),k&&A&&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:P=>P.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. ",N?"⌘+1":"Ctrl+1",", ",N?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})})]})}function r1({conversations:e,ides:t,clearedTabs:n,actionLogs:r,sendDaemonCommand:o,setActionLogs:a,isStandalone:i,hasRegisteredMachines:c,userName:u,groupIndex:h,onFocus:d,isSplitMode:m,numGroups:f,onMoveTab:x,onReceiveTab:w,style:p,onActiveTabChange:y,initialActiveTabId:k,initialTabOrder:b,onTabOrderChange:j,onHideTab:S,isFocused:v,allowTabShortcuts:g=!0,onOpenNewSession:N,liveSessionInboxState:C}){const{sendCommand:A}=yt(),T=l.useRef(null),{activeTabId:M,activeConv:L,sortedConversations:P,draggingTabRef:B,selectTab:K,handleTabReorder:F,updatePreviewOrder:R,commitPreviewOrder:Q,clearPreviewOrder:E,moveTabToEnd:I,setDraggingTabKey:$}=e1({conversations:e,initialActiveTabId:k,initialTabOrder:b,onActiveTabChange:y,onTabOrderChange:j}),D=Po({sendDaemonCommand:o,activeConv:L,setActionLogs:a,isStandalone:i}),{dragOver:U,dropAction:Y,resetDragState:ae,handleDragEnter:z,handleDragOver:X,handleDragLeave:de,handleDrop:re}=XC({conversations:e,numGroups:f,onMoveTab:x,onReceiveTab:w,onOwnTabDrop:I,onClearPreviewOrder:E}),W=L&&!lt(L)&&Tn(L)==="terminal",oe=l.useMemo(()=>L?t.find(xe=>xe.id===L.routeId):void 0,[t,L]),V=l.useMemo(()=>L?r.filter(xe=>xe.routeId===L.tabKey):[],[r,L]),ie=l.useMemo(()=>new Set(P.filter(xe=>Pb(xe,C,{isOpenConversation:xe.tabKey===M})).map(xe=>xe.tabKey)),[M,C,P]);mr("PaneGroup",{groupIndex:h,conversationCount:e.length,activeTabId:M,dragOver:U});const ke=l.useCallback(xe=>{xe.streamSource==="agent-stream"&&xe.agentType&&A(xe.routeId,Hu(),{agentType:xe.agentType,...xe.sessionId&&{targetSessionId:xe.sessionId}}).catch(()=>{})},[A]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:d,style:{...p,outline:U?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(n1,{conversations:P,activeTabId:M,groupIndex:h,numGroups:f,unreadTabKeys:ie,draggingTabRef:B,onFocus:d,onSelectTab:K,onConversationActivated:ke,onPreviewReorder:R,onReorderTab:F,onCommitPreviewOrder:Q,onClearPreviewOrder:E,onDragStateReset:ae,onDragTabKeyChange:$,onMoveTab:x,onReceiveTab:w,onHideTab:S,isGroupActive:v??!1,allowTabShortcuts:g}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:z,onDragOver:X,onDragLeave:de,onDrop:re,children:[U&&s.jsx(t1,{dropAction:Y,canSplit:!!(f<4&&x)}),L?s.jsx(nl,{activeConv:L,clearToken:n[L.tabKey]||0,isCliTerminal:!!W,ideEntry:oe,terminalRef:T,handleModalButton:D.handleModalButton,handleRelaunch:D.handleRelaunch,handleSendChat:D.handleSendChat,handleForceSendChat:D.handleForceSendChat,isSendingChat:D.isSendingChat,sendFeedbackMessage:D.sendFeedbackMessage,handleFocusAgent:D.handleFocusAgent,isFocusingAgent:D.isFocusingAgent,actionLogs:V,userName:u,isInputActive:!m||!!v}):s.jsx("div",{className:"flex-1 flex flex-col items-center justify-center",children:s.jsx(ol,{conversationsCount:e.length,isSplitMode:m,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:N})})]})]})}function o1({containerRef:e,isSplitMode:t,numGroups:n,groupSizes:r,groupedConvs:o,clearedTabs:a,ides:i,actionLogs:c,sendDaemonCommand:u,setActionLogs:h,isStandalone:d,hasRegisteredMachines:m,userName:f,focusedGroup:x,focusGroup:w,moveTabToGroup:p,splitTabRelative:y,closeGroup:k,handleResizeStart:b,groupActiveTabIds:j,setGroupActiveTab:S,groupTabOrders:v,setGroupTabOrder:g,toggleHiddenTab:N,onOpenNewSession:C,allowTabShortcuts:A=!0,liveSessionInboxState:T}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:o.map((M,L)=>{const P=t&&r.length===n?`${r[L]}%`:void 0;return s.jsxs(Rt.Fragment,{children:[t&&L>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=>b(L-1,B),onDoubleClick:()=>k(L),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(r1,{style:t?{flexBasis:P??`${100/n}%`,flexGrow:P?0:1,flexShrink:P?0:1}:void 0,conversations:M,clearedTabs:a,ides:i,actionLogs:c,sendDaemonCommand:u,setActionLogs:h,isStandalone:d,hasRegisteredMachines:m,userName:f,groupIndex:L,isFocused:t&&x===L,onFocus:()=>w(L),isSplitMode:t,numGroups:n,onMoveTab:(B,K)=>{K==="left"&&L>0?p(B,L-1):K==="right"&&L<n-1?p(B,L+1):K==="split-left"&&n<4?y(B,L,"left"):K==="split-right"&&n<4&&y(B,L,"right")},onReceiveTab:B=>p(B,L),onActiveTabChange:B=>S(L,B),initialActiveTabId:j[L],initialTabOrder:v[L],onTabOrderChange:B=>g(L,B),onHideTab:N,onOpenNewSession:C,allowTabShortcuts:A,liveSessionInboxState:T})]},L)})})}const op="adhdev-dashboard-action-shortcuts",a1=1200,i1=[["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 l1(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function mt(e,t){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return t?"⌘+⇧+Enter":"Ctrl+Shift+Enter";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+Ctrl+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return t?"⌘+Ctrl+⇧+↓":"Ctrl+Alt+Shift+↓";case"focusLeftPane":return"";case"focusRightPane":return"";case"focusUpPane":return"";case"focusDownPane":return"";case"moveActiveTabToLeftPane":return"";case"moveActiveTabToRightPane":return"";case"moveActiveTabToUpPane":return"";case"moveActiveTabToDownPane":return"";case"triggerPrimaryApprovalAction":return t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌘+⇧+←":"Ctrl+Shift+←";case"selectNextGroupTab":return t?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function ap(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:mt("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:mt("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:mt("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:mt("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:mt("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:mt("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:mt("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:mt("popoutActiveTab",e)},{id:"dockActiveTab",label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window.",defaultShortcut:mt("dockActiveTab",e)},{id:"splitActiveTabRight",label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it.",defaultShortcut:mt("splitActiveTabRight",e)},{id:"splitActiveTabDown",label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it.",defaultShortcut:mt("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:mt("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:mt("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:mt("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:mt("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:mt("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:mt("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:mt("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:mt("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:mt("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:mt("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:mt("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:mt("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:mt("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:mt("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:mt("toggleCliView",e)}]}function mi(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function yo(e){const t=Object.fromEntries(ap(e).map(n=>[n.id,n.defaultShortcut]));try{const n=JSON.parse(localStorage.getItem(op)||"{}"),r={...t,...n};for(const[o,a]of i1)r[o]===a&&(r[o]=t[o]);return r}catch{return t}}function ip(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function c1({enabled:e=!0,onTrigger:t}){const n=l1(),[r,o]=l.useState(()=>yo(n)),[a,i]=l.useState(null),[c,u]=l.useState([]),h=l.useRef({parts:[],timer:null}),d=l.useCallback(p=>{const y=[];return p.metaKey&&y.push(n?"⌘":"Meta"),p.ctrlKey&&y.push("Ctrl"),p.altKey&&y.push(n?"⌥":"Alt"),p.shiftKey&&p.key.length!==1&&y.push(n?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(p.key)?null:(y.push(ip(p.key)),y.join("+"))},[n]),m=l.useCallback(p=>{o(p);try{localStorage.setItem(op,JSON.stringify(p))}catch{}},[]);l.useEffect(()=>{const p=yo(n),y=Object.entries(r),k=Object.entries(p);y.length===k.length&&y.every(([b,j])=>p[b]===j)||m(p)},[r,n,m]);const f=l.useCallback(()=>{typeof window<"u"&&h.current.timer!=null&&window.clearTimeout(h.current.timer),h.current={parts:[],timer:null}},[]),x=l.useCallback(()=>{typeof window>"u"||(h.current.timer!=null&&window.clearTimeout(h.current.timer),h.current.timer=window.setTimeout(()=>{h.current={parts:[],timer:null}},a1))},[]);l.useEffect(()=>{if(!a)return;const p=y=>{if(y.preventDefault(),y.stopPropagation(),y.key==="Escape"){i(null),u([]);return}const k=d(y);if(!k)return;const j=!(y.metaKey||y.ctrlKey||y.altKey)&&/^[A-Z0-9]$/.test(k);if(c.length===0&&j){u([k]);return}const v=[...c,k].slice(0,2).join(" "),g={...r};for(const[N,C]of Object.entries(g))C===v&&delete g[N];g[a]=v,m(g),i(null),u([])};return window.addEventListener("keydown",p,!0),()=>window.removeEventListener("keydown",p,!0)},[r,d,m,a,c]),l.useEffect(()=>{if(!e||a)return;const p=y=>{if(y.defaultPrevented)return;const k=d(y);if(!k)return;const b=y.metaKey||y.ctrlKey||y.altKey;if(mi(y.target))return;const j=h.current.parts,S=b?[k]:[...j.slice(-1),k].slice(-2),v=S.join(" "),g=S[S.length-1],N=Object.entries(r).filter(([,L])=>!!L),C=N.find(([,L])=>L===v);if(C){y.preventDefault(),f(),t(C[0]);return}if(N.some(([,L])=>L.startsWith(`${v} `))){y.preventDefault(),h.current.parts=S,x();return}const T=N.find(([,L])=>L===g);if(T){y.preventDefault(),f(),t(T[0]);return}if(N.some(([,L])=>L.startsWith(`${g} `))){y.preventDefault(),h.current.parts=[g],x();return}f()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[r,x,e,d,t,f,a]),l.useEffect(()=>()=>f(),[f]);const w=l.useMemo(()=>ap(n),[n]);return{isMac:n,actionDefinitions:w,actionShortcuts:r,shortcutListening:a,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:u,saveShortcuts:m}}function d1({isTabInPopout:e,isTabFloating:t,tabShortcut:n,actionShortcuts:r}){const o=[];return e?(t&&o.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:r.dockActiveTab}),o.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:r.dockActiveTab})):t?o.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:r.dockActiveTab}):o.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:r.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:r.popoutActiveTab}),o.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:n?`Change shortcut (${n})`:"Set shortcut",shortcut:r.setActiveTabShortcut}),n&&o.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),o.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:r.hideCurrentTab,tone:"muted"}),o}function lp(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function Uc({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:n,ides:r}){return!e||n>0?!1:t?!lp(r):!0}function u1({previousVisibleConversationCount:e,visibleConversationCount:t,ides:n}){return t>0||e<=0?!1:lp(n)}const cp=1e3,h1=4;function Gc(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function Kc(e,t,n){return Math.abs(t.clientX-e.clientX)>n||Math.abs(t.clientY-e.clientY)>n}function p1({detachDelayMs:e=cp,stillnessThresholdPx:t=h1,onDetach:n,setTimeoutFn:r=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:o=globalThis.clearTimeout.bind(globalThis)}){let a=null,i=null,c=null,u=null,h=null,d=!1;const m=()=>{h!=null&&(o(h),h=null)},f=()=>{m(),c=null},x=()=>{m(),a=null,i=null,c=null,u=null,d=!1},w=()=>{!a||!c||!u||d||h!=null||(h=r(()=>{h=null,!(!a||!c||!u||d)&&Gc(u,i)&&(Kc(c,u,t)||(d=!0,n({panelId:a,clientX:u.clientX,clientY:u.clientY})))},e))},p=k=>{if(!(!a||d)){if(!Gc(k,i)){u={clientX:k.clientX,clientY:k.clientY},f();return}(!c||Kc(c,k,t))&&(m(),c={clientX:k.clientX,clientY:k.clientY}),u={clientX:k.clientX,clientY:k.clientY},w()}},y=k=>{!a||d||(k&&(u={clientX:k.clientX,clientY:k.clientY}),f())};return{startDrag:k=>{m(),a=k.panelId,i=k.selfPanelBounds??null,c=null,u={clientX:k.clientX,clientY:k.clientY},d=!1},markSelfPanel:p,markNonSelfPanel:y,markNoDropTarget:y,markDockTarget:y,endDrag:x,isDragging:()=>a!=null,hasDetached:()=>d,dispose:x}}function m1(e=typeof window>"u"?null:window.localStorage){return(e==null?void 0:e.getItem("adhdev:dockviewIdleDragFloat"))!=="off"}function Jr(e){return xt(e)||e.tabKey}function f1(e){return`remote:${e}`}function rs(e){return e.startsWith("remote:")}function zc(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function ya(e){var r;const t=e==null?void 0:e.defaultView;if(!t)return;const n=o=>{if(o)try{o.focus({preventScroll:!0})}catch{try{o.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 va(e,t){e.classList.remove(Fa.className,Ha.className),e.classList.add(t==="light"?Fa.className:Ha.className)}function qc(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 b1(e,t,n){var i;const r=[t];let o;for(const c of r){let u;for(const h of c){const d=e.addPanel({id:h.tabKey,component:"conversation",title:Jr(h),params:{kind:"conversation",tabKey:h.tabKey},...u?{position:{referencePanel:u,direction:"within"},inactive:!0}:o?{position:{referencePanel:o,direction:"right"},inactive:!0}:{}});u||(u=d.id)}o=u??o}return n??((i=t[0])==null?void 0:i.tabKey)??null}function Vc(e,t){const n=new Set(t.map(o=>o.tabKey)),r=new Map;for(const o of t)r.set(o.tabKey,(r.get(o.tabKey)||0)+1);for(const o of[...e.panels])rs(o.id)||n.has(o.id)||e.removePanel(o);for(const o of t){const a=e.getPanel(o.tabKey);if(a){(r.get(o.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:o.tabKey,daemonId:o.daemonId,sessionId:o.sessionId,providerSessionId:o.providerSessionId,panelId:a.id}),a.update({params:{tabKey:o.tabKey}}),a.title!==Jr(o)&&a.api.setTitle(Jr(o));continue}e.addPanel({id:o.tabKey,component:"conversation",title:Jr(o),params:{kind:"conversation",tabKey:o.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 Yc(e,t,n){var u,h;const r=n?f1(n):null;for(const d of[...e.panels])rs(d.id)&&(!r||d.id!==r)&&e.removePanel(d);if(!n||!r)return;const o=cs(t,n);if(!o&&e.totalPanels===0)return;const a=e.getPanel(r),i=ch(o);if(a){a.title!==i&&a.api.setTitle(i);return}const c=(o==null?void 0:o.tabKey)??((u=e.activePanel)==null?void 0:u.id)??((h=e.panels.find(d=>!rs(d.id)))==null?void 0:h.id);e.addPanel({id:r,component:"remote",title:i,params:{kind:"remote",routeId:n},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function dp({doId:e,targetSessionId:t,connState:n,viewMode:r}){const[o,a]=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=()=>a(f.result),f.readAsDataURL(m)}):void 0,[e]),l.useEffect(()=>{n!=="connected"&&a(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(()=>{a(null)},[e,t]),l.useEffect(()=>{const h=e?kt.get(e):null;if(!(!h||n!=="connected"))return r!=="chat"&&t?h.startScreenshots(t):h.stopScreenshots(t),()=>{h.stopScreenshots(t)}},[r,n,t,e]);const u=l.useCallback(async(h,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(h,d,t)},[e,n,t]);return{connScreenshot:o,screenshotUsage:i,handleRemoteAction:u}}const up=l.createContext(null);function Eo(){const e=l.useContext(up);if(!e)throw new Error("DashboardDockviewContext missing");return e}function g1(e){const[,t]=l.useState(0);l.useEffect(()=>{const n=()=>t(o=>o+1),r=[e.api.onDidActiveGroupChange(n),e.api.onDidTitleChange(n),e.api.onDidGroupChange(n),e.containerApi.onDidActivePanelChange(n)];return()=>{for(const o of r)o.dispose()}},[e.api,e.containerApi])}function x1({params:e}){var u;const t=Eo(),n=l.useMemo(()=>cs([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),r=l.useMemo(()=>t.ides.find(h=>h.id===e.routeId),[t.ides,e.routeId]),o=(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:a,screenshotUsage:i,handleRemoteAction:c}=dp({doId:o,targetSessionId:n?Fu(n):(r==null?void 0:r.sessionId)||(r==null?void 0:r.instanceId),connState:(n==null?void 0:n.connectionState)||"new",viewMode:"remote"});return n?s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden bg-black",children:s.jsx(iu,{addLog:()=>{},connState:n.connectionState||"new",connScreenshot:a,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 y1(){const e=Eo();return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col items-center justify-center",children:s.jsx(ol,{conversationsCount:0,isSplitMode:!1,isStandalone:e.isStandalone,hasRegisteredMachines:e.hasRegisteredMachines,onOpenNewSession:e.onOpenNewSession,suppressGuide:e.hasDetachedConversationPanels})})}function v1(e){var b,j;g1(e);const t=Eo(),n=l.useCallback(S=>{"button"in S&&S.button!==0||e.api.setActive()},[e.api]),r=e.params.kind==="remote"?void 0:t.conversationsByTabKey.get(e.params.tabKey),o=r==null?void 0:r.sessionId,a=l.useCallback(S=>t0(S),[]),i=l.useCallback(()=>e0(o),[o]),c=l.useSyncExternalStore(a,i,i);if(e.params.kind==="remote"){const S=cs([...t.conversationsByTabKey.values()],e.params.routeId),v=((b=e.api.group.activePanel)==null?void 0:b.id)===e.api.id,g=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${v?" is-active":""}${g?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(S==null?void 0:S.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:S!=null&&S.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:S.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 h=((j=e.api.group.activePanel)==null?void 0:j.id)===e.api.id,d=e.api.isGroupActive,m=No(u,t.liveSessionInboxState,{isOpenConversation:h}),f=m.isReconnecting,x=m.isConnecting,w=m.isGenerating||c,p=m.isWaiting,y=m.unread,k=t.tabShortcuts[u.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${h?" is-active":""}${d?" is-group-active":""}${f?" is-reconnecting":""}`,title:xt(u),"data-tab-key":e.params.tabKey,onMouseDown:n,onTouchStart:n,onContextMenu:S=>{var v;S.preventDefault(),n(S),t.openTabContextMenu({x:S.clientX,y:S.clientY,tabKey:u.tabKey,sourceDocument:((v=S.target)==null?void 0:v.ownerDocument)??document})},children:[y&&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"}):p?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:"○"}):x?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)}):x?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 Jc(e){return e.isVisible}function w1(e){e.preventDefault()}function k1({params:e,api:t}){var x;const n=Eo(),r=l.useRef(null),[o,a]=l.useState(()=>Er(t)),[i,c]=l.useState(()=>Jc(t)),u=n.conversationsByTabKey.get(e.tabKey),h=Po({sendDaemonCommand:n.sendDaemonCommand,activeConv:u,setActionLogs:n.setActionLogs,isStandalone:n.isStandalone});l.useEffect(()=>{a(Er(t)),c(Jc(t));const w=[t.onDidActiveChange(p=>a(p.isActive)),t.onDidActiveGroupChange(p=>{if(!Er(t)&&!p.isActive){a(!1);return}a(Er(t))}),t.onDidVisibilityChange(p=>c(p.isVisible))];return()=>{for(const p of w)p.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(ol,{conversationsCount:0,isSplitMode:!1,isStandalone:n.isStandalone,hasRegisteredMachines:n.hasRegisteredMachines,onOpenNewSession:n.onOpenNewSession,suppressGuide:n.hasDetachedConversationPanels})});const f=!lt(u)&&Tn(u)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(nl,{activeConv:u,clearToken:n.clearedTabs[u.tabKey]||0,isCliTerminal:f,ideEntry:d,terminalRef:r,handleModalButton:h.handleModalButton,handleRelaunch:h.handleRelaunch,handleSendChat:h.handleSendChat,handleForceSendChat:h.handleForceSendChat,isSendingChat:h.isSendingChat,handleFocusAgent:h.handleFocusAgent,isFocusingAgent:h.isFocusingAgent,actionLogs:m,userName:n.userName,scrollToBottomRequestNonce:((x=n.scrollToBottomRequest)==null?void 0:x.tabKey)===u.tabKey?n.scrollToBottomRequest.nonce:void 0,isInputActive:o,isVisible:i})})}function S1({visibleConversations:e,clearedTabs:t,ides:n,actionLogs:r,sendDaemonCommand:o,setActionLogs:a,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:u,userName:h,toggleHiddenTab:d,actionShortcuts:m,registerActionHandlers:f,onActiveTabChange:x,onOpenNewSession:w,onRequestScrollToBottom:p,requestedActiveTabKey:y,requestedRemoteIdeId:k,onRequestedActiveTabConsumed:b,scrollToBottomRequest:j,liveSessionInboxState:S,layoutProfile:v}){var ut,at,ht;const{theme:g}=Ls(),{sendCommand:N}=yt(),C=l.useRef(null),A=l.useRef(null),T=l.useRef(null),M=l.useRef(!1),L=l.useRef(!1),P=l.useRef(!1),B=l.useRef(null),K=l.useRef([]),[F,R]=l.useState(null),[Q,E]=l.useState(0),I=l.useRef(typeof window>"u"?{}:OS(v)),$=l.useMemo(()=>new Map(e.map(J=>[J.tabKey,J])),[e]),D=l.useMemo(()=>{const J=C.current;return J?J.groups.some(ee=>{try{const le=ee.model.location.type;return le!=="floating"&&le!=="popout"?!1:ee.panels.some(ue=>$.has(ue.id))}catch{return!1}}):!1},[$,Q,e]),U=l.useCallback(()=>{var J;(J=C.current)==null||J.focus()},[]),Y=l.useCallback((J,ee)=>{p==null||p(J,ee)},[p]),ae=l.useCallback(J=>{const ee=document,le=J.document;for(const Ne of ee.querySelectorAll('link[rel="stylesheet"]')){const He=le.createElement("link");He.rel="stylesheet",He.href=Ne.href,Ne.crossOrigin&&(He.crossOrigin=Ne.crossOrigin),le.head.appendChild(He)}for(const Ne of ee.querySelectorAll("style")){const He=le.createElement("style");He.textContent=Ne.textContent,le.head.appendChild(He)}const ue=[];for(const Ne of ee.styleSheets)try{for(const He of Ne.cssRules)He instanceof CSSStyleRule&&(He.selectorText===":root"||He.selectorText==="html")&&ue.push(He.cssText)}catch{}if(ue.length>0){const Ne=le.createElement("style");Ne.textContent=ue.join(`
71
+ `),le.head.appendChild(Ne)}const ge=ee.documentElement.getAttribute("data-theme");ge&&le.documentElement.setAttribute("data-theme",ge),le.documentElement.style.colorScheme=ge==="light"?"light":"dark",le.body.className=ee.body.className;const Ae=ee.documentElement.getAttribute("style");Ae&&le.documentElement.setAttribute("style",Ae);const Pe=le.getElementById("dv-popout-window");Pe instanceof HTMLElement&&(Pe.classList.add("adhdev-dockview"),va(Pe,g))},[g]),z=l.useCallback(()=>{var ee;const J=C.current;if(J)for(const le of J.groups)try{const ue=(ee=le.element)==null?void 0:ee.ownerDocument;if(!ue||ue===document)continue;const ge=ue.getElementById("dv-popout-window");ge instanceof HTMLElement&&(ge.classList.add("adhdev-dockview"),va(ge,g));const Ae=document.documentElement.getAttribute("data-theme");Ae&&ue.documentElement.setAttribute("data-theme",Ae),ue.documentElement.style.colorScheme=Ae==="light"?"light":"dark",ue.body.className=document.body.className;const Pe=document.documentElement.getAttribute("style");Pe?ue.documentElement.setAttribute("style",Pe):ue.documentElement.removeAttribute("style")}catch{}},[g]),X=l.useCallback(J=>{const ee=C.current;if(!ee)return;const le=ee.getPanel(J);le&&ee.addPopoutGroup(le,{popoutUrl:"/popout.html",onDidOpen:({window:ue})=>{ae(ue),Se();const ge=$.get(J);ue.document.title=ge?`${xt(ge)} — ADHDev`:"ADHDev — Popout"}})},[$,ae]),de=l.useCallback(J=>{const ee=C.current,le=ee==null?void 0:ee.getPanel(J);if(!ee||!le)return;const ue=ee.groups.filter(ge=>{var Ae;try{return((Ae=ge.element)==null?void 0:Ae.ownerDocument)===document}catch{return!0}});ue.length>0?le.api.moveTo({group:ue[0],position:"center"}):le.api.moveTo({position:"center"}),le.api.setActive()},[]),re=l.useCallback(J=>{var ue;const ee=C.current;if(!ee)return!1;const le=ee.getPanel(J);if(!le)return!1;try{return((ue=le.group.element)==null?void 0:ue.ownerDocument)!==document}catch{return!1}},[]),W=l.useCallback(J=>{re(J)&&de(J),d(J)},[re,de,d]),oe=l.useCallback(J=>{const ee=C.current,le=ee==null?void 0:ee.getPanel(J);!ee||!le||ee.addFloatingGroup(le,{width:600,height:500})},[]),V=l.useCallback(J=>{var le;const ee=(le=C.current)==null?void 0:le.getPanel(J);if(!ee)return!1;try{return ee.group.model.location.type==="floating"}catch{return!1}},[]),ie=l.useCallback(()=>{var ee,le;const J=(le=(ee=C.current)==null?void 0:ee.activePanel)==null?void 0:le.id;return!J||rs(J)?null:$.has(J)?J:null},[$]),ke=l.useCallback(J=>{const ee=C.current,le=ee==null?void 0:ee.getPanel(J);if(!ee||!le)return;const ue=ee.groups.filter(ge=>{try{return ge.model.location.type==="grid"}catch{return!0}});ue.length>0?le.api.moveTo({group:ue[0],position:"center"}):le.api.moveTo({position:"center"}),le.api.setActive()},[]),xe=l.useCallback(()=>{var Ae;const J=C.current;if(!J)return;const le=J.groups.filter(Pe=>{var Ne;try{return((Ne=Pe.element)==null?void 0:Ne.ownerDocument)===document&&Pe.model.location.type==="grid"}catch{return!1}})[0]||null,ue=[...J.panels];for(const Pe of ue){const Ne=(Ae=Pe.group.element)==null?void 0:Ae.ownerDocument,He=Pe.group.model.location.type;Ne===document&&He==="grid"||(le&&le.id!==Pe.group.id?Pe.api.moveTo({group:le,position:"center"}):Pe.api.moveTo({position:"center"}))}const ge=J.activePanel;ge&&(ge.group.model.openPanel(ge),ge.api.setActive()),ya(document)},[]),Se=l.useCallback(()=>{var ee,le;const J=C.current;if(J)for(const ue of J.groups){const ge=(ee=ue.element)==null?void 0:ee.ownerDocument;if(!ge||ge===document)continue;const Ae=ge.getElementById("dv-popout-window");if(!(Ae instanceof HTMLElement))continue;let Pe=null,Ne=ge.title||"ADHDev",He="Popout workspace";const Ke=ue.activePanel;if(Ke)if(Pe=Ke.id,rs(Ke.id)){const se=((le=Ke.params)==null?void 0:le.routeId)||Ke.id.slice(7),be=cs([...$.values()],se);Ne=ch(be),He=be!=null&&be.machineName?`Remote view · ${be.machineName}`:"Remote view"}else{const se=$.get(Ke.id);Ne=se?xt(se):Ke.title||Ke.id,He=se?Gs(se):"Dockview panel"}ge.title=`${Ne} — ADHDev`;const Ze=Array.from(ge.querySelectorAll("#adhdev-popout-header"));for(const se of Ze)se.remove();const _e=ge.createElement("div");_e.id="adhdev-popout-header",ge.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
+ <div style="min-width:0;display:flex;flex-direction:column;gap:2px;">
73
+ <div style="font-size:10px;line-height:1;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.08em;">ADHDev</div>
74
+ <div style="min-width:0;font-size:13px;font-weight:700;color:var(--text-primary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${zc(Ne)}</div>
75
+ <div style="min-width:0;font-size:10px;line-height:1.1;color:var(--text-secondary);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">${zc(He)}</div>
76
+ </div>
77
+ <div style="display:flex;align-items:center;gap:8px;flex:0 0 auto;">
78
+ <button type="button" data-adhdev-popout-focus style="height:30px;padding:0 10px;border-radius:9px;background:var(--bg-glass);color:var(--text-secondary);font-size:11px;font-weight:600;">Dashboard</button>
79
+ <button type="button" data-adhdev-popout-dock style="height:30px;padding:0 10px;border-radius:9px;background:var(--surface-primary);color:var(--text-primary);font-size:11px;font-weight:700;">Dock</button>
80
+ </div>
81
+ `,Ae.style.top="52px",Ae.style.height="calc(100% - 52px)";const Ue=_e.querySelector("[data-adhdev-popout-focus]");Ue&&(Ue.onclick=()=>{window.focus()});const et=_e.querySelector("[data-adhdev-popout-dock]");et&&(et.disabled=!Pe,et.style.opacity=Pe?"1":"0.5",et.style.cursor=Pe?"pointer":"default",et.onclick=()=>{var se;Pe&&de(Pe),(se=ge.defaultView)==null||se.focus()})}},[$,de]),pe=l.useCallback(J=>{var ue;const ee=C.current,le=ee==null?void 0:ee.getPanel(J);if(!(!ee||!le)){le.group.model.openPanel(le),le.api.setActive(),Y(J,"dockview-shortcut");try{const ge=le.group.model.location;ge.type==="popout"?ge.getWindow().focus():ya((ue=le.group.element)==null?void 0:ue.ownerDocument)}catch{}}},[Y]),G=l.useCallback(J=>{const ee=C.current,le=ee==null?void 0:ee.activePanel,ue=(ee==null?void 0:ee.activeGroup)||(le==null?void 0:le.group);if(!ee||!le||!ue)return;const ge=ue.panels||[];if(ge.length<=1)return;const Ae=ge.findIndex(He=>He.id===le.id);if(Ae<0)return;const Pe=(Ae+J+ge.length)%ge.length,Ne=ge[Pe];Ne&&(Ne.group.model.openPanel(Ne),Ne.api.setActive(),rs(Ne.id)||Y(Ne.id,"dockview-shortcut"))},[Y]),O=l.useCallback(J=>{var Ue;const ee=C.current,le=(ee==null?void 0:ee.activeGroup)||((Ue=ee==null?void 0:ee.activePanel)==null?void 0:Ue.group);if(!ee||!le)return;const ue=ee.groups||[],ge=ue.find(et=>et.id===le.id);if(!ge)return;const Ae=ge.element.getBoundingClientRect(),Pe=Ae.left+Ae.width/2,Ne=Ae.top+Ae.height/2,He=(et,se,be,we)=>Math.max(0,Math.min(se,we)-Math.max(et,be)),Ke=et=>{const se=et.element.getBoundingClientRect(),be=se.left+se.width/2,we=se.top+se.height/2;let ze=0,We=0,tt=0,qe=!1;if(J==="left"?(qe=be<Pe,ze=Math.max(0,Ae.left-se.right),We=Math.abs(we-Ne),tt=He(Ae.top,Ae.bottom,se.top,se.bottom)):J==="right"?(qe=be>Pe,ze=Math.max(0,se.left-Ae.right),We=Math.abs(we-Ne),tt=He(Ae.top,Ae.bottom,se.top,se.bottom)):J==="above"?(qe=we<Ne,ze=Math.max(0,Ae.top-se.bottom),We=Math.abs(be-Pe),tt=He(Ae.left,Ae.right,se.left,se.right)):(qe=we>Ne,ze=Math.max(0,se.top-Ae.bottom),We=Math.abs(be-Pe),tt=He(Ae.left,Ae.right,se.left,se.right)),!qe)return Number.POSITIVE_INFINITY;const Ye=tt>0?0:120;return ze*3+We+Ye};let Ze=null,_e=Number.POSITIVE_INFINITY;for(const et of ue){if(et.id===ge.id)continue;const se=Ke(et);Number.isFinite(se)&&(se>=_e||(_e=se,Ze=et))}return Ze||void 0},[]),Z=l.useCallback(J=>{var ue;const ee=O(J);if(!ee)return;const le=ee.activePanel||ee.panels[0];le&&(ee.model.openPanel(le),le.api.setActive(),rs(le.id)||Y(le.id,"dockview-focus"),ya((ue=ee.element)==null?void 0:ue.ownerDocument))},[O,Y]),q=l.useCallback((J,ee)=>{const le=C.current,ue=le==null?void 0:le.activePanel,ge=(le==null?void 0:le.activeGroup)||(ue==null?void 0:ue.group);if(!le||!ue||!ge)return;let Ae=O(J);!Ae&&(ee!=null&&ee.createGroupIfMissing)&&(Ae=le.addGroup({referenceGroup:ge,direction:J})),Ae&&(ue.api.moveTo({group:Ae,position:"center"}),ue.group.model.openPanel(ue),ue.api.setActive(),rs(ue.id)||Y(ue.id,ee!=null&&ee.createGroupIfMissing?"dockview-split":"dockview-move"))},[O,Y]),{isMac:me,tabShortcuts:Te,shortcutListening:_,setShortcutListening:te,saveShortcuts:ve}=rp({sortedTabKeys:e.map(J=>J.tabKey),onFocus:U,onSelectTab:pe}),ce=l.useCallback(()=>{var le;const J=C.current;if(!J)return;const ee=J.activePanel;if(ee){if(rs(ee.id)){const ue=((le=ee.params)==null?void 0:le.routeId)||ee.id.slice(7),ge=cs(e,ue);ge!=null&&ge.tabKey&&te(ge.tabKey);return}$.has(ee.id)&&te(ee.id)}},[$,pe,te,e]),H=l.useCallback(J=>{const ee=[];return J.metaKey&&ee.push(me?"⌘":"Meta"),J.ctrlKey&&ee.push("Ctrl"),J.altKey&&ee.push(me?"⌥":"Alt"),J.shiftKey&&J.key.length!==1&&ee.push(me?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(J.key)?null:(ee.push(ip(J.key)),ee.join("+"))},[me]),fe=l.useCallback(J=>{var ee,le;switch(J){case"splitActiveTabRight":q("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":q("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const ue=ie();ue&&oe(ue);return}case"popoutActiveTab":{const ue=ie();ue&&X(ue);return}case"dockActiveTab":{const ue=ie();if(!ue)return;re(ue)?de(ue):V(ue)&&ke(ue);return}case"focusLeftPane":Z("left");return;case"focusRightPane":Z("right");return;case"focusUpPane":Z("above");return;case"focusDownPane":Z("below");return;case"moveActiveTabToLeftPane":q("left");return;case"moveActiveTabToRightPane":q("right");return;case"moveActiveTabToUpPane":q("above");return;case"moveActiveTabToDownPane":q("below");return;case"selectPreviousGroupTab":G(-1);return;case"selectNextGroupTab":G(1);return;case"setActiveTabShortcut":ce();return;case"hideCurrentTab":{const ue=(le=(ee=C.current)==null?void 0:ee.activePanel)==null?void 0:le.id;ue&&!rs(ue)&&W(ue);return}default:return}},[G,ke,Z,oe,ie,W,V,re,de,q,X,ce]);l.useEffect(()=>{if(!F)return;const J=F.sourceDocument,ee=J.defaultView??window,le=ue=>{const ge=J.querySelector("[data-dockview-tab-context-menu]");ge&&ge.contains(ue.target)||R(null)};return ee.addEventListener("mousedown",le,!0),ee!==window&&window.addEventListener("mousedown",()=>R(null),!0),()=>{ee.removeEventListener("mousedown",le,!0),ee!==window&&window.removeEventListener("mousedown",()=>R(null),!0)}},[F]);const je=l.useMemo(()=>({actionLogs:r,clearedTabs:t,conversationsByTabKey:$,hasDetachedConversationPanels:D,ides:n,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:w,liveSessionInboxState:S,sendDaemonCommand:o,setActionLogs:a,toggleHiddenTab:W,userName:h,scrollToBottomRequest:j,tabShortcuts:Te,openTabContextMenu:({x:J,y:ee,tabKey:le,sourceDocument:ue})=>R({x:J,y:ee,tabKey:le,sourceDocument:ue??document}),popoutTab:X,moveTabBackToMain:de,isTabInPopout:re,floatTab:oe,isTabFloating:V}),[r,t,$,D,n,i,c,w,S,o,a,W,h,j,Te,X,de,re,oe,V]),Ce=F?d1({isTabInPopout:re(F.tabKey),isTabFloating:V(F.tabKey),tabShortcut:Te[F.tabKey],actionShortcuts:m}):[],Be=l.useCallback(J=>{var ue;const ee=C.current;if((((ue=ee==null?void 0:ee.activePanel)==null?void 0:ue.id)??null)===J.id){J.group.model.openPanel(J);return}J.group.model.openPanel(J),J.api.setActive()},[]),Xe=l.useCallback((J,ee="requested-tab")=>{if(!J)return!1;const le=C.current;if(!le)return!1;const ue=le.getPanel(J);return ue?(Be(ue),Y(J,ee),b==null||b(),!0):!1},[Be,b,Y]),dt=l.useCallback(()=>{if(P.current)return!1;const J=Xe(B.current,"stored-layout-restore");return J&&(P.current=!0),J},[Xe]),it=l.useCallback(()=>{var ee;const J=C.current;J&&WS(v,{activeTabId:((ee=J.activePanel)==null?void 0:ee.id)??null,layout:J.toJSON()})},[v]),he=l.useCallback(()=>{US(v,I.current)},[v]),$e=l.useCallback(J=>{var ue,ge,Ae,Pe;const ee=C.current;if(!ee)return{kind:"grid"};const le=ee.toJSON();for(const Ne of le.floatingGroups||[])if((ge=(ue=Ne.data)==null?void 0:ue.views)!=null&&ge.includes(J)&&Ne.position)return{kind:"floating",position:Ne.position};for(const Ne of le.popoutGroups||[])if((Pe=(Ae=Ne.data)==null?void 0:Ae.views)!=null&&Pe.includes(J))return{kind:"popout",position:Ne.position,popoutUrl:Ne.url};return{kind:"grid"}},[]),Fe=l.useCallback(J=>{const ee=C.current;if(!ee)return;const le=ee.getPanel(J),ue=I.current[J];if(!le||!ue||ue.kind==="grid")return;if(le.group.model.location.type===ue.kind){delete I.current[J],he();return}if(ue.kind==="floating"){ee.addFloatingGroup(le,{x:ue.position.left??24,y:ue.position.top??24,width:ue.position.width,height:ue.position.height}),delete I.current[J],he();return}delete I.current[J],he()},[he]);l.useEffect(()=>(f==null||f({setShortcutForActiveTab:ce,restoreHiddenTabToSavedLocation:Fe,activateConversationTab:pe,resetAllPanelsToMain:xe,activatePreviousTabInGroup:()=>G(-1),activateNextTabInGroup:()=>G(1),floatActiveTab:()=>{const J=ie();J&&oe(J)},popoutActiveTab:()=>{const J=ie();J&&X(J)},dockActiveTab:()=>{const J=ie();J&&(re(J)?de(J):V(J)&&ke(J))},splitActiveTabRight:()=>q("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>q("below",{createGroupIfMissing:!0}),focusLeftPane:()=>Z("left"),focusRightPane:()=>Z("right"),focusUpPane:()=>Z("above"),focusDownPane:()=>Z("below"),moveActiveTabToLeftPane:()=>q("left"),moveActiveTabToRightPane:()=>q("right"),moveActiveTabToUpPane:()=>q("above"),moveActiveTabToDownPane:()=>q("below")}),()=>f==null?void 0:f(null)),[G,ke,oe,Z,ie,V,re,q,de,X,f,xe,Fe,pe,ce]),l.useEffect(()=>()=>{var J;(J=T.current)==null||J.call(T),T.current=null},[]);const Ie=l.useCallback(J=>{var le,ue;C.current=J.api,(le=T.current)==null||le.call(T),T.current=null;const ee=HS(v);if(B.current=(ee==null?void 0:ee.activeTabId)??null,ee!=null&&ee.layout&&J.api.fromJSON(ee.layout,{reuseExistingPanels:!1}),L.current=Uc({hasStoredLayout:!!(ee!=null&&ee.layout),initialDataLoaded:u,visibleConversationCount:e.length,ides:n}),L.current||(Vc(J.api,e),Yc(J.api,e,k)),J.api.totalPanels===0&&e.length>0){const ge=b1(J.api,e,y);if(ge){const Ae=J.api.getPanel(ge);Ae&&Be(Ae)}}else!L.current&&!Xe(y)&&dt();if(M.current=!0,J.api.onDidActivePanelChange(ge=>{var Pe;if(B.current=(ge==null?void 0:ge.id)??null,P.current=!0,Se(),ge&&rs(ge.id)){const Ne=((Pe=ge.params)==null?void 0:Pe.routeId)||ge.id.slice(7),He=cs(e,Ne);x((He==null?void 0:He.tabKey)??null),it();return}if(x((ge==null?void 0:ge.id)??null),it(),!ge)return;const Ae=$.get(ge.id);(Ae==null?void 0:Ae.streamSource)==="agent-stream"&&Ae.agentType&&N(Ae.routeId,Hu(),{agentType:Ae.agentType,...Ae.sessionId&&{targetSessionId:Ae.sessionId}}).catch(()=>{})}),J.api.onDidLayoutChange(()=>{it(),Se(),E(ge=>ge+1)}),m1()){const ge=_e=>({clientX:_e.clientX,clientY:_e.clientY}),Ae=_e=>{const Ue=_e==null?void 0:_e.getBoundingClientRect();return Ue?{left:Ue.left,right:Ue.right,top:Ue.top,bottom:Ue.bottom}:null},Pe=_e=>{var et;const Ue=(et=A.current)==null?void 0:et.getBoundingClientRect();return Ue?_e.clientX<Ue.left||_e.clientX>Ue.right||_e.clientY<Ue.top||_e.clientY>Ue.bottom:!1},Ne=p1({detachDelayMs:cp,onDetach:({panelId:_e,clientX:Ue,clientY:et})=>{var tt,qe;const se=J.api.getPanel(_e);if(!se)return;try{if(se.group.model.location.type!=="grid")return}catch{return}const be=(tt=A.current)==null?void 0:tt.getBoundingClientRect(),we=(qe=se.group.element)==null?void 0:qe.getBoundingClientRect(),ze=Math.round(Math.min(Math.max((we==null?void 0:we.width)??600,360),720)),We=Math.round(Math.min(Math.max((we==null?void 0:we.height)??500,260),640));J.api.addFloatingGroup(se,{x:be?Math.max(0,Ue-be.left-32):void 0,y:be?Math.max(0,et-be.top-18):void 0,width:ze,height:We}),se.api.setActive(),it(),Se(),E(Ye=>Ye+1)}}),He=[J.api.onWillDragPanel(_e=>{if(!(_e.nativeEvent.defaultPrevented||_e.nativeEvent.shiftKey)){try{if(_e.panel.group.model.location.type!=="grid")return}catch{return}Ne.startDrag({panelId:_e.panel.id,selfPanelBounds:Ae(_e.panel.group.element),...ge(_e.nativeEvent)})}}),J.api.onWillShowOverlay(_e=>{if(Ne.hasDetached()){_e.preventDefault();return}Ne.markDockTarget(ge(_e.nativeEvent))}),J.api.onWillDrop(_e=>{if(Ne.hasDetached()){_e.preventDefault(),Ne.endDrag();return}Ne.markDockTarget(ge(_e.nativeEvent))}),J.api.onDidDrop(()=>Ne.endDrag()),J.api.onUnhandledDragOverEvent(_e=>{Ne.isDragging()&&Ne.markSelfPanel(ge(_e.nativeEvent))})],Ke=_e=>{if(!Ne.isDragging())return;const Ue=ge(_e);Pe(Ue)&&Ne.markNonSelfPanel(Ue)},Ze=()=>Ne.endDrag();window.addEventListener("dragover",Ke,!0),window.addEventListener("drop",Ze,!0),window.addEventListener("dragend",Ze,!0),T.current=()=>{Ne.dispose();for(const _e of He)_e.dispose();window.removeEventListener("dragover",Ke,!0),window.removeEventListener("drop",Ze,!0),window.removeEventListener("dragend",Ze,!0)}}J.api.onDidAddGroup(ge=>{requestAnimationFrame(()=>{var Ae,Pe;try{const Ne=(Ae=ge.element)==null?void 0:Ae.ownerDocument;if(!Ne||Ne===document)return;(Pe=Ne.getElementById("dv-popout-window"))==null||Pe.classList.add("adhdev-dockview");const He=document.documentElement.getAttribute("data-theme");He&&Ne.documentElement.setAttribute("data-theme",He),Ne.body.className=document.body.className;const Ke=document.documentElement.getAttribute("style");Ke&&Ne.documentElement.setAttribute("style",Ke)}catch{}Se(),E(Ne=>Ne+1)})}),x(((ue=J.api.activePanel)==null?void 0:ue.id)??null)},[Be,Xe,$,n,u,v,x,it,y,k,N,Se,e]);l.useLayoutEffect(()=>{const J=C.current;if(!J||!M.current||L.current&&Uc({hasStoredLayout:!0,initialDataLoaded:u,visibleConversationCount:e.length,ides:n}))return;L.current&&(L.current=!1);const ee=K.current,le=new Set(ee),ue=e.map(Ze=>Ze.tabKey),ge=new Set(ue),Ae=u1({previousVisibleConversationCount:ee.length,visibleConversationCount:e.length,ides:n});let Pe=!1;for(const Ze of ee)ge.has(Ze)||Ae||(I.current[Ze]=$e(Ze),Pe=!0);Pe&&he(),Ae||(Vc(J,e),Yc(J,e,k));const Ne=ue.filter(Ze=>!le.has(Ze));let He=!1;for(const Ze of Ne){const _e=J.getPanel(Ze),Ue=I.current[Ze];if(!_e||!Ue||Ue.kind==="grid")continue;if(_e.group.model.location.type===Ue.kind){delete I.current[Ze],He=!0;continue}if(Ue.kind==="floating"){J.addFloatingGroup(_e,{x:Ue.position.left??24,y:Ue.position.top??24,width:Ue.position.width,height:Ue.position.height}),delete I.current[Ze],He=!0;continue}}if(He&&he(),K.current=ue,y&&Xe(y))return;!J.activePanel&&J.panels[0]&&Be(J.panels[0]),!!(J.activePanel&&J.getPanel(J.activePanel.id))||dt()},[Be,Xe,dt,n,u,he,$e,y,k,e]),l.useEffect(()=>{M.current&&Xe(y)},[Xe,y]),l.useEffect(()=>{const J=le=>{const ue=le.target;if(!ue)return;const ge=ue.querySelector("[data-tab-key]")||ue.closest("[data-tab-key]");if(ge){const Ae=ge.getAttribute("data-tab-key");if(Ae&&le.dataTransfer){const Pe=ue.closest(".dv-tab")||ge.closest(".dv-tab")||ge;le.dataTransfer.effectAllowed="move",le.dataTransfer.setData("text/tab-key",Ae),Pe instanceof HTMLElement&&le.dataTransfer.setDragImage(Pe,Math.max(12,Math.round(Pe.clientWidth/2)),Math.max(10,Math.round(Pe.clientHeight/2)))}}};window.addEventListener("dragstart",J);const ee=qc(C.current);for(const le of ee)le.addEventListener("dragstart",J);return()=>{window.removeEventListener("dragstart",J);for(const le of ee)le.removeEventListener("dragstart",J)}},[Q]),l.useEffect(()=>{var ee;const J=(ee=A.current)==null?void 0:ee.querySelector(".adhdev-dockview");J instanceof HTMLElement&&va(J,g),z(),Se()},[Se,z,g]),l.useEffect(()=>{Se()},[Se]),l.useEffect(()=>{const J=ee=>{if(ee.defaultPrevented||_)return;const le=H(ee);if(!le)return;const ue=ee.metaKey||ee.ctrlKey||ee.altKey;mi(ee.target)&&!ue||yo(me).setActiveTabShortcut!==le||(ee.preventDefault(),ee.stopPropagation(),ce())};return window.addEventListener("keydown",J,!0),()=>window.removeEventListener("keydown",J,!0)},[H,me,_,ce]),l.useEffect(()=>{const J=A.current;if(!J)return;const ee=le=>{var Ne,He;if(!le.isTrusted)return;const ue=(He=(Ne=le.target)==null?void 0:Ne.closest)==null?void 0:He.call(Ne,".dv-scrollable");if(!ue)return;le.preventDefault(),le.stopPropagation();const ge=Math.abs(le.deltaX),Ae=Math.abs(le.deltaY),Pe=ge>Ae?le.deltaX:le.deltaY;ue.dispatchEvent(new WheelEvent("wheel",{deltaY:Pe,deltaMode:le.deltaMode,bubbles:!1,cancelable:!0}))};return J.addEventListener("wheel",ee,{passive:!1,capture:!0}),()=>J.removeEventListener("wheel",ee,{capture:!0})},[]),l.useEffect(()=>{const J=qc(C.current);if(J.length===0)return;const ee=J.map(le=>{let ue=[],ge=null;const Ae=()=>{ge!=null&&le.clearTimeout(ge),ge=null,ue=[]},Pe=()=>{ge!=null&&le.clearTimeout(ge),ge=le.setTimeout(()=>{ge=null,ue=[]},1200)},Ne=Ke=>{if(!Ke.ctrlKey&&!Ke.metaKey&&!Ke.altKey)return;const Ze=H(Ke);if(!Ze)return;const _e=np();for(const[Ue,et]of Object.entries(_e))if(e.some(se=>se.tabKey===Ue)&&et===Ze){Ke.preventDefault(),pe(Ue);return}},He=Ke=>{if(Ke.defaultPrevented||_)return;const Ze=H(Ke);if(!Ze)return;const _e=Ke.metaKey||Ke.ctrlKey||Ke.altKey;if(mi(Ke.target))return;const Ue=yo(me),et=Object.entries(Ue).filter(([Ye,Tt])=>!!Tt&&(Ye==="splitActiveTabRight"||Ye==="splitActiveTabDown"||Ye==="floatActiveTab"||Ye==="popoutActiveTab"||Ye==="dockActiveTab"||Ye==="focusLeftPane"||Ye==="focusRightPane"||Ye==="focusUpPane"||Ye==="focusDownPane"||Ye==="moveActiveTabToLeftPane"||Ye==="moveActiveTabToRightPane"||Ye==="moveActiveTabToUpPane"||Ye==="moveActiveTabToDownPane"||Ye==="selectPreviousGroupTab"||Ye==="selectNextGroupTab"||Ye==="setActiveTabShortcut"||Ye==="hideCurrentTab")),se=_e?[Ze]:[...ue.slice(-1),Ze].slice(-2),be=se.join(" "),we=se[se.length-1],ze=et.find(([,Ye])=>Ye===be);if(ze){Ke.preventDefault(),Ae(),fe(ze[0]);return}if(et.some(([,Ye])=>Ye.startsWith(`${be} `))){Ke.preventDefault(),ue=se,Pe();return}const tt=et.find(([,Ye])=>Ye===we);if(tt){Ke.preventDefault(),Ae(),fe(tt[0]);return}if(et.some(([,Ye])=>Ye.startsWith(`${we} `))){Ke.preventDefault(),ue=[we],Pe();return}Ae()};return le.addEventListener("keydown",Ne),le.addEventListener("keydown",He),()=>{Ae(),le.removeEventListener("keydown",Ne),le.removeEventListener("keydown",He)}});return()=>{for(const le of ee)le()}},[H,me,Q,pe,_,fe,e]);const ye=g==="light"?Fa:Ha,Oe=((ht=(at=(ut=C.current)==null?void 0:ut.activePanel)==null?void 0:at.group.element)==null?void 0:ht.ownerDocument)??document;return s.jsxs(up.Provider,{value:je,children:[s.jsx("div",{ref:A,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(jm,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:k1,remote:x1},defaultTabComponent:v1,watermarkComponent:y1,onReady:Ie,singleTabMode:"default",tabAnimation:"smooth",theme:ye,popoutUrl:"/popout.html"})}),F&&fn.createPortal(s.jsx("div",{"data-dockview-tab-context-menu":!0,className:"fixed z-[var(--z-popover)] min-w-[220px] rounded-xl border border-border-subtle bg-bg-primary shadow-2xl py-1",style:{left:F.x,top:F.y},children:Ce.map(J=>{if(J.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},J.id);let ee=s.jsx(Yf,{size:13,className:"shrink-0 opacity-70"}),le=()=>{};switch(J.id){case"dockInWindow":case"dockBackToGrid":ee=s.jsx(Qf,{size:13,className:"shrink-0 opacity-70"}),le=()=>{ke(F.tabKey),R(null)};break;case"moveBackToMain":ee=s.jsx(Vf,{size:13,className:"shrink-0 opacity-70"}),le=()=>{de(F.tabKey),R(null)};break;case"floatAsPanel":ee=s.jsx(Jf,{size:13,className:"shrink-0 opacity-70"}),le=()=>{oe(F.tabKey),R(null)};break;case"openInNewWindow":ee=s.jsx(qf,{size:13,className:"shrink-0 opacity-70"}),le=()=>{X(F.tabKey),R(null)};break;case"setShortcut":le=ue=>{ue.stopPropagation(),te(F.tabKey),R(null)};break;case"removeShortcut":ee=s.jsx(At,{size:13,className:"shrink-0 opacity-70"}),le=()=>{const ue={...Te};delete ue[F.tabKey],ve(ue),R(null)};break;case"hideTab":ee=s.jsx(Ti,{size:13,className:"shrink-0 opacity-70"}),le=()=>{W(F.tabKey),R(null)};break}return s.jsxs("button",{type:"button",className:`w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors flex items-center gap-2 ${J.tone==="muted"?"text-text-muted":""}`,onMouseDown:w1,onClick:le,children:[ee,s.jsx("span",{className:"flex-1 min-w-0",children:J.label}),J.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:J.shortcut}):null]},J.id)})}),F.sourceDocument.body),_&&fn.createPortal(s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>te(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:J=>J.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. ",me?"⌘+1":"Ctrl+1",", ",me?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:"Press Esc to cancel"})]})}),Oe.body)]})}const hp="adhdev-recent-launch-args-v1",C1=8;function j1(e){return String(e||"").trim().replace(/\s+/g," ")}function pp(e,t){return`${e.trim()}::${t.trim()}`}function mp(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(hp)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function N1(e){if(!(typeof window>"u"))try{window.localStorage.setItem(hp,JSON.stringify(e))}catch{}}function A1(e,t){var a;const n=String(e||"").trim(),r=String(t||"").trim();return!n||!r?[]:((a=mp().byKey[pp(n,r)])==null?void 0:a.items)||[]}function T1(e,t,n){var d;const r=String(e||"").trim(),o=String(t||"").trim(),a=j1(n);if(!r||!o||!a)return;const i=mp(),c=pp(r,o),u=((d=i.byKey[c])==null?void 0:d.items)||[],h=[a,...u.filter(m=>m!==a)].slice(0,C1);i.byKey[c]={items:h},N1(i)}function I1(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Vn({title:e,description:t,action:n,children:r,className:o="",contentClassName:a=""}){return s.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${o}`.trim(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),t&&s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:t})]}),n?s.jsx("div",{className:"flex items-center gap-2",children:n}):null]}),r?s.jsx("div",{className:t||n?`mt-3 ${a}`.trim():a,children:r}):null]})}function M1({savedSessionsLoading:e,savedSessionsLoaded:t,savedSessionsCount:n=0}){return e?"Refreshing saved history…":t?n>0?`${n} saved ${n===1?"history":"histories"} loaded. Open saved history to choose one.`:"No saved history found yet. New Hermes CLI conversations will appear here after ADHDev captures provider history.":"Start fresh, or open saved history when you want continuity."}function D1({busy:e,savedSessionsLoading:t,savedSessionsError:n,savedSessionsLoaded:r,savedSessionsCount:o=0,selectedSession:a,onRefresh:i,onOpenHistory:c,onClearSelection:u}){const{t:h}=Le("common"),d=a?Qh(a):null,m=M1({savedSessionsLoading:t,savedSessionsLoaded:r,savedSessionsCount:o});return s.jsxs(Vn,{title:"Saved history",description:zi(h),action:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e||t,onClick:i,children:t?"Loading…":"Refresh"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:e,onClick:c,children:Q0(h)})]}),children:[d?s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:s.jsxs("div",{className:"flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:"Selected saved history"}),s.jsx("div",{className:"mt-1 font-semibold text-text-primary truncate",children:d.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:d.providerSessionId}),s.jsx("div",{className:"mt-1",children:d.metaLine}),d.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:d.updatedLabel}),d.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:d.preview})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:u,disabled:e,children:"Clear"})]})}):s.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:m}),n&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:n})]})}function fp({setup:e,providerName:t,className:n=""}){return e?s.jsxs("div",{className:`rounded-xl border border-accent/25 bg-accent/10 px-4 py-3 text-sm text-text-primary ${n}`,children:[s.jsxs("div",{className:"font-semibold",children:["Manual MCP setup required",t?` for ${t}`:""]}),e.instructions&&s.jsx("p",{className:"mt-1 text-xs leading-relaxed text-text-secondary",children:e.instructions}),s.jsxs("div",{className:"mt-2 flex flex-wrap gap-2 text-[11px] text-text-muted",children:[e.serverName&&s.jsxs("span",{children:["Server: ",s.jsx("code",{children:e.serverName})]}),e.configFormat&&s.jsxs("span",{children:["Format: ",s.jsx("code",{children:e.configFormat})]}),e.configPathCommand&&s.jsxs("span",{children:["Config path: ",s.jsx("code",{children:e.configPathCommand})]}),e.requiresRestart&&s.jsx("span",{children:"Start a fresh CLI session after editing config."})]}),e.template&&s.jsx("pre",{className:"mt-3 max-h-72 overflow-auto rounded-lg border border-border-subtle bg-bg-primary p-3 text-xs font-mono leading-relaxed text-text-primary select-all whitespace-pre-wrap",children:e.template})]}):null}const wa={cli:"CLI",ide:"IDE",acp:"ACP"};function P1({workspaceMode:e,activeKind:t,cliEnabled:n,ideEnabled:r,acpEnabled:o,busy:a,onSelect:i}){const{t:c}=Le();return e==="mesh"?null:s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:c("newSession.category")}),s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"cli",label:wa.cli,enabled:n},{id:"ide",label:wa.ide,enabled:r},{id:"acp",label:wa.acp,enabled:o}].map(u=>s.jsx("button",{type:"button",className:`btn btn-sm ${t===u.id?"btn-primary":"btn-secondary"}`,onClick:()=>i(u.id),disabled:!u.enabled||a,children:u.label},u.id))})]})}function ka(e){var r;if(!e)return null;const t=e.availableProviders||[];return t.some(o=>Sn(o,"cli"))?"cli":(((r=e.detectedIdes)==null?void 0:r.length)||0)>0?"ide":t.some(o=>Sn(o,"acp"))?"acp":null}function _r(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function L1({machines:e,ides:t,onClose:n,onBrowseDirectory:r,onSaveWorkspace:o,onLaunchIde:a,onLaunchProvider:i,onListMeshes:c,onLaunchMeshCoordinator:u,onListSavedSessions:h}){var jt,Ot;const{t:d}=Le(),m=In(),f=l.useMemo(()=>[...e].sort(Ei),[e]),[x,w]=l.useState(((jt=f[0])==null?void 0:jt.id)||""),p=l.useMemo(()=>f.find(ne=>ne.id===x)||f[0],[x,f]),y=l.useMemo(()=>((p==null?void 0:p.workspaces)||[]).map(ne=>({id:ne.id,path:ne.path,label:ne.label})),[p]),k=(p==null?void 0:p.defaultWorkspaceId)||null,[b,j]=l.useState("workspace"),[S,v]=l.useState(""),[g,N]=l.useState(""),[C,A]=l.useState([]),[T,M]=l.useState(""),[L,P]=l.useState(!1),[B,K]=l.useState(null),[F,R]=l.useState(""),[Q,E]=l.useState(ka(f[0])),[I,$]=l.useState(""),[D,U]=l.useState(""),[Y,ae]=l.useState(""),[z,X]=l.useState(""),[de,re]=l.useState(!1),[W,oe]=l.useState([]),[V,ie]=l.useState(""),[ke,xe]=l.useState([]),[Se,pe]=l.useState(!1),[G,O]=l.useState(!1),[Z,q]=l.useState(""),[me,Te]=l.useState(!1),[_,te]=l.useState(()=>Ft()),[ve,ce]=l.useState(null),[H,fe]=l.useState(!1),[je,Ce]=l.useState(""),[Be,Xe]=l.useState("error"),[dt,it]=l.useState(null),[he,$e]=l.useState(!1),[Fe,Ie]=l.useState(""),[ye,Oe]=l.useState([]),[ut,at]=l.useState(!1),[ht,J]=l.useState(""),[ee,le]=l.useState(!1),ue=l.useRef(null),ge=l.useRef(0);l.useEffect(()=>{var ne;!x&&((ne=f[0])!=null&&ne.id)&&w(f[0].id)},[x,f]),l.useEffect(()=>{!p||!(!p.workspaces||!p.availableProviders||!p.detectedIdes||!p.recentLaunches)||m(p.id,{minFreshMs:3e4}).catch(()=>{})},[m,p]);const Ae=l.useCallback(ne=>{ne&&m(ne,{minFreshMs:3e4}).catch(()=>{})},[m]),Pe=l.useMemo(()=>((p==null?void 0:p.availableProviders)||[]).filter(ne=>Sn(ne,"cli")),[p]),Ne=l.useMemo(()=>((p==null?void 0:p.availableProviders)||[]).filter(ne=>Sn(ne,"acp")),[p]),He=l.useMemo(()=>((p==null?void 0:p.detectedIdes)||[]).map(ne=>({id:ne.type,label:ne.name||ne.type,meta:ne.running?d("newSession.detectedLocally"):d("newSession.availableToOpen")})),[p,d]),Ke=l.useMemo(()=>Q==="cli"?Pe.map(ne=>({id:ne.type,label:ne.displayName||ne.type,meta:""})):Q==="acp"?Ne.map(ne=>({id:ne.type,label:ne.displayName||ne.type,meta:""})):He,[Ne,Q,Pe,He]),Ze=l.useMemo(()=>C.find(ne=>ne.id===T)||null,[C,T]),_e=l.useMemo(()=>Pe.find(ne=>ne.type===I)||null,[Pe,I]),Ue=l.useMemo(()=>[...Pe,...Ne].find(ne=>ne.type===I),[Pe,Ne,I]),et=l.useMemo(()=>ck(Ue?[Ue]:[],Ue==null?void 0:Ue.type),[Ue]),se=l.useMemo(()=>{const ne=dk(Ue?[Ue]:[],Ue==null?void 0:Ue.type);return ne.length?ne:["low","medium","high"]},[Ue]),be=l.useMemo(()=>Kh(_e==null?void 0:_e.meshCoordinator,{meshId:(Ze==null?void 0:Ze.id)||"",workspace:(Ze==null?void 0:Ze.workspace)||""}),[_e,Ze]),we=dt||be,ze=l.useCallback(async ne=>{P(!0),R("");try{const Ge=await c(ne);A(Ge),M(Ee=>{var vt;return Ge.some(Jt=>Jt.id===Ee)?Ee:((vt=Ge[0])==null?void 0:vt.id)||""}),K(ne)}catch(Ge){A([]),M(""),K(ne),R(Ge instanceof Error?Ge.message:d("newSession.errorLoadMeshes"))}finally{P(!1)}},[c,d]);l.useEffect(()=>{var Ge;if(!p)return;if(ue.current!==p.id){ue.current=p.id,j("workspace"),v(k||((Ge=y[0])==null?void 0:Ge.id)||"__home__"),N(""),A([]),M(""),K(null),R(""),E(ka(p)),$(""),U(""),ae(""),X(""),re(!1),ie(""),xe([]),O(!1),q(""),te(Ft()),Ce(""),it(null);return}v(Ee=>{var vt;return Ee==="__custom__"||Ee==="__home__"||y.some(Jt=>Jt.id===Ee)?Ee:k||((vt=y[0])==null?void 0:vt.id)||"__home__"}),E(Ee=>Ee==="ide"&&He.length>0||Ee==="cli"&&Pe.length>0||Ee==="acp"&&Ne.length>0?Ee:ka(p))},[Ne.length,Pe.length,k,He.length,p,y]),l.useEffect(()=>{!p||b!=="mesh"||B===p.id||L||ze(p.id)},[ze,B,L,p,b]),l.useEffect(()=>{b==="mesh"&&Q!=="cli"&&Pe.length>0&&E("cli")},[Q,Pe.length,b]),l.useEffect(()=>{var ne;Q&&(Ke.some(Ge=>Ge.id===I)||$(((ne=Ke[0])==null?void 0:ne.id)||""))},[Q,Ke,I]),l.useEffect(()=>{it(null)},[p==null?void 0:p.id,T,I,b]),l.useEffect(()=>{ae(""),X(""),re(!1)},[I]);const We=l.useCallback(async(ne,Ge)=>{const Ee=ge.current+1;return ge.current=Ee,pe(!0),q(""),h(ne,Ge).then(vt=>{ge.current===Ee&&xe(vt)}).catch(vt=>{ge.current===Ee&&(xe([]),q(vt instanceof Error?vt.message:d("newSession.errorLoadSavedSessions")))}).finally(()=>{ge.current===Ee&&(pe(!1),O(!0))})},[h,d]),tt=l.useCallback((ne,Ge)=>{oe(A1(ne,Ge))},[]);l.useEffect(()=>{ge.current+=1,ie(""),te(Ft()),!p||!I||Q==="ide"?oe([]):tt(p.id,I),O(!1),xe([]),q(""),pe(!1)},[Q,tt,We,p,I]),l.useEffect(()=>{if(!V)return;const ne=ke.find(Ge=>Ge.providerSessionId===V);ne!=null&&ne.canResume||ie("")},[ke,V]);const qe=S==="__custom__"?g.trim():S==="__home__"?"":((Ot=y.find(ne=>ne.id===S))==null?void 0:Ot.path)||"",Ye=l.useMemo(()=>p?t.filter(ne=>ne.id!==p.id&&ne.daemonId===p.id).map(ne=>ne.workspace):[],[t,p]),Tt=l.useMemo(()=>((p==null?void 0:p.recentLaunches)||[]).map(ne=>ne.workspace),[p]),Wt=l.useCallback(ne=>{const Ge=String(ne.workspace||"").trim();if(!Ge)return;const Ee=y.find(vt=>_r(vt.path)===_r(Ge));if(Ee){v(Ee.id),N("");return}v("__custom__"),N(Ge)},[y]),ss=l.useCallback(ne=>{const Ge=String(ne.workspace||"").trim();if(!Ge)return{workspaceId:null,workspacePath:null};const Ee=y.find(vt=>_r(vt.path)===_r(Ge));return Ee?{workspaceId:Ee.id,workspacePath:null}:{workspaceId:null,workspacePath:Ge}},[y]),Me=l.useMemo(()=>ke.find(ne=>ne.providerSessionId===V)||null,[ke,V]),Qe=l.useMemo(()=>{var Ge;if(Q!=="cli"||!p||!I)return null;const ne=((Ge=Pe.find(Ee=>Ee.type===I))==null?void 0:Ge.displayName)||I;return{routeId:p.id,daemonId:p.id,providerSessionId:V||void 0,transport:"pty",mode:"chat",agentName:ne,agentType:I,status:"idle",title:ne,messages:[],ideType:I,workspaceName:qe,workspacePath:qe,displayPrimary:ne,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${p.id}:${I}`,machineName:ts(p,{fallbackId:p.id})}},[Q,Pe,qe,p,V,I]),Dt=l.useCallback(()=>{var Ge;if(!p)return;v("__custom__"),$e(!0),J("");const ne=tl(p.platform,el(g.trim(),qe,Ye,Tt,p.defaultWorkspacePath,(Ge=y.find(Ee=>Ee.id===k))==null?void 0:Ge.path,y.map(Ee=>Ee.path)));at(!0),r(p.id,ne).then(Ee=>{Ie(Ee.path),N(Ee.path),Oe(Ee.directories)}).catch(Ee=>{J(Ee instanceof Error?Ee.message:d("newSession.errorLoadFolder"))}).finally(()=>at(!1))},[g,k,Tt,Ye,r,qe,p,y]),It=l.useCallback(ne=>{p&&(at(!0),J(""),r(p.id,ne).then(Ge=>{Ie(Ge.path),N(Ge.path),Oe(Ge.directories)}).catch(Ge=>{J(Ge instanceof Error?Ge.message:d("newSession.errorLoadFolder"))}).finally(()=>at(!1)))},[r,p]),qt=l.useCallback(async()=>{if(!p||!qe)return;le(!0),Ce("");const ne=await o(p.id,qe);if(le(!1),!ne.ok){Xe("error"),Ce(ne.error||d("newSession.errorSaveWorkspace"));return}Xe("info"),Ce(d("newSession.workspaceSaved"))},[o,qe,p,d]),Vt=l.useCallback(async()=>{if(!p)return;if(b==="mesh"){if(!T||!I)return;fe(!0),Ce(""),it(null);const Ee=await u(p.id,T,I,{initialModel:Y.trim()?Y.trim():null,initialThinkingLevel:z.trim()?z.trim():null});if(fe(!1),!Ee.ok){if(Ee.code==="mesh_coordinator_manual_mcp_setup_required"&&Ee.manualSetup){it(Ee.manualSetup),Xe("info"),Ce(d("newSession.errorManualMcpSetup"));return}Xe("error"),Ce(Ee.error||d("newSession.errorStartMeshCoordinator"));return}n();return}if(!Q||!I)return;fe(!0),Ce("");const ne=D.trim()?D.trim().split(/\s+/).filter(Boolean):[],Ge=Q==="ide"?await a(p.id,I,{workspacePath:qe||null}):await i(p.id,Q,I,{workspaceId:S!=="__home__"&&S!=="__custom__"?S:null,workspacePath:S==="__custom__"&&qe||null,resumeSessionId:Q==="cli"&&V?V:null,cliArgs:ne,initialModel:Y.trim()?Y.trim():null,initialThinkingLevel:z.trim()?z.trim():null});if(fe(!1),!Ge.ok){Xe("error"),Ce(Ge.error||d("newSession.errorStartSession"));return}Q!=="ide"&&D.trim()&&(T1(p.id,I,D),tt(p.id,I)),n()},[Q,D,Y,z,tt,n,a,u,i,qe,p,T,V,I,S,b,d]),Yt=Q==="cli"&&!!V,xs=d(b==="mesh"?"newSession.startMeshCoordinator":Q==="cli"?Yt?"newSession.resumeSavedHistory":"newSession.startFresh":Q==="ide"?"newSession.startIde":Q==="acp"?"newSession.startAcpSession":"newSession.start"),Re=d(b==="mesh"?"newSession.startingCoordinator":Q==="cli"?Yt?"newSession.resumingSavedHistory":"newSession.startingFresh":Q==="ide"?"newSession.startingIde":Q==="acp"?"newSession.startingAcpSession":"newSession.starting"),rt=f.length>5;return p?s.jsxs(s.Fragment,{children:[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":"dashboard-new-title",children:s.jsxs("div",{className:"w-full max-w-3xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,860px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-4 py-4 sm:px-5 border-b border-border-subtle shrink-0",children:[s.jsx("div",{className:"min-w-0",children:s.jsx("h2",{id:"dashboard-new-title",className:"m-0 text-base font-semibold text-text-primary",children:d("newSession.title")})}),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:n,"aria-label":d("newSession.close"),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 space-y-4",children:[f.length>1&&s.jsx(Vn,{title:d("newSession.machine"),children:rt?s.jsx("select",{"aria-label":d("newSession.machine"),value:p.id,onChange:ne=>w(ne.target.value),onFocus:()=>f.forEach(ne=>Ae(ne.id)),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:H,children:f.map(ne=>s.jsx("option",{value:ne.id,children:ts(ne,{fallbackId:ne.id})},ne.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":d("newSession.machine"),children:f.map(ne=>{const Ge=ts(ne,{fallbackId:ne.id}),Ee=p.id===ne.id;return s.jsxs("button",{type:"button","aria-label":d("newSession.selectMachine",{name:Ge}),"aria-pressed":Ee,className:`inline-flex min-w-0 items-center gap-2 rounded-full border px-3 py-2 text-sm transition-colors ${Ee?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/60 text-text-secondary hover:bg-bg-secondary hover:text-text-primary"}`,onClick:()=>w(ne.id),onMouseEnter:()=>Ae(ne.id),onFocus:()=>Ae(ne.id),disabled:H,title:Ge,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${ne.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:Ge})]},ne.id)})})}),s.jsxs(Vn,{title:d("newSession.workspace"),action:b==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Dt,disabled:H,children:d("newSession.browse")}):void 0,children:[s.jsx("div",{className:"mb-3 grid grid-cols-2 gap-2",role:"radiogroup","aria-label":d("newSession.launchTargetType"),children:[{id:"workspace",label:d("newSession.modeWorkspace"),desc:d("newSession.modeWorkspaceDesc")},{id:"mesh",label:d("newSession.modeMesh"),desc:d("newSession.modeMeshDesc")}].map(ne=>s.jsxs("button",{type:"button",role:"radio","aria-checked":b===ne.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${b===ne.id?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/40 text-text-secondary hover:bg-bg-secondary/70 hover:text-text-primary"}`,onClick:()=>{j(ne.id),Ce(""),ne.id==="mesh"&&p&&B!==p.id&&!L&&ze(p.id)},disabled:H,children:[s.jsx("div",{className:"text-sm font-semibold",children:ne.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:ne.desc})]},ne.id))}),b==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:S,onChange:ne=>{const Ge=ne.target.value;v(Ge),Ge==="__custom__"?Dt():Ce("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:H,children:[s.jsx("option",{value:"__home__",children:d("newSession.homeDirectory")}),y.map(ne=>s.jsxs("option",{value:ne.id,children:[ne.id===k?"⭐ ":"",xu(ne.path,ne.label)||ne.path]},ne.id)),s.jsx("option",{value:"__custom__",children:d("newSession.customFolder")})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:S==="__home__"?d("newSession.launchWithoutWorkspace"):qe||d("newSession.selectWorkspaceFolder")}),S==="__custom__"&&qe&&s.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Dt,disabled:H,children:[s.jsx(xn,{size:14}),d("newSession.selectFolder")]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:qt,disabled:H||ee,children:d(ee?"newSession.saving":"newSession.saveWorkspace")})]})]}):s.jsxs("div",{className:"space-y-3",children:[L&&s.jsx("div",{className:"text-sm text-text-muted",children:d("newSession.loadingMeshes")}),!L&&F&&s.jsx("div",{className:"rounded-lg border border-status-error/25 bg-status-error/10 px-3 py-2 text-sm text-status-error",children:F}),!L&&!F&&C.length===0&&s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 px-3 py-2 text-sm text-text-muted",children:d("newSession.noMeshes")}),C.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":d("newSession.mesh"),children:C.map(ne=>s.jsxs("button",{type:"button",role:"radio","aria-checked":T===ne.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${T===ne.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>M(ne.id),disabled:H,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:ne.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[ne.repoIdentity||d("newSession.repoMesh"),typeof ne.nodesCount=="number"?` · ${d("newSession.nodeCount",{count:ne.nodesCount})}`:""]}),ne.workspace&&s.jsx("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:d("newSession.coordinatorWorkspace",{path:ne.workspace})})]},ne.id))})]})]}),s.jsx(P1,{workspaceMode:b,activeKind:Q,cliEnabled:Pe.length>0,ideEnabled:He.length>0,acpEnabled:Ne.length>0,busy:H,onSelect:E}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-4 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-2",children:d(Q==="ide"?"newSession.chooseIde":Q==="cli"?"newSession.chooseCliProvider":"newSession.chooseAcpProvider")}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[Ke.map(ne=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${I===ne.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>$(ne.id),disabled:H,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:ne.label}),ne.meta&&s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:ne.meta})]},ne.id)),Ke.length===0&&s.jsx("div",{className:"text-sm text-text-muted",children:d("newSession.noProviders")})]})]}),b==="mesh"&&we&&s.jsx(fp,{setup:we,providerName:(_e==null?void 0:_e.displayName)||(_e==null?void 0:_e.name)||I}),b!=="mesh"&&Q!=="ide"&&s.jsxs(Vn,{title:d("newSession.startupArguments"),children:[s.jsx("input",{type:"text",value:D,onChange:ne=>U(ne.target.value),placeholder:d("newSession.optionalFlags"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:H}),W.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:W.map(ne=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>U(ne),disabled:H,title:ne,children:ne},ne))})]}),(b==="mesh"&&!!I||b!=="mesh"&&Q!=="ide")&&s.jsx(Vn,{title:d("newSession.modelAndThinking"),children:s.jsxs("div",{className:"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:d("newSession.model")}),et.length>0&&!de?s.jsxs("select",{value:et.includes(Y)?Y:"",onChange:ne=>{ne.target.value==="__custom__"?(re(!0),ae("")):ae(ne.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:H,children:[s.jsx("option",{value:"",children:d("newSession.providerDefault")}),et.map(ne=>s.jsx("option",{value:ne,children:ne},ne)),s.jsx("option",{value:"__custom__",children:d("newSession.custom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:Y,onChange:ne=>ae(ne.target.value),placeholder:d("newSession.typeModelName"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:H,autoFocus:de}),et.length>0&&s.jsx("button",{type:"button",className:"self-start text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{re(!1),ae("")},disabled:H,children:d("newSession.backToModelList")})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:d("newSession.thinkingLevel")}),s.jsxs("select",{value:z,onChange:ne=>X(ne.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:H,children:[s.jsx("option",{value:"",children:d("newSession.providerDefault")}),se.map(ne=>s.jsx("option",{value:ne,children:ne},ne))]})]})]})}),b!=="mesh"&&Q==="cli"&&s.jsx(D1,{busy:H,savedSessionsLoading:Se,savedSessionsError:Z,selectedSession:Me,onRefresh:()=>{!p||!I||We(p.id,I)},onOpenHistory:()=>{!p||!I||(Te(!0),I1({hasLoadedInitialResults:G,isLoading:Se})&&We(p.id,I))},onClearSelection:()=>ie("")}),je&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${Be==="info"?"border-accent/25 bg-accent/10 text-text-primary":"border-status-error/25 bg-status-error/10 text-status-error"}`,children:je})]}),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:n,disabled:H,children:d("common.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:Vt,disabled:H||(b==="mesh"?!T||!I||Q!=="cli"||L:!Q||!I||S==="__custom__"&&!qe),children:[s.jsx(Qd,{size:14}),H?Re:xs]})]})]})}),he&&s.jsx(rl,{title:d("newSession.selectWorkspaceTitle"),description:d("newSession.selectWorkspaceDescription"),currentPath:Fe,directories:ye,busy:ut,error:ht,onClose:()=>$e(!1),onNavigate:It,onConfirm:ne=>{N(ne),Ie(ne),v("__custom__"),$e(!1)}}),me&&Qe&&s.jsx(bh,{activeConv:Qe,ides:[],isCreatingChat:!1,isRefreshingHistory:Se,savedSessions:ke,isSavedSessionsLoading:Se,isResumingSavedSessionId:ve,savedHistoryFilters:_,missingWorkspaceResumePath:qe||null,onSavedHistoryFiltersChange:te,onClose:()=>Te(!1),onNewChat:()=>{ie(""),Te(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!p||!I||We(p.id,I)},onResumeSavedSession:ne=>{if(!p||!I||ve||!ne.canResume)return;const Ge=ss(ne);ie(ne.providerSessionId),Wt(ne),ce(ne.providerSessionId),Te(!1),fe(!0),Ce(""),i(p.id,"cli",I,{workspaceId:Ge.workspaceId,workspacePath:Ge.workspacePath,resumeSessionId:ne.providerSessionId}).then(Ee=>{if(!Ee.ok){Xe("error"),Ce(Ee.error||d("newSession.errorResumeSession"));return}n()}).finally(()=>{fe(!1),ce(Ee=>Ee===ne.providerSessionId?null:Ee)})}})]}):null}function bp(e){return e.ahead<=0&&e.behind<=0?null:e.ahead>0&&e.behind>0?`ahead ${e.ahead} / behind ${e.behind}`:e.behind>0?`behind ${e.behind}`:`ahead ${e.ahead}`}function al(e){if(e.type==="submoduleNode")return e.outOfSync||e.error?{label:"submodule drift",tone:"danger"}:e.dirty?{label:"submodule dirty",tone:"warn"}:null;const t=e.branchConvergence;if((t==null?void 0:t.status)==="not_mergeable")return{label:e.hasConflicts?"conflicts present":"dirty workspace",tone:"danger"};if((t==null?void 0:t.status)==="blocked_review"){if(t.reason==="upstream_unverified")return{label:"upstream unverified",tone:"warn"};const n=bp(e);return n?{label:n,tone:"danger"}:!e.upstream&&e.branch&&e.branch!==t.defaultBranch?{label:"push branch",tone:"warn"}:{label:"blocked review",tone:"danger"}}return e.refineJobStatus==="failed"?{label:"refine failed",tone:"danger"}:e.refineJobStatus==="running"||e.refineJobStatus==="accepted"?{label:"refining…",tone:"info"}:(t==null?void 0:t.status)==="pushed_feature_branch_needs_merge"?{label:"needs merge",tone:"warn"}:(t==null?void 0:t.status)==="cleanup_candidate"?{label:"refine worktree",tone:"info"}:e.isOrphan?{label:"needs follow-up",tone:"warn"}:e.health==="offline"?{label:"offline",tone:"danger"}:null}function il(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function gp(e){var t;return!il(e)||e.type==="defaultBranchNode"?!1:!!((t=e.branchConvergence)!=null&&t.needsConvergence||e.isOrphan||e.hasConflicts||e.outOfSync||e.error||e.health==="offline"||e.health==="degraded"||e.health==="wrong_branch"||e.dirty)}function $r(e){return[...new Set(e.filter(t=>!!t))]}function R1(e){const t=e.nodes.find(i=>i.type==="defaultBranchNode")??null,n=(t==null?void 0:t.branch)??null,r=e.nodes.filter(i=>i.type!=="defaultBranchNode"&&i.type!=="submoduleNode"&&!i.isOrphan&&!!n&&i.branch===n),o=e.nodes.filter(i=>i.type!=="submoduleNode"&&!i.isOrphan),a=e.nodes.filter(i=>i.type!=="submoduleNode");return t||r.length>0?$r([t==null?void 0:t.id,...r.map(i=>i.id)]):o.length>0?$r(o.map(i=>i.id)):a.length>0?$r(a.map(i=>i.id)):$r(e.nodes.map(i=>i.id))}function xp(e){const t=[...e.nodes].sort((r,o)=>r.id.localeCompare(o.id)).map(r=>[r.id,r.type,r.branch??"",r.parentNodeId??"",r.submodulePath??""].join(":")).join("|"),n=[...e.edges].sort((r,o)=>r.id.localeCompare(o.id)).map(r=>[r.id,r.source,r.target,r.type].join(":")).join("|");return`${e.meshId}::${t}::${n}`}function E1(e,t,n){const r=Math.max(0,Math.round(t)),o=Math.max(0,Math.round(n));return`${xp(e)}::${r}x${o}`}const _1={default:"border-white/10 bg-white/[0.04] text-slate-200",good:"border-emerald-400/20 bg-emerald-500/10 text-emerald-200",warn:"border-amber-400/20 bg-amber-500/10 text-amber-100",danger:"border-rose-400/20 bg-rose-500/10 text-rose-100",info:"border-sky-400/20 bg-sky-500/10 text-sky-100"},$1={default:"border-slate-300 bg-white/95 text-slate-700",good:"border-emerald-300 bg-emerald-50 text-emerald-700",warn:"border-amber-300 bg-amber-50 text-amber-700",danger:"border-rose-300 bg-rose-50 text-rose-700",info:"border-sky-300 bg-sky-50 text-sky-700"},B1={default:"border-white/10 bg-white/[0.04] text-slate-200 hover:bg-white/[0.08]",info:"border-sky-400/25 bg-sky-500/10 text-sky-100 hover:bg-sky-500/16",success:"border-emerald-400/25 bg-emerald-500/10 text-emerald-100 hover:bg-emerald-500/16"},F1={default:"border-slate-300 bg-white text-slate-700 hover:bg-slate-50",info:"border-sky-300 bg-sky-50 text-sky-700 hover:bg-sky-100",success:"border-emerald-300 bg-emerald-50 text-emerald-700 hover:bg-emerald-100"};function Rs(e){return e==="light"?{theme:e,isDark:!1,flowColorMode:"light",textPrimary:"text-slate-900",textSecondary:"text-slate-700",textMuted:"text-slate-500",graphShellClass:"relative flex min-h-0 flex-1 flex-col w-full min-w-0 overflow-hidden rounded-2xl border border-slate-200 bg-[radial-gradient(circle_at_top,_rgba(14,165,233,0.16),_rgba(248,250,252,0.98)_42%,_rgba(255,255,255,1))]",graphStatChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-slate-700 shadow-sm",graphHintChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1 text-[10px] text-slate-500 shadow-sm",graphControlsClass:"!bottom-4 !left-4 !shadow-md",graphBackgroundDotColor:"rgba(148, 163, 184, 0.34)",edgeLabelTextColor:"#334155",edgeLabelBackgroundColor:"rgba(255, 255, 255, 0.96)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.45)",dialogOverlayClass:"fixed inset-0 z-[var(--z-modal-backdrop)] flex items-stretch justify-center bg-[rgba(15,23,42,0.82)] p-0 md:items-center md:p-4",dialogShellClass:"flex h-[100dvh] max-h-[100dvh] w-full flex-col overflow-hidden bg-white md:h-auto md:max-h-[90dvh] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-slate-200 md:bg-white/98 md:shadow-[0_28px_120px_rgba(148,163,184,0.28)]",dialogHeaderClass:"sticky top-0 z-10 flex shrink-0 flex-col gap-3 border-b border-slate-200 bg-white/96 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-slate-900 md:text-xl",dialogKickerClass:"rounded-full border border-slate-300 bg-slate-50 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-600",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-500",dialogRefreshedChipClass:"rounded-full border border-slate-300 bg-white/95 px-3 py-1.5 text-xs text-slate-600",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-slate-300 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",dialogBodyClass:"min-h-0 flex-1 flex flex-col overflow-y-auto bg-[linear-gradient(180deg,rgba(248,250,252,0.98),rgba(241,245,249,0.96))] px-4 py-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))] md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-slate-300 bg-white/90 px-6 text-center text-sm text-slate-500",cardClass:"rounded-2xl border border-slate-200 bg-white/95 shadow-sm",cardHeaderClass:"border-b border-slate-200 px-4 py-3",cardTitleClass:"text-sm font-semibold text-slate-900",cardSubtitleClass:"mt-1 text-xs text-slate-500",rowClass:"flex min-w-0 items-start justify-between gap-3 border-b border-slate-200/80 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"shrink-0 text-slate-500",rowValueClass:"min-w-0 flex-1 break-all text-right text-slate-800",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-slate-200 bg-white/95 p-4 shadow-md md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-slate-200 bg-white/95 p-4 text-xs text-slate-500 shadow-sm md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-900",panelCloseButtonClass:"text-xs text-slate-500 hover:text-slate-900",panelFieldRowClass:"flex min-w-0 justify-between gap-3 border-b border-slate-200/80 py-0.5 text-[11px]",panelFieldLabelClass:"shrink-0 text-slate-500",panelFieldValueClass:"min-w-0 flex-1 break-all text-right font-medium text-slate-700",infoCalloutClass:"mt-1 rounded border border-sky-300 bg-sky-50 px-2 py-1.5 text-[10px] text-sky-700",badge:t=>$1[t],actionButton:t=>F1[t]}:{theme:e,isDark:!0,flowColorMode:"dark",textPrimary:"text-slate-100",textSecondary:"text-slate-300",textMuted:"text-slate-400",graphShellClass:"relative flex min-h-0 flex-1 flex-col w-full min-w-0 overflow-hidden rounded-2xl border border-white/10 bg-[radial-gradient(circle_at_top,_rgba(56,189,248,0.12),_rgba(15,23,42,0.98)_42%,_rgba(2,6,23,1))]",graphStatChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-slate-200",graphHintChipClass:"rounded-full border border-white/10 bg-slate-950/60 px-3 py-1 text-[10px] text-slate-300",graphControlsClass:"!bottom-4 !left-4 !shadow-lg",graphBackgroundDotColor:"rgba(148, 163, 184, 0.22)",edgeLabelTextColor:"#cbd5e1",edgeLabelBackgroundColor:"rgba(2, 6, 23, 0.86)",edgeLabelBorderColor:"rgba(148, 163, 184, 0.2)",dialogOverlayClass:"fixed inset-0 z-[var(--z-modal-backdrop)] flex items-stretch justify-center bg-[#030617]/[0.92] p-0 md:items-center md:p-4",dialogShellClass:"flex h-[100dvh] max-h-[100dvh] w-full flex-col overflow-hidden bg-slate-950 md:h-auto md:max-h-[90dvh] md:max-w-[min(1480px,calc(100vw-32px))] md:rounded-[24px] md:border md:border-white/10 md:bg-slate-950/96 md:shadow-[0_28px_120px_rgba(2,6,23,0.46)]",dialogHeaderClass:"sticky top-0 z-10 flex shrink-0 flex-col gap-3 border-b border-white/10 bg-slate-950/92 px-4 pb-4 pt-[calc(16px+env(safe-area-inset-top,0px))] backdrop-blur md:flex-row md:items-center md:justify-between md:px-5",dialogTitleClass:"truncate text-lg font-semibold text-white md:text-xl",dialogKickerClass:"rounded-full border border-white/10 bg-white/6 px-2.5 py-1 text-[11px] uppercase tracking-[0.18em] text-slate-300",dialogSubtitleClass:"mt-1 truncate text-sm text-slate-400",dialogRefreshedChipClass:"rounded-full border border-white/10 bg-white/6 px-3 py-1.5 text-xs text-slate-300",dialogCloseButtonClass:"inline-flex h-9 w-9 items-center justify-center rounded-xl border border-white/10 bg-white/6 text-slate-300 transition hover:bg-white/10 hover:text-white",dialogBodyClass:"min-h-0 flex-1 flex flex-col overflow-y-auto bg-[linear-gradient(180deg,rgba(2,6,23,0.95),rgba(15,23,42,0.98))] px-4 py-4 pb-[calc(16px+env(safe-area-inset-bottom,0px))] md:px-5 md:py-5",dialogEmptyClass:"flex h-full min-h-[320px] items-center justify-center rounded-[28px] border border-dashed border-white/10 bg-white/[0.03] px-6 text-center text-sm text-slate-400",cardClass:"rounded-2xl border border-white/10 bg-white/[0.04]",cardHeaderClass:"border-b border-white/10 px-4 py-3",cardTitleClass:"text-sm font-semibold text-white",cardSubtitleClass:"mt-1 text-xs text-slate-400",rowClass:"flex min-w-0 items-start justify-between gap-3 border-b border-white/5 py-1.5 text-xs last:border-b-0 last:pb-0 first:pt-0",rowLabelClass:"shrink-0 text-slate-400",rowValueClass:"min-w-0 flex-1 break-all text-right text-slate-100",panelShellClass:"flex w-full max-w-full flex-col gap-2 rounded-xl border border-white/10 bg-white/[0.04] p-4 shadow-lg md:w-64",panelEmptyClass:"w-full max-w-full rounded-xl border border-white/10 bg-white/[0.04] p-4 text-xs text-slate-400 md:w-64",panelTitleClass:"truncate text-xs font-semibold text-slate-100",panelCloseButtonClass:"text-xs text-slate-400 hover:text-slate-100",panelFieldRowClass:"flex min-w-0 justify-between gap-3 border-b border-white/6 py-0.5 text-[11px]",panelFieldLabelClass:"shrink-0 text-slate-400",panelFieldValueClass:"min-w-0 flex-1 break-all text-right font-medium text-slate-200",infoCalloutClass:"mt-1 rounded bg-blue-500/10 border border-blue-500/20 px-2 py-1.5 text-[10px] text-blue-300",badge:t=>_1[t],actionButton:t=>B1[t]}}const Cn={worktreeCardWidth:256,submoduleCardWidth:228,minWorktreeCardHeight:174,minSubmoduleCardHeight:146,maxEstimatedCardHeight:304,layerGap:220,nodeGap:82,edgeLabelBuffer:180,placeholderTopOffset:0},xr={worktreeCardWidth:188,submoduleCardWidth:188,minWorktreeCardHeight:88,minSubmoduleCardHeight:88,maxEstimatedCardHeight:178,layerGap:160,nodeGap:52,edgeLabelBuffer:120},H1={maxWidth:180};function W1(e){return e==="TB"?"DOWN":"RIGHT"}function ll(e,t){return{"elk.algorithm":"layered","elk.direction":W1(t),"elk.edgeRouting":"ORTHOGONAL","elk.spacing.nodeNode":String(e.nodeGap),"elk.layered.spacing.nodeNodeBetweenLayers":String(e.layerGap),"elk.layered.spacing.edgeNodeBetweenLayers":String(e.edgeLabelBuffer),"elk.layered.layering.strategy":"NETWORK_SIMPLEX","elk.layered.nodePlacement.strategy":"NETWORK_SIMPLEX","elk.layered.crossingMinimization.strategy":"LAYER_SWEEP","elk.layered.considerModelOrder.strategy":"NODES_AND_EDGES","elk.layered.cycleBreaking.strategy":"GREEDY","elk.layered.mergeEdges":"false","elk.randomSeed":"1"}}const O1=ll(Cn,"LR");ll(xr,"LR");function U1(e){const t=e.nodes.length;if(t<8)return"LR";const n=new Map;for(const o of e.edges)n.set(o.source,(n.get(o.source)??0)+1);let r=0;for(const o of n.values())o>r&&(r=o);return r>=Math.max(6,Math.floor(t/2))?"TB":"LR"}const G1=new Nm;function ur(e,t=!1){const n=t?xr:Cn;return e.type==="submoduleNode"?n.submoduleCardWidth:n.worktreeCardWidth}function Qr(e){var n;if(e.type==="defaultBranchNode")return e.nextStepHint||"Default branch anchor";if(e.type==="submoduleNode"){const r=[e.machineLabel?`parent ${e.machineLabel}`:null];return e.outOfSync?r.push("out of sync"):e.dirty?r.push("local changes"):r.push("synced"),r.filter(Boolean).join(" · ")}const t=[];if(e.upstream&&t.push(e.upstream),e.upstream&&e.upstreamStatus!=="fresh")t.push("upstream unverified");else{const r=bp(e);r&&t.push(r)}return e.activeSessionCount>0&&t.push(`${e.activeSessionCount} session${e.activeSessionCount===1?"":"s"}`),e.dirtyFiles>0&&t.push(`${e.dirtyFiles} dirty`),e.hasConflicts&&t.push("conflicts"),t.length===0?(n=e.branchConvergence)!=null&&n.needsConvergence?"Needs follow-up":"Clean and even with upstream":t.join(" · ")}function yp(e,t=!1){const n=t?xr:Cn,r=ur(e,t),o=t?e.type==="submoduleNode"?20:22:e.type==="submoduleNode"?24:30,a=t?(e.type==="submoduleNode",2):e.type==="submoduleNode"?2:3,i=Math.ceil(K1(e)/a),c=Br(e.label,o,2),u=Br(e.type==="submoduleNode"?e.submodulePath:e.machineLabel||e.workspace,o,2),h=Br(Qr(e),o+(t?1:4),t?2:3),d=al(e),m=gp(e)?il(e):null,f=t?0:Br(m,Math.max(24,Math.floor(r/8)),4),x=t?40+c*16+u*12+(d?22:0)+Math.max(0,i-1)*18+Math.max(18,h*16):52+c*18+u*14+(d?30:0)+i*24+Math.max(22,h*18)+(f>0?22+f*16:0),w=e.type==="submoduleNode"?n.minSubmoduleCardHeight:n.minWorktreeCardHeight;return Math.min(n.maxEstimatedCardHeight,Math.max(w,Math.ceil(x)))}function Br(e,t,n){const r=(e||"").trim();return r?Math.max(1,Math.min(n,Math.ceil(r.length/t))):0}function K1(e){let t=1;return e.type==="submoduleNode"&&(t+=1),e.branch&&e.type!=="submoduleNode"&&(t+=1),e.submoduleCommit&&e.type==="submoduleNode"&&(t+=1),e.dirty&&(t+=1),e.outOfSync&&(t+=1),e.hasConflicts&&(t+=1),e.type!=="submoduleNode"&&e.upstream&&e.upstreamStatus!=="fresh"&&(t+=1),e.isOrphan&&(t+=1),t}function z1(e,t){return e.type==="defaultBranchNode"&&t.type!=="defaultBranchNode"?-1:t.type==="defaultBranchNode"&&e.type!=="defaultBranchNode"||e.type==="submoduleNode"&&t.type!=="submoduleNode"?1:t.type==="submoduleNode"&&e.type!=="submoduleNode"?-1:e.branch&&t.branch&&e.branch!==t.branch?e.branch.localeCompare(t.branch):e.branch&&!t.branch?-1:!e.branch&&t.branch?1:e.label.localeCompare(t.label)||e.id.localeCompare(t.id)}function q1(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.id.localeCompare(t.id)}function V1(e,t,n,r=!0){return{id:e.id,type:"meshNode",position:{x:t,y:n},graphNode:e,selected:!1,draggable:!1,selectable:r}}function Y1(e,t,n){return{id:e.id,x:t,y:n,width:ur(e),height:yp(e)}}function J1(e,t){return{id:`${e.id}__placeholder`,type:"worktreeNode",label:"No active worktrees",workspace:t.repoIdentity,branch:e.branch,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:null,locality:"unknown",connectionTransport:null,connectionState:null,connectionReason:null,connectionReported:!1,connectionRttMs:null,health:"unknown",ahead:0,behind:0,dirty:!1,dirtyFiles:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],sessionDetails:[],providers:[],isOrphan:!1,orphanReasons:[],nextStepHint:"Waiting for worktree nodes to report live mesh status.",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{nodeId:`${e.id}__placeholder`,machineLabel:"",workspace:t.repoIdentity,health:"unknown",providers:[],activeSessions:[]}}}function vp(e){const t=[...e.nodes].sort(z1),n=t.find(o=>o.type==="defaultBranchNode")??null,r=t.some(o=>o.id!==(n==null?void 0:n.id)&&o.type!=="submoduleNode");return!n||r?t:[...t,J1(n,e)]}function Q1(e,t=O1,n=!1,r="LR"){const o=vp(e),a=new Set(o.map(u=>u.id)),i=o.map(u=>({id:u.id,width:ur(u,n),height:yp(u,n)})),c=e.edges.filter(u=>a.has(u.source)&&a.has(u.target)).sort(q1).map(u=>({id:u.id,sources:[u.source],targets:[u.target]}));return{id:`${e.meshId||"mesh"}__elk_root`,layoutOptions:{...t},children:i,edges:c}}function X1(e,t=!1){const n=[...new Set(e.map(o=>Math.round(o.x)))].sort((o,a)=>o-a),r=t?xr.layerGap:Cn.layerGap;return n.length<2?r:Math.min(...n.slice(1).map((o,a)=>o-n[a]))}async function wp(e,t=!1,n="LR",r){var w,p;const a=ll(t?xr:Cn,n),i=vp(e),c=new Map(i.map(y=>[y.id,y])),u=Q1(e,a,t,n);if(r&&r.size>0)for(const y of u.children??[]){const k=r.get(y.id);k&&k>0&&(y.height=k)}const h=await G1.layout(u),d=(h.children??[]).map(y=>{const k=c.get(y.id);return k?V1(k,Math.round(y.x??0),Math.round(y.y??Cn.placeholderTopOffset),!y.id.endsWith("__placeholder")):null}).filter(Boolean),m=new Map(i.map((y,k)=>[y.id,k]));d.sort((y,k)=>(m.get(y.id)??0)-(m.get(k.id)??0));const f=d.map(y=>Y1(y.graphNode,y.position.x,y.position.y)),x=new Map;for(const y of h.edges??[]){const k=y.sections;if(!k||k.length===0)continue;const b=k[0],j=(w=y.sources)==null?void 0:w[0],S=(p=y.targets)==null?void 0:p[0];if(!j||!S)continue;const v=[];v.push({x:Math.round(b.startPoint.x),y:Math.round(b.startPoint.y)});for(const g of b.bendPoints??[])v.push({x:Math.round(g.x),y:Math.round(g.y)});v.push({x:Math.round(b.endPoint.x),y:Math.round(b.endPoint.y)}),x.set(y.id,{id:y.id,source:j,target:S,points:v})}return{nodes:d,bounds:f,edgeRoutes:x,columnGap:X1(f,t),layoutOptions:{...a}}}function Z1(e){var t,n;return[e.id,e.type,e.label,e.branch??"",e.upstream??"",e.upstreamStatus??"",e.daemonId??"",e.machineId??"",e.machineLabel??"",e.locality,e.health,e.ahead,e.behind,e.dirty?1:0,e.dirtyFiles,e.hasConflicts?1:0,e.activeSessionCount,e.sessionDetails.map(r=>[r.sessionId,r.providerType??"",r.state??"",r.chatStatus??"",r.lifecycle??"",r.role??"",r.isSelfCoordinator?1:0,r.statusNote??"",r.startedAt??"",r.createdAt??""].join("/")).join(","),e.isOrphan?1:0,e.outOfSync?1:0,e.snapshotCompleteness,((t=e.branchConvergence)==null?void 0:t.status)??"",(n=e.branchConvergence)!=null&&n.needsConvergence?1:0,e.nextStepHint??"",e.error??"",e.parentNodeId??"",e.submodulePath??"",e.submoduleCommit??""].join("|")}function kp(e){return[e.id,e.source,e.target,e.type,e.label??"",e.direction].join("|")}function ej(e){return[e.meshId,e.refreshedAt,e.nodes.length,e.edges.length,...e.nodes.map(Z1),...e.edges.map(kp)].join("::")}function tj(e){return[e.meshId,e.nodes.length,e.edges.length,...e.nodes.map(t=>{var n,r;return[t.id,t.type,t.label,t.branch??"",t.machineLabel??"",t.locality,t.health,t.dirty?1:0,t.dirtyFiles,t.hasConflicts?1:0,t.activeSessionCount,t.isOrphan?1:0,t.outOfSync?1:0,t.snapshotCompleteness,((n=t.branchConvergence)==null?void 0:n.status)??"",(r=t.branchConvergence)!=null&&r.needsConvergence?1:0,t.nextStepHint??"",t.parentNodeId??"",t.submodulePath??"",t.submoduleCommit??""].join("|")}),...e.edges.map(kp)].join("::")}const sj=5*60*1e3;function Sp(e){return typeof e.daemonId=="string"&&e.daemonId.trim()?e.daemonId.trim():null}function Cp(e){return typeof e.machineId=="string"&&e.machineId.trim()?e.machineId.trim():null}function nj(e){var t,n,r;return((t=e.connection)==null?void 0:t.state)==="self"||e.isLocalWorktree===!0?"local":((n=e.connection)==null?void 0:n.transport)==="direct"||((r=e.connection)==null?void 0:r.transport)==="relay"||Sp(e)||Cp(e)?"remote":"unknown"}function rj(e){const t=e.connection;if(!t)return{connectionTransport:null,connectionState:null,connectionReason:null,connectionReported:!1,connectionRttMs:null};const n=t.rttMs,r=typeof n=="number"&&Number.isFinite(n)&&n>=0?n:null;return{connectionTransport:t.transport??null,connectionState:t.state??null,connectionReason:typeof t.reason=="string"&&t.reason.trim()?t.reason.trim():null,connectionReported:t.reported===!0,connectionRttMs:r}}function jp(e){const t=e.connectionTransport;if(t==="direct"||t==="relay"||t==="local")return t;const n=e.connectionState;return n==="connecting"?"connecting":n==="disconnected"?"disconnected":n==="failed"?"failed":n==="closed"?"closed":null}function oj(e){if(e.connectionTransport==="local"||e.connectionState==="self")return null;const t=jp(e);return!t||t==="local"||typeof e.connectionRttMs!="number"||!Number.isFinite(e.connectionRttMs)?null:`${Math.round(e.connectionRttMs)}ms`}function aj(e){return Fi(e)}function Np(e){var t;return aj(e)?!1:!!(e.gitProbePending||((t=e.connection)==null?void 0:t.state)==="connecting")}function Ap(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function ij(e){return e.activeSessionDetails&&e.activeSessionDetails.length>0?e.activeSessionDetails:(e.activeSessions??[]).map(t=>({sessionId:t,workspace:e.workspace,isCached:!0}))}function Tp(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function Ip(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.dirty)}function cl(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.outOfSync||!!t.error)}function lj(e){return cl(e)?"degraded":Ip(e)?"dirty":"online"}function cj(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function Qc(e){switch(e){case"online":return 0;case"dirty":return 1;case"degraded":return 2;case"wrong_branch":return 3;case"offline":return 4;case"unknown":default:return 5}}function Sa(e){return e.length===0?"unknown":e.reduce((t,n)=>Qc(n)>Qc(t)?n:t)}function dj(e){var a,i,c,u,h;const t=new Map,n=new Map;for(const d of e){const m=(i=(a=d.git)==null?void 0:a.branch)==null?void 0:i.trim();m&&(n.set(m,(n.get(m)??0)+1),(c=d.git)!=null&&c.upstream&&t.set(m,(t.get(m)??0)+1))}const r=[...t.entries()].sort((d,m)=>{if(m[1]!==d[1])return m[1]-d[1];const f=["main","master","develop","dev"],x=f.indexOf(d[0]),w=f.indexOf(m[0]);return x!==-1||w!==-1?x===-1?1:w===-1?-1:x-w:d[0].localeCompare(m[0])});return(u=r[0])!=null&&u[0]?r[0][0]:((h=[...n.entries()].sort((d,m)=>m[1]-d[1])[0])==null?void 0:h[0])??null}function uj(e,t){const n=[],r=e.git;return r?r.isGitRepo?(!r.branch&&r.headCommit&&n.push("Detached HEAD"),r.hasConflicts&&n.push("Merge conflicts need resolution"),r.branch&&t&&r.branch!==t&&!r.upstream&&n.push(`No upstream tracking for ${r.branch}`),r.upstream&&r.upstreamStatus&&r.upstreamStatus!=="fresh"&&n.push(`Upstream freshness unverified for ${r.branch??"workspace"}`),e.error&&n.push(e.error),n):(n.push("Not a git repository"),n):(n.push("No git status available"),n)}function Xc(e){switch(e){case"merged_to_main":return 0;case"pushed_feature_branch_needs_merge":return 1;case"cleanup_candidate":return 2;case"blocked_review":return 3;case"not_mergeable":default:return 4}}function hj(e){return e.reduce((t,n)=>Xc(n.status)>Xc(t.status)?n:t)}function pj(e){const t=e.branchConvergenceSummary;if(Array.isArray(t==null?void 0:t.followUps))return t.followUps;const n=e.followUps;return Array.isArray(n)?n:(t==null?void 0:t.needsFollowUp)===!1||(t==null?void 0:t.unresolvedCount)===0?[]:null}function mj(e){var o,a,i;const t=e.sourceOfTruth,n=[],r=(o=t==null?void 0:t.fallback)==null?void 0:o.warning;return typeof r=="string"&&r.trim()&&n.push(r.trim()),(t==null?void 0:t.currentStatus)==="bootstrap_inventory_fallback"&&((a=t.directPeerTruth)==null?void 0:a.required)===!0&&((i=t.directPeerTruth)==null?void 0:i.satisfied)!==!0&&!n.some(c=>c.includes("direct mesh truth"))&&n.push("Direct mesh truth is not confirmed yet; this graph is drawn from setup inventory only."),n}function fj(e){const t=e.asyncRefineJobs;if(!Array.isArray(t))return[];const n=[];for(const r of t){if(!r||typeof r!="object")continue;const o=r,a=typeof o.jobId=="string"?o.jobId:null,i=o.status;a&&(i!=="accepted"&&i!=="running"&&i!=="completed"&&i!=="failed"||n.push({jobId:a,status:i,nodeId:typeof o.nodeId=="string"?o.nodeId:void 0,targetNodeId:typeof o.targetNodeId=="string"?o.targetNodeId:void 0,workspace:typeof o.workspace=="string"?o.workspace:void 0,branch:typeof o.branch=="string"?o.branch:void 0,into:typeof o.into=="string"?o.into:void 0,lastUpdatedAt:typeof o.lastUpdatedAt=="string"?o.lastUpdatedAt:void 0,startedAt:typeof o.startedAt=="string"?o.startedAt:void 0,completedAt:typeof o.completedAt=="string"?o.completedAt:void 0}))}return n}function Zc(e){switch(e){case"running":case"accepted":return 0;case"failed":return 1;case"completed":default:return 2}}function ed(e){const t=e.lastUpdatedAt||e.completedAt||e.startedAt||"";return Ap(t)??0}function bj(e){return e.length===0?null:e.reduce((t,n)=>{const r=Zc(t.status),o=Zc(n.status);return o!==r?o<r?n:t:ed(n)>ed(t)?n:t})}function gj(e){var n,r;const t=new Map;for(const o of e){const a=((n=o.nodeId)==null?void 0:n.trim())||((r=o.targetNodeId)==null?void 0:r.trim());if(!a)continue;const i=t.get(a)??[];i.push(o),t.set(a,i)}return t}function xj(e,t){return e.type!=="submoduleNode"&&e.branch===t&&e.ahead===0&&e.behind===0&&!e.dirty&&!e.hasConflicts&&(!e.upstreamStatus||e.upstreamStatus==="fresh")&&e.snapshotCompleteness==="complete"}function yj(e,t){var n,r;return{status:"merged_to_main",needsConvergence:!1,reason:"clean_default_branch_aggregate",nextStep:null,branch:e,defaultBranch:e,upstream:((n=t.find(o=>o.upstream))==null?void 0:n.upstream)??null,upstreamStatus:((r=t.find(o=>o.upstreamStatus))==null?void 0:r.upstreamStatus)??null,ahead:0,behind:0,dirty:!1,hasConflicts:!1}}function vj(e,t){if(Np(e))return null;const n=e.branchConvergence;if(!n||typeof n!="object")return null;const r=n.status;if(!r||!["merged_to_main","pushed_feature_branch_needs_merge","blocked_review","cleanup_candidate","not_mergeable"].includes(r))return null;const o=e.git,a=Tp(o)||Ip(o),i=!!(o!=null&&o.hasConflicts)||cl(o),c=(o==null?void 0:o.ahead)??0,u=(o==null?void 0:o.behind)??0,h=(o==null?void 0:o.branch)??null,d=(o==null?void 0:o.upstream)??null,m=(o==null?void 0:o.upstreamStatus)??null,f=n.defaultBranch??t??null;return{status:r,needsConvergence:n.needsConvergence??r!=="merged_to_main",reason:n.reason??"provided_by_coordinator",nextStep:n.nextStep??null,branch:n.branch??h,defaultBranch:f,upstream:n.upstream??d,upstreamStatus:n.upstreamStatus??m,ahead:n.ahead??c,behind:n.behind??u,dirty:n.dirty??a,hasConflicts:n.hasConflicts??i}}function wj(e,t){const n=vj(e,t);return n?{...n,defaultBranch:n.defaultBranch??t}:null}function kj(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function Sj(e){var u,h,d;const{nodeStatus:t,expectedSubmodulePaths:n,refreshedAtMs:r}=e,o=[],a=t.machineLabel||t.nodeId,i=t.git;if(!i){if(Np(t))return o.push(`${a} is still waiting for a live peer git snapshot from the selected coordinator.`),{snapshotCompleteness:"pending_git",snapshotWarnings:o};const m=t.health==="online"||t.machineStatus==="online"||((u=t.connection)==null?void 0:u.state)==="connected"||((h=t.connection)==null?void 0:h.state)==="self";return o.push(m?`${a} is online but no peer git snapshot is visible yet.`:`${a} has no peer git snapshot visible yet.`),{snapshotCompleteness:"missing_git",snapshotWarnings:o}}const c=new Set((i.submodules??[]).map(m=>m.path));if(n.size>0){const m=[...n].filter(f=>!c.has(f));m.length>0&&o.push(`${a} is missing submodule visibility for ${m.join(", ")} even though another peer reported it.`)}return((d=t.connection)==null?void 0:d.state)!=="self"&&r!==null&&typeof i.lastCheckedAt=="number"&&r-i.lastCheckedAt>sj&&o.push(`${a} is relying on a peer git snapshot older than 5m; re-probe before trusting convergence.`),o.some(m=>m.includes("submodule visibility"))?{snapshotCompleteness:"missing_submodule_report",snapshotWarnings:o}:o.some(m=>m.includes("older than 5m"))?{snapshotCompleteness:"stale",snapshotWarnings:o}:{snapshotCompleteness:"complete",snapshotWarnings:o}}function Mp(e){const t=Mu(e),r=(typeof t.defaultBranch=="string"&&t.defaultBranch.trim().length>0?t.defaultBranch.trim():null)??dj(t.nodes),o=Ap(t.refreshedAt),a=new Set(t.nodes.flatMap(F=>{var R;return(((R=F.git)==null?void 0:R.submodules)??[]).map(Q=>Q.path)})),i=[],c=[],u=mj(t),h=new Map,d=gj(fj(t));for(const F of t.nodes){const R=F.git,Q=(R==null?void 0:R.branch)??null,E=lj(R),I=Tp(R)||E==="dirty",$=uj(F,r),D=wj(F,r),U=Sj({nodeStatus:F,expectedSubmodulePaths:a,refreshedAtMs:o}),Y=typeof F.clonedFromNodeId=="string"?F.clonedFromNodeId:null,ae=ij(F),z=bj(d.get(F.nodeId)??[]),X=rj(F),de={id:F.nodeId,type:$.length>0?"orphanNode":"worktreeNode",label:F.machineLabel||F.nodeId.slice(0,8),workspace:F.workspace,branch:Q,upstream:(R==null?void 0:R.upstream)??null,upstreamStatus:(R==null?void 0:R.upstreamStatus)??null,daemonId:Sp(F),machineId:Cp(F),machineLabel:F.machineLabel||null,locality:nj(F),connectionTransport:X.connectionTransport,connectionState:X.connectionState,connectionReason:X.connectionReason,connectionReported:X.connectionReported,connectionRttMs:X.connectionRttMs,health:Sa([F.health,E]),ahead:(R==null?void 0:R.ahead)??0,behind:(R==null?void 0:R.behind)??0,dirty:I,dirtyFiles:cj(R),hasConflicts:(R==null?void 0:R.hasConflicts)??!1,activeSessionCount:ae.length,activeSessions:ae.map(re=>re.sessionId),sessionDetails:ae,providers:F.providers??[],isOrphan:$.length>0,orphanReasons:$,error:F.error,nextStepHint:U.snapshotWarnings[0]??$[0]??(D==null?void 0:D.nextStep)??void 0,parentNodeId:null,clonedFromNodeId:Y,worktreeBranch:F.worktreeBranch??null,submodulePath:null,submoduleCommit:(R==null?void 0:R.headCommit)??null,outOfSync:cl(R),snapshotCompleteness:U.snapshotCompleteness,snapshotWarnings:U.snapshotWarnings,branchConvergence:D,refineJobStatus:(z==null?void 0:z.status)??null,refineJobId:(z==null?void 0:z.jobId)??null,refineJobBranch:(z==null?void 0:z.branch)??null,refineJobInto:(z==null?void 0:z.into)??null,source:F};if(i.push(de),Q){const re=h.get(Q)??[];re.push(de.id),h.set(Q,re)}for(const re of(R==null?void 0:R.submodules)??[]){const W=`${de.id}::submodule::${re.path}`,oe=re.path.split("/").filter(Boolean).pop()||re.path;i.push({id:W,type:"submoduleNode",label:oe,workspace:re.repoPath,branch:null,upstream:null,upstreamStatus:null,daemonId:de.daemonId,machineId:de.machineId,machineLabel:de.machineLabel,locality:de.locality,connectionTransport:de.connectionTransport,connectionState:de.connectionState,connectionReason:de.connectionReason,connectionReported:de.connectionReported,connectionRttMs:de.connectionRttMs,health:kj(re),ahead:0,behind:0,dirty:re.dirty,dirtyFiles:re.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],sessionDetails:[],providers:[],isOrphan:!1,orphanReasons:[],error:re.error,nextStepHint:re.error||(re.outOfSync?`${re.path} is out of sync with the parent checkout`:re.dirty?`${re.path} has local changes`:`${re.path} is in sync with the parent checkout`),parentNodeId:de.id,submodulePath:re.path,submoduleCommit:re.commit,outOfSync:re.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:de.id,parentWorkspace:F.workspace,submodule:re}}),c.push({id:`${de.id}--${W}`,source:de.id,target:W,type:"submoduleLink",label:re.outOfSync?"submodule out of sync":"submodule",direction:"directed"})}}const m=r?`__branch_${r}`:null;if(m&&r){const R=(h.get(r)??[]).map(Y=>i.find(ae=>ae.id===Y)).filter(Boolean),Q=R.map(Y=>Y.branchConvergence).filter(Boolean),E=pj(t),I=R.length>0&&R.every(Y=>xj(Y,r)),$=(E==null?void 0:E.length)===0&&I?yj(r,R):Q.length>0?hj(Q):null,D=(E==null?void 0:E.length)===0&&I?0:Q.filter(Y=>Y.needsConvergence).length,U={id:m,type:"defaultBranchNode",label:r,workspace:t.repoIdentity,branch:r,upstream:null,upstreamStatus:null,daemonId:null,machineId:null,machineLabel:"default branch",locality:"unknown",connectionTransport:null,connectionState:null,connectionReason:null,connectionReported:!1,connectionRttMs:null,health:Sa(R.map(Y=>Y.health)),ahead:0,behind:0,dirty:R.some(Y=>Y.dirty),dirtyFiles:R.reduce((Y,ae)=>Y+ae.dirtyFiles,0),hasConflicts:R.some(Y=>Y.hasConflicts),activeSessionCount:R.reduce((Y,ae)=>Y+ae.activeSessionCount,0),activeSessions:R.flatMap(Y=>Y.activeSessions),sessionDetails:R.flatMap(Y=>Y.sessionDetails),providers:[...new Set(R.flatMap(Y=>Y.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:D>0?`${D} workspace(s) on ${r} still need follow-up`:R.length>0?`${R.length} workspace(s) currently on ${r}`:"No workspaces currently checked out to the default branch",error:void 0,parentNodeId:null,submodulePath:null,submoduleCommit:null,outOfSync:!1,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:$,source:{nodeId:m,machineLabel:r,workspace:t.repoIdentity,health:Sa(R.map(Y=>Y.health)),providers:[],activeSessions:[],activeSessionDetails:[]}};i.push(U);for(const Y of i)if(!(Y.id===m||Y.type==="submoduleNode")){if(Y.branch===r){c.push({id:`${m}--${Y.id}`,source:m,target:Y.id,type:"parentBranch",label:"checked out",direction:"undirected"});continue}if(Y.branch){c.push({id:`${m}--${Y.id}`,source:m,target:Y.id,type:Y.isOrphan?"orphanLink":"parentBranch",label:Y.branch,direction:"undirected"});continue}Y.isOrphan&&c.push({id:`${m}--${Y.id}`,source:m,target:Y.id,type:"orphanLink",label:"detached",direction:"undirected"})}}const f=new Set(i.map(F=>F.id)),x=new Set;for(const F of i){if(!F.clonedFromNodeId||F.type==="submoduleNode"||!f.has(F.clonedFromNodeId))continue;const R=`clone_${F.clonedFromNodeId}--${F.id}`;if(x.has(R))continue;x.add(R);const Q=F.worktreeBranch??F.branch??void 0;c.push({id:R,source:F.clonedFromNodeId,target:F.id,type:"cloneLink",label:Q?`cloned · ${Q}`:"cloned",direction:"directed"})}const w=i.filter(F=>F.type!=="defaultBranchNode"),p=w.filter(F=>F.isOrphan).length,y=w.filter(F=>F.hasConflicts).length,k=w.filter(F=>F.health==="offline").length,b=w.filter(F=>F.type==="submoduleNode"&&F.outOfSync).length,j=w.filter(F=>{var R;return F.type!=="submoduleNode"&&((R=F.branchConvergence)==null?void 0:R.needsConvergence)}).length,S=w.filter(F=>{var R;return((R=F.branchConvergence)==null?void 0:R.status)==="blocked_review"}).length,v=w.filter(F=>{var R;return((R=F.branchConvergence)==null?void 0:R.status)==="pushed_feature_branch_needs_merge"}).length,g=w.filter(F=>{var R;return((R=F.branchConvergence)==null?void 0:R.status)==="cleanup_candidate"}).length,N=w.filter(F=>{var R;return((R=F.branchConvergence)==null?void 0:R.status)==="not_mergeable"}).length,C=w.filter(F=>F.snapshotWarnings.length>0).length,A=w.filter(F=>F.snapshotCompleteness==="pending_git").length,T=w.filter(F=>F.snapshotCompleteness==="missing_git").length,M=w.filter(F=>F.snapshotCompleteness==="missing_submodule_report").length,L=w.filter(F=>F.snapshotCompleteness==="stale").length,P=w.filter(F=>F.refineJobStatus==="running"||F.refineJobStatus==="accepted").length,B=w.filter(F=>F.refineJobStatus==="failed").length,K=[A>0?`${A} node(s) are still waiting for a live peer git snapshot`:null,T>0?`${T} node(s) have no visible peer git snapshot`:null,M>0?`${M} node(s) are missing peer submodule visibility reported elsewhere in the mesh`:null,L>0?`${L} node(s) rely on peer git snapshots older than 5m`:null].filter(Boolean);return j>0&&u.push(`${j} workspace(s) still need follow-up before the mesh is converged`),p>0&&u.push(`${p} workspace(s) need attention before safe coordination`),S>0&&u.push(`${S} workspace(s) are blocked on branch convergence or upstream sync`),v>0&&u.push(`${v} clean feature branch workspace(s) still need merge follow-up`),g>0&&u.push(`${g} worktree workspace(s) are ready for refine / cleanup`),N>0&&u.push(`${N} workspace(s) have local changes or conflicts blocking convergence`),y>0&&u.push(`${y} workspace(s) report merge conflicts`),k>0&&u.push(`${k} node(s) are currently offline`),b>0&&u.push(`${b} submodule(s) are out of sync with their parent checkout`),u.push(...K),r||u.push("Could not infer a default branch from live mesh status"),{meshId:t.meshId,meshName:t.meshName,repoIdentity:t.repoIdentity,refreshedAt:t.refreshedAt,nodes:i,edges:c,stats:{totalNodes:w.length,onlineNodes:w.filter(F=>F.health==="online").length,dirtyNodes:w.filter(F=>F.dirty).length,orphanNodes:p,errorNodes:w.filter(F=>!!F.error||F.outOfSync).length,offlineNodes:k,followUpNodes:j,blockedReviewNodes:S,mergeReadyNodes:v,cleanupCandidateNodes:g,notMergeableNodes:N,incompleteSnapshotNodes:C,pendingGitSnapshotNodes:A,missingGitSnapshotNodes:T,missingSubmoduleSnapshotNodes:M,staleGitSnapshotNodes:L,activeRefineNodes:P,failedRefineNodes:B,totalActiveSessions:w.reduce((F,R)=>F+R.activeSessionCount,0)},warnings:u,snapshotWarnings:K}}function Cj(e){return!e.nodes.some(t=>t.snapshotCompleteness==="pending_git"||t.snapshotCompleteness==="missing_git"||t.snapshotCompleteness==="missing_submodule_report")}const jj=7,Nj=640,dl=l.createContext(Rs("dark")),Dp=l.createContext(!1),Pp=l.createContext("LR"),Lp={overflowWrap:"anywhere",wordBreak:"break-word"},Aj={...Lp,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:3,overflow:"hidden"},Tj={...Lp,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:4,overflow:"hidden"};function Rp(e){return e.activeSessionCount>0}function Ij(e){return e.health==="offline"||e.snapshotCompleteness==="stale"&&e.activeSessionCount===0}function td(e,t,n){const r=Rp(e),o=Ij(e);let a;t?a="border-cyan-400/70 shadow-[0_0_0_1px_rgba(34,211,238,0.35),0_24px_60px_rgba(8,145,178,0.18)]":r?a=n?"border-emerald-400/40 shadow-[0_0_0_1px_rgba(52,211,153,0.18),0_18px_48px_rgba(3,7,18,0.22)]":"border-emerald-400/60 shadow-[0_0_0_1px_rgba(52,211,153,0.2),0_18px_48px_rgba(148,163,184,0.20)]":o?a=n?"border-white/6 shadow-[0_12px_32px_rgba(3,7,18,0.16)] opacity-60":"border-slate-200/70 shadow-[0_12px_32px_rgba(148,163,184,0.14)] opacity-60":a=n?"border-white/10 shadow-[0_18px_48px_rgba(3,7,18,0.22)]":"border-slate-300/90 shadow-[0_18px_48px_rgba(148,163,184,0.20)]";const i=al(e);if((i==null?void 0:i.tone)==="danger")return`${a} ${n?"bg-rose-500/12":"bg-rose-50/95"}`;if((i==null?void 0:i.tone)==="warn")return`${a} ${n?"bg-amber-500/10":"bg-amber-50/95"}`;if((i==null?void 0:i.tone)==="info")return`${a} ${n?"bg-violet-500/10":"bg-violet-50/95"}`;switch(e.health){case"online":return`${a} ${n?r?"bg-emerald-500/10":"bg-emerald-500/8":r?"bg-emerald-50":"bg-emerald-50/95"}`;case"dirty":return`${a} ${n?"bg-amber-500/8":"bg-amber-50/95"}`;case"degraded":return`${a} ${n?"bg-rose-500/10":"bg-rose-50/95"}`;case"wrong_branch":return`${a} ${n?"bg-violet-500/10":"bg-violet-50/95"}`;case"offline":return`${a} ${n?"bg-slate-500/10":"bg-slate-100/90"}`;default:return`${a} ${n?"bg-slate-950/78":"bg-white/96"}`}}function Lt(e,t){switch(e){case"refineDone":return t?"border-emerald-400/25 bg-emerald-500/10 text-emerald-200":"border-emerald-300 bg-emerald-50 text-emerald-700";case"health":return t?"border-white/10 bg-slate-950/60 text-slate-200":"border-slate-300 bg-white/95 text-slate-700";case"dirty":return t?"border-amber-400/25 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700";case"conflict":return t?"border-rose-400/25 bg-rose-500/10 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700";case"orphan":return t?"border-fuchsia-400/25 bg-fuchsia-500/10 text-fuchsia-200":"border-fuchsia-300 bg-fuchsia-50 text-fuchsia-700";case"submodule":return t?"border-violet-400/25 bg-violet-500/10 text-violet-200":"border-violet-300 bg-violet-50 text-violet-700";case"meta":default:return t?"border-cyan-400/20 bg-cyan-500/8 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700"}}function sd(e,t){switch(e){case"danger":return t?"border-rose-400/35 bg-rose-500/14 text-rose-50":"border-rose-300 bg-rose-50 text-rose-700";case"warn":return t?"border-amber-400/35 bg-amber-500/14 text-amber-50":"border-amber-300 bg-amber-50 text-amber-700";case"info":return t?"border-violet-400/35 bg-violet-500/14 text-violet-50":"border-violet-300 bg-violet-50 text-violet-700";case"good":default:return t?"border-emerald-400/35 bg-emerald-500/12 text-emerald-50":"border-emerald-300 bg-emerald-50 text-emerald-700"}}function nd(e){switch(e){case"online":return"#34d399";case"dirty":return"#fbbf24";case"degraded":return"#fb7185";case"wrong_branch":return"#a78bfa";case"offline":return"#94a3b8";default:return"#64748b"}}function Mj(e){return e.replace(/_/g," ")}function hs(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const n=t.toLowerCase().replace(/[\s-]+/g,"_");return n.includes("approval")?"awaiting approval":n.includes("generating")||n.includes("running")||n.includes("busy")?"generating":n.includes("failed")||n.includes("stopped")||n.includes("interrupted")?n.replace(/_/g," "):n.includes("idle")||n.includes("ready")||n.includes("waiting_input")?"idle":n.replace(/_/g," ")}function Dj(e){var t;return((t=e.sessionDetails)==null?void 0:t.some(n=>hs(n)==="generating"))??!1}function Ca(e,t){const n=hs(e);return n.includes("approval")?t?"border-amber-400/30 bg-amber-500/12 text-amber-100":"border-amber-300 bg-amber-50 text-amber-700":n==="generating"?t?"border-cyan-400/30 bg-cyan-500/12 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700":n==="idle"?t?"border-emerald-400/30 bg-emerald-500/12 text-emerald-100":"border-emerald-300 bg-emerald-50 text-emerald-700":n.includes("failed")||n.includes("stopped")||n.includes("interrupted")?t?"border-rose-400/30 bg-rose-500/12 text-rose-100":"border-rose-300 bg-rose-50 text-rose-700":Lt("health",t)}function Pj(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function rd(e){const t=Pj(e);if(t===null)return"runtime age not reported";const n=Math.max(0,Math.floor((Date.now()-t)/1e3));if(n<60)return`${n}s`;const r=Math.floor(n/60);if(r<60)return`${r}m`;const o=Math.floor(r/60);return o<48?`${o}h ${r%60}m`:`${Math.floor(o/24)}d ${o%24}h`}function ja(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function On(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function Lj(e){if(e.sessionDetails.length===0)return null;const t=e.sessionDetails.filter(a=>hs(a)==="generating").length,n=e.sessionDetails.filter(a=>a.isSelfCoordinator).length,r=e.sessionDetails.length-n,o=[`${e.sessionDetails.length} chat${e.sessionDetails.length===1?"":"s"}`];return t>0&&o.push(`${t} generating`),n>0&&o.push(n===1?"coordinator attached":`${n} coordinators`),r>0&&o.push(`${r} worker${r===1?"":"s"}`),t===0&&n>0&&o.push("sampled status"),o.join(" · ")}function od(e){return e==="local"?"local":e==="remote"?"remote":"machine unknown"}function Rj(e){return e.locality==="remote"?"meta":"health"}function Ej({data:e,selected:t}){const{t:n}=Le("common"),r=l.useContext(dl),o=l.useContext(Dp),a=l.useContext(Pp),i=e.graphNode,c=i.type==="defaultBranchNode",u=i.type==="submoduleNode",h=gp(i),d=c?"default branch anchor":u?i.submodulePath||"submodule checkout":[i.machineLabel,od(i.locality)].filter(Boolean).join(" · ")||i.workspace,m=i.submoduleCommit?i.submoduleCommit.slice(0,7):null,f=!u&&!c&&i.connectionState!=="self",x=f?jp(i):null,w=x==="local"?null:x,p=f?oj(i):null,y=al(i),k=il(i),b=Rp(i),j=i.sessionDetails,S=i.sessionDetails,v=Lj(i),g=i.sessionDetails.map(C=>{const A=hs(C),T=C.providerType||"provider unknown",M=On(C),L=C.startedAt||C.createdAt||null,P=C.statusNote?` · ${C.statusNote}`:"";return`Session: ${C.sessionId} · ${T} · ${A} · ${M} · ${rd(L)}${P}`});if(o)return s.jsxs("div",{className:`rounded-xl border px-3 py-2.5 backdrop-blur-sm transition-all ${td(i,t,r.isDark)}`,style:{width:ur(i,!0)},title:[i.label,i.branch?`Branch: ${i.branch}`:null,i.machineLabel?`Machine: ${i.machineLabel}`:null,i.workspace?`Workspace: ${i.workspace}`:null,y?`Status: ${y.label}`:null,Qr(i),...g].filter(Boolean).join(`
82
+ `),children:[s.jsx(vr,{type:"target",position:a==="TB"?Cs.Top:Cs.Left,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}}),s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`truncate text-xs font-semibold leading-4 ${r.textPrimary}`,children:i.label}),!c&&s.jsx("div",{className:`truncate text-[10px] leading-3.5 ${r.textMuted}`,children:d})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[b&&s.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${r.isDark?"bg-emerald-400":"bg-emerald-500"} animate-pulse`,"aria-label":"active session"}),s.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full",style:{backgroundColor:nd(i.health)},"aria-hidden":!0})]})]}),i.health==="unknown"&&!y&&s.jsx("div",{className:`mt-1.5 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[9px] italic ${Lt("health",r.isDark)}`,children:s.jsx("span",{className:"truncate",children:n("meshGraph.obs.connecting")})}),y&&s.jsx("div",{className:`mt-1.5 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[9px] font-semibold uppercase tracking-[0.14em] ${sd(y.tone,r.isDark)}`,title:y.label,children:s.jsx("span",{className:"truncate",children:y.label})}),!y&&i.branch&&!u&&i.health!=="unknown"&&s.jsx("div",{className:`mt-1 min-w-0 max-w-full truncate text-[10px] ${Lt("meta",r.isDark)} rounded-full border px-2 py-0.5 inline-block`,title:i.branch,children:i.branch}),v&&s.jsx("div",{className:`mt-1 min-w-0 max-w-full truncate text-[9px] ${r.isDark?"text-cyan-100/85":"text-sky-700"}`,title:g.join(`
83
+ `),children:v}),S.length>0&&s.jsx("div",{className:"mt-1.5 flex max-h-28 min-w-0 flex-col gap-1 overflow-y-auto pr-1",children:S.map(C=>s.jsxs("div",{className:`min-w-0 rounded-md border px-1.5 py-1 ${r.isDark?"border-cyan-400/15 bg-cyan-500/[0.055]":"border-sky-200 bg-white/80"}`,title:[`Session ID: ${C.sessionId}`,C.providerType?`Provider: ${C.providerType}`:null,`Status: ${hs(C)}`,`Role: ${On(C)}`].filter(Boolean).join(`
84
+ `),children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-1.5",children:[s.jsx("span",{className:`min-w-0 truncate text-[9px] ${r.textMuted}`,children:C.providerType||n("meshGraph.panel.providerUnknown")}),s.jsx("span",{className:`shrink-0 rounded-full border px-1 py-0 text-[8px] font-semibold uppercase tracking-[0.1em] ${Ca(C,r.isDark)}`,children:hs(C)})]}),s.jsxs("div",{className:`mt-0.5 flex min-w-0 items-center gap-1.5 text-[8px] ${r.textMuted}`,children:[s.jsx("span",{className:"min-w-0 truncate font-mono",children:ja(C.sessionId)}),s.jsx("span",{className:"shrink-0",children:On(C)})]})]},C.sessionId))}),s.jsx(vr,{type:"source",position:a==="TB"?Cs.Bottom:Cs.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]});const N=[i.label,d,y?`Status: ${y.label}`:null,Qr(i),i.branch?`Branch: ${i.branch}`:null,i.dirty?u?"Local changes":`${i.dirtyFiles} dirty`:null,i.hasConflicts?"Has conflicts":null,i.outOfSync?"Out of sync":null,!u&&i.upstream&&i.upstreamStatus!=="fresh"?"Upstream unverified":null,i.isOrphan?"Needs follow-up":null,h&&k?`Note: ${k}`:null,...g].filter(Boolean).join(`
85
+ `);return s.jsxs("div",{className:`rounded-2xl border px-4 py-3 backdrop-blur-sm transition-all ${td(i,t,r.isDark)}${Dj(i)?" mesh-node-generating":""}`,style:{width:ur(i)},title:N,children:[s.jsx(vr,{type:"target",position:a==="TB"?Cs.Top:Cs.Left,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}}),s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${r.textPrimary}`,children:i.label}),s.jsx("div",{className:`truncate text-[11px] ${r.textMuted}`,children:d})]}),s.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 shrink-0",children:[b&&s.jsx("span",{className:`h-2 w-2 rounded-full ${r.isDark?"bg-emerald-400":"bg-emerald-500"} animate-pulse`,"aria-label":"active session"}),s.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{backgroundColor:nd(i.health)},"aria-hidden":!0})]})]}),y?s.jsx("div",{className:`mt-2 inline-flex min-w-0 max-w-full items-center rounded-full border px-2.5 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] ${sd(y.tone,r.isDark)}`,title:y.label,children:s.jsx("span",{className:"truncate",children:y.label})}):i.branch&&!u?s.jsx("div",{className:`mt-2 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[10px] ${Lt("meta",r.isDark)}`,title:i.branch,children:s.jsx("span",{className:"truncate",children:i.branch})}):null,v&&s.jsx("div",{className:`mt-2 inline-flex min-w-0 max-w-full items-center rounded-full border px-2 py-0.5 text-[10px] font-medium ${r.isDark?"border-cyan-400/20 bg-cyan-500/8 text-cyan-100":"border-sky-300 bg-sky-50 text-sky-700"}`,title:g.join(`
86
+ `),children:s.jsx("span",{className:"truncate",children:v})}),S.length>0&&s.jsx("div",{className:"mt-2 flex max-h-44 min-w-0 flex-col gap-1.5 overflow-y-auto pr-1",children:S.map(C=>{const A=On(C);return s.jsxs("div",{className:`min-w-0 rounded-lg border px-2.5 py-1.5 ${r.isDark?"border-cyan-400/15 bg-cyan-500/[0.055]":"border-sky-200 bg-white/85"}`,title:[`Session ID: ${C.sessionId}`,C.providerType?`Provider: ${C.providerType}`:null,`Status: ${hs(C)}`,`Role: ${A}`].filter(Boolean).join(`
87
+ `),children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate text-[10px] ${r.textMuted}`,children:C.providerType||"provider unknown"}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${Ca(C,r.isDark)}`,children:hs(C)})]}),s.jsxs("div",{className:`mt-0.5 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[9px] ${r.textMuted}`,children:[s.jsx("span",{className:"min-w-0 truncate font-mono",children:ja(C.sessionId)}),s.jsx("span",{children:A})]})]},C.sessionId)})}),s.jsxs("div",{className:"mt-3",children:[s.jsxs("div",{className:"flex min-w-0 flex-wrap gap-1.5 text-[10px]",children:[i.health==="unknown"?s.jsx("span",{className:`rounded-full border px-2 py-0.5 italic ${Lt("health",r.isDark)}`,children:n("meshGraph.obs.connecting")}):s.jsx("span",{className:`rounded-full border px-2 py-0.5 capitalize ${Lt("health",r.isDark)}`,children:Mj(i.health)}),u&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("submodule",r.isDark)}`,children:n("meshGraph.panel.submoduleBadge")}),!c&&i.health==="unknown"&&!i.locality&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 italic ${Lt("health",r.isDark)}`,children:"..."}),!c&&(i.health!=="unknown"||i.locality)&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt(Rj(i),r.isDark)}`,children:od(i.locality)}),w&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("meta",r.isDark)}`,title:w==="relay"?"P2P link relayed through TURN (slower path)":`P2P transport: ${w}`,children:w}),p&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("meta",r.isDark)}`,title:"P2P round-trip latency",children:p}),m&&u&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("meta",r.isDark)}`,children:m}),i.dirty&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("dirty",r.isDark)}`,children:u?"local changes":`${i.dirtyFiles} dirty`}),i.outOfSync&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("conflict",r.isDark)}`,children:n("meshGraph.panel.outOfSyncBadge")}),i.hasConflicts&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("conflict",r.isDark)}`,children:n("meshGraph.panel.conflictBadge")}),!u&&i.upstream&&i.upstreamStatus!=="fresh"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("orphan",r.isDark)}`,children:n("meshGraph.panel.upstreamUnverified")}),i.isOrphan&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("orphan",r.isDark)}`,children:n("meshGraph.panel.needsFollowUp")}),!u&&i.refineJobStatus==="completed"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("refineDone",r.isDark)}`,title:i.refineJobBranch?`refined ${i.refineJobBranch}${i.refineJobInto?` → ${i.refineJobInto}`:""}`:"refine completed",children:n("meshGraph.panel.refined")})]}),s.jsx("div",{className:`mt-3 text-[11px] leading-5 ${r.textSecondary}`,style:Aj,children:Qr(i)}),j.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[9px] font-semibold uppercase tracking-[0.16em] ${r.textMuted}`,children:n("meshGraph.panel.attachedChats")}),s.jsx("div",{className:"flex max-h-56 flex-col gap-1.5 overflow-y-auto pr-1",children:j.map(C=>{const A=C.startedAt||C.createdAt||null,T=On(C);return s.jsxs("div",{className:`min-w-0 rounded-lg border px-2.5 py-1.5 ${r.isDark?"border-white/8 bg-white/[0.035]":"border-slate-200 bg-white/80"}`,title:[`Session ID: ${C.sessionId}`,C.providerType?`Provider: ${C.providerType}`:null,`Status: ${hs(C)}`,`Role: ${T}`,A?`Started: ${A}`:"Started: not reported",C.statusNote?`Note: ${C.statusNote}`:null].filter(Boolean).join(`
88
+ `),children:[s.jsxs("div",{className:"flex min-w-0 items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate font-mono text-[10px] select-text ${r.textPrimary}`,children:ja(C.sessionId)}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${Ca(C,r.isDark)}`,children:hs(C)})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 text-[9px] ${r.textMuted}`,children:[s.jsx("span",{className:"truncate",children:C.providerType||n("meshGraph.panel.providerUnknown")}),s.jsx("span",{children:T}),s.jsx("span",{children:rd(A)})]}),C.statusNote&&s.jsx("div",{className:`mt-1 text-[9px] leading-4 ${r.textMuted}`,children:C.statusNote})]},C.sessionId)})})]}),h&&k&&s.jsx("div",{className:`mt-3 rounded-xl border px-3 py-2 text-[10px] leading-4 ${r.isDark?"border-cyan-400/15 bg-cyan-500/8 text-cyan-50/90":"border-sky-300 bg-sky-50 text-sky-700"}`,style:Tj,children:k})]}),s.jsx(vr,{type:"source",position:a==="TB"?Cs.Bottom:Cs.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const _j={meshNode:Ej},$j=8;function Bj(e){if(e.length<2)return null;if(e.length===2){const[h,d]=e;return{d:`M ${h.x},${h.y} L ${d.x},${d.y}`,labelX:(h.x+d.x)/2,labelY:(h.y+d.y)/2}}const t=$j,n=[`M ${e[0].x},${e[0].y}`];for(let h=1;h<e.length-1;h+=1){const d=e[h-1],m=e[h],f=e[h+1],x=Math.sign(m.x-d.x),w=Math.sign(m.y-d.y),p=Math.sign(f.x-m.x),y=Math.sign(f.y-m.y),k=Math.hypot(m.x-d.x,m.y-d.y),b=Math.hypot(f.x-m.x,f.y-m.y),j=Math.min(t,k/2,b/2);if(j<1||x===p&&w===y){n.push(`L ${m.x},${m.y}`);continue}const S=m.x-x*j,v=m.y-w*j,g=m.x+p*j,N=m.y+y*j;n.push(`L ${S},${v}`),n.push(`Q ${m.x},${m.y} ${g},${N}`)}const r=e[e.length-1];n.push(`L ${r.x},${r.y}`);let o=0;const a=[0];for(let h=1;h<e.length;h+=1)o+=Math.hypot(e[h].x-e[h-1].x,e[h].y-e[h-1].y),a.push(o);const i=o/2;let c=e[0].x,u=e[0].y;for(let h=1;h<e.length;h+=1)if(a[h]>=i){const d=a[h]-a[h-1],m=d===0?0:(i-a[h-1])/d;c=e[h-1].x+(e[h].x-e[h-1].x)*m,u=e[h-1].y+(e[h].y-e[h-1].y)*m;break}return{d:n.join(" "),labelX:c,labelY:u}}function Fj(e){const t=e.data.routePoints;if(t&&t.length>=2){const a=Bj(t);if(a)return[a.d,a.labelX,a.labelY]}const n={sourceX:e.sourceX,sourceY:e.sourceY,sourcePosition:e.sourcePosition,targetX:e.targetX,targetY:e.targetY,targetPosition:e.targetPosition},r=e.data.graphEdge;let o;return r.type==="parentBranch"?o=Fm(n):r.type==="worktreeLink"||r.type==="submoduleLink"||r.type==="cloneLink"?o=$m(n):o=Bm(n),[o[0],o[1],o[2]]}function Hj(e,t){const n="nodrag nopan rounded-md border px-2 py-1 text-[10px] font-semibold shadow-sm backdrop-blur-sm";switch(e.type){case"orphanLink":return t?`${n} border-orange-400/35 bg-orange-500/14 text-orange-100`:`${n} border-orange-300 bg-orange-50 text-orange-700`;case"submoduleLink":return t?`${n} border-violet-400/30 bg-violet-500/14 text-violet-100`:`${n} border-violet-300 bg-violet-50 text-violet-700`;case"sessionLink":return t?`${n} border-emerald-400/30 bg-emerald-500/14 text-emerald-100`:`${n} border-emerald-300 bg-emerald-50 text-emerald-700`;case"cloneLink":return t?`${n} border-teal-400/30 bg-teal-500/14 text-teal-100`:`${n} border-teal-300 bg-teal-50 text-teal-700`;default:return t?`${n} border-sky-400/25 bg-slate-950/78 text-sky-100`:`${n} border-sky-300 bg-white/95 text-sky-700`}}function Wj(e){const t=l.useContext(dl),n=e.data.graphEdge,[r,o,a]=Fj(e),i=typeof e.label=="string"?e.label:void 0;return s.jsxs(s.Fragment,{children:[s.jsx(Pm,{id:e.id,path:r,markerEnd:e.markerEnd,style:e.style,interactionWidth:24}),e.label&&s.jsx(Lm,{children:s.jsx("div",{className:Hj(n,t.isDark),title:i,style:{position:"absolute",transform:`translate(-50%, -50%) translate(${o}px, ${a}px)`,pointerEvents:"none",maxWidth:H1.maxWidth},children:s.jsx("span",{className:"block truncate",children:e.label})})})]})}const Oj={meshEdge:Wj};async function Uj(e,t,n,r,o){const a=await wp(e,n,r,o);return Ep(e,a,t,n)}async function Gj(e,t=Rs("dark"),n=!1,r="LR"){const o=await wp(e,n,r);return Ep(e,o,t,n)}function Ep(e,t,n,r=!1){const o=new Set(t.nodes.map(h=>h.id)),a=t.nodes.map(h=>({id:h.id,type:h.type,position:h.position,data:{graphNode:h.graphNode,compact:r},selected:h.selected,draggable:h.draggable,selectable:h.selectable})),i=e.edges.filter(h=>o.has(h.source)&&o.has(h.target)),c=qj(i),u=i.map(h=>{var d;return{id:h.id,source:h.source,target:h.target,label:c.has(h.id)?h.label:void 0,type:"meshEdge",data:{graphEdge:h,routePoints:(d=t.edgeRoutes.get(h.id))==null?void 0:d.points},animated:h.type==="orphanLink",markerEnd:h.direction==="directed"?{type:_m.ArrowClosed,width:h.type==="submoduleLink"?16:18,height:h.type==="submoduleLink"?16:18,color:id(h)}:void 0,style:{stroke:id(h),strokeWidth:h.type==="orphanLink"?2.25:h.type==="submoduleLink"?1.7:h.type==="worktreeLink"?1.8:h.type==="cloneLink"?1.6:2,strokeDasharray:h.type==="orphanLink"?"5 4":h.type==="submoduleLink"?"4 3":h.type==="cloneLink"?"6 3":void 0},labelStyle:{fill:n.edgeLabelTextColor,fontSize:10,fontWeight:600},labelBgStyle:{fill:n.edgeLabelBackgroundColor,fillOpacity:1,stroke:n.edgeLabelBorderColor},labelBgPadding:[6,4],labelBgBorderRadius:7}});return{nodes:a,edges:u}}const Kj=3,zj=2;function ad(e){switch(e.type){case"orphanLink":return 5;case"parentBranch":return 4;case"submoduleLink":return 3;case"cloneLink":return 2;case"worktreeLink":return 1;case"sessionLink":return 0;default:return 0}}function qj(e){const t=new Set,n=new Map;for(const r of e){if(!r.label)continue;const o=n.get(r.source);o?o.push(r):n.set(r.source,[r])}for(const r of n.values()){if(r.length<Kj){for(const a of r)t.add(a.id);continue}const o=[...r].sort((a,i)=>{const c=ad(i)-ad(a);return c!==0?c:a.id.localeCompare(i.id)});for(const a of o.slice(0,zj))t.add(a.id)}return t}function id(e){switch(e.type){case"parentBranch":return"#38bdf8";case"worktreeLink":return"#a78bfa";case"sessionLink":return"#34d399";case"orphanLink":return"#f97316";case"submoduleLink":return"#c084fc";case"cloneLink":return"#2dd4bf";default:return"#64748b"}}function Vj(e){const t=e.data.graphNode;if(t.locality==="local")return"#38bdf8";switch(t.health){case"online":return"#34d399";case"dirty":return"#fbbf24";case"degraded":case"offline":return"#fb7185";case"wrong_branch":return"#a78bfa";default:return"#94a3b8"}}function Yj(e){const t=e.data.graphNode;return["mesh-minimap-node",`mesh-minimap-node--${t.type}`,`mesh-minimap-node--${t.health}`,t.isOrphan?"mesh-minimap-node--attention":null,t.dirty?"mesh-minimap-node--dirty":null,t.outOfSync?"mesh-minimap-node--out-of-sync":null].filter(Boolean).join(" ")}function Jj({data:e,viewportKey:t}){const n=Rm(),r=Em(),o=l.useRef(null),a=l.useMemo(()=>xp(e),[e]),i=l.useMemo(()=>R1(e),[e]);return l.useEffect(()=>{if(!n||e.nodes.length===0||o.current===t)return;let c=!1;const u=requestAnimationFrame(()=>{if(c)return;const h=i.length>0&&i.length<e.nodes.length;r.fitView({nodes:h?i.map(d=>({id:d})):void 0,padding:h?.24:.2,maxZoom:h?.98:.9,duration:260}),o.current=t});return()=>{c=!0,cancelAnimationFrame(u)}},[e.nodes.length,i,a,n,r,t]),null}const Qj=12;function Xj(e){return e>=16?"min-h-[720px]":e>=10?"min-h-[580px]":"min-h-[460px]"}function Zj({data:e,selectedNodeId:t=null,directionPref:n,onNodeClick:r,onEdgeClick:o,onNodeHoverChange:a,onEdgeHoverChange:i}){const{theme:c}=Ls(),u=l.useMemo(()=>Rs(c),[c]),h=l.useMemo(()=>ej(e),[e]),d=l.useMemo(()=>tj(e),[e]),m=l.useRef(null),[f,x]=l.useState({width:0,height:0}),w=f.width>0&&f.width<Nj,p=e.nodes.length>=jj||w,[y]=l.useState("LR"),k=n??y,b=l.useMemo(()=>n==="LR"||n==="TB"?n:w?"TB":k==="auto"?U1(e):k,[k,n,h,e,w]),j=e.nodes.length>=Qj,[S,v]=l.useState({nodes:[],edges:[]}),g=l.useMemo(()=>`${E1(e,f.width,f.height)}::${b}`,[h,e,f.height,f.width,b]);l.useEffect(()=>{let C=!1;return Gj(e,u,p,b).then(A=>{if(C)return;v(A);const T=requestAnimationFrame(()=>{if(C)return;const M=m.current;if(!M)return;const L=new Map;for(const P of A.nodes){const B=M.querySelector(`.react-flow__node[data-id="${CSS.escape(P.id)}"]`);B&&B.offsetHeight>0&&L.set(P.id,B.offsetHeight)}L.size!==0&&Uj(e,u,p,b,L).then(P=>{C||v(P)})});return()=>cancelAnimationFrame(T)}),()=>{C=!0}},[e,d,u,p,b]);const N=l.useMemo(()=>S.nodes.map(C=>({...C,selected:C.id===t})),[S.nodes,t]);return l.useEffect(()=>{const C=m.current;if(!C)return;const A=()=>{const M=Math.max(0,Math.round(C.clientWidth)),L=Math.max(0,Math.round(C.clientHeight));x(P=>P.width===M&&P.height===L?P:{width:M,height:L})};A();const T=typeof ResizeObserver=="function"?new ResizeObserver(()=>A()):null;return T==null||T.observe(C),window.addEventListener("resize",A),()=>{T==null||T.disconnect(),window.removeEventListener("resize",A)}},[]),s.jsx(dl.Provider,{value:u,children:s.jsx(Dp.Provider,{value:p,children:s.jsx(Pp.Provider,{value:b,children:s.jsxs("div",{ref:m,className:`${u.graphShellClass} ${Xj(e.nodes.length)}`,style:{height:"100%"},children:[s.jsx("div",{className:`pointer-events-none absolute left-1/2 top-2 z-10 -translate-x-1/2 px-3 py-1 text-[10px] ${u.graphStatChipClass}`,children:"drag or scroll to pan"}),s.jsx("div",{className:"w-full min-w-0 flex-1",style:{height:"100%"},children:s.jsxs(Am,{nodes:N,edges:S.edges,nodeTypes:_j,edgeTypes:Oj,minZoom:w?.3:.18,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!0,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(C,A)=>r==null?void 0:r(A.data.graphNode),onEdgeClick:(C,A)=>{var M;const T=(M=A.data)==null?void 0:M.graphEdge;T&&(o==null||o(T))},onNodeMouseEnter:(C,A)=>a==null?void 0:a(A.data.graphNode),onNodeMouseLeave:()=>a==null?void 0:a(null),onEdgeMouseEnter:(C,A)=>{var T;return i==null?void 0:i(((T=A.data)==null?void 0:T.graphEdge)??null)},onEdgeMouseLeave:()=>i==null?void 0:i(null),className:"h-full w-full",colorMode:u.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(Jj,{data:e,viewportKey:g}),s.jsx(Tm,{className:u.graphControlsClass,position:"bottom-left",showZoom:!0,showFitView:!0,showInteractive:!1}),j&&s.jsx(Im,{position:"bottom-right",pannable:!0,zoomable:!0,nodeColor:Vj,nodeClassName:Yj,nodeStrokeWidth:3,className:u.isDark?"overflow-hidden rounded-xl border border-white/10 bg-slate-950/85":"overflow-hidden rounded-xl border border-slate-200 bg-white/95"}),s.jsx(Mm,{variant:Dm.Dots,gap:18,size:1.2,color:u.graphBackgroundDotColor})]})})]})})})})}const eN="You are one independent member of a multi-agent cross-verification quorum";function tN(e){var r,o;const t=(e??"").trim();if(!t)return"";if(!t.startsWith(eN))return t;const n=(o=(r=t.match(/\n## Question\n([\s\S]*?)(?:\n## |$)/))==null?void 0:r[1])==null?void 0:o.trim().replace(/\s+/g," ");return n?`MAGI cross-verify — ${n}`:"MAGI cross-verification task"}function sN(e){return`${e.state??""} ${e.chatStatus??""} ${e.lifecycle??""}`.toLowerCase()}function nN(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=n.activeSessionDetails;if(Array.isArray(r))for(const o of r)o!=null&&o.sessionId&&sN(o).includes("approval")&&t.push({nodeId:n.nodeId,sessionId:o.sessionId,providerType:o.providerType,machineLabel:n.machineLabel||n.nodeId,detail:o.statusNote??o.title??null})}return t}function rN({approvals:e,nodes:t,onResolve:n,hideWhenEmpty:r=!0}){const{t:o}=Le(),a=l.useMemo(()=>e??nN(t),[e,t]),[i,c]=l.useState({});if(r&&a.length===0)return null;const u=(h,d)=>{i[h.sessionId]||(c(m=>({...m,[h.sessionId]:d})),Promise.resolve(n(h.nodeId,h.sessionId,d)).finally(()=>{c(m=>{const f={...m};return delete f[h.sessionId],f})}))};return s.jsxs("div",{className:"rounded-lg border p-3",style:{borderColor:"color-mix(in srgb, var(--status-warning) 40%, transparent)",background:"color-mix(in srgb, var(--status-warning) 8%, transparent)"},children:[s.jsxs("div",{className:"flex items-center gap-2 mb-2 font-black text-xs",style:{color:"var(--status-warning)"},children:[s.jsx(Ys,{size:14}),o("meshGraph.approvals.title"),s.jsxs("span",{className:"opacity-70 font-semibold",children:["(",a.length,")"]})]}),a.length===0?s.jsx("div",{className:"text-[11px] opacity-70",children:o("meshGraph.approvals.empty")}):s.jsx("ul",{className:"flex flex-col gap-2",children:a.map(h=>{const d=i[h.sessionId]??null,m=d!==null;return s.jsxs("li",{className:"flex items-center justify-between gap-3 rounded-md px-2.5 py-2",style:{background:"color-mix(in srgb, var(--surface-primary) 82%, transparent)"},children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"text-xs font-semibold truncate",children:[h.machineLabel||h.nodeId,h.providerType&&s.jsx("span",{className:"ml-2 opacity-60 font-normal",children:h.providerType})]}),s.jsx("div",{className:"text-[10px] opacity-60 truncate",children:h.detail?h.detail.replace(/[\n\r]+/g," ").slice(0,120):o("meshGraph.approvals.sessionFallback",{id:h.sessionId})})]}),s.jsxs("div",{className:"flex gap-2 shrink-0",children:[s.jsx("button",{onClick:()=>u(h,"approve"),disabled:m,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 font-extrabold ${m?"cursor-not-allowed opacity-60":"cursor-pointer"}`,style:{color:"var(--status-warning)",background:"var(--surface-primary)"},children:d==="approve"?"⏳ ...":o("meshGraph.approvals.approve")}),s.jsx("button",{onClick:()=>u(h,"reject"),disabled:m,className:`btn btn-sm border-none rounded-md text-xs px-3 py-1 font-semibold text-white bg-red-500/30 ${m?"cursor-not-allowed opacity-60":"cursor-pointer"}`,children:d==="reject"?"⏳ ...":o("meshGraph.approvals.reject")})]})]},`${h.nodeId}:${h.sessionId}`)})})]})}const oN=5,aN=40,iN={meshId:"",totalEntries:0,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0};function _o(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function _p(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const n=t.toLowerCase().replace(/[\s-]+/g,"_");return n.includes("approval")?"awaiting approval":n.includes("generating")||n.includes("running")||n.includes("busy")?"generating":n.includes("idle")||n.includes("ready")||n.includes("waiting_input")?"idle":n.replace(/_/g," ")}function $p(e){return e.includes("approval")?"amber":e.includes("generating")?"sky":e.includes("idle")?"emerald":e.includes("failed")||e.includes("stopped")||e.includes("interrupted")?"rose":"muted"}function lN(e){const t=e.git;if(!t)return e.gitProbePending?"git probe pending":"no git probe";const n=(t.staged??0)+(t.modified??0)+(t.untracked??0)+(t.deleted??0)+(t.renamed??0),r=[];return t.upstreamStatus==="fresh"&&((t.ahead??0)>0||(t.behind??0)>0)&&r.push(`↑${t.ahead??0}/↓${t.behind??0}`),n>0&&r.push(`✎${n}`),t.hasConflicts&&r.push("conflicts"),r.join(" · ")||"clean"}function Bp(e){switch(e){case"active":return"emerald";case"paused":return"amber";case"completed":return"sky";case"abandoned":return"rose";default:return"muted"}}function cN(e){switch(e){case"online":return"emerald";case"dirty":return"amber";case"degraded":case"offline":return"rose";case"wrong_branch":return"sky";default:return"muted"}}function Fp(e){switch(e){case"completed":return"emerald";case"failed":return"rose";case"cancelled":return"muted";case"assigned":return"sky";case"pending":return"amber";default:return"muted"}}function ld(e){switch(e){case"assigned":return 0;case"pending":return 1;case"completed":case"failed":case"cancelled":return 2;default:return 3}}function ds(e){if(!e)return null;const t=Date.parse(e);if(!Number.isFinite(t))return null;const n=Math.max(0,Math.floor((Date.now()-t)/1e3));if(n<60)return`${n}s ago`;const r=Math.floor(n/60);if(r<60)return`${r}m ago`;const o=Math.floor(r/60);return o<48?`${o}h ago`:`${Math.floor(o/24)}d ago`}function cd(e){if(typeof e!="number"||!Number.isFinite(e)||e<0)return null;if(e<1e3)return`${Math.round(e)}ms`;const t=Math.round(e/1e3),n=t%60,r=Math.floor(t/60),o=r%60,a=Math.floor(r/60),i=[];return a>0&&i.push(`${a}h`),o>0&&i.push(`${o}m`),(n>0||i.length===0)&&i.push(`${n}s`),i.join(" ")}function ul(e){return e.replace(/[_-]+/g," ")}function Hp(e){const t=e.toLowerCase();return t.includes("fail")||t.includes("stall")||t.includes("error")?"rose":t.includes("complete")?"emerald":t.includes("dispatch")||t.includes("launch")||t.includes("assign")?"sky":t.includes("checkpoint")?"amber":"muted"}function Wp(e){if(!e)return null;const t=e.message??e.summary??e.reason??e.title;return typeof t=="string"&&t.trim()?t.trim():null}function dN({status:e,daemonId:t=null,meshId:n=null,sendDaemonCommand:r=null}){var S,v,g,N;const{theme:o}=Ls(),a=l.useMemo(()=>Rs(o),[o]),i=((S=e.queue)==null?void 0:S.summary)??null,c=((v=e.queue)==null?void 0:v.tasks)??[],u=((g=e.ledger)==null?void 0:g.summary)??iN,h=((N=e.ledger)==null?void 0:N.entries)??[],d=e.missions??[],m=d.filter(C=>C.status==="active"||C.status==="paused"),f=d.filter(C=>C.status==="completed"||C.status==="abandoned"),x=e.asyncRefineJobs??[],[w,p]=l.useState(null),y=l.useCallback(()=>p(null),[]),k=l.useCallback(async(C,A,T)=>{!t||!r||await r(t,"mesh_approve",{meshId:n??void 0,node_id:C,session_id:A,action:T})},[t,n,r]),b=l.useCallback(C=>{if(!C)return"";const A=e.nodes.find(T=>T.nodeId===C);return(A==null?void 0:A.machineLabel)||C},[e.nodes]),j=l.useMemo(()=>{const C=[];for(const A of e.nodes){const T=A.activeSessionDetails&&A.activeSessionDetails.length>0?A.activeSessionDetails:(A.activeSessions??[]).map(M=>({sessionId:M,workspace:A.workspace,isCached:!0}));for(const M of T)C.push({node:A,session:M})}return C},[e.nodes]);return s.jsxs("div",{className:"flex flex-col gap-3 pb-2",children:[s.jsx(rN,{nodes:e.nodes,onResolve:k}),s.jsx(yN,{meshTheme:a,liveMissions:m,historyMissions:f,hasMissionField:Array.isArray(e.missions),onSelect:C=>p({kind:"mission",mission:C})}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(vN,{meshTheme:a,ledgerSummary:u,entries:h,resolveNodeLabel:b,onSelect:C=>p({kind:"ledger",entry:C})}),s.jsx(wN,{meshTheme:a,queueSummary:i,tasks:c,onSelect:C=>p({kind:"queue",task:C})})]}),s.jsx(SN,{meshTheme:a,nodes:e.nodes}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(CN,{meshTheme:a,entries:j,onSelect:(C,A)=>p({kind:"session",node:C,session:A})}),s.jsx(jN,{meshTheme:a,jobs:x})]}),w&&s.jsx(hN,{meshTheme:a,detail:w,onClose:y,daemonId:t,meshId:n??e.meshId??null,sendDaemonCommand:r,resolveNodeLabel:b})]})}function Qs({meshTheme:e,title:t,count:n,children:r,action:o}){const a=e.isDark;return s.jsxs("div",{className:`flex min-w-0 flex-col overflow-hidden rounded-2xl border p-4 ${a?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/80"}`,children:[s.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[s.jsx("span",{className:`text-[11px] font-semibold uppercase tracking-[0.14em] ${e.textSecondary}`,children:t}),n!==void 0&&s.jsx("span",{className:`tabular-nums text-[11px] ${e.textMuted}`,children:n}),o&&s.jsx("span",{className:"ml-auto",children:o})]}),r]})}function Kt({meshTheme:e,label:t,tone:n}){const r=e.isDark,o=n==="rose"?r?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700":n==="sky"?r?"border-sky-400/25 bg-sky-500/10 text-sky-200":"border-sky-300 bg-sky-50 text-sky-700":n==="amber"?r?"border-amber-400/25 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700":n==="emerald"?r?"border-emerald-400/25 bg-emerald-500/10 text-emerald-200":"border-emerald-300 bg-emerald-50 text-emerald-700":r?"border-white/10 bg-white/[0.04] text-slate-300":"border-slate-200 bg-slate-50 text-slate-600";return s.jsx("span",{className:`shrink-0 rounded-full border px-2 py-0.5 text-[10px] font-semibold uppercase tracking-[0.14em] ${o}`,children:t})}function St({meshTheme:e,label:t,value:n,tone:r}){const o=e.isDark,a=r==="rose"?o?"text-rose-300":"text-rose-600":r==="sky"?o?"text-sky-300":"text-sky-600":r==="amber"?o?"text-amber-300":"text-amber-600":r==="emerald"?o?"text-emerald-300":"text-emerald-600":r==="muted"?e.textMuted:e.textPrimary;return s.jsxs("div",{className:`flex flex-col items-center rounded-lg border px-2 py-2 ${o?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/70"}`,children:[s.jsx("span",{className:`tabular-nums text-base font-semibold leading-none ${a}`,children:n}),s.jsx("span",{className:`mt-1 text-[9px] uppercase tracking-wide ${e.textMuted}`,children:t})]})}function yr({meshTheme:e,children:t}){return s.jsx("div",{className:`text-xs ${e.textMuted}`,children:t})}function $o({meshTheme:e,onClick:t,children:n}){const r=e.isDark,o=t?r?"hover:bg-white/[0.05]":"hover:bg-slate-100/70":"";return s.jsx("button",{type:"button",onClick:t,disabled:!t,className:`flex w-full min-w-0 items-center gap-2 overflow-hidden rounded-md px-1.5 py-1 text-left text-xs transition ${o} ${t?"cursor-pointer":"cursor-default"}`,children:n})}function Bo({meshTheme:e,expanded:t,hiddenCount:n,onToggle:r}){const{t:o}=Le("common");return n<=0?null:s.jsx("button",{type:"button",onClick:r,className:`mt-1 self-start rounded-md px-1.5 py-0.5 text-[11px] font-medium ${e.textSecondary} hover:underline`,children:t?o("mesh.overview.showFewer"):o("mesh.overview.showMore",{count:n})})}function Fo(e,t=oN){const[n,r]=l.useState(!1),o=n?e:e.slice(0,t),a=Math.max(0,e.length-t),i=l.useCallback(()=>r(c=>!c),[]);return{visible:o,hiddenCount:a,expanded:n,toggle:i}}function gt({meshTheme:e,label:t,value:n}){return s.jsxs("div",{className:e.rowClass,children:[s.jsx("span",{className:e.rowLabelClass,children:t}),s.jsx("span",{className:e.rowValueClass,children:n})]})}function uN(e,t){switch(e.kind){case"mission":return{kicker:t("mesh.overview.detailKickerMission"),title:e.mission.title};case"ledger":return{kicker:t("mesh.overview.detailKickerLedger"),title:ul(e.entry.kind)};case"queue":return{kicker:t("mesh.overview.detailKickerQueue"),title:e.task.id};case"session":return{kicker:t("mesh.overview.detailKickerSession"),title:_o(e.session.sessionId)}}}function hN({meshTheme:e,detail:t,onClose:n,daemonId:r,meshId:o,sendDaemonCommand:a,resolveNodeLabel:i}){const{t:c}=Le("common");l.useEffect(()=>{const x=w=>{w.key==="Escape"&&n()};return window.addEventListener("keydown",x),()=>window.removeEventListener("keydown",x)},[n]);const u=e.isDark,{kicker:h,title:d}=uN(t,c),m=u?"bg-[#030617]/[0.92]":"bg-[rgba(15,23,42,0.82)]",f=u?"border-white/10 bg-slate-950 md:bg-slate-950/98 shadow-[0_28px_120px_rgba(2,6,23,0.5)]":"border-slate-200 bg-white md:bg-white/98 shadow-[0_28px_120px_rgba(148,163,184,0.3)]";return s.jsx("div",{className:`fixed inset-0 z-[var(--z-modal)] flex items-stretch justify-center p-0 md:items-center md:p-4 ${m}`,role:"dialog","aria-modal":"true",onClick:n,children:s.jsxs("div",{className:`flex h-[100dvh] max-h-[100dvh] w-full flex-col overflow-hidden border ${f} md:h-auto md:max-h-[88dvh] md:max-w-[min(640px,calc(100vw-32px))] md:rounded-2xl`,onClick:x=>x.stopPropagation(),children:[s.jsxs("div",{className:`sticky top-0 z-10 flex shrink-0 items-start justify-between gap-3 border-b px-4 py-3 ${u?"border-white/8":"border-slate-200"}`,children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`text-[10px] font-semibold uppercase tracking-[0.16em] ${e.textMuted}`,children:h}),s.jsx("div",{className:`mt-0.5 break-all text-sm font-semibold ${e.textPrimary}`,children:d})]}),s.jsx("button",{type:"button",onClick:n,"aria-label":c("mesh.overview.closeDetail"),className:u?"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-xl border border-white/10 bg-white/[0.04] text-slate-300 transition hover:bg-white/[0.08] hover:text-white":"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-xl border border-slate-200 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",children:"✕"})]}),s.jsxs("div",{className:"min-h-0 min-w-0 flex-1 overflow-y-auto px-4 py-4",children:[t.kind==="mission"&&s.jsx(fN,{meshTheme:e,mission:t.mission,daemonId:r,meshId:o,sendDaemonCommand:a}),t.kind==="ledger"&&s.jsx(bN,{meshTheme:e,entry:t.entry,resolveNodeLabel:i}),t.kind==="queue"&&s.jsx(gN,{meshTheme:e,task:t.task}),t.kind==="session"&&s.jsx(xN,{meshTheme:e,node:t.node,session:t.session})]})]})})}const pN=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function mN(e){const t=pN(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function fN({meshTheme:e,mission:t,daemonId:n,meshId:r,sendDaemonCommand:o}){var v;const{t:a}=Le("common"),i=t.tasks,c="goal"in t&&typeof t.goal=="string"&&t.goal?t.goal:"goalPreview"in t?t.goalPreview:"",u="goalTruncated"in t?t.goalTruncated===!0:!1,[h,d]=l.useState(null),[m,f]=l.useState(!1),[x,w]=l.useState(null),p=u&&!h&&!!n&&!!o,y=l.useCallback(async()=>{if(!(!n||!o)){f(!0),w(null);try{const g=await o(n,"mesh_status",{meshId:r??void 0,verbose:!0}),N=mN(g),A=(Array.isArray(N==null?void 0:N.missions)?N.missions:[]).find(M=>(M==null?void 0:M.id)===t.id),T=typeof(A==null?void 0:A.goal)=="string"&&A.goal?A.goal:null;T?d(T):w("Full goal unavailable")}catch(g){w(g instanceof Error?g.message:"Failed to fetch full mission goal")}finally{f(!1)}}},[n,r,o,t.id]),k=h??c,b=u&&!h,j=t.stats??null,S=((v=j==null?void 0:j.incompleteTaskIds)==null?void 0:v.length)??0;return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx(Kt,{meshTheme:e,label:t.status,tone:Bp(t.status)}),s.jsx(Kt,{meshTheme:e,label:`${i.total} tasks`,tone:"muted"})]}),k&&s.jsxs("div",{className:`max-h-64 overflow-y-auto whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:[k,b&&!p&&s.jsx("span",{className:e.textMuted,children:" … (truncated)"})]}),x&&s.jsx("div",{className:"text-[11px] text-amber-400",children:x}),p&&s.jsx("button",{type:"button",className:"self-start text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:y,disabled:m,children:a(m?"mesh.overview.loadingGoal":"mesh.overview.showFullGoal")}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5 sm:grid-cols-6",children:[s.jsx(St,{meshTheme:e,label:a("mesh.overview.statCompleted"),value:i.completed,tone:"emerald"}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statAssigned"),value:i.assigned,tone:i.assigned>0?"sky":void 0}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statPending"),value:i.pending}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statFailed"),value:i.failed,tone:i.failed>0?"rose":void 0}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statBlocked"),value:i.blocked,tone:i.blocked>0?"amber":void 0}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statCancelled"),value:i.cancelled,tone:"muted"})]}),j&&s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(St,{meshTheme:e,label:a("mesh.overview.statWallClock"),value:cd(j.wallClockMs)??"—"}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statTotalRuntime"),value:cd(j.totalDurationMs)??"—"}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statRetries"),value:j.retries,tone:j.retries>0?"amber":void 0})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(gt,{meshTheme:e,label:a("mesh.overview.detailLabelMissionId"),value:t.id}),s.jsx(gt,{meshTheme:e,label:a("mesh.overview.detailLabelCreated"),value:ds(t.createdAt)??t.createdAt}),s.jsx(gt,{meshTheme:e,label:a("mesh.overview.detailLabelUpdated"),value:ds(t.updatedAt)??t.updatedAt}),i.lastActivityAt&&s.jsx(gt,{meshTheme:e,label:a("mesh.overview.detailLabelLastActivity"),value:ds(i.lastActivityAt)??i.lastActivityAt}),S>0&&j&&s.jsx(gt,{meshTheme:e,label:a("mesh.overview.detailLabelIncompleteEvidence"),value:s.jsxs("details",{children:[s.jsx("summary",{className:"cursor-pointer select-none",children:a("mesh.overview.incompleteTaskCount_other",{count:S})}),s.jsx("div",{className:"mt-1 flex flex-col gap-0.5 break-all",children:j.incompleteTaskIds.map(g=>s.jsx("span",{className:`font-mono text-[10px] ${e.textMuted}`,children:g},g))})]})})]})]})}function bN({meshTheme:e,entry:t,resolveNodeLabel:n}){const{t:r}=Le("common"),o=Wp(t.payload);let a="";try{a=JSON.stringify(t.payload??{},null,2)}catch{a=String(t.payload)}return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"flex flex-wrap items-center gap-1.5",children:s.jsx(Kt,{meshTheme:e,label:ul(t.kind),tone:Hp(t.kind)})}),o&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:o}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelEntryId"),value:t.id}),s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelWhen"),value:ds(t.timestamp)??t.timestamp}),t.nodeId&&s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelNode"),value:n(t.nodeId)}),t.sessionId&&s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelSession"),value:_o(t.sessionId)}),t.providerType&&s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelProvider"),value:t.providerType})]}),a&&a!=="{}"&&s.jsxs("div",{children:[s.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:r("mesh.overview.detailLabelPayload")}),s.jsx("pre",{className:`max-h-60 max-w-full overflow-auto rounded-lg border p-2 text-[10px] leading-4 ${e.isDark?"border-white/8 bg-black/30 text-slate-300":"border-slate-200 bg-slate-50 text-slate-700"}`,children:a})]})]})}function gN({meshTheme:e,task:t}){const{t:n}=Le("common");return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx(Kt,{meshTheme:e,label:t.status,tone:Fp(t.status)}),(t.requeueCount??0)>0&&s.jsx(Kt,{meshTheme:e,label:n("mesh.overview.detailLabelRequeued",{count:t.requeueCount}),tone:"amber"})]}),t.message&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:t.message}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(gt,{meshTheme:e,label:n("mesh.overview.detailLabelTaskId"),value:t.id}),s.jsx(gt,{meshTheme:e,label:n("mesh.overview.detailLabelCreated"),value:ds(t.createdAt)??t.createdAt}),s.jsx(gt,{meshTheme:e,label:n("mesh.overview.detailLabelUpdated"),value:ds(t.updatedAt)??t.updatedAt}),(t.assignedNodeId||t.targetNodeId)&&s.jsx(gt,{meshTheme:e,label:n("mesh.overview.detailLabelNode"),value:t.assignedNodeId||t.targetNodeId}),(t.assignedSessionId||t.targetSessionId)&&s.jsx(gt,{meshTheme:e,label:n("mesh.overview.detailLabelSession"),value:_o(t.assignedSessionId||t.targetSessionId)}),t.cancelReason&&s.jsx(gt,{meshTheme:e,label:n("mesh.overview.detailLabelCancelReason"),value:t.cancelReason}),t.requeueReason&&s.jsx(gt,{meshTheme:e,label:n("mesh.overview.detailLabelRequeueReason"),value:t.requeueReason}),t.autoLaunch&&s.jsx(gt,{meshTheme:e,label:n("mesh.overview.detailLabelAutoLaunch"),value:`${t.autoLaunch.status}${t.autoLaunch.reason?` · ${t.autoLaunch.reason}`:""}`})]})]})}function xN({meshTheme:e,node:t,session:n}){var a,i;const{t:r}=Le("common"),o=_p(n);return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx(Kt,{meshTheme:e,label:o,tone:$p(o)}),s.jsx(Kt,{meshTheme:e,label:n.providerType||"provider unknown",tone:"muted"})]}),n.statusNote&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:n.statusNote}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelSessionId"),value:n.sessionId}),s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelNode"),value:t.machineLabel}),s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelWorkspace"),value:n.workspace||t.workspace}),(((a=t.git)==null?void 0:a.branch)??t.worktreeBranch)&&s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelBranch"),value:((i=t.git)==null?void 0:i.branch)??t.worktreeBranch}),typeof n.role=="string"&&n.role&&s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelRole"),value:n.role}),(n.startedAt||n.createdAt)&&s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelStarted"),value:ds(n.startedAt||n.createdAt)??(n.startedAt||n.createdAt)})]})]})}function dd({meshTheme:e,mission:t,onSelect:n}){const r=t.tasks,o=ds(r.lastActivityAt);return s.jsxs($o,{meshTheme:e,onClick:n,children:[s.jsx(Kt,{meshTheme:e,label:t.status,tone:Bp(t.status)}),s.jsx("span",{className:`min-w-0 flex-1 truncate font-medium ${e.textPrimary}`,children:t.title}),s.jsxs("span",{className:`shrink-0 tabular-nums text-[11px] ${e.textMuted}`,children:["✓",r.completed,"/",r.total]}),o&&s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:o})]})}function yN({meshTheme:e,liveMissions:t,historyMissions:n,hasMissionField:r,onSelect:o}){const{t:a}=Le("common"),[i,c]=l.useState(!1),u=e.isDark,h=Fo(t);return s.jsxs(Qs,{meshTheme:e,title:a("mesh.overview.missionCard"),count:t.length||void 0,children:[t.length>0?s.jsxs("div",{className:"flex flex-col gap-0.5",children:[h.visible.map(d=>s.jsx(dd,{meshTheme:e,mission:d,onSelect:()=>o(d)},d.id)),s.jsx(Bo,{meshTheme:e,expanded:h.expanded,hiddenCount:h.hiddenCount,onToggle:h.toggle})]}):s.jsx(yr,{meshTheme:e,children:a(r?"mesh.overview.noActiveMissions":"mesh.overview.missionDataUnavailable")}),n.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${u?"border-white/8":"border-slate-200"}`,children:[s.jsxs("button",{type:"button",onClick:()=>c(d=>!d),className:`flex w-full items-center gap-1.5 text-[11px] font-medium ${e.textSecondary}`,children:[s.jsx("span",{className:`inline-block transition-transform ${i?"rotate-90":""}`,children:"▸"}),s.jsx("span",{children:a("mesh.overview.completedHistory")}),s.jsx("span",{className:`tabular-nums ${e.textMuted}`,children:n.length})]}),i&&s.jsx("div",{className:"mt-2 flex flex-col gap-0.5",children:n.map(d=>s.jsx(dd,{meshTheme:e,mission:d,onSelect:()=>o(d)},d.id))})]})]})}function vN({meshTheme:e,ledgerSummary:t,entries:n,resolveNodeLabel:r,onSelect:o}){const{t:a}=Le("common"),i=ds(t.lastActivityAt),c=l.useMemo(()=>[...n].reverse(),[n]),u=Fo(c);return s.jsxs(Qs,{meshTheme:e,title:a("mesh.overview.ledgerCard"),children:[s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(St,{meshTheme:e,label:a("mesh.overview.statDispatched"),value:t.taskDispatched}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statCompleted"),value:t.taskCompleted,tone:"emerald"}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statFailed"),value:t.taskFailed,tone:t.taskFailed>0?"rose":void 0}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statStalled"),value:t.taskStalled,tone:t.taskStalled>0?"amber":void 0}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statSessions"),value:t.sessionLaunched}),s.jsx(St,{meshTheme:e,label:a("mesh.overview.statCheckpoints"),value:t.checkpointCreated})]}),c.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${e.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:a("mesh.overview.recentActivity")}),s.jsxs("div",{className:"flex flex-col gap-0.5",children:[u.visible.map(h=>{const d=Wp(h.payload);return s.jsxs($o,{meshTheme:e,onClick:()=>o(h),children:[s.jsx(Kt,{meshTheme:e,label:ul(h.kind),tone:Hp(h.kind)}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,title:h.nodeId||void 0,children:d||r(h.nodeId)||h.sessionId||"—"}),s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:ds(h.timestamp)??""})]},h.id)}),s.jsx(Bo,{meshTheme:e,expanded:u.expanded,hiddenCount:u.hiddenCount,onToggle:u.toggle})]})]}),(t.recentFailures>0||i&&c.length===0)&&s.jsxs("div",{className:`mt-2 flex items-center justify-between text-[11px] ${e.textMuted}`,children:[t.recentFailures>0?s.jsx("span",{className:e.isDark?"text-amber-300":"text-amber-600",children:a("mesh.overview.recentFailures",{count:t.recentFailures})}):s.jsx("span",{}),i&&c.length===0&&s.jsx("span",{children:i})]})]})}function wN({meshTheme:e,queueSummary:t,tasks:n,onSelect:r}){const o=l.useMemo(()=>[...n].sort((c,u)=>{const h=ld(c.status)-ld(u.status);return h!==0?h:(u.updatedAt||"").localeCompare(c.updatedAt||"")}).slice(0,aN),[n]),a=Fo(o),{t:i}=Le("common");return t?s.jsxs(Qs,{meshTheme:e,title:i("mesh.overview.queueCard"),count:t.active>0?i("mesh.overview.activeCount",{count:t.active}):void 0,children:[s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(St,{meshTheme:e,label:i("mesh.overview.statPending"),value:t.pending}),s.jsx(St,{meshTheme:e,label:i("mesh.overview.statAssigned"),value:t.assigned,tone:t.assigned>0?"sky":void 0}),s.jsx(St,{meshTheme:e,label:i("mesh.overview.statActive"),value:t.active,tone:t.active>0?"sky":void 0}),s.jsx(St,{meshTheme:e,label:i("mesh.overview.statCompleted"),value:t.completed,tone:"emerald"}),s.jsx(St,{meshTheme:e,label:i("mesh.overview.statFailed"),value:t.failed,tone:t.failed>0?"rose":void 0}),s.jsx(St,{meshTheme:e,label:i("mesh.overview.statCancelled"),value:t.cancelled,tone:"muted"})]}),o.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${e.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsx("div",{className:`mb-1 text-[10px] uppercase tracking-wide ${e.textMuted}`,children:i("mesh.overview.recentTasks")}),s.jsxs("div",{className:"flex flex-col gap-0.5",children:[a.visible.map(c=>s.jsxs($o,{meshTheme:e,onClick:()=>r(c),children:[s.jsx(Kt,{meshTheme:e,label:c.status,tone:Fp(c.status)}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,title:c.message||void 0,children:tN(c.message)||c.id}),s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:ds(c.updatedAt)??""})]},c.id)),s.jsx(Bo,{meshTheme:e,expanded:a.expanded,hiddenCount:a.hiddenCount,onToggle:a.toggle})]})]})]}):s.jsx(Qs,{meshTheme:e,title:i("mesh.overview.queueCard"),children:s.jsx(yr,{meshTheme:e,children:i("mesh.overview.noQueueActivity")})})}function kN(e){return e.autoFastForwardEligible||e.suggestedAction==="auto_fast_forward"?{label:"fast-forward",tone:"sky"}:e.launchBlockedReason?{label:"blocked",tone:"rose"}:null}function SN({meshTheme:e,nodes:t}){const{t:n}=Le("common"),r=e.isDark;return s.jsx(Qs,{meshTheme:e,title:n("mesh.overview.nodesCard"),count:t.length,children:t.length===0?s.jsx(yr,{meshTheme:e,children:n("mesh.overview.noNodes")}):s.jsx("div",{className:"flex flex-col gap-1.5",children:t.map(o=>{var u,h,d;const a=(((u=o.activeSessionDetails)==null?void 0:u.length)??0)||(((h=o.activeSessions)==null?void 0:h.length)??0),i=kN(o),c=((d=o.git)==null?void 0:d.branch)??o.worktreeBranch??null;return s.jsxs("div",{className:`flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 overflow-hidden rounded-xl border px-3 py-2 ${r?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsx(Kt,{meshTheme:e,label:o.health,tone:cN(o.health)}),s.jsx("span",{className:`min-w-0 max-w-full flex-1 truncate text-sm font-medium ${e.textPrimary}`,title:o.workspace,children:o.machineLabel}),c&&s.jsx("span",{className:`max-w-full truncate font-mono text-[11px] ${e.textSecondary}`,title:c,children:c}),s.jsx("span",{className:`max-w-full truncate font-mono text-[10px] ${e.textMuted}`,children:lN(o)}),a>0&&s.jsxs("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:[a," session",a>1?"s":""]}),typeof o.daemonBuildVersion=="string"&&o.daemonBuildVersion&&s.jsxs("span",{className:`shrink-0 font-mono text-[10px] ${e.textMuted}`,title:"Daemon build version reported by this node",children:["v",o.daemonBuildVersion]}),i&&s.jsx(Kt,{meshTheme:e,label:i.label,tone:i.tone})]},o.nodeId)})})})}function CN({meshTheme:e,entries:t,onSelect:n}){const{t:r}=Le("common"),o=Fo(t);return s.jsx(Qs,{meshTheme:e,title:r("mesh.overview.sessionsCard"),count:t.length||void 0,children:t.length===0?s.jsx(yr,{meshTheme:e,children:r("mesh.overview.noActiveSessions")}):s.jsxs("div",{className:"flex flex-col gap-0.5",children:[o.visible.map(({node:a,session:i})=>{const c=_p(i);return s.jsxs($o,{meshTheme:e,onClick:()=>n(a,i),children:[s.jsx("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${e.textMuted}`,children:_o(i.sessionId)}),s.jsx("span",{className:`shrink-0 ${e.textMuted}`,children:i.providerType||"?"}),s.jsx(Kt,{meshTheme:e,label:c,tone:$p(c)})]},i.sessionId)}),s.jsx(Bo,{meshTheme:e,expanded:o.expanded,hiddenCount:o.hiddenCount,onToggle:o.toggle})]})})}function jN({meshTheme:e,jobs:t}){const{t:n}=Le("common"),r=e.isDark,o=t.filter(a=>a.status==="failed").length;return s.jsx(Qs,{meshTheme:e,title:n("mesh.overview.refineCard"),count:t.length||void 0,action:o>0?s.jsx(Kt,{meshTheme:e,label:n("mesh.overview.failedCount",{count:o}),tone:"rose"}):void 0,children:t.length===0?s.jsx(yr,{meshTheme:e,children:n("mesh.overview.noRefineJobs")}):s.jsx("div",{className:"flex flex-col gap-1",children:t.slice(0,8).map(a=>s.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[s.jsxs("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${e.textMuted}`,children:[a.branch??a.jobId.slice(0,14),a.into?` → ${a.into}`:""]}),s.jsx("span",{className:`shrink-0 text-[10px] font-semibold ${a.status==="failed"?r?"text-rose-300":"text-rose-600":a.status==="running"||a.status==="accepted"?r?"text-sky-300":"text-sky-600":r?"text-emerald-300":"text-emerald-600"}`,children:a.status})]},a.jobId))})})}const NN=["node","p2p","session","task","mission","refinery","completion","magi","magiPanel","convergence"];function AN({meshTheme:e,open:t,onToggle:n}){const{t:r}=Le(),o=e.isDark,a="inline-flex h-7 w-7 items-center justify-center rounded-lg border transition",i=t?o?"border-sky-400/40 bg-sky-500/15 text-sky-100":"border-sky-400 bg-sky-100 text-sky-800":o?"border-white/10 bg-white/[0.04] text-slate-400 hover:bg-white/[0.08] hover:text-slate-100":"border-slate-200 bg-white text-slate-400 hover:bg-slate-50 hover:text-slate-700";return s.jsx("button",{type:"button",onClick:n,"aria-label":r("meshGraph.help.toggleAria"),"aria-expanded":t,title:r("meshGraph.help.toggleTitle"),className:`${a} ${i}`,children:s.jsx(Pf,{size:15})})}function TN({meshTheme:e,onClose:t}){const{t:n}=Le(),r=e.isDark,o=l.useMemo(()=>NN.map(a=>({term:n(`meshGraph.help.sections.${a}.term`),summary:n(`meshGraph.help.sections.${a}.summary`),details:n(`meshGraph.help.sections.${a}.details`,{returnObjects:!0})})),[n]);return l.useEffect(()=>{const a=i=>{i.key==="Escape"&&t()};return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[t]),s.jsxs("div",{className:`shrink-0 rounded-2xl border p-4 ${r?"border-white/10 bg-white/[0.03]":"border-slate-200 bg-white/80"}`,role:"region","aria-label":n("meshGraph.help.regionAria"),children:[s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`text-[10px] font-semibold uppercase tracking-[0.16em] ${e.textMuted}`,children:n("meshGraph.help.kicker")}),s.jsx("div",{className:`mt-0.5 text-sm font-semibold ${e.textPrimary}`,children:n("meshGraph.help.title")})]}),s.jsx("button",{type:"button",onClick:t,"aria-label":n("meshGraph.help.close"),className:r?"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border border-white/10 bg-white/[0.04] text-slate-300 transition hover:bg-white/[0.08] hover:text-white":"inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border border-slate-200 bg-white text-slate-500 transition hover:bg-slate-50 hover:text-slate-900",children:s.jsx(At,{size:14})})]}),s.jsx("dl",{className:"grid gap-3 sm:grid-cols-2",children:o.map(a=>s.jsxs("div",{className:`rounded-xl border p-3 ${r?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsx("dt",{className:`text-xs font-semibold ${e.textPrimary}`,children:a.term}),s.jsx("dd",{className:`mt-1 text-[11px] leading-5 ${e.textSecondary}`,children:a.summary}),a.details&&a.details.length>0&&s.jsx("ul",{className:`mt-1.5 flex flex-col gap-1 text-[11px] leading-5 ${e.textMuted}`,children:a.details.map((i,c)=>s.jsxs("li",{className:"flex gap-1.5",children:[s.jsx("span",{"aria-hidden":!0,className:"select-none",children:"·"}),s.jsx("span",{className:"min-w-0",children:i})]},c))})]},a.term))})]})}const tn=l.createContext(Rs("dark"));function Ve({label:e,tone:t="default",className:n,title:r}){const o=l.useContext(tn);return s.jsx("span",{title:r,className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${o.badge(t)}${n?` ${n}`:""}`,children:e})}function Pt({label:e,value:t}){const n=l.useContext(tn);return s.jsxs("div",{className:n.rowClass,children:[s.jsx("span",{className:n.rowLabelClass,children:e}),s.jsx("span",{className:n.rowValueClass,children:t})]})}const IN={meshId:"",totalEntries:0,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0};function Op(e){switch(e){case"online":return"good";case"dirty":return"warn";case"degraded":case"offline":return"danger";case"wrong_branch":return"info";default:return"default"}}function Na(e){switch((e||"").toLowerCase()){case"idle":return"good";case"generating":case"running":return"info";case"waiting_approval":case"starting":case"pending":return"warn";case"failed":case"stopped":case"interrupted":return"danger";default:return"default"}}function Xr(e){const t=(e.chatStatus||e.state||e.lifecycle||"").trim();if(!t)return"unknown";const n=t.toLowerCase().replace(/[\s-]+/g,"_");return n.includes("approval")?"awaiting approval":n.includes("generating")||n.includes("running")||n.includes("busy")?"generating":n.includes("idle")||n.includes("ready")||n.includes("waiting_input")?"idle":n.replace(/_/g," ")}function MN(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function DN(e){return e.startedAt||e.createdAt||null}function PN(e){const t=DN(e);if(!t)return"runtime age not reported";const n=Date.parse(t);if(!Number.isFinite(n))return"runtime age not reported";const r=Math.max(0,Math.floor((Date.now()-n)/1e3));if(r<60)return`${r}s`;const o=Math.floor(r/60);if(o<60)return`${o}m`;const a=Math.floor(o/60);return a<48?`${a}h ${o%60}m`:`${Math.floor(a/24)}d ${a%24}h`}function Up(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function LN(e){if(!e)return"default";if(e.state==="self")return"info";if(e.transport==="direct"&&e.state==="connected")return"good";if(e.transport==="relay"&&e.state==="connected")return"info";switch(e.state){case"connected":return"good";case"connecting":return"warn";case"disconnected":case"failed":case"closed":return"danger";default:return"default"}}function RN(e){return e?e.state==="self"?"mesh self":e.transport==="direct"&&e.state==="connected"?"mesh direct":e.transport==="relay"&&e.state==="connected"?"mesh relay":!e.reported&&e.source==="not_reported"?"mesh unknown / not reported":`mesh ${e.state}`:"mesh unknown"}function EN(e){const t=e.git;if(!t)return e.gitProbePending?"Git probe pending":"No git probe";const n=(t.staged??0)+(t.modified??0)+(t.untracked??0)+(t.deleted??0)+(t.renamed??0),r=[];t.branch&&r.push(t.branch),t.upstream&&t.upstreamStatus!=="fresh"&&r.push("upstream unverified"),t.upstreamStatus==="fresh"&&((t.ahead??0)>0||(t.behind??0)>0)&&r.push(`↑${t.ahead??0}/↓${t.behind??0}`),n>0&&r.push(`${n} dirty`);const o=(t.submodules??[]).filter(i=>i.dirty),a=(t.submodules??[]).filter(i=>i.outOfSync||i.error);return o.length>0&&r.push(`${o.length} submodule dirty`),a.length>0&&r.push(`${a.length} submodule drift`),t.hasConflicts&&r.push("conflicts"),r.join(" · ")||"Clean"}const _N={first_eligible:"In order",least_loaded:"Spread",round_robin:"Spread (round-robin)",priority_only:"Spread (priority)"};function $N(e){if(e.startsWith("max_provider_parallel_reached:"))return`provider cap reached (${e.slice(30)})`;switch(e){case"global_max_parallel_tasks_reached":return"global parallel cap reached";case"node_has_active_assignment":return"already running a write task";default:return e.replace(/_/g," ")}}function BN(e){var n;const t=[];for(const r of e.nodes){const o=r.activeSessionDetails&&r.activeSessionDetails.length>0?r.activeSessionDetails:(r.activeSessions??[]).map(a=>({sessionId:a,workspace:r.workspace,isCached:!0}));for(const a of o)t.push({nodeId:r.nodeId,machineLabel:r.machineLabel,workspace:r.workspace,branch:((n=r.git)==null?void 0:n.branch)??null,nodeHealth:r.health,session:a})}return t}function FN(e){return e.assignedNodeId||e.targetNodeId||null}function fi(e){return e?e.slice(0,7):null}function HN(e,t){var a,i,c;const n=fi((a=e==null?void 0:e.git)==null?void 0:a.headCommit),r=((c=(i=e==null?void 0:e.git)==null?void 0:i.headMessage)==null?void 0:c.trim())||"";if(n||r)return[n,r].filter(Boolean).join(" · ");const o=t[0];return o?[fi(o.commit),o.message].filter(Boolean).join(" · "):null}function WN(e,t){const n=HN(e,t);return n||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function ON(e){const t=(e==null?void 0:e.result)??e,n=(t==null?void 0:t.log)??(e==null?void 0:e.log)??t;return Array.isArray(n==null?void 0:n.entries)?n.entries:[]}function UN(e){var n,r,o,a,i,c;const t=((n=e.selectedSessionEntry)==null?void 0:n.session.workspace)||((r=e.selectedSessionEntry)==null?void 0:r.workspace)||((a=(o=e.selectedNodeStatus)==null?void 0:o.git)==null?void 0:a.workspace)||((i=e.selectedNodeStatus)==null?void 0:i.workspace)||null;if(t&&e.selectedSessionEntry){const u=((c=e.selectedNodeStatus)==null?void 0:c.daemonId)||e.coordinatorDaemonId;return u?{daemonId:u,workspace:t}:null}if(t&&e.selectedNodeStatus){const u=e.selectedNodeStatus.daemonId||e.coordinatorDaemonId;return u?{daemonId:u,workspace:t}:null}return null}function GN(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":RN(e.connection)}function KN(e){var n;const t=e.source;return t!=null&&t.kind?t.kind:((n=t==null?void 0:t.connection)==null?void 0:n.source)??"mesh_status"}function ud(e){switch(e.type){case"parentBranch":return"default branch link";case"worktreeLink":return"worktree relationship";case"sessionLink":return"session relationship";case"orphanLink":return"orphan relationship";case"submoduleLink":return"submodule relationship";case"cloneLink":return"clone relationship";default:return e.type}}function zN(e){return e.direction==="directed"?"directed":"undirected"}function qN(e,t){return t?e.nodes.find(n=>n.id===t)??null:null}function VN(e){var t,n,r,o;return[e.meshId,e.refreshedAt,e.nodes.length,((n=(t=e.queue)==null?void 0:t.summary)==null?void 0:n.active)??"",((o=(r=e.ledger)==null?void 0:r.summary)==null?void 0:o.recentFailures)??"",...e.nodes.map(a=>{var i,c,u,h,d,m,f,x,w,p,y,k,b,j,S,v,g,N,C,A,T,M;return[a.nodeId,a.daemonId??"",a.machineId??"",a.machineLabel,a.machineStatus??"",((i=a.connection)==null?void 0:i.state)??"",((c=a.connection)==null?void 0:c.transport)??"",((u=a.connection)==null?void 0:u.source)??"",a.health,a.gitProbePending?1:0,((h=a.git)==null?void 0:h.branch)??"",((d=a.git)==null?void 0:d.upstream)??"",((m=a.git)==null?void 0:m.upstreamStatus)??"",((f=a.git)==null?void 0:f.ahead)??"",((x=a.git)==null?void 0:x.behind)??"",((w=a.git)==null?void 0:w.headCommit)??"",((p=a.git)==null?void 0:p.staged)??"",((y=a.git)==null?void 0:y.modified)??"",((k=a.git)==null?void 0:k.untracked)??"",((b=a.git)==null?void 0:b.deleted)??"",((j=a.git)==null?void 0:j.renamed)??"",(S=a.git)!=null&&S.hasConflicts?1:0,((v=a.git)==null?void 0:v.lastCheckedAt)??"",((g=a.activeSessions)==null?void 0:g.join(","))??"",((N=a.activeSessionDetails)==null?void 0:N.length)??"",((C=a.activeSessionDetails)==null?void 0:C.map(L=>[L.sessionId,L.providerType??"",L.state??"",L.chatStatus??"",L.lifecycle??"",L.role??"",L.isSelfCoordinator?1:0,L.statusNote??"",L.startedAt??"",L.createdAt??""].join("/")).join(","))??"",((A=a.providers)==null?void 0:A.join(","))??"",((T=a.providerPriority)==null?void 0:T.join(","))??"",a.error??"",(((M=a.git)==null?void 0:M.submodules)??[]).map(L=>[L.path,L.commit,L.dirty?1:0,L.outOfSync?1:0,L.error??""].join("/")).join(",")].join("|")})].join("::")}function YN(e){return e.nodes.length===0?!1:e.nodes.every(t=>t.health==="unknown"&&(!t.connection||t.connection.state==="unknown"))}function JN({scheduling:e}){const{t}=Le("common"),n=l.useContext(tn);if(!e)return s.jsx("div",{className:`${n.cardClass} rounded-2xl p-4 text-[12px] ${n.textSecondary}`,children:t("mesh.status.schedulingNotReported")});const r=e.globalWriteCapReached?"warn":"good";return s.jsxs("div",{className:`${n.cardClass} rounded-2xl p-4`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[12px] font-semibold ${n.textPrimary}`,children:t("mesh.status.schedulingTitle")}),s.jsx(Ve,{label:_N[e.strategy]??e.strategy,tone:"info"}),s.jsx(Ve,{label:`write ${e.activeWriteAssigned}/${e.maxParallelTasks}`,tone:r,title:"Active write (non-readonly) assigned tasks vs the global parallel cap"}),s.jsx(Ve,{label:`readonly ${e.activeReadonlyAssigned}/${e.maxReadonlyParallelTasks}`,tone:e.globalReadonlyCapReached?"warn":"default",title:"Active read-only diagnosis tasks vs their (2× write) cap"})]}),s.jsx("p",{className:`mt-2 text-[11px] ${n.textSecondary}`,children:t("mesh.status.distributionTitle")})]})}function QN({scheduling:e}){return e?s.jsxs(s.Fragment,{children:[s.jsx(Ve,{label:`load ${e.load}`,tone:e.load>0?"info":"default",title:"Active assigned tasks on this node"}),typeof e.schedulingPriority=="number"&&e.schedulingPriority!==0&&s.jsx(Ve,{label:`priority ${e.schedulingPriority}`,tone:"default",title:"Soft scheduling priority (higher = preferred)"}),(e.providerRoles??[]).map(t=>s.jsx(Ve,{label:`${t.providerType} ${t.activeAssigned}${typeof t.maxParallel=="number"?`/${t.maxParallel}`:""}`,tone:t.capReached?"warn":"default",title:"Per-(node, provider) active assignments vs declared maxParallel cap"},t.providerType)),e.capReached&&(e.capReasons??[]).map(t=>s.jsx(Ve,{label:$N(t),tone:"warn",title:"Why this node cannot currently claim a new write task"},t))]}):null}function XN({node:e}){var d,m,f,x;const t=l.useContext(tn),n=((d=e.activeSessionDetails)==null?void 0:d.length)??((m=e.activeSessions)==null?void 0:m.length)??0,r=fi((f=e.git)==null?void 0:f.headCommit),o=e.isLocalWorktree===!0,a=e.worktreeBootstrap,i=e.staleDaemonBuild,c=e.providerVersions&&typeof e.providerVersions=="object"?e.providerVersions:void 0,u=c?Object.entries(c).filter(([,w])=>typeof w=="string"&&w):[],h=typeof e.daemonBuildVersion=="string"&&e.daemonBuildVersion?e.daemonBuildVersion:void 0;return s.jsxs("div",{className:`rounded-xl border p-3 ${t.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[12px] font-semibold ${t.textPrimary}`,children:e.machineLabel||e.nodeId}),s.jsx(Ve,{label:e.health,tone:Op(e.health)}),o&&s.jsx(Ve,{label:"worktree",tone:"info",title:e.worktreeBranch?`Worktree branch ${e.worktreeBranch}`:"Local worktree node"}),(a==null?void 0:a.status)&&a.status!=="ready"&&s.jsx(Ve,{label:`bootstrap ${a.status}`,tone:"warn",title:"Worktree bootstrap is still in progress"}),((x=e.connection)==null?void 0:x.state)&&e.connection.state!=="self"&&s.jsx(Ve,{label:e.connection.state,tone:e.connection.state==="connected"?"good":"warn",title:"Mesh peer connection state"}),n>0&&s.jsx(Ve,{label:`${n} session${n===1?"":"s"}`,tone:"default"}),e.autoFastForwardEligible&&s.jsx(Ve,{label:"fast-forward ready",tone:"info",title:"Clean, behind upstream — safe for fast-forward"}),!!i&&s.jsx(Ve,{label:"stale build",tone:"warn",title:"Live daemon was built behind workspace HEAD — merged fixes may not be live"}),h&&s.jsx(Ve,{label:`build ${h}`,tone:"default",title:"Daemon build version reported by this node"}),s.jsx(QN,{scheduling:e.scheduling})]}),u.length>0&&s.jsx("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:u.map(([w,p])=>s.jsx(Ve,{label:`${w}@${p}`,tone:"info",title:"Detected provider version on this node"},w))}),s.jsxs("div",{className:`mt-1.5 text-[11px] ${t.textSecondary}`,children:[EN(e),r?s.jsxs("span",{className:"ml-2 font-mono opacity-70",children:["@",r]}):null]})]})}function ZN({status:e}){const{t}=Le("common"),n=l.useContext(tn),r=e.meshProtocolMetrics,o=Array.isArray(e.providerVersionSkew)?e.providerVersionSkew:[];return!r&&o.length===0?null:s.jsxs("div",{className:`${n.cardClass} rounded-2xl p-4`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[12px] font-semibold ${n.textPrimary}`,children:t("mesh.status.protocolTitle")}),r&&s.jsx(Ve,{label:`v2 ${Math.round(r.v2Ratio*100)}% (${r.v2}/${r.total})`,tone:r.total>0&&r.v2===r.total?"good":"info",title:"Share of pending coordinator events carrying a mesh-protocol-v2 envelope in this drain"}),o.length>0&&s.jsx(Ve,{label:`${o.length} provider skew`,tone:"warn",title:"Providers running different versions across nodes"})]}),r&&Object.keys(r.scopes).length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:Object.entries(r.scopes).map(([a,i])=>s.jsx(Ve,{label:`${a}: ${i}`,tone:"default",title:"v2 event scope breakdown"},a))}),o.length>0&&s.jsx("div",{className:"mt-2 flex flex-col gap-1.5",children:o.map(a=>s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx("span",{className:`text-[11px] font-semibold ${n.textPrimary}`,children:a.provider}),a.versions.map(i=>s.jsx(Ve,{label:`${i.version} · ${i.nodeIds.length} node${i.nodeIds.length===1?"":"s"}`,tone:"default",title:i.nodeIds.join(", ")},i.version))]},a.provider))}),e.providerVersionSkewWarning&&s.jsx("p",{className:`mt-2 text-[11px] ${n.textSecondary}`,children:e.providerVersionSkewWarning})]})}function eA({canonicalStatus:e}){const{t}=Le("common"),n=l.useContext(tn);return s.jsxs("div",{className:"flex flex-col gap-3 p-1",children:[s.jsx(JN,{scheduling:e.scheduling}),s.jsx(ZN,{status:e}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx("span",{className:`px-1 text-[11px] font-semibold uppercase tracking-[0.16em] ${n.textSecondary}`,children:t("mesh.status.nodesRuntime")}),e.nodes.length===0?s.jsx("div",{className:`rounded-xl border p-3 text-[12px] ${n.textSecondary} ${n.isDark?"border-white/10":"border-slate-200"}`,children:t("mesh.status.noNodesReporting")}):e.nodes.map(r=>s.jsx(XN,{node:r},r.nodeId))]})]})}function tA({canonicalStatus:e,queueSummary:t,ledgerSummary:n,isBootstrapMode:r,meshTheme:o,sessionEntries:a,inlineMode:i=!1}){var v;const c=t&&(t.active>0||t.historical>0),u=n.recentFailures>0||n.taskFailed>0,h=(v=e.queue)!=null&&v.tasks?e.queue.tasks.filter(g=>g.status==="failed"||g.status==="cancelled").slice(0,5):[],d=e.asyncRefineJobs,m=(d==null?void 0:d.filter(g=>g.status==="running"||g.status==="accepted"))??[],f=(d==null?void 0:d.filter(g=>g.status==="failed"))??[],x=e.staleDirectWorkSummary,w=x&&x.count>0;if(!c&&!u&&e.nodes.length===0&&!r&&m.length===0&&f.length===0&&!w&&a.length===0)return null;const p=o.isDark,y=`border-t ${p?"border-white/8":"border-slate-200"}`,k=`group w-full rounded-lg border text-xs ${p?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,b=`flex cursor-pointer list-none items-center gap-1.5 px-2.5 py-1.5 [&::-webkit-details-marker]:hidden ${o.textSecondary}`;function j({label:g,value:N,tone:C}){const A=C==="rose"?p?"text-rose-300":"text-rose-600":C==="sky"?p?"text-sky-300":"text-sky-600":C==="amber"?p?"text-amber-300":"text-amber-600":C==="emerald"?p?"text-emerald-300":"text-emerald-600":C==="muted"?o.textMuted:o.textPrimary;return s.jsxs("div",{className:`flex flex-col items-center rounded-lg border px-2 py-1.5 ${p?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-white/70"}`,children:[s.jsx("span",{className:`tabular-nums text-sm font-semibold leading-none ${A}`,children:N}),s.jsx("span",{className:`mt-0.5 text-[9px] uppercase tracking-wide ${o.textMuted}`,children:g})]})}const S=s.jsxs("div",{className:"flex flex-col gap-3 text-xs",children:[s.jsx("div",{className:"grid grid-cols-4 gap-1.5",children:t?s.jsxs(s.Fragment,{children:[s.jsx(j,{label:"Pending",value:t.pending}),s.jsx(j,{label:"Active",value:t.active,tone:t.active>0?"sky":void 0}),s.jsx(j,{label:"Done",value:t.completed,tone:"emerald"}),s.jsx(j,{label:"Failed",value:t.failed,tone:t.failed>0?"rose":void 0})]}):s.jsxs(s.Fragment,{children:[s.jsx(j,{label:"Done",value:n.taskCompleted,tone:"emerald"}),s.jsx(j,{label:"Failed",value:n.taskFailed,tone:n.taskFailed>0?"rose":void 0}),s.jsx(j,{label:"Sessions",value:n.sessionLaunched}),s.jsx(j,{label:"Recent↯",value:n.recentFailures,tone:n.recentFailures>0?"amber":"muted"})]})}),t&&s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(j,{label:"Ledger done",value:n.taskCompleted,tone:"emerald"}),s.jsx(j,{label:"Sessions",value:n.sessionLaunched}),s.jsx(j,{label:"Recent↯",value:n.recentFailures,tone:n.recentFailures>0?"amber":"muted"})]}),n.lastActivityAt&&s.jsxs("div",{className:`flex items-center justify-between ${o.textMuted}`,children:[s.jsx("span",{children:"Last activity"}),s.jsx("span",{className:"font-mono text-[10px]",children:n.lastActivityAt.slice(5,16)})]}),e.nodes.length>0&&s.jsx("div",{className:`pt-2.5 ${y}`,children:s.jsx("div",{className:"flex flex-col gap-1",children:e.nodes.map(g=>{var L;const N=((L=g.connection)==null?void 0:L.state)??"unknown",C=N==="unknown"||N==="connecting",M=C?"bg-amber-400":N==="failed"||N==="closed"||N==="disconnected"?p?"bg-rose-400":"bg-rose-500":N==="connected"||N==="self"?p?"bg-emerald-400":"bg-emerald-500":p?"bg-slate-500":"bg-slate-400";return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`size-1.5 shrink-0 rounded-full ${M}`}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${o.textSecondary}`,title:g.workspace,children:g.machineLabel}),s.jsx("span",{className:`shrink-0 font-mono text-[10px] ${o.textMuted}`,children:C?"…":N})]},g.nodeId)})})}),d&&d.length>0&&s.jsx("div",{className:`pt-2.5 ${y}`,children:s.jsxs("details",{className:k,children:[s.jsxs("summary",{className:b,children:[s.jsx("span",{className:"flex-1",children:"Refine jobs"}),s.jsx("span",{className:`tabular-nums ${p?"text-slate-400":"text-slate-500"}`,children:d.length}),f.length>0&&s.jsxs("span",{className:p?"text-rose-300":"text-rose-600",children:[f.length," failed"]})]}),s.jsx("div",{className:"flex flex-col gap-0.5 px-2.5 pb-2",children:d.slice(0,8).map(g=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${o.textMuted}`,children:[g.branch??g.jobId.slice(0,14),g.into?` → ${g.into}`:""]}),s.jsx("span",{className:`shrink-0 text-[9px] font-semibold ${g.status==="failed"?p?"text-rose-300":"text-rose-600":g.status==="running"||g.status==="accepted"?p?"text-sky-300":"text-sky-600":p?"text-emerald-300":"text-emerald-600"}`,children:g.status})]},g.jobId))})]})}),h.length>0&&s.jsx("div",{className:d&&d.length>0?"":`pt-2.5 ${y}`,children:s.jsxs("details",{className:k,children:[s.jsxs("summary",{className:b,children:[s.jsx("span",{className:`flex-1 ${p?"text-rose-300":"text-rose-600"}`,children:"Failed tasks"}),s.jsx("span",{className:`tabular-nums ${p?"text-rose-400":"text-rose-500"}`,children:h.length})]}),s.jsx("div",{className:"flex flex-col gap-1 px-2.5 pb-2",children:h.map(g=>s.jsxs("div",{className:"flex flex-col gap-0.5",children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`font-mono text-[10px] ${o.textMuted}`,children:g.id.slice(0,10)}),g.message&&s.jsx("span",{className:`flex-1 truncate ${p?"text-slate-300":"text-slate-700"}`,children:g.message.slice(0,55)})]}),g.cancelReason&&s.jsx("div",{className:`truncate text-[10px] ${o.textMuted}`,children:g.cancelReason.slice(0,55)})]},g.id))})]})}),w&&s.jsxs("div",{className:`flex items-center justify-between pt-2.5 ${y}`,children:[s.jsx("span",{className:o.textMuted,children:"Stale work"}),s.jsx("span",{className:`tabular-nums ${p?"text-amber-300":"text-amber-600"}`,children:x.count})]}),a.length>0&&s.jsx("div",{className:`pt-2.5 ${y}`,children:s.jsxs("details",{className:k,children:[s.jsxs("summary",{className:b,children:[s.jsx("span",{className:"flex-1",children:"Sessions"}),s.jsx("span",{className:`tabular-nums ${p?"text-slate-400":"text-slate-500"}`,children:a.length})]}),s.jsx("div",{className:"flex flex-col gap-0.5 px-2.5 pb-2",children:a.map(g=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${o.textMuted}`,title:g.session.sessionId,children:Up(g.session.sessionId)}),s.jsx("span",{className:`shrink-0 ${o.textMuted}`,children:g.session.providerType||"?"}),s.jsx("span",{className:`shrink-0 text-[9px] font-semibold ${o.textMuted}`,children:Xr(g.session)})]},g.session.sessionId))})]})})]});return i?S:s.jsxs("details",{className:`rounded-2xl border text-xs ${o.isDark?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,children:[s.jsxs("summary",{className:`flex cursor-pointer list-none items-center gap-2 px-4 py-3 font-medium [&::-webkit-details-marker]:hidden ${o.textSecondary}`,children:[s.jsx("span",{className:"flex-1",children:"Mesh Health Panel"}),m.length>0&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${o.isDark?"border-sky-400/25 bg-sky-500/10 text-sky-200":"border-sky-300 bg-sky-50 text-sky-700"}`,children:[m.length," refining"]}),f.length>0&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${o.isDark?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700"}`,children:[f.length," refine failed"]}),u&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${o.isDark?"border-rose-400/30 bg-rose-500/12 text-rose-200":"border-rose-300 bg-rose-50 text-rose-700"}`,children:[n.recentFailures," recent failures"]}),r&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${o.isDark?"border-amber-400/20 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700"}`,children:"awaiting live data"})]}),S]})}function Gp({meshTheme:e,activeTab:t,onActiveTabChange:n,helpOpen:r,onHelpOpenChange:o}){const{t:a}=Le("common"),i=c=>c?e.isDark?"rounded-lg px-3.5 py-1.5 text-xs font-semibold text-slate-100 bg-white/[0.08] border border-white/12":"rounded-lg px-3.5 py-1.5 text-xs font-semibold text-slate-900 bg-white border border-slate-300 shadow-sm":`rounded-lg px-3.5 py-1.5 text-xs font-medium ${e.textSecondary} border border-transparent hover:bg-white/[0.04]`;return s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("div",{className:`inline-flex w-fit items-center gap-1 rounded-xl border p-1 ${e.isDark?"border-white/10 bg-slate-950/40":"border-slate-200 bg-slate-50"}`,role:"tablist","aria-label":"Mesh view",children:[s.jsx("button",{type:"button",role:"tab","aria-selected":t==="overview",className:i(t==="overview"),onClick:()=>n("overview"),children:a("meshGraph.obs.tabOverview")}),s.jsx("button",{type:"button",role:"tab","aria-selected":t==="status",className:i(t==="status"),onClick:()=>n("status"),children:a("meshGraph.obs.tabStatus")}),s.jsx("button",{type:"button",role:"tab","aria-selected":t==="graph",className:i(t==="graph"),onClick:()=>n("graph"),children:a("meshGraph.obs.tabGraph")})]}),s.jsx(AN,{meshTheme:e,open:r,onToggle:()=>o(!r)})]})}function sA({status:e,emptyMessage:t,daemonId:n=null,sendDaemonCommand:r=null,bootstrapFallback:o,activeTab:a,onActiveTabChange:i,helpOpen:c,onHelpOpenChange:u,hideControls:h=!1}){var Xe,dt,it;const{t:d}=Le("common"),{theme:m}=Ls(),f=l.useMemo(()=>Rs(m),[m]),x=l.useMemo(()=>({merged_to_main:d("meshGraph.obs.convergenceMergedToMain"),pushed_feature_branch_needs_merge:d("meshGraph.obs.convergenceNeedsMerge"),blocked_review:d("meshGraph.obs.convergenceBlockedReview"),cleanup_candidate:d("meshGraph.obs.convergenceCleanup"),not_mergeable:d("meshGraph.obs.convergenceNotMergeable")}),[d]),w=t??d("meshGraph.obs.emptyGraph"),p=l.useMemo(()=>Mu(e),[e]),y=o??YN(p),k=l.useMemo(()=>VN(p),[p]),b=l.useMemo(()=>Mp(p),[k]),[j,S]=l.useState("overview"),[v,g]=l.useState(!1),N=a??j,C=c??v,A=l.useCallback(he=>{i?i(he):S(he)},[i]),T=l.useCallback(he=>{u?u(he):g(he)},[u]),[M,L]=l.useState(!1);l.useEffect(()=>{N==="graph"&&L(!0)},[N]);const[P,B]=l.useState(null),[K,F]=l.useState(null),[R,Q]=l.useState(null),[E,I]=l.useState({}),[$,D]=l.useState(null),[U,Y]=l.useState(null),ae=l.useMemo(()=>new Map(p.nodes.map(he=>[he.nodeId,he])),[p.nodes]),z=l.useMemo(()=>new Map(b.nodes.map(he=>[he.id,he])),[b.nodes]),X=((Xe=p.queue)==null?void 0:Xe.summary)??null,de=((dt=p.ledger)==null?void 0:dt.summary)??IN,re=l.useMemo(()=>BN(p),[p]),W=l.useMemo(()=>{const he=new Map;for(const $e of re){const Fe=Xr($e.session);he.set(Fe,(he.get(Fe)??0)+1)}return[...he.entries()].sort(($e,Fe)=>Fe[1]-$e[1])},[re]);l.useEffect(()=>{P&&(z.has(P)||(B(null),Q(he=>!he||"nodeId"in he&&he.nodeId===P?null:he)))},[z,P]);const oe=P?ae.get(P)??null:null,V=qN(b,P),ie=(R==null?void 0:R.kind)==="edge"&&K?b.edges.find(he=>he.id===K)??null:null,ke=ie?b.nodes.find(he=>he.id===ie.source)??null:null,xe=ie?b.nodes.find(he=>he.id===ie.target)??null:null;l.useEffect(()=>{var he,$e,Fe;if(P)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:p.meshId,selectedNodeId:P,canonicalNode:Pv(oe),graphNode:V?{id:V.id,branch:V.branch,upstream:V.upstream,headCommit:V.submoduleCommit,submoduleCount:(($e=(he=oe==null?void 0:oe.git)==null?void 0:he.submodules)==null?void 0:$e.length)??0,snapshotCompleteness:V.snapshotCompleteness,snapshotWarnings:V.snapshotWarnings,branchConvergence:((Fe=V.branchConvergence)==null?void 0:Fe.status)??null}:null})}catch{}},[p.meshId,V,P,oe]);const Se=(R==null?void 0:R.kind)==="session"?re.find(he=>he.nodeId===R.nodeId&&he.session.sessionId===R.sessionId)??null:null,pe=l.useMemo(()=>re.filter(he=>he.nodeId===P),[P,re]),G=UN({coordinatorDaemonId:n,selectedNodeStatus:oe,selectedSessionEntry:Se}),O=(G==null?void 0:G.workspace)??null,Z=O?E[O]??null:null,q=WN(oe,(Z==null?void 0:Z.entries)??[]),me=(V==null?void 0:V.daemonId)??(oe==null?void 0:oe.daemonId)??n??null,Te=!!(V&&r&&me&&V.type!=="submoduleNode"&&V.behind>0&&V.ahead===0&&V.dirtyFiles===0&&!V.dirty&&!V.hasConflicts&&V.upstreamStatus==="fresh"),_=l.useCallback(()=>{B(null),F(null),Q(null),D(null)},[]);l.useEffect(()=>{D(null)},[P]);const te=l.useCallback(async()=>{if(!V||!me||!r||!Te)return;Y(V.id),D(null);const he=(oe==null?void 0:oe.workspace)??V.workspace??"";try{const $e=await r(me,"fast_forward_mesh_node",{meshId:p.meshId,nodeId:V.id,workspace:he,updateSubmodules:!0,dryRun:!0,execute:!1}),Fe=($e==null?void 0:$e.result)??$e;if(D({phase:"dry_run",code:typeof(Fe==null?void 0:Fe.code)=="string"?Fe.code:void 0,error:typeof(Fe==null?void 0:Fe.operationError)=="string"?Fe.operationError:null,executed:(Fe==null?void 0:Fe.executed)===!0}),!(Fe!=null&&Fe.success)||Fe.code!=="fast_forward_available"||!window.confirm(`Apply fast-forward for ${V.label}?`))return;const ye=await r(me,"fast_forward_mesh_node",{meshId:p.meshId,nodeId:V.id,workspace:he,updateSubmodules:!0,dryRun:!1,execute:!0}),Oe=(ye==null?void 0:ye.result)??ye;D({phase:"execute",code:typeof(Oe==null?void 0:Oe.code)=="string"?Oe.code:void 0,error:typeof(Oe==null?void 0:Oe.operationError)=="string"?Oe.operationError:null,executed:(Oe==null?void 0:Oe.executed)===!0})}catch($e){D({phase:"dry_run",error:$e instanceof Error?$e.message:"fast-forward failed"})}finally{Y(null)}},[Te,p.meshId,V,me,r]);l.useEffect(()=>{if(!V&&!ie)return;const he=$e=>{$e.key==="Escape"&&_()};return window.addEventListener("keydown",he),()=>window.removeEventListener("keydown",he)},[_,ie,V]),l.useEffect(()=>{if(!G||!r)return;const{daemonId:he,workspace:$e}=G,Fe=E[$e];if(Fe!=null&&Fe.loading||Fe&&(Fe.entries.length>0||Fe.error))return;let Ie=!1;return I(ye=>{var Oe;return{...ye,[$e]:{loading:!0,error:null,entries:((Oe=ye[$e])==null?void 0:Oe.entries)??[]}}}),r(he,"git_log",{workspace:$e,limit:5}).then(ye=>{Ie||I(Oe=>({...Oe,[$e]:{loading:!1,error:null,entries:ON(ye)}}))}).catch(ye=>{Ie||I(Oe=>({...Oe,[$e]:{loading:!1,error:ye instanceof Error?ye.message:"git_log failed",entries:[]}}))}),()=>{Ie=!0}},[E,G,r]);const ve=[...b.warnings??[],...p.nodes.filter(he=>he.machineStatus&&he.machineStatus!=="online").map(he=>`${he.machineLabel}: ${he.machineStatus}`)],ce=b.stats.incompleteSnapshotNodes>0,H=b.stats.followUpNodes>0?`${b.stats.followUpNodes} need follow-up`:ce?"mesh visibility incomplete":"mesh converged",fe=b.stats.followUpNodes>0?"danger":ce?"warn":"good",[je,Ce]=l.useState("LR"),Be=he=>he?f.isDark?"rounded-md border border-cyan-400/40 bg-cyan-500/15 px-2 py-0.5 text-cyan-100":"rounded-md border border-sky-400 bg-sky-100 px-2 py-0.5 text-sky-800":f.isDark?"rounded-md border border-white/10 bg-white/[0.03] px-2 py-0.5 text-slate-400 hover:text-slate-200":"rounded-md border border-slate-300 bg-white/80 px-2 py-0.5 text-slate-500 hover:text-slate-800";return s.jsx(tn.Provider,{value:f,children:s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[!h&&s.jsx("div",{className:"shrink-0 flex items-center justify-end",children:s.jsx(Gp,{meshTheme:f,activeTab:N,onActiveTabChange:A,helpOpen:C,onHelpOpenChange:T})}),C&&s.jsx(TN,{meshTheme:f,onClose:()=>T(!1)}),s.jsx("div",{className:`${N==="overview"?"flex":"hidden"} min-h-0 flex-1 flex-col gap-3 overflow-y-auto`,children:N==="overview"&&s.jsx(dN,{status:p,daemonId:n,meshId:p.meshId,sendDaemonCommand:r})}),s.jsx("div",{className:`${N==="status"?"flex":"hidden"} min-h-0 flex-1 flex-col overflow-y-auto`,children:N==="status"&&s.jsx(eA,{canonicalStatus:p})}),s.jsx("div",{className:`${N==="graph"?"flex":"hidden"} min-h-0 flex-1 flex-col gap-4`,children:s.jsxs("div",{className:`${f.cardClass} relative flex min-h-0 flex-1 flex-col rounded-[28px]`,style:{minHeight:480},children:[s.jsxs("div",{className:`relative z-30 max-h-[42dvh] overflow-y-auto sm:max-h-none sm:mb-3 sm:overflow-visible shrink-0 flex flex-wrap items-start justify-between gap-2 px-4 pt-3 pb-2.5 border-b ${f.isDark?"border-white/8":"border-slate-200"}`,children:[s.jsxs("div",{className:`flex min-w-0 flex-1 flex-nowrap overflow-x-auto sm:flex-wrap sm:overflow-visible gap-2 text-xs ${f.textSecondary}`,children:[s.jsx(Ve,{label:H,tone:fe,className:"shrink-0"}),b.stats.blockedReviewNodes>0&&s.jsx(Ve,{label:`${b.stats.blockedReviewNodes} blocked`,title:`${b.stats.blockedReviewNodes} blocked review`,tone:"danger",className:"shrink-0"}),b.stats.notMergeableNodes>0&&s.jsx(Ve,{label:`${b.stats.notMergeableNodes} not mergeable`,tone:"danger",className:"shrink-0"}),b.stats.mergeReadyNodes>0&&s.jsx(Ve,{label:`${b.stats.mergeReadyNodes} need merge`,tone:"warn",className:"shrink-0"}),b.stats.cleanupCandidateNodes>0&&s.jsx(Ve,{label:`${b.stats.cleanupCandidateNodes} cleanup`,title:`${b.stats.cleanupCandidateNodes} refine/cleanup`,tone:"info",className:"shrink-0"}),b.stats.offlineNodes>0&&s.jsx(Ve,{label:`${b.stats.offlineNodes} offline`,tone:"danger",className:"shrink-0"}),b.stats.incompleteSnapshotNodes>0&&s.jsx(Ve,{label:`${b.stats.incompleteSnapshotNodes} incomplete`,title:`${b.stats.incompleteSnapshotNodes} incomplete peer snapshot`,tone:"warn",className:"shrink-0"}),b.stats.missingGitSnapshotNodes>0&&s.jsx(Ve,{label:`${b.stats.missingGitSnapshotNodes} no-git`,title:`${b.stats.missingGitSnapshotNodes} no git snapshot`,tone:"warn",className:"shrink-0"}),b.stats.missingSubmoduleSnapshotNodes>0&&s.jsx(Ve,{label:`${b.stats.missingSubmoduleSnapshotNodes} no-submod`,title:`${b.stats.missingSubmoduleSnapshotNodes} missing submodule visibility`,tone:"warn",className:"shrink-0"}),b.stats.staleGitSnapshotNodes>0&&s.jsx(Ve,{label:`${b.stats.staleGitSnapshotNodes} stale`,title:`${b.stats.staleGitSnapshotNodes} stale peer snapshot`,tone:"warn",className:"shrink-0"}),((X==null?void 0:X.active)??0)>0&&s.jsx(Ve,{label:`${(X==null?void 0:X.active)??0} active queue`,tone:"info",className:"shrink-0 hidden sm:inline-flex"}),s.jsx(Ve,{label:`${b.stats.totalNodes} nodes`,tone:"default",className:"shrink-0 hidden sm:inline-flex"}),b.stats.totalActiveSessions>0&&s.jsx(Ve,{label:`${b.stats.totalActiveSessions} attached chats`,tone:"info",className:"shrink-0 hidden sm:inline-flex"})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[s.jsxs("div",{className:f.isDark?"flex items-center gap-0.5 rounded-md border border-white/10 bg-slate-950/40 p-0.5 text-[10px]":"flex items-center gap-0.5 rounded-md border border-slate-300 bg-white/70 p-0.5 text-[10px]",role:"group","aria-label":"Graph layout direction",children:[s.jsx("button",{type:"button",onClick:()=>Ce("auto"),className:Be(je==="auto"),title:"Auto-detect direction",children:"Auto"}),s.jsx("button",{type:"button",onClick:()=>Ce("LR"),className:Be(je==="LR"),title:"Left to right",children:"LR"}),s.jsx("button",{type:"button",onClick:()=>Ce("TB"),className:Be(je==="TB"),title:"Top to bottom",children:"TB"})]}),s.jsx("div",{className:"relative",children:s.jsxs("details",{className:`rounded-xl px-3 py-1.5 text-xs ${f.isDark?"border border-white/10 bg-white/[0.03] text-slate-300":"border border-slate-200 bg-slate-50 text-slate-600"}`,children:[s.jsx("summary",{className:`cursor-pointer list-none font-medium ${f.textSecondary} [&::-webkit-details-marker]:hidden`,children:(()=>{var Fe;const he=((Fe=p.asyncRefineJobs)==null?void 0:Fe.filter(Ie=>Ie.status==="failed").length)??0,$e=de.recentFailures;return he>0?s.jsxs("span",{className:f.isDark?"text-rose-300":"text-rose-600",children:[he," refine failed"]}):$e>0?s.jsxs("span",{className:f.isDark?"text-amber-300":"text-amber-600",children:[$e," failures"]}):d("meshGraph.obs.health")})()}),s.jsx("div",{className:`absolute right-0 z-40 mt-2 w-72 max-h-[70vh] overflow-y-auto rounded-xl border p-4 shadow-xl backdrop-blur-xl ${f.isDark?"border-white/10 bg-slate-950/96":"border-slate-200 bg-white/98 shadow-slate-900/10"}`,children:s.jsx(tA,{canonicalStatus:p,queueSummary:X,ledgerSummary:de,isBootstrapMode:y,meshTheme:f,sessionEntries:re,inlineMode:!0})})]})}),s.jsx("div",{className:"relative",children:s.jsxs("details",{className:`rounded-xl px-3 py-1.5 text-xs ${f.isDark?"border border-white/10 bg-white/[0.03] text-slate-300":"border border-slate-200 bg-slate-50 text-slate-600"}`,children:[s.jsx("summary",{className:`cursor-pointer list-none font-medium ${f.textSecondary} [&::-webkit-details-marker]:hidden`,children:d("meshGraph.obs.legend")}),s.jsx("div",{className:`absolute right-0 z-40 mt-2 w-72 rounded-xl border p-3 shadow-xl backdrop-blur-xl ${f.isDark?"border-white/10 bg-slate-950/96":"border-slate-200 bg-white/98 shadow-slate-900/10"}`,children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ve,{label:`${b.stats.dirtyNodes} dirty`,tone:b.stats.dirtyNodes>0?"warn":"good"}),s.jsx(Ve,{label:`${b.stats.orphanNodes} orphan`,tone:b.stats.orphanNodes>0?"warn":"good"}),s.jsx(Ve,{label:`${de.recentFailures} recent failures`,tone:de.recentFailures>0?"danger":"good"}),W.length===0?s.jsx(Ve,{label:"no session metadata"}):W.slice(0,2).map(([he,$e])=>s.jsx(Ve,{label:`${$e} ${he}`,tone:Na(he)},he))]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(Ve,{label:"Anchor = default branch",tone:"info"}),s.jsx(Ve,{label:"Peer link = same-branch worktree",tone:"default"}),s.jsx(Ve,{label:"Submodule link = child checkout",tone:"warn"})]}),ve.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:ve.map(he=>s.jsx("span",{className:f.isDark?"rounded-full border border-amber-400/20 bg-amber-500/10 px-3 py-1 text-xs text-amber-100":"rounded-full border border-amber-300 bg-amber-50 px-3 py-1 text-xs text-amber-700",children:he},he))}),s.jsx("div",{className:`text-xs ${f.textMuted}`,children:"Click a node or edge to pin its drill-down details in the side panel. Click it again to close."})]})})]})})]})]}),y&&b.nodes.length>0&&s.jsxs("div",{className:`shrink-0 mx-4 mt-2 flex items-center gap-2 rounded-xl border px-3.5 py-2 text-xs ${f.isDark?"border-amber-400/20 bg-amber-500/10 text-amber-200":"border-amber-300 bg-amber-50 text-amber-700"}`,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full animate-pulse ${f.isDark?"bg-amber-400":"bg-amber-500"}`,"aria-hidden":!0}),s.jsx("span",{children:d("meshGraph.obs.bootstrapBanner")})]}),s.jsxs("div",{className:"relative flex flex-1 min-w-0",style:{minHeight:360},children:[s.jsx("div",{className:"flex-1 min-w-0",children:M?b.nodes.length>0?s.jsx(Zj,{data:b,selectedNodeId:P,directionPref:je,onNodeClick:he=>{if((R==null?void 0:R.kind)==="node"&&P===he.id){_();return}F(null),B(he.id),Q({kind:"node",nodeId:he.id})},onEdgeClick:he=>{if((R==null?void 0:R.kind)==="edge"&&K===he.id){_();return}B(null),F(he.id),Q({kind:"edge",edgeId:he.id})}}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:w}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:d("meshGraph.obs.loadingGraph")})}),V&&(R==null?void 0:R.kind)==="node"&&s.jsxs("div",{role:"dialog",className:`absolute inset-x-3 bottom-3 top-20 z-20 rounded-2xl border shadow-2xl sm:relative sm:inset-auto sm:z-auto sm:w-72 sm:shrink-0 sm:rounded-none sm:border-0 sm:border-l sm:shadow-none overflow-y-auto p-4 ${f.isDark?"border-white/10 bg-slate-950 sm:bg-transparent":"border-slate-200 bg-white sm:bg-transparent"}`,children:[s.jsx("div",{className:`mb-2 text-[10px] font-semibold uppercase tracking-wide ${f.textMuted}`,children:d("meshGraph.obs.selectedNode")}),s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${f.textPrimary}`,children:V.label}),s.jsx("div",{className:`mt-0.5 font-mono text-[11px] ${f.textMuted}`,children:V.id.slice(0,16)})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[V.behind>0&&s.jsx("button",{type:"button",onClick:()=>{te()},disabled:!Te||U===V.id,className:f.isDark?"rounded-full border border-emerald-400/25 bg-emerald-500/10 px-2 py-0.5 text-xs font-semibold text-emerald-100 transition hover:bg-emerald-500/18 disabled:cursor-not-allowed disabled:opacity-45":"rounded-full border border-emerald-300 bg-emerald-50 px-2 py-0.5 text-xs font-semibold text-emerald-700 transition hover:bg-emerald-100 disabled:cursor-not-allowed disabled:opacity-45",children:U===V.id?d("meshGraph.obs.checking"):d("meshGraph.obs.heal")}),s.jsx("button",{type:"button",onClick:_,"aria-label":"Close detail panel",className:f.isDark?"rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-xs text-slate-200 transition hover:bg-white/[0.08]":"rounded-full border border-slate-200 bg-white px-2 py-0.5 text-xs text-slate-600 transition hover:bg-slate-50",children:"✕"})]})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-1.5",children:[(()=>{const he=(oe==null?void 0:oe.health)??V.health;return he==="unknown"?s.jsx(Ve,{label:d("meshGraph.obs.connecting"),tone:"default"}):s.jsx(Ve,{label:he,tone:Op(he)})})(),V.branch&&s.jsx(Ve,{label:V.branch,tone:"default"}),V.ahead>0&&s.jsx(Ve,{label:`ahead ${V.ahead}`,tone:"warn"}),V.behind>0&&s.jsx(Ve,{label:`behind ${V.behind}`,tone:"warn"}),V.dirtyFiles>0&&s.jsx(Ve,{label:`${V.dirtyFiles} dirty`,tone:"warn"}),(oe==null?void 0:oe.connection)&&oe.connection.state!=="unknown"&&s.jsx(Ve,{label:GN(oe),tone:LN(oe.connection)}),((it=oe==null?void 0:oe.connection)==null?void 0:it.state)==="unknown"&&s.jsx(Ve,{label:d("meshGraph.obs.meshConnecting"),tone:"warn"}),pe.length>0&&s.jsx(Ve,{label:`${pe.length} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[V.machineLabel&&s.jsx(Pt,{label:d("meshGraph.obs.fieldMachine"),value:V.machineLabel}),V.locality&&V.locality!=="unknown"&&s.jsx(Pt,{label:d("meshGraph.obs.fieldLocality"),value:V.locality}),s.jsx(Pt,{label:d("meshGraph.obs.fieldWorkspace"),value:(oe==null?void 0:oe.workspace)??V.workspace}),q&&s.jsx(Pt,{label:d("meshGraph.obs.fieldHead"),value:q}),(V.dirtyFiles>0||V.ahead>0||V.behind>0)&&s.jsx(Pt,{label:d("meshGraph.obs.fieldDirtyAheadBehind"),value:`${V.dirtyFiles}/${V.ahead}/${V.behind}`}),pe.length>0&&s.jsx(Pt,{label:d("meshGraph.obs.fieldSessions"),value:String(pe.length)}),V.upstream&&s.jsx(Pt,{label:d("meshGraph.obs.fieldUpstream"),value:V.upstream}),(()=>{var $e;const he=(($e=oe==null?void 0:oe.connection)==null?void 0:$e.source)??KN(V);return he&&he!=="unknown"?s.jsx(Pt,{label:d("meshGraph.obs.fieldSource"),value:String(he)}):null})(),(()=>{var $e;const he=($e=oe==null?void 0:oe.connection)==null?void 0:$e.transport;return he&&he!=="unknown"?s.jsx(Pt,{label:d("meshGraph.obs.fieldTransport"),value:he}):null})(),(()=>{const he=V.machineId??(oe==null?void 0:oe.machineId);return he?s.jsx(Pt,{label:d("meshGraph.obs.fieldMachineId"),value:he}):null})(),(()=>{const he=V.daemonId??(oe==null?void 0:oe.daemonId);return he?s.jsx(Pt,{label:d("meshGraph.obs.fieldDaemonId"),value:he}):null})()]}),pe.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${f.textMuted}`,children:d("meshGraph.obs.activeSessions")}),s.jsx("div",{className:"flex flex-col gap-1.5",children:pe.map(he=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${f.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`min-w-0 truncate font-mono select-text ${f.textMuted}`,title:he.session.sessionId,children:Up(he.session.sessionId)}),s.jsx(Ve,{label:Xr(he.session),tone:Na(Xr(he.session))})]}),s.jsxs("div",{className:`mt-1 flex min-w-0 flex-wrap gap-x-2 gap-y-0.5 ${f.textMuted}`,children:[s.jsx("span",{className:"truncate",children:he.session.providerType||d("meshGraph.obs.providerUnknown")}),s.jsx("span",{children:MN(he.session)}),s.jsx("span",{children:PN(he.session)})]}),he.session.statusNote&&s.jsx("div",{className:`mt-1 text-[10px] leading-4 ${f.textMuted}`,children:he.session.statusNote}),s.jsxs("div",{className:`mt-0.5 truncate ${f.textMuted}`,title:he.session.workspace||he.workspace,children:[(he.session.workspace||he.workspace).slice(0,38),he.branch?` · ${he.branch}`:""]})]},he.session.sessionId))})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${f.textMuted}`,children:d("meshGraph.obs.ledger")}),s.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[s.jsx(Pt,{label:d("meshGraph.obs.fieldCompleted"),value:String(de.taskCompleted)}),s.jsx(Pt,{label:d("meshGraph.obs.fieldFailed"),value:s.jsx("span",{className:de.taskFailed>0?f.isDark?"text-rose-300":"text-rose-600":"",children:de.taskFailed})}),s.jsx(Pt,{label:d("meshGraph.obs.fieldLaunched"),value:String(de.sessionLaunched)}),s.jsx(Pt,{label:d("meshGraph.obs.fieldRecentFailures"),value:s.jsx("span",{className:de.recentFailures>0?f.isDark?"text-amber-300":"text-amber-600":"",children:de.recentFailures})})]})]}),(()=>{var Fe,Ie;const he=((Fe=p.queue)==null?void 0:Fe.tasks)??((Ie=p.queue)==null?void 0:Ie.items)??null;if(!Array.isArray(he)||he.length===0)return null;const $e=he.filter(ye=>FN(ye)===P).slice(0,3);return $e.length===0?null:s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${f.textMuted}`,children:d("meshGraph.obs.queueTasks")}),s.jsx("div",{className:"flex flex-col gap-1.5",children:$e.map(ye=>s.jsxs("div",{className:`rounded-lg border px-2.5 py-1.5 text-[11px] ${f.isDark?"border-white/8 bg-white/[0.03]":"border-slate-200 bg-slate-50/80"}`,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:`font-mono ${f.textMuted}`,children:ye.id.slice(0,12)}),s.jsx(Ve,{label:ye.status??"unknown",tone:Na(ye.status)})]}),ye.message&&s.jsx("div",{className:`mt-0.5 truncate ${f.textMuted}`,children:ye.message.slice(0,48)})]},ye.id))})]})})(),V.snapshotWarnings.length>0&&s.jsxs("div",{className:f.isDark?"mt-3 rounded-xl border border-amber-400/20 bg-amber-500/10 p-3 text-xs text-amber-100":"mt-3 rounded-xl border border-amber-300 bg-amber-50 p-3 text-xs text-amber-800",children:[s.jsx("div",{className:"font-medium",children:d("meshGraph.obs.keyWarning")}),s.jsx("div",{className:"mt-1",children:V.snapshotWarnings[0]})]}),V.branchConvergence&&(V.branchConvergence.reason||V.branchConvergence.nextStep)&&s.jsxs("div",{className:f.isDark?"mt-3 rounded-xl border border-sky-400/20 bg-sky-500/10 p-3 text-xs text-sky-100":"mt-3 rounded-xl border border-sky-300 bg-sky-50 p-3 text-xs text-sky-800",children:[s.jsx("div",{className:"font-medium",children:d("meshGraph.obs.followUpLabel",{status:x[V.branchConvergence.status]??V.branchConvergence.status})}),V.branchConvergence.reason&&s.jsx("div",{className:"mt-1",children:V.branchConvergence.reason}),V.branchConvergence.nextStep&&s.jsx("div",{className:`${V.branchConvergence.reason?"mt-1.5 pt-1.5 border-t border-sky-400/20":"mt-1"}`,children:V.branchConvergence.nextStep})]}),$&&s.jsxs("div",{className:f.isDark?"mt-3 rounded-xl border border-emerald-400/20 bg-emerald-500/10 p-3 text-xs text-emerald-100":"mt-3 rounded-xl border border-emerald-300 bg-emerald-50 p-3 text-xs text-emerald-800",children:[s.jsx("div",{className:"font-medium",children:$.phase==="execute"?d("meshGraph.obs.healResult"):d("meshGraph.obs.healPreview")}),s.jsx("div",{className:"mt-1",children:$.code??$.error??d("meshGraph.obs.noResultCode")})]})]}),ie&&(R==null?void 0:R.kind)==="edge"&&s.jsxs("div",{role:"dialog",className:`absolute inset-x-3 bottom-3 top-20 z-20 rounded-2xl border shadow-2xl sm:relative sm:inset-auto sm:z-auto sm:w-72 sm:shrink-0 sm:rounded-none sm:border-0 sm:border-l sm:shadow-none overflow-y-auto p-4 ${f.isDark?"border-white/10 bg-slate-950 sm:bg-transparent":"border-slate-200 bg-white sm:bg-transparent"}`,children:[s.jsx("div",{className:`mb-2 text-[10px] font-semibold uppercase tracking-wide ${f.textMuted}`,children:d("meshGraph.obs.selectedEdge")}),s.jsxs("div",{className:"mb-3 flex items-start justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:`truncate text-sm font-semibold ${f.textPrimary}`,children:ie.label||ud(ie)}),s.jsx("div",{className:`mt-0.5 break-all font-mono text-[11px] ${f.textMuted}`,children:ie.id})]}),s.jsx("button",{type:"button",onClick:_,"aria-label":"Close detail panel",className:f.isDark?"shrink-0 rounded-full border border-white/10 bg-white/[0.04] px-2 py-0.5 text-xs text-slate-200 transition hover:bg-white/[0.08]":"shrink-0 rounded-full border border-slate-200 bg-white px-2 py-0.5 text-xs text-slate-600 transition hover:bg-slate-50",children:"✕"})]}),s.jsxs("div",{className:"mb-3 flex flex-wrap gap-1.5",children:[s.jsx(Ve,{label:ud(ie),tone:"default"}),s.jsx(Ve,{label:zN(ie),tone:"info"})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(Pt,{label:d("meshGraph.obs.fieldFrom"),value:(ke==null?void 0:ke.label)??ie.source}),s.jsx(Pt,{label:d("meshGraph.obs.fieldTo"),value:(xe==null?void 0:xe.label)??ie.target}),s.jsx(Pt,{label:d("meshGraph.obs.fieldLabel"),value:ie.label??"none"})]})]})]})]})})]})})}function Nt(e){return typeof e=="string"?e.trim():""}function bi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function hl(...e){const t=new Set;for(const n of e){const r=Nt(n);r&&t.add(r)}return[...t]}function nA(e,t){var m,f;const n=bi(e==null?void 0:e.settings),r=Nt((m=e==null?void 0:e.coordinator)==null?void 0:m.meshId)||Nt(n.meshCoordinatorFor),o=Nt(n.meshNodeFor),a=!!r||!!o,i=r===t||o===t;if(a&&!i)return null;const c=bi(e==null?void 0:e.activeChat),u=hl(e==null?void 0:e.id,e==null?void 0:e.sessionId,e==null?void 0:e.session_id,e==null?void 0:e.providerSessionId,e==null?void 0:e.provider_session_id,e==null?void 0:e.targetSessionId,e==null?void 0:e.target_session_id,c.sessionId,c.session_id,c.providerSessionId,c.provider_session_id),h=u[0]||"";if(!h)return null;const d=r===t?Nt((f=e==null?void 0:e.coordinator)==null?void 0:f.role)||"coordinator":o===t?Nt(n.meshNodeRole)||"worker":Nt(e==null?void 0:e.role)||Nt(n.meshNodeRole)||void 0;return{sessionId:h,aliases:u,meshId:t,nodeId:i&&Nt(n.meshNodeId)||null,providerType:Nt(e==null?void 0:e.providerType)||void 0,state:Nt(e==null?void 0:e.status)||void 0,chatStatus:Nt(c.status)||void 0,lifecycle:Nt(e==null?void 0:e.runtimeLifecycle)||void 0,surfaceKind:Nt(e==null?void 0:e.runtimeSurfaceKind)||void 0,recoveryState:Nt(e==null?void 0:e.runtimeRecoveryState)||void 0,...d?{role:d}:{},...i?{isSelfCoordinator:r===t}:{},workspace:Nt(e==null?void 0:e.workspace)||null}}function Kp(e,t){var r;return t?(Array.isArray((r=e.status)==null?void 0:r.sessions)?e.status.sessions:[]).map(o=>nA(o,t)).filter(o=>o!==null):[]}function vo(e){return e.aliases&&e.aliases.length>0?e.aliases:[e.sessionId]}function rA(e,t){const n=new Set(vo(t));return vo(e).some(r=>n.has(r))}function oA(e,t){const n=t.filter(o=>!!o);return n.length===0?e:[...e.filter(o=>!n.some(a=>rA(o,a))),...n]}function aA(e,t){if(t.length===0)return e;const n=new Map;for(const i of t)for(const c of vo(i))n.set(c,i);let r=!1;const a=(e.nodes??[]).map((i,c)=>{const u=Array.isArray(i.activeSessionDetails)?i.activeSessionDetails:Array.isArray(i.sessions)?i.sessions:[],h=new Map;for(const f of u){const x=hl(f==null?void 0:f.sessionId,f==null?void 0:f.session_id,f==null?void 0:f.id,f==null?void 0:f.providerSessionId,f==null?void 0:f.provider_session_id),w=x[0]||"";if(!w)continue;const p=x.map(y=>n.get(y)).find(Boolean);p&&(r=!0),h.set(w,p?{...f,sessionId:w,providerType:p.providerType||f.providerType,state:p.state||f.state,chatStatus:p.chatStatus||f.chatStatus,lifecycle:p.lifecycle||f.lifecycle,surfaceKind:p.surfaceKind||f.surfaceKind,recoveryState:p.recoveryState||f.recoveryState,role:p.role||f.role,isSelfCoordinator:p.isSelfCoordinator??f.isSelfCoordinator,workspace:p.workspace||f.workspace}:{...f,sessionId:w})}for(const f of i.activeSessions??[])h.has(f)||h.set(f,{sessionId:f,workspace:i.workspace,isCached:!0});const d=c===0;for(const f of t){if(vo(f).some(y=>h.has(y)))continue;const w=f.nodeId!=null&&f.nodeId===i.nodeId,p=f.isSelfCoordinator&&!f.nodeId&&d;!w&&!p||(r=!0,h.set(f.sessionId,{sessionId:f.sessionId,providerType:f.providerType,state:f.state,chatStatus:f.chatStatus,lifecycle:f.lifecycle,surfaceKind:f.surfaceKind,recoveryState:f.recoveryState,role:f.role,isSelfCoordinator:f.isSelfCoordinator,workspace:f.workspace||i.workspace}))}const m=[...h.values()];return m.length===0?i:{...i,activeSessionDetails:m,activeSessions:m.map(f=>f.sessionId)}});return r?{...e,nodes:a}:e}function iA(e,t){const r=Kp(e,t).map(o=>{var u;const a=(Array.isArray((u=e.status)==null?void 0:u.sessions)?e.status.sessions:[]).find(h=>Nt(h==null?void 0:h.id)===o.sessionId),i=bi(a==null?void 0:a.activeInteractivePrompt),c=a!=null&&a.meshQueueStats&&typeof a.meshQueueStats=="object"?JSON.stringify(a.meshQueueStats):"";return[o.sessionId,o.providerType??"",o.state??"",o.chatStatus??"",o.lifecycle??"",o.surfaceKind??"",o.recoveryState??"",Nt(i.status)||Nt(i.kind)||Nt(i.type),o.nodeId??"",o.isSelfCoordinator?"coordinator":"worker",c].join("|")}).filter(o=>!!o).sort();return r.length>0?r.join(`
89
+ `):null}function zp({status:e,daemonId:t,extraDaemonIds:n,meshId:r,sendData:o,extraLiveSessions:a=[]}){const[i,c]=l.useState(new Map),u=l.useRef(new Map),h=l.useMemo(()=>{const x=new Set;if(t&&x.add(t),n)for(const w of n)w&&x.add(w);return[...x].sort()},[t,n]),d=h.join(",");l.useEffect(()=>{u.current=new Map,c(new Map)},[t,r]),l.useEffect(()=>{if(!r||!o||h.length===0)return;const x=h.map(w=>ls.subscribe({sendData:o},w,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${w}`,params:{includeSessions:!0}},p=>{if(p.topic!=="daemon.metadata")return;const y=iA(p,r);if(y===(u.current.get(w)??null))return;u.current.set(w,y);const k=Kp(p,r);c(b=>{const j=new Map(b);return j.set(w,k),j})}));return()=>{for(const w of x)w()}},[d,r,o]);const m=l.useMemo(()=>{const x=[];for(const w of i.values())x.push(...w);return x},[i]),f=l.useMemo(()=>oA(m,a),[a,m]);return l.useMemo(()=>e?aA(e,f):null,[f,e])}const hd=[1500,4e3,9e3];function lA(e){var t,n,r,o,a,i;return!!(((t=e.git)==null?void 0:t.isGitRepo)===!0||(n=e.git)!=null&&n.branch||(r=e.git)!=null&&r.upstream||(o=e.git)!=null&&o.headCommit||(a=e.git)!=null&&a.workspace||(i=e.git)!=null&&i.repoRoot)}function cA(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>{var n;return lA(t)?!1:t.gitProbePending||((n=t.connection)==null?void 0:n.state)==="connecting"?!0:t.machineStatus==="online"||t.launchReady===!0})}function dA(e){return!Number.isInteger(e)||e<0?hd[0]:hd[e]??null}const Aa=new Map;function uA(e,t){return!e||!t?null:`${e}::${t}`}function hA(e,t){var a,i,c,u;if(!t||!e.sessionId)return null;const n=((a=e.coordinator)==null?void 0:a.meshId)??(typeof((i=e.settings)==null?void 0:i.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),r=typeof((c=e.settings)==null?void 0:c.meshNodeFor)=="string"?e.settings.meshNodeFor:null;if(n!==t&&r!==t)return null;const o=typeof((u=e.settings)==null?void 0:u.meshNodeId)=="string"?e.settings.meshNodeId:null;return{sessionId:e.sessionId,aliases:hl(e.sessionId,e.providerSessionId,e.historySessionId,e.nativeSessionId),meshId:t,nodeId:o,providerType:e.agentType,state:e.status,chatStatus:e.status,role:n===t?"coordinator":"worker",isSelfCoordinator:n===t,workspace:e.workspacePath??null}}function qp({activeConv:e,sendDaemonCommand:t,onClose:n}){var ae,z,X,de,re,W;const r=((ae=e.coordinator)==null?void 0:ae.meshId)??(typeof((z=e.settings)==null?void 0:z.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),o=e.daemonId??null,a=uA(o,r),i=a?Aa.get(a)??null:null,c=Bi(),{sendData:u}=yt(),{theme:h}=Ls(),d=l.useMemo(()=>Rs(h),[h]),[m,f]=l.useState("overview"),[x,w]=l.useState(!1),p=l.useMemo(()=>hA(e,r),[e.agentType,(X=e.coordinator)==null?void 0:X.meshId,e.sessionId,(de=e.settings)==null?void 0:de.meshCoordinatorFor,(re=e.settings)==null?void 0:re.meshNodeFor,(W=e.settings)==null?void 0:W.meshNodeId,e.status,e.workspacePath,r]),[y,k]=l.useState(i),[b,j]=l.useState(!1),[S,v]=l.useState(!1),[g,N]=l.useState(!1),[C,A]=l.useState(null),[T,M]=l.useState((i==null?void 0:i.refreshedAt)??null),L=l.useRef(i!==null),P=l.useRef(!1),B=l.useRef(!1),K=l.useRef(!0),F=l.useRef(0),R=l.useRef(null);l.useEffect(()=>{L.current=y!==null},[y]);const Q=l.useCallback(()=>{R.current!==null&&(clearTimeout(R.current),R.current=null)},[]);l.useEffect(()=>{Q(),F.current=0;const oe=a?Aa.get(a)??null:null;k(oe),M((oe==null?void 0:oe.refreshedAt)??null),L.current=oe!==null,B.current=!1,v(!1),A(null)},[a,Q]);const E=l.useCallback(async(oe=!1,V=!1)=>{if(!o||!r){A("This coordinator does not expose a live mesh id."),k(null);return}if(P.current){oe&&(B.current=!0);return}V||(Q(),F.current=0),P.current=!0;const ie=!L.current;j(ie),v(oe&&L.current),A(null);try{const ke=c!=null&&c.loadMeshStatus?await c.loadMeshStatus(o,r,{refresh:oe,retryProfile:V?"interactive":"settled"}):await t(o,"mesh_status",{meshId:r,refresh:oe}),xe=Hi(ke);if(!xe){A("mesh_status returned an unexpected payload.");return}if(a&&Aa.set(a,xe),k(xe),L.current=!0,M(xe.refreshedAt||new Date().toISOString()),cA(xe.nodes)){const Se=dA(F.current);Se!==null&&K.current&&(F.current+=1,R.current=setTimeout(()=>{K.current&&E(!0,!0)},Se))}else F.current=0}catch(ke){A(ke instanceof Error?ke.message:"Failed to load live mesh status")}finally{P.current=!1,j(!1),v(!1),B.current&&K.current&&(B.current=!1,window.setTimeout(()=>{K.current&&E(!0)},0))}},[a,Q,o,r,c,t]);l.useEffect(()=>(K.current=!0,F.current=0,(async()=>(await E(!1,!0),K.current&&R.current===null&&!P.current&&E(!0,!0)))(),()=>{K.current=!1,Q()}),[E,Q]),l.useEffect(()=>{const oe=V=>{V.key==="Escape"&&n()};return window.addEventListener("keydown",oe),()=>window.removeEventListener("keydown",oe)},[n]);const I=(y==null?void 0:y.meshName)||r||"Repo Mesh",$=l.useMemo(()=>p?[p]:[],[p]),D=zp({status:y,daemonId:o,meshId:r,sendData:u,extraLiveSessions:$}),U=T?new Date(T).toLocaleTimeString():null,Y=l.useMemo(()=>b?"Loading live mesh status…":"No live mesh graph is available for this coordinator yet.",[b]);return s.jsx("div",{className:d.dialogOverlayClass,onClick:n,children:s.jsxs("div",{role:"dialog","aria-modal":"true",className:d.dialogShellClass,onClick:oe=>oe.stopPropagation(),children:[s.jsxs("div",{className:`relative ${d.dialogHeaderClass}`,children:[s.jsx("button",{type:"button",onClick:n,className:`absolute right-4 top-[calc(16px+env(safe-area-inset-top,0px))] z-10 md:right-5 md:top-1/2 md:-translate-y-1/2 ${d.dialogCloseButtonClass}`,"aria-label":"Close mesh graph",children:s.jsx(At,{size:16})}),s.jsx("div",{className:"min-w-0 flex-1 pr-12 md:pr-0",children:s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-2xl border border-sky-400/20 bg-sky-500/12 text-sky-200 shadow-[0_12px_30px_rgba(14,165,233,0.18)]",children:s.jsx(es,{size:18})}),s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("h2",{className:d.dialogTitleClass,children:I}),s.jsx("span",{className:d.dialogKickerClass,children:"Mesh observability"}),s.jsx("button",{type:"button",onClick:()=>N(oe=>!oe),"aria-expanded":g,"aria-label":g?"Hide mesh details":"Show mesh details",className:"btn btn-secondary btn-sm rounded-lg px-1.5 py-1 md:hidden",title:g?"Hide mesh details":"Show mesh details",children:s.jsx(Ni,{size:14})})]}),s.jsxs("p",{className:`${d.dialogSubtitleClass} ${g?"block":"hidden"} md:block`,children:[xt(e),e.workspaceName?` · ${e.workspaceName}`:"",y!=null&&y.repoIdentity?` · ${y.repoIdentity}`:""]})]})]})}),s.jsxs("div",{className:"flex flex-wrap items-center gap-2 md:justify-end md:pr-12",children:[s.jsx(Gp,{meshTheme:d,activeTab:m,onActiveTabChange:f,helpOpen:x,onHelpOpenChange:w}),U&&s.jsx("span",{className:`${d.dialogRefreshedChipClass} ${g?"inline-flex":"hidden"} md:inline-flex`,children:`Refreshed ${U}`}),!S&&y&&s.jsx("span",{className:`${d.dialogRefreshedChipClass} ${g?"inline-flex":"hidden"} md:inline-flex`,children:u&&!C?"Live daemon metadata":"Metadata subscription unavailable"}),s.jsx("button",{type:"button",onClick:()=>{E(!0)},disabled:b||S,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:"Refresh live mesh graph",children:b||S?"Refreshing…":"Refresh"})]})]}),C&&s.jsx("div",{className:d.isDark?"shrink-0 border-b border-rose-400/20 bg-rose-500/12 px-4 py-2 text-sm text-rose-200 md:px-5":"shrink-0 border-b border-rose-300 bg-rose-50 px-4 py-2 text-sm text-rose-700 md:px-5",children:C}),s.jsx("div",{className:d.dialogBodyClass,children:D?s.jsx(sA,{status:D,emptyMessage:Y,daemonId:o,sendDaemonCommand:t,activeTab:m,onActiveTabChange:f,helpOpen:x,onHelpOpenChange:w,hideControls:!0}):s.jsx("div",{className:d.dialogEmptyClass,children:Y})})]})})}function pA(e,t){const{sendCommand:n}=yt(),[r,o]=l.useState(null),[a,i]=l.useState(!1);l.useEffect(()=>{if(!e||!t){o(null);return}i(!0),n(e,"git_remote_url",{workspace:t}).then(u=>{const h=(u==null?void 0:u.result)??u;o(typeof(h==null?void 0:h.remoteUrl)=="string"?h.remoteUrl:null)}).catch(()=>{o(null)}).finally(()=>i(!1))},[e,t,n]);const c=mA(r);return{remoteUrl:r,githubUrl:c,loading:a}}function mA(e){if(!e)return null;const t=e.match(/git@github\.com[:/](.+?)(?:\.git)?$/);if(t)return`https://github.com/${t[1]}`;const n=e.match(/https?:\/\/github\.com\/(.+?)(?:\.git)?$/);return n?`https://github.com/${n[1]}`:null}const Vp=5e3;function fA(e){return`git:${e}`}function bA({workspace:e,includeDiffSummary:t=!1,intervalMs:n=Vp}){return{type:"subscribe",topic:"workspace.git",key:fA(e),params:{workspace:e,includeDiffSummary:t,intervalMs:n}}}function pl(e){return e&&typeof e=="object"&&"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function Xs(e,t){if(e instanceof Error)return e.message;if(e&&typeof e=="object"){const n=e;if(typeof n.error=="string"&&n.error.trim())return n.error;if(typeof n.message=="string"&&n.message.trim())return n.message}return t}function gA(e){const t=pl(e);return(t==null?void 0:t.success)===!1?{status:null,error:Xs(t,"Git status request failed")}:t!=null&&t.status?{status:t.status,error:null}:{status:null,error:Xs(t,"Git status response did not include status")}}function xA(e){const t=pl(e);return(t==null?void 0:t.success)===!1?{diffSummary:null,error:Xs(t,"Git diff summary request failed")}:t!=null&&t.diffSummary?{diffSummary:t.diffSummary,error:null}:{diffSummary:null,error:Xs(t,"Git diff summary response did not include diffSummary")}}function Ta(e){return e===void 0||typeof e=="boolean"}function yA(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&Ta(t.binary)&&Ta(t.truncated)&&Ta(t.staged)}function vA(e){const t=pl(e);return(t==null?void 0:t.success)===!1?{diff:null,error:Xs(t,"Git file diff request failed")}:yA(t==null?void 0:t.diff)?{diff:t.diff,error:null}:{diff:null,error:Xs(t,"Git file diff response did not include a valid diff object")}}function wA({daemonId:e,workspace:t,enabled:n=!0,includeDiffSummary:r=!1,intervalMs:o=Vp}){const{sendCommand:a,sendData:i}=yt(),c=typeof t=="string"?t.trim():"",u=!!(n&&e&&c),[h,d]=l.useState(null),[m,f]=l.useState(null),[x,w]=l.useState(!1),[p,y]=l.useState(null),k=l.useCallback(async()=>{if(!(!u||!e||!c)){w(!0),y(null);try{const j=gA(await a(e,"git_status",{workspace:c}));if(j.error){d(null),f(null),y(j.error);return}if(d(j.status),!r){f(null);return}const S=xA(await a(e,"git_diff_summary",{workspace:c}));if(S.error){f(null),y(S.error);return}f(S.diffSummary)}catch(j){y(Xs(j,"Git status request failed"))}finally{w(!1)}}},[u,e,r,a,c]),b=l.useMemo(()=>c?bA({workspace:c,includeDiffSummary:r,intervalMs:o}):null,[r,o,c]);return l.useEffect(()=>{if(!u||!e||!c||!b){d(null),f(null),w(!1),y(null);return}const j=i?ls.subscribe({sendData:i},e,b,S=>{var v,g;S.workspace===c&&(d(S.status),f(S.diffSummary??null),y(((v=S.status)==null?void 0:v.error)||((g=S.diffSummary)==null?void 0:g.error)||null),w(!1))},{retryIntervalMs:1e3}):null;return k(),()=>{j==null||j()}},[u,e,k,b,i,c]),{status:h,diffSummary:m,loading:x,error:p,refresh:k}}const kA={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},SA={added:"text-status-online",modified:"text-orange-400",deleted:"text-status-error",renamed:"text-accent-primary",copied:"text-accent-primary",untracked:"text-text-muted",conflict:"text-status-error font-bold"};function pd(e){return e.split("/").pop()??e}function CA(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function jA({files:e,truncated:t,onFileClick:n,selectedPath:r,className:o=""}){return e.length===0?s.jsx("p",{className:"px-3 py-2 text-xs text-text-secondary",children:"No changed files."}):s.jsxs("div",{className:`flex flex-col ${o}`,children:[s.jsx("ul",{className:"min-w-0 divide-y divide-border/30",children:e.map(a=>{const i=r===a.path,c=kA[a.status]??"?",u=SA[a.status]??"text-text-muted",h=CA(a.path),d=pd(a.path),m=a.staged?s.jsx("span",{className:"ml-1 inline-block h-1.5 w-1.5 rounded-full bg-status-online align-middle",title:"Staged"}):null;return s.jsxs("li",{className:`flex cursor-pointer items-center gap-2 px-3 py-1.5 text-xs hover:bg-surface-elevated/60 ${i?"bg-surface-elevated":""}`,onClick:()=>n==null?void 0:n(a),children:[s.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${u}`,title:a.status,children:c}),s.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[h&&s.jsxs("span",{className:"text-text-secondary",children:[h,"/"]}),s.jsx("span",{className:"text-text-primary",children:d}),a.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",pd(a.oldPath)]}),m]}),!a.binary&&(a.insertions>0||a.deletions>0)&&s.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[a.insertions>0&&s.jsxs("span",{className:"text-status-online",children:["+",a.insertions]}),a.insertions>0&&a.deletions>0&&s.jsx("span",{className:"text-text-secondary",children:" "}),a.deletions>0&&s.jsxs("span",{className:"text-status-error",children:["-",a.deletions]})]}),a.binary&&s.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:"bin"})]},`${a.path}-${a.staged?"S":"U"}`)})}),t&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary",children:["File list truncated — run ",s.jsx("code",{className:"font-mono",children:"git status"})," locally for full output."]})]})}function NA(e,t){let n="text-text-secondary";return e.startsWith("+")&&!e.startsWith("+++")?n="bg-status-online/10 text-status-online":e.startsWith("-")&&!e.startsWith("---")?n="bg-status-error/10 text-status-error":e.startsWith("@@")?n="text-accent-primary":(e.startsWith("diff ")||e.startsWith("index ")||e.startsWith("--- ")||e.startsWith("+++ "))&&(n="text-text-secondary"),s.jsx("div",{className:`px-3 ${n}`,children:s.jsx("code",{className:"whitespace-pre font-mono text-[11px] leading-5",children:e})},t)}function AA({diff:e,binary:t,truncated:n,loading:r,error:o,className:a=""}){const i=l.useRef(null);if(l.useEffect(()=>{i.current&&(i.current.scrollTop=0)},[e]),r)return s.jsx("div",{className:`flex items-center justify-center py-8 text-xs text-text-secondary ${a}`,children:"Loading diff…"});if(o)return s.jsx("div",{className:`px-3 py-4 text-xs text-status-error ${a}`,children:o});if(t)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${a}`,children:"Binary file — diff not available."});if(!e)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${a}`,children:"No diff available."});const c=e.split(`
90
+ `);return s.jsxs("div",{ref:i,className:`overflow-auto ${a}`,children:[s.jsx("div",{className:"py-1",children:c.map((u,h)=>NA(u,h))}),n&&s.jsxs("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary border-t border-border/30",children:["Diff truncated — run ",s.jsx("code",{className:"font-mono",children:"git diff"})," locally for full output."]})]})}function TA(e,t){const n=[`Branch: ${e||"unknown"}`];n.push(`Changed: ${t.files.length} file(s) +${t.totalInsertions}/-${t.totalDeletions}`);const r={};for(const o of t.files)r[o.status]||(r[o.status]=[]),r[o.status].push(o.path);for(const[o,a]of Object.entries(r))n.push(`${o}: ${a.slice(0,5).join(", ")}${a.length>5?` (+${a.length-5} more)`:""}`);return n.join(`
91
+ `)}function Yp({daemonId:e,workspace:t,onClose:n}){const{sendCommand:r}=yt(),{status:o,diffSummary:a,loading:i,error:c,refresh:u}=wA({daemonId:e,workspace:t,includeDiffSummary:!0}),[h,d]=l.useState(null),[m,f]=l.useState(null),[x,w]=l.useState(""),[p,y]=l.useState(!1),[k,b]=l.useState(!1),[j,S]=l.useState(null),[v,g]=l.useState(null),{githubUrl:N}=pA(e,t),C=l.useCallback(async B=>{if(!((h==null?void 0:h.path)===B.path&&!h.loading)){d({path:B.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const K=await r(e,"git_diff_file",{workspace:t,path:B.path,staged:B.staged}),F=vA(K);if(F.error||!F.diff){d({path:B.path,diff:"",binary:!1,truncated:!1,loading:!1,error:F.error??"Failed to load diff"});return}d({path:B.path,diff:F.diff.diff,binary:F.diff.binary??!1,truncated:F.diff.truncated??!1,loading:!1,error:null})}catch(K){const F=K instanceof Error?K.message:"Failed to load diff";d({path:B.path,diff:"",binary:!1,truncated:!1,loading:!1,error:F})}}},[e,r,h,t]),A=l.useCallback(B=>{w(""),y(!1),S(null),g(null),f(B)},[]),T=l.useCallback(()=>{f(null),S(null),b(!1)},[]),M=l.useCallback(async()=>{var B,K,F;if(m){b(!0),S(null);try{let R;m==="checkpoint"?R=await r(e,"git_checkpoint",{workspace:t,message:x,includeUntracked:p}):m==="stash"?R=await r(e,"git_stash_push",{workspace:t,message:x,includeUntracked:p}):m==="stash_pop"?R=await r(e,"git_stash_pop",{workspace:t}):m==="checkout_files"&&h&&(R=await r(e,"git_checkout_files",{workspace:t,paths:[h.path]}));const Q=(R==null?void 0:R.result)??R;if((Q==null?void 0:Q.success)===!1||Q!=null&&Q.error){S((Q==null?void 0:Q.error)??"Action failed"),b(!1);return}m==="checkpoint"?g(`Checkpoint created: ${((K=(B=Q==null?void 0:Q.checkpoint)==null?void 0:B.commit)==null?void 0:K.slice(0,7))??"done"}`):m==="stash"?g(`Stashed as ${((F=Q==null?void 0:Q.stash)==null?void 0:F.stashRef)??"stash@{0}"}`):m==="stash_pop"?g("Stash restored"):(g("File reverted"),d(null)),f(null),await u()}catch(R){S(R instanceof Error?R.message:"Action failed")}finally{b(!1)}}},[m,r,e,t,x,p,h,u]),L=!!(o!=null&&o.hasConflicts),P=o?o.staged+o.modified+o.untracked+o.deleted+o.renamed:null;return s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4",onClick:B=>{B.target===B.currentTarget&&n()},children:s.jsxs("div",{className:"relative flex h-[80vh] w-full max-w-3xl flex-col overflow-hidden rounded-xl border border-border bg-surface shadow-xl",children:[s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-b border-border px-4 py-3",children:[s.jsx("span",{"aria-hidden":"true",className:"text-sm",children:"⑂"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate text-sm font-semibold text-text-primary",children:(o==null?void 0:o.branch)??"Git Status"}),s.jsx("p",{className:"truncate text-xs text-text-secondary",children:t}),N&&s.jsx("a",{href:`${N}/tree/${(o==null?void 0:o.branch)||"main"}`,target:"_blank",rel:"noopener noreferrer",className:"truncate text-[10px] text-text-secondary hover:text-accent-primary underline",title:"Open on GitHub",children:"GitHub ↗"})]}),s.jsx("button",{onClick:u,disabled:i,className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40",title:"Refresh",children:"↺"}),s.jsx("button",{onClick:n,className:"rounded p-1 text-text-secondary hover:text-text-primary","aria-label":"Close",children:s.jsx(At,{className:"h-4 w-4"})})]}),o&&s.jsxs("div",{className:"flex shrink-0 flex-wrap gap-x-4 gap-y-1 border-b border-border/50 px-4 py-2 text-xs text-text-secondary",children:[o.headCommit&&s.jsxs("span",{title:o.headMessage??void 0,children:[s.jsx("span",{className:"font-mono",children:o.headCommit.slice(0,7)}),o.headMessage&&s.jsx("span",{className:"ml-1 truncate",children:o.headMessage.slice(0,60)})]}),o.ahead>0&&s.jsxs("span",{className:"text-orange-400",children:["↑",o.ahead," ahead"]}),o.behind>0&&s.jsxs("span",{className:"text-orange-400",children:["↓",o.behind," behind"]}),o.staged>0&&s.jsxs("span",{className:"text-status-online",children:[o.staged," staged"]}),o.modified>0&&s.jsxs("span",{children:[o.modified," modified"]}),o.untracked>0&&s.jsxs("span",{children:[o.untracked," untracked"]}),o.deleted>0&&s.jsxs("span",{className:"text-status-error",children:[o.deleted," deleted"]}),o.stashCount>0&&s.jsxs("span",{children:[o.stashCount," stashed"]}),o.hasConflicts&&s.jsx("span",{className:"font-bold text-status-error",children:"conflicts"}),P===0&&!o.error&&s.jsx("span",{className:"text-status-online",children:"clean"}),a&&a.files.length>0&&s.jsxs("span",{className:"text-text-secondary",children:[a.files.length," file",a.files.length!==1?"s":"",a.totalInsertions>0&&s.jsxs("span",{className:"text-status-online",children:[" +",a.totalInsertions]}),a.totalDeletions>0&&s.jsxs("span",{className:"text-status-error",children:[" -",a.totalDeletions]})]})]}),c&&s.jsx("div",{className:"shrink-0 border-b border-border/50 bg-status-error/10 px-4 py-2 text-xs text-status-error",children:c}),s.jsxs("div",{className:"flex min-h-0 flex-1",children:[s.jsxs("div",{className:"flex w-56 shrink-0 flex-col overflow-y-auto border-r border-border/50",children:[i&&!a&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),a&&s.jsx(jA,{files:a.files,truncated:a.truncated,selectedPath:(h==null?void 0:h.path)??null,onFileClick:C}),!i&&!a&&!c&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"No diff data."})]}),s.jsx("div",{className:"min-w-0 flex-1 overflow-hidden",children:h?s.jsx(AA,{diff:h.diff,binary:h.binary,truncated:h.truncated,loading:h.loading,error:h.error,className:"h-full"}):s.jsx("div",{className:"flex h-full items-center justify-center text-xs text-text-secondary",children:"Select a file to view diff"})})]}),v&&s.jsxs("div",{className:"shrink-0 border-t border-border/50 bg-status-online/10 px-4 py-2 text-xs text-status-online flex items-center justify-between",children:[s.jsx("span",{children:v}),s.jsx("button",{onClick:()=>g(null),className:"ml-2 text-status-online hover:text-text-primary",children:"×"})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-2 border-t border-border px-4 py-2",children:[s.jsx("button",{onClick:()=>A("checkpoint"),disabled:L,title:L?"Resolve conflicts before checkpointing":"Create a git commit checkpoint",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkpoint"}),s.jsx("button",{onClick:()=>A("stash"),disabled:L,title:L?"Resolve conflicts before stashing":"Stash current changes",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Stash"}),s.jsx("button",{onClick:()=>A("stash_pop"),disabled:L||!(o!=null&&o.stashCount),title:L?"Resolve conflicts before restoring a stash":o!=null&&o.stashCount?"Restore the latest stash":"No stashes to restore",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Pop stash"}),s.jsx("button",{onClick:()=>A("checkout_files"),disabled:!h,title:h?`Revert changes to ${h.path}`:"Select a file to revert",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkout selected"}),a&&a.files.length>0&&s.jsx("button",{onClick:()=>{const B=TA((o==null?void 0:o.branch)??null,a);navigator.clipboard.writeText(B),g("Copied to clipboard"),setTimeout(()=>g(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),m&&s.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:s.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[s.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[m==="checkpoint"&&"Create checkpoint commit",m==="stash"&&"Stash changes",m==="stash_pop"&&"Restore latest stash?",m==="checkout_files"&&`Revert changes to ${(h==null?void 0:h.path)??"file"}?`]}),(m==="checkpoint"||m==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:x,onChange:B=>w(B.target.value),maxLength:200,placeholder:"Message (required)",className:"rounded border border-border bg-surface-secondary px-2 py-1 text-xs text-text-primary placeholder:text-text-secondary focus:outline-none focus:ring-1 focus:ring-border",autoFocus:!0}),s.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:p,onChange:B=>y(B.target.checked)}),"Include untracked files"]})]}),j&&s.jsx("p",{className:"text-xs text-status-error",children:j}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:T,disabled:k,className:"rounded px-3 py-1 text-xs text-text-secondary hover:text-text-primary border border-border/50 disabled:opacity-40",children:"Cancel"}),s.jsx("button",{onClick:M,disabled:k||(m==="checkpoint"||m==="stash")&&!x.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:k?"Working…":"Confirm"})]})]})})]})})}function IA({isMobile:e,showMobileChatMode:t,visibleConversationCount:n}){const[r,o]=l.useState(!1),[a,i]=l.useState(!1),[c,u]=l.useState(!1),[h,d]=l.useState(!1),[m,f]=l.useState(!1),[x,w]=l.useState("quickstart"),[p,y]=l.useState("workspace"),k=l.useMemo(()=>!t&&!e,[t,e]),b=l.useCallback(C=>{o(C),C&&i(!1)},[]),j=l.useCallback(C=>{i(C),C&&o(!1)},[]),S=l.useCallback(()=>{w(n===0?"quickstart":"shortcuts"),y("workspace"),u(!0),o(!1),i(!1)},[n]),v=l.useCallback(()=>{u(!1)},[]),g=l.useCallback(()=>{d(!0)},[]),N=l.useCallback(()=>{d(!1)},[]);return l.useEffect(()=>{if(!k){f(!1);return}f(!0);const C=window.setTimeout(()=>{f(!1)},1e4);return()=>window.clearTimeout(C)},[k]),{inboxOpen:r,hiddenOpen:a,shortcutHelpOpen:c,newSessionOpen:h,guideNudgeVisible:m,guideTab:x,shortcutSection:p,isDesktopDashboard:k,setGuideTab:w,setShortcutSection:y,handleInboxOpenChange:b,handleHiddenOpenChange:j,handleOpenShortcutHelp:S,closeShortcutHelp:v,openNewSession:g,closeNewSession:N}}function MA(e){switch(e.id){case"triggerPrimaryApprovalAction":case"triggerSecondaryApprovalAction":case"triggerTertiaryApprovalAction":return"approvals";case"splitActiveTabRight":case"splitActiveTabDown":case"focusLeftPane":case"focusRightPane":case"focusUpPane":case"focusDownPane":case"moveActiveTabToLeftPane":case"moveActiveTabToRightPane":case"moveActiveTabToUpPane":case"moveActiveTabToDownPane":return"panes";default:return"workspace"}}function DA(e){return e instanceof Error?e.message:String(e||"")}function PA(e){const t=DA(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function LA({showMobileChatMode:e,isMobile:t,activeConv:n,wsStatus:r,isConnected:o,onOpenHistory:a,onOpenRemote:i,onStopCli:c,activeCliViewMode:u,onSetActiveCliViewMode:h,mobileChatConversations:d,hiddenConversations:m,ides:f,actionLogs:x,sendDaemonCommand:w,setActionLogs:p,setCliViewModeOverrides:y,isStandalone:k,initialDataLoaded:b,userName:j,requestedMobileTabKey:S,onRequestedMobileTabConsumed:v,requestedMachineId:g,onRequestedMachineConsumed:N,requestedMobileSection:C,onRequestedMobileSectionConsumed:A,containerRef:T,isSplitMode:M,numGroups:L,groupSizes:P,groupedConvs:B,clearedTabs:K,focusedGroup:F,focusGroup:R,moveTabToGroup:Q,splitTabRelative:E,closeGroup:I,handleResizeStart:$,groupActiveTabIds:D,setGroupActiveTab:U,groupTabOrders:Y,setGroupTabOrder:ae,toggleHiddenTab:z,visibleConversations:X,requestedDesktopTabKey:de,onRequestedDesktopTabConsumed:re,onDesktopActiveTabChange:W,onRequestScrollToBottom:oe,onHideConversation:V,onShowHiddenConversation:ie,onShowAllHiddenConversations:ke,scrollToBottomRequest:xe,machineEntries:Se,layoutProfile:pe,onBrowseMachineDirectory:G,onSaveMachineWorkspace:O,onLaunchMachineIde:Z,onLaunchMachineProvider:q,onListMachineMeshes:me,onLaunchMeshCoordinator:Te,onListMachineSavedSessions:_,notifications:te,notificationUnreadCount:ve,liveSessionInboxState:ce,onMarkNotificationRead:H,onMarkNotificationUnread:fe,onDeleteNotification:je}){const Ce=Rt.useRef(null),{inboxOpen:Be,hiddenOpen:Xe,shortcutHelpOpen:dt,newSessionOpen:it,guideNudgeVisible:he,guideTab:$e,shortcutSection:Fe,isDesktopDashboard:Ie,setGuideTab:ye,setShortcutSection:Oe,handleInboxOpenChange:ut,handleHiddenOpenChange:at,handleOpenShortcutHelp:ht,closeShortcutHelp:J,openNewSession:ee,closeNewSession:le}=IA({isMobile:t,showMobileChatMode:e,visibleConversationCount:X.length}),[ue,ge]=Rt.useState(null),[Ae,Pe]=Rt.useState(null),Ne=Rt.useCallback((Me,Qe)=>{ge({daemonId:Me,workspace:Qe})},[]),He=Rt.useCallback(Me=>{Pe(Me)},[]),Ke=Rt.useCallback(Me=>{var Qe;fn.flushSync(()=>{ie(Me)}),(Qe=Ce.current)==null||Qe.restoreHiddenTabToSavedLocation(Me.tabKey)},[ie]),Ze=Rt.useCallback(Me=>{var Dt;const Qe=d.find(It=>Ja(It,Me))||m.find(It=>Ja(It,Me));Qe&&(m.some(It=>It.tabKey===Qe.tabKey)&&Ke(Qe),W(Qe.tabKey),(Dt=Ce.current)==null||Dt.activateConversationTab(Qe.tabKey),oe(Qe.tabKey,"notification-open")),H(Me.id),ut(!1)},[Ke,m,d,W,H,oe]),_e=Rt.useCallback(()=>{var Qe;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Qe=Ce.current)==null||Qe.resetAllPanelsToMain(),at(!1))},[at]),Ue=Rt.useCallback(async Me=>{var Vt;if(!n)return;const Qe=(Vt=n.modalButtons)==null?void 0:Vt[Me];if(!Qe)return;const Dt=Us(n);if(!Dt)return;const It=Qe.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),qt=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(It);try{await w(Dt,"resolve_action",{button:Qe,action:qt?"approve":"reject",buttonIndex:Me,...Os(n)})}catch(Yt){PA(Yt)||console.error("[Shortcut approval] Failed:",Yt)}},[n,w]),{isMac:et,actionDefinitions:se,actionShortcuts:be,shortcutListening:we,shortcutListeningDraft:ze,setShortcutListening:We,setShortcutListeningDraft:tt,saveShortcuts:qe}=c1({enabled:Ie&&!dt,onTrigger:Me=>{var Qe,Dt,It,qt,Vt,Yt,xs,Re,rt,jt,Ot,ne,Ge,Ee,vt,Jt;if(Me==="openShortcutHelp"){ht();return}if(Me==="openNewSession"){ee();return}if(Me==="hideCurrentTab"){n&&V(n);return}if(Me==="toggleHiddenTabs"){at(!Xe);return}if(Me==="openHistoryForActiveTab"){n&&!lt(n)&&a(n);return}if(Me==="openRemoteForActiveTab"){n&&!ct(n)&&!lt(n)&&i(n);return}if(Me==="splitActiveTabRight"){(Qe=Ce.current)==null||Qe.splitActiveTabRight();return}if(Me==="splitActiveTabDown"){(Dt=Ce.current)==null||Dt.splitActiveTabDown();return}if(Me==="floatActiveTab"){(It=Ce.current)==null||It.floatActiveTab();return}if(Me==="popoutActiveTab"){(qt=Ce.current)==null||qt.popoutActiveTab();return}if(Me==="dockActiveTab"){(Vt=Ce.current)==null||Vt.dockActiveTab();return}if(Me==="focusLeftPane"){(Yt=Ce.current)==null||Yt.focusLeftPane();return}if(Me==="focusRightPane"){(xs=Ce.current)==null||xs.focusRightPane();return}if(Me==="focusUpPane"){(Re=Ce.current)==null||Re.focusUpPane();return}if(Me==="focusDownPane"){(rt=Ce.current)==null||rt.focusDownPane();return}if(Me==="moveActiveTabToLeftPane"){(jt=Ce.current)==null||jt.moveActiveTabToLeftPane();return}if(Me==="moveActiveTabToRightPane"){(Ot=Ce.current)==null||Ot.moveActiveTabToRightPane();return}if(Me==="moveActiveTabToUpPane"){(ne=Ce.current)==null||ne.moveActiveTabToUpPane();return}if(Me==="moveActiveTabToDownPane"){(Ge=Ce.current)==null||Ge.moveActiveTabToDownPane();return}if(Me==="triggerPrimaryApprovalAction"){Ue(0);return}if(Me==="triggerSecondaryApprovalAction"){Ue(1);return}if(Me==="triggerTertiaryApprovalAction"){Ue(2);return}if(Me==="setActiveTabShortcut"){(Ee=Ce.current)==null||Ee.setShortcutForActiveTab();return}if(Me==="selectPreviousGroupTab"){(vt=Ce.current)==null||vt.activatePreviousTabInGroup();return}if(Me==="selectNextGroupTab"){(Jt=Ce.current)==null||Jt.activateNextTabInGroup();return}!n||!ct(n)||lt(n)||Me==="toggleCliView"&&h(u==="chat"?"terminal":"chat")}}),Ye=Rt.useCallback(()=>{J(),We(null),tt([])},[J,We,tt]),Tt=Rt.useMemo(()=>Fe==="all"?se:se.filter(Me=>MA(Me)===Fe),[se,Fe]),Wt=Rt.useCallback(()=>{const Me=Object.fromEntries(se.map(Qe=>[Qe.id,""]));qe(Me)},[se,qe]),ss=Rt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const Me=Object.fromEntries(se.map(Qe=>[Qe.id,Qe.defaultShortcut]));qe(Me)},[se,qe]);return Rt.useEffect(()=>{const Me=Qe=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Qe.metaKey&&Qe.key.toLowerCase()==="w":Qe.ctrlKey&&Qe.key.toLowerCase()==="w")&&(Qe.preventDefault(),n&&V&&V(n))};return window.addEventListener("keydown",Me),()=>window.removeEventListener("keydown",Me)},[n,V]),Rt.useEffect(()=>{if(!dt||we)return;const Me=Qe=>{Qe.key==="Escape"&&(Qe.preventDefault(),Ye())};return window.addEventListener("keydown",Me,!0),()=>window.removeEventListener("keydown",Me,!0)},[Ye,dt,we]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(K0,{activeConv:n,wsStatus:r,isConnected:o,conversations:X,hiddenConversations:m,onOpenHistory:a,onHideConversation:V,onShowConversation:Ke,onShowAllHidden:ke,onResetPanelsToMain:_e,notifications:te,notificationUnreadCount:ve,onOpenNotification:Ze,onMarkNotificationRead:H,onMarkNotificationUnread:fe,onDeleteNotification:je,inboxOpen:Be,onInboxOpenChange:ut,hiddenOpen:Xe,onHiddenOpenChange:at,onOpenNewSession:t?void 0:ee,onOpenDashboardGuide:ht,guideNudgeVisible:he,actionShortcuts:be,onOpenRemote:()=>{!n||ct(n)||lt(n)||i(n)},onStopCli:c,activeCliViewMode:u,onSetCliViewMode:h,onOpenGitDialog:Ne,onOpenMeshGraph:He}),e?s.jsx(QC,{conversations:d,hiddenConversations:m,ides:f,actionLogs:x,sendDaemonCommand:w,setActionLogs:p,setCliViewModeOverrides:y,isStandalone:k,userName:j,requestedActiveTabKey:S,onRequestedActiveTabConsumed:v,requestedMachineId:g,onRequestedMachineConsumed:N,requestedMobileSection:C,onRequestedMobileSectionConsumed:A,onOpenHistory:a,onOpenRemote:i,onStopCli:c,wsStatus:r,isConnected:o,onShowAllHiddenConversations:ke,onHideConversation:V,onOpenMeshGraph:He,onOpenNewSession:ee,liveSessionInboxState:ce}):t?s.jsx(o1,{containerRef:T,isSplitMode:M,numGroups:L,groupSizes:P,groupedConvs:B,clearedTabs:K,ides:f,actionLogs:x,sendDaemonCommand:w,setActionLogs:p,isStandalone:k,hasRegisteredMachines:Se.length>0,userName:j,focusedGroup:F,focusGroup:R,moveTabToGroup:Q,splitTabRelative:E,closeGroup:I,handleResizeStart:$,groupActiveTabIds:D,setGroupActiveTab:U,groupTabOrders:Y,setGroupTabOrder:ae,toggleHiddenTab:z,onOpenNewSession:ee,allowTabShortcuts:!1,liveSessionInboxState:ce}):s.jsx(S1,{visibleConversations:X,clearedTabs:K,ides:f,actionLogs:x,sendDaemonCommand:w,setActionLogs:p,isStandalone:k,hasRegisteredMachines:Se.length>0,initialDataLoaded:b,userName:j,toggleHiddenTab:z,actionShortcuts:be,registerActionHandlers:Me=>{Ce.current=Me},onActiveTabChange:W,requestedActiveTabKey:de,onRequestedActiveTabConsumed:re,onRequestScrollToBottom:oe,scrollToBottomRequest:xe,onOpenNewSession:ee,liveSessionInboxState:ce,layoutProfile:pe}),it&&s.jsx(L1,{machines:Se,ides:f,onClose:le,onBrowseDirectory:G,onSaveWorkspace:O,onLaunchIde:Z,onLaunchProvider:q,onListMeshes:me,onLaunchMeshCoordinator:Te,onListSavedSessions:_}),Ae&&s.jsx(qp,{activeConv:Ae,sendDaemonCommand:w,onClose:()=>Pe(null)}),ue&&s.jsx(Yp,{daemonId:ue.daemonId,workspace:ue.workspace,onClose:()=>ge(null)}),dt&&s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:Ye,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl w-[min(560px,calc(100vw-32px))] max-h-[min(80vh,720px)] overflow-y-auto px-6 py-5 shadow-xl",onClick:Me=>Me.stopPropagation(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-4 mb-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:"Dashboard guide"}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:"A quick guide to the dashboard flow, floating and popout tabs, plus grouped shortcuts you can tune."})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center justify-center w-8 px-0",onClick:Ye,"aria-label":"Close dashboard guide",children:s.jsx(At,{size:14})})]}),s.jsx("div",{className:"flex gap-2 mb-4 overflow-x-auto",children:[{id:"overview",label:"Overview"},{id:"quickstart",label:"Quick start"},{id:"shortcuts",label:"Shortcuts"}].map(Me=>s.jsx("button",{type:"button",className:`btn btn-sm ${$e===Me.id?"btn-primary":"btn-secondary"}`,onClick:()=>ye(Me.id),children:Me.label},Me.id))}),$e==="overview"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3 mb-4",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"What lives where"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Tabs:"})," active sessions across IDE, CLI, and ACP agents."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Hidden tabs:"})," stash sessions you do not want in the main strip but still want to keep around."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Activity inbox:"})," sessions waiting for approval or finished tasks you have not reviewed yet."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"CLI view toggle:"})," switch a PTY session between terminal and chat rendering without relaunching it."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Useful flows"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Review notifications:"})," open the inbox, jump to the session, then use the conversation or approval controls directly from the active pane."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Reduce clutter:"})," hide less important sessions instead of closing them, then restore from hidden tabs when needed."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Split work:"})," keep one pane active for input and let secondary panes stay read-only until you focus them."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Detached views:"})," float a tab for quick side-by-side work, or pop it into a new window when you want a separate monitor."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Docking:"})," use Dock to bring a floating tab back into the grid, or move a popped out tab back to the main dashboard."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Per-tab shortcuts:"})," right-click a Dockview tab to assign a direct shortcut for that specific session."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"Approval buttons:"})," use ",et?"⌥J / ⌥K / ⌥L":"Ctrl+Alt+J / K / L"," for the first three visible approval actions on the active session."]})]})]})]}),$e==="quickstart"&&s.jsxs("div",{className:"space-y-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Desktop quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Start from the machine or workspace flow first. Pick or save a workspace before launching CLI or ACP sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Keep the main strip focused on active work and push overflow into Hidden tabs."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Use the inbox for approval-required or completed sessions instead of scanning every tab."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"4."})," Split only when you need parallel reading; float or pop out a tab when you want to detach it without losing the main layout."]})]})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/30 px-4 py-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:"Mobile quick start"}),s.jsxs("div",{className:"text-xs text-text-secondary mt-2 space-y-2",children:[s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"1."})," Stay in chat mode for review and replies; use workspace mode mainly to launch or reopen sessions."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"2."})," Start from the machine screen, choose a workspace, then launch IDE, CLI, or ACP from there."]}),s.jsxs("div",{children:[s.jsx("span",{className:"font-semibold text-text-primary",children:"3."})," Treat mobile as the simpler control surface: no split workflow, fewer tab mechanics, faster session switching."]})]})]})]}),$e==="shortcuts"&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-3",children:[s.jsx("div",{className:"flex flex-wrap gap-2",children:[{id:"all",label:"All"},{id:"workspace",label:"Workspace"},{id:"panes",label:"Panes"},{id:"approvals",label:"Approvals"}].map(Me=>s.jsx("button",{type:"button",className:`btn btn-sm ${Fe===Me.id?"btn-primary":"btn-secondary"}`,onClick:()=>Oe(Me.id),children:Me.label},Me.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Wt,children:"Disable all"}),s.jsx("button",{type:"button",className:"btn btn-sm",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, var(--border-subtle, transparent))",background:"color-mix(in srgb, var(--status-error, #ef4444) 8%, var(--bg-primary, transparent))"},onClick:ss,children:"Reset to defaults"})]})]}),s.jsx("div",{className:"space-y-2",children:Tt.map(Me=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${we===Me.id?"border-accent bg-bg-secondary/70":"border-border-subtle bg-bg-secondary/30"}`,children:s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:Me.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:Me.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:Me.defaultShortcut})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[s.jsx("span",{className:"text-[11px] font-mono px-2 py-1 rounded bg-surface-secondary border border-border-subtle min-w-[72px] text-center",children:we===Me.id?ze.length>0?`${ze.join(" ")} ...`:"Listening...":be[Me.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{We(Me.id),tt([])},children:we===Me.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Qe={...be};Qe[Me.id]="",qe(Qe)},children:"Disable"})]})]})},Me.id))}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-4",children:["Use modifier shortcuts like ",et?"⌘⇧Enter, ⌘⇧→, ⌘Ctrl⇧↓":"Ctrl+Shift+Enter, Ctrl+Shift+→, Ctrl+Alt+Shift+↓",", or set your own combo. Dashboard action shortcuts are ignored while typing in text inputs."]})]})]})})]})}const RA=[{icon:"🦦",title:"Welcome to ADHDev",desc:"Drive any local CLI coding agent — Claude Code, Codex, Gemini — straight from your browser or phone. The agents keep running on your machine; you control them from the web.",visual:"🎉"},{icon:"💬",title:"Real-time chat",desc:"See what your AI agent is doing in real-time. Send messages, approve or reject actions — all from your browser or phone.",visual:"📱"},{icon:"👀",title:"Watch and steer, live",desc:"Follow each agent's session in real time and steer it as it works — switch sessions, take screenshots, and (for IDE sessions) view and control the screen over a P2P connection.",visual:"🖱️"},{icon:"🕸️",title:"Orchestrate your agents",desc:"Repo Mesh (Cloud Pro) lets one coordinator hand work to agents across many machines — parallel git worktrees, automatic branch convergence, and cross-checking the same repo from several angles.",visual:"🕸️"}],EA={icon:"🚀",title:"Get started",desc:"Run this on any machine you want to drive, then sign in — the daemon pairs itself to your dashboard automatically.",code:"curl -fsSL https://adhf.dev/install | sh"},_A={icon:"🚀",title:"You're all set",desc:"This dashboard is already connected to your local daemon. Start a session from the Dashboard tab, or add more providers under Burrow → Providers.",visual:"✅"};function $A({onClose:e,standalone:t=!1}){const[n,r]=l.useState(0),o=[...RA,t?_A:EA],a=o[n],i=n===o.length-1;return s.jsxs("div",{className:"onboarding-overlay",style:{position:"fixed",inset:0,zIndex:"var(--z-modal)",background:"rgba(0,0,0,0.65)",backdropFilter:"blur(6px)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.3s ease-out"},onClick:c=>{c.stopPropagation()},children:[s.jsxs("div",{style:{background:"var(--bg-secondary, #1a1a2e)",border:"1px solid var(--border-subtle, #333)",borderRadius:"1.25rem",width:"min(440px, 92vw)",padding:"2.5rem 2rem 2rem",position:"relative",animation:"slideUp 0.3s ease-out"},children:[s.jsx("button",{onClick:e,className:"absolute top-3 right-4 bg-transparent border-none text-text-muted hover:text-text-primary transition-colors cursor-pointer",children:s.jsx(At,{size:20})}),s.jsx("div",{style:{display:"flex",justifyContent:"center",gap:6,marginBottom:"1.5rem"},children:o.map((c,u)=>s.jsx("div",{style:{width:u===n?24:8,height:8,borderRadius:4,background:u===n?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},u))}),s.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:a.visual||a.icon}),s.jsxs("div",{style:{textAlign:"center"},children:[s.jsxs("h2",{style:{fontSize:"1.35rem",fontWeight:700,color:"var(--text-primary)",marginBottom:"0.75rem",display:"flex",alignItems:"center",justifyContent:"center",gap:8},children:[s.jsx("span",{children:a.icon})," ",a.title]}),s.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:a.desc}),a.code&&s.jsxs("div",{style:{background:"var(--bg-primary, #111)",border:"1px solid var(--border-subtle, #333)",borderRadius:"0.5rem",padding:"0.75rem 1rem",fontFamily:"monospace",fontSize:"0.8rem",color:"var(--accent, #a78bfa)",textAlign:"left",overflowX:"auto",marginBottom:"0.5rem"},children:[s.jsx("span",{style:{color:"var(--text-muted)",marginRight:8},children:"$"}),a.code]}),i&&s.jsx("a",{href:"https://docs.adhf.dev",target:"_blank",rel:"noopener noreferrer",style:{fontSize:"0.75rem",color:"var(--accent, #a78bfa)",textDecoration:"none"},children:"📚 Learn more in the docs →"})]}),s.jsx("div",{className:"flex justify-end items-center mt-6",children:s.jsx("button",{onClick:()=>i?e():r(c=>c+1),className:"btn btn-primary",children:i?"Get Started →":"Next →"})})]}),s.jsx("style",{children:`
92
+ @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
93
+ @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
94
+ `})]})}function BA({hasExtensions:e,ideName:t,activeChatTab:n,extensionTabs:r,onSelectTab:o}){return e?s.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[s.jsx("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] ${n==="native"?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>o("native"),children:t}),r.map(a=>{const i=n===a.tabKey,c=a.status==="waiting_approval",u=a.status==="generating";return s.jsxs("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] flex items-center justify-center gap-1.5 ${i?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>o(a.tabKey),children:[s.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:c?"var(--status-warning)":u?"var(--accent-primary)":"var(--text-muted)",boxShadow:u?"0 0 6px var(--accent-primary)":"none"}}),a.title,c&&s.jsx("span",{className:"inline-flex items-center justify-center min-w-[18px] h-[18px] px-1 rounded-full text-[10px] font-bold ml-0.5",style:{background:"color-mix(in srgb, var(--status-warning) 13%, transparent)",color:"var(--status-warning)"},children:"!"})]},a.tabKey)})]}):null}function FA({ideData:e,allIdes:t,connectionStates:n,ideName:r,preferredTabKey:o}){const[a,i]=l.useState(()=>o||"native"),c=l.useMemo(()=>yh(t),[t]),u=l.useMemo(()=>e?qi(e,{machineNames:c,connectionStates:n,defaultConnectionState:"new"}):[],[e,c,n]),h=l.useMemo(()=>u.find(p=>p.streamSource==="native"),[u]),d=l.useMemo(()=>u.filter(p=>p.streamSource==="agent-stream"),[u]),m=l.useMemo(()=>e?cs(u,e.id):null,[u,e]);l.useEffect(()=>{o&&i(o)},[o]),l.useEffect(()=>{if(o||!m)return;const p=m.streamSource==="native"?"native":m.tabKey;!p||a===p||a==="native"&&i(p)},[a,m,o]),l.useEffect(()=>{var p;a!=="native"&&(d.some(y=>y.tabKey===a)||i(((p=d[0])==null?void 0:p.tabKey)||"native"))},[a,d]),l.useEffect(()=>{a==="native"&&(h||d[0]&&i(d[0].tabKey))},[a,h,d]);const f=l.useMemo(()=>a==="native"&&h?h:d.find(p=>p.tabKey===a)||m||h||d[0],[a,h,m,d]),x=l.useMemo(()=>d.map(p=>({tabKey:p.tabKey,title:lh(p)||r,status:p.status})),[d,r]),w=l.useCallback(p=>{if(p)return u.find(y=>Ja(y,{sessionId:p,routeId:p,tabKey:p,providerSessionId:p}))},[u]);return{activeChatTab:a,setActiveChatTab:i,activeConv:f,conversations:u,extensionTabs:x,hasExtensions:x.length>0,resolveConversationByTarget:w}}function HA({activeConv:e,ideEntry:t,ides:n,connectionStates:r,actionLogs:o,sendDaemonCommand:a,setActionLogs:i,isStandalone:c,userName:u,onOpenHistory:h,onConversationChange:d,onClose:m}){const[f,x]=l.useState("split"),[w,p]=l.useState(()=>Ms(e)?"native":e.tabKey),y=l.useRef(null),k=l.useMemo(()=>t||n.find(R=>R.id===e.routeId),[e.routeId,t,n]),b=l.useMemo(()=>$t((k==null?void 0:k.type)||""),[k==null?void 0:k.type]),{conversations:j,extensionTabs:S,hasExtensions:v}=FA({ideData:k,allIdes:n,connectionStates:r,ideName:b||"IDE",preferredTabKey:Ms(e)?void 0:e.tabKey}),g=l.useMemo(()=>k?cs(j,k.id):null,[k,j]);l.useEffect(()=>{const R=y.current,Q={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(y.current=Q,!(R&&R.routeId===Q.routeId&&R.tabKey===Q.tabKey&&R.streamSource===Q.streamSource)){if(Ms(e)){p("native");return}p(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),l.useEffect(()=>{if(w==="native"){if(j.some(R=>R.streamSource==="native"))return;(g==null?void 0:g.streamSource)==="agent-stream"&&p(g.tabKey);return}if(!j.some(R=>R.tabKey===w)){if((g==null?void 0:g.streamSource)==="agent-stream"){p(g.tabKey);return}p("native")}},[j,w,g]);const N=l.useMemo(()=>w==="native"?j.find(R=>R.streamSource==="native")||e:j.find(R=>R.tabKey===w)||e,[e,j,w]),C=Ph(N),A=l.useMemo(()=>C.status||C.modalMessage||C.modalButtons?{...N,...C.status?{status:C.status}:{},...C.modalMessage!==void 0?{modalMessage:C.modalMessage}:{},...C.modalButtons!==void 0?{modalButtons:C.modalButtons}:{}}:N,[N,C]),T=en(A),M=Po({sendDaemonCommand:a,activeConv:A,setActionLogs:i,isStandalone:c}),{connScreenshot:L,screenshotUsage:P,handleRemoteAction:B}=dp({doId:T,targetSessionId:Fu(A),connState:A.connectionState||"new",viewMode:f}),K=l.useMemo(()=>o.filter(R=>R.routeId===A.tabKey),[o,A.tabKey]);l.useEffect(()=>{d==null||d(A)},[A,d]),l.useEffect(()=>{const R=Q=>{Q.key==="Escape"&&m()};return window.addEventListener("keydown",R),()=>window.removeEventListener("keydown",R)},[m]);const F=l.useCallback(R=>{R.stopPropagation()},[]);return s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal-backdrop)] flex items-center justify-center p-0 md:p-3 bg-black/60 backdrop-blur-md",onClick:m,children:s.jsxs("div",{className:"w-full h-[100dvh] md:h-[calc(100vh-24px)] md:w-[calc(100vw-24px)] flex flex-col overflow-hidden md:rounded-[14px] md:border border-border-default bg-surface-primary shadow-[0_24px_80px_rgba(2,6,23,0.32)]",role:"dialog","aria-modal":"true",onClick:F,children:[s.jsxs("div",{className:"sticky top-0 z-20 flex flex-col gap-3 md:flex-row md:items-center md:justify-between px-4 pt-[calc(14px+env(safe-area-inset-top,0px))] pb-3 border-b border-border-subtle bg-bg-primary/96 backdrop-blur-md shrink-0 overflow-visible",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 min-w-0 w-full md:w-auto md:flex-1",children:[s.jsx("div",{className:"min-w-0 flex-1 flex flex-col justify-center",children:s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 font-extrabold text-[18px] md:text-xl tracking-tight text-text-primary",children:[s.jsx("span",{className:"w-7 h-7 flex items-center justify-center rounded-lg bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(us,{size:16})}),s.jsx("span",{className:"truncate",children:Wi(N)||"Remote"})]})}),s.jsx("button",{className:"btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold md:hidden shrink-0",onClick:m,children:"Close"})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0 w-full md:w-auto justify-between md:justify-end",children:[s.jsx("div",{className:"flex items-center gap-2 mr-auto md:mr-0",children:["split","remote"].map(R=>{const Q=f===R;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${Q?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>x(R),title:R==="split"?"Split view":"Remote only",children:R==="split"?s.jsx(_f,{size:15}):s.jsx(us,{size:15})},R)})}),s.jsx("div",{className:"hidden md:block w-[1px] h-5 bg-border-subtle mx-1"}),s.jsxs("button",{className:"btn btn-secondary btn-sm h-8 px-2.5 md:px-3 rounded-lg",onClick:()=>h(N),title:"Chat History",children:[s.jsx(Ai,{size:14,className:"md:mr-1.5"}),s.jsx("span",{className:"hidden md:inline",children:"History"})]}),s.jsx("button",{className:"hidden md:inline-flex btn btn-primary btn-sm h-8 px-4 rounded-lg font-bold",onClick:m,children:"Close"})]})]}),s.jsxs("div",{className:`flex-1 min-h-0 grid bg-bg-primary ${f==="split"?"grid-cols-1 grid-rows-[1fr_minmax(320px,42vh)] md:grid-cols-[minmax(360px,0.92fr)_minmax(420px,1.08fr)] md:grid-rows-1":"grid-cols-1 grid-rows-1"}`,children:[f!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${f==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(BA,{hasExtensions:v,ideName:b||"IDE",activeChatTab:w,extensionTabs:S,onSelectTab:p}),s.jsx(hu,{activeConv:A,onModalButton:M.handleModalButton}),s.jsx(ri,{activeConv:A,ideEntry:k,showMetaChips:!1,handleSendChat:M.handleSendChat,handleForceSendChat:M.handleForceSendChat,isSendingChat:M.isSendingChat,sendFeedbackMessage:M.sendFeedbackMessage,handleFocusAgent:M.handleFocusAgent,isFocusingAgent:M.isFocusingAgent,actionLogs:K,userName:u})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${f==="split"?"order-1 md:order-2":""}`,children:s.jsx(iu,{addLog:()=>{},connState:A.connectionState||"new",connScreenshot:L,screenshotUsage:P,transportType:A.transport,onAction:B})})]})]})})}function WA({activeConv:e,canSaveAndStop:t=!1,onCancel:n,onStopNow:r,onSaveAndStop:o}){const{t:a}=Le(),i=C0(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:n,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true",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",{className:"m-0 text-base md:text-lg font-extrabold",children:a("cliStop.title",{agent:i})}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:a(t?"cliStop.gracefulDescription":"cliStop.forceOnlyDescription")})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[t&&s.jsx("button",{onClick:o,className:"btn btn-primary w-full justify-center min-h-[42px]",children:a("cliStop.stop")}),s.jsx("button",{onClick:r,className:"btn btn-secondary w-full justify-center min-h-[42px] text-red-400 border-red-500/25 hover:bg-red-500/10",children:a("cliStop.forceStop")}),s.jsx("button",{onClick:n,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:a("common.cancel")})]})]})]})}function OA({historyModal:e,remoteDialog:t,cliStopDialog:n,connectionBanner:r,toastOverlay:o,onboarding:a,interactivePrompt:i}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(F0,{wsStatus:r.wsStatus,showReconnected:r.showReconnected,loginUrl:r.loginUrl,onReconnect:r.onReconnect}),e.open&&e.targetConv&&s.jsx(bh,{activeConv:e.targetConv,ides:e.ides,isCreatingChat:e.isCreatingChat,isRefreshingHistory:e.isRefreshingHistory,savedSessions:e.savedSessions,isSavedSessionsLoading:e.isSavedSessionsLoading,isResumingSavedSessionId:e.isResumingSavedSessionId,savedHistoryFilters:e.savedHistoryFilters,missingWorkspaceResumePath:e.missingWorkspaceResumePath,onSavedHistoryFiltersChange:e.onSavedHistoryFiltersChange,onClose:e.onClose,onNewChat:e.onNewChat,onSwitchSession:e.onSwitchSession,onRefreshHistory:e.onRefreshHistory,onResumeSavedSession:e.onResumeSavedSession}),t.conversation&&s.jsx(HA,{activeConv:t.conversation,ideEntry:t.ideEntry,ides:t.ides,connectionStates:t.connectionStates,actionLogs:t.actionLogs,sendDaemonCommand:t.sendDaemonCommand,setActionLogs:t.setActionLogs,isStandalone:t.isStandalone,userName:t.userName,onOpenHistory:t.onOpenHistory,onConversationChange:t.onConversationChange,onClose:t.onClose}),n.open&&n.targetConv&&(ct(n.targetConv)||lt(n.targetConv))&&s.jsx(WA,{activeConv:n.targetConv,canSaveAndStop:ct(n.targetConv)&&!lt(n.targetConv)&&!!((c=n.targetConv.resume)!=null&&c.supported),onCancel:n.onCancel,onStopNow:n.onStopNow,onSaveAndStop:n.onSaveAndStop}),s.jsx(gh,{toasts:o.toasts,onDismiss:o.onDismiss,onClickToast:o.onClick}),s.jsx(cu,{promptSession:(i==null?void 0:i.promptSession)??null,isSubmitting:(i==null?void 0:i.isSubmitting)??!1,error:(i==null?void 0:i.responseError)??null,onSubmit:(i==null?void 0:i.submit)??(async()=>{}),onCancel:(i==null?void 0:i.cancel)??(()=>{})}),a.open&&s.jsx($A,{onClose:a.onClose,standalone:a.standalone})]})}function UA({daemons:e,targetVersion:t,required:n=!1,upgradingDaemons:r,onUpgrade:o,onDismiss:a}){return e.length===0?null:s.jsxs("div",{className:"flex items-center gap-2.5 px-4 py-2 border-b text-xs text-text-secondary shrink-0 flex-wrap",style:{background:n?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",borderColor:n?"color-mix(in srgb, var(--status-danger) 24%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"},children:[s.jsx("span",{className:"text-sm shrink-0 mt-0.5",style:{color:n?"var(--status-danger)":"var(--status-warning)"},children:s.jsx(Co,{size:14})}),s.jsxs("span",{className:"flex-1 flex items-center gap-2 flex-wrap min-w-0",children:[s.jsxs("span",{children:[n?"Daemon update required":"Update available",t?s.jsxs(s.Fragment,{children:[": ",s.jsxs("strong",{children:["v",t]})]}):null]}),e.map(i=>{const c=ts(i,{fallbackId:i.id}),u=r[i.id],h=i.version||i.daemonVersion||"unknown",d=i.versionUpdateRequired===!0,f=Oh(i)==="preview"?"Update to preview":d?"Update now":"Upgrade";return s.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 15%, transparent)"}`},children:[s.jsx("span",{className:"font-medium text-text-primary",children:c}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",h]}),d&&s.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:"required"}),u==="upgrading"?s.jsx("span",{className:"text-[10px] animate-pulse",style:{color:d?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):u==="done"?s.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):u==="error"?s.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>o(i.id),children:"retry"}):s.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:d?"var(--status-danger)":"var(--status-warning)",background:d?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${d?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>o(i.id),children:f})]},i.id)})]}),!n&&s.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:a,title:"Dismiss",children:s.jsx(At,{size:16})})]})}function GA(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function KA(e){const t=e.machine;return typeof(t==null?void 0:t.cpus)!="number"||typeof(t==null?void 0:t.totalMem)!="number"||typeof(t==null?void 0:t.arch)!="string"||typeof(t==null?void 0:t.release)!="string"}function zA(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>KA(t)).map(t=>t.id)}}function qA(){var yl,vl,wl,kl;const{sendCommand:e}=yt(),t=In(),n=Dh(),r=ki(),o=pr(),[a,i]=Hm(),c=a.get("activeTab"),u=((yl=r.state)==null?void 0:yl.openRemoteForTabKey)||null,h=((vl=r.state)==null?void 0:vl.openMachineId)||null,d=((wl=r.state)==null?void 0:wl.mobileSection)||null,m=nh(),f=m.ides||[],x=m.initialLoaded??!0,{updateRouteChats:w,setToasts:p}=m,[y,k]=l.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),b=m.toasts||[],j=m.wsStatus||"connected",S=m.isConnected??!0,v=m.connectionStates||{},g=m.showReconnected||!1,{layoutProfile:N,groupAssignments:C,updateGroupAssignments:A,focusedGroup:T,updateFocusedGroup:M,focusGroup:L,groupActiveTabIds:P,updateGroupActiveTabIds:B,setGroupActiveTab:K,groupTabOrders:F,updateGroupTabOrders:R,setGroupTabOrder:Q,groupSizes:E,updateGroupSizes:I,isMobile:$,hasHydratedStoredLayout:D,hydrateStoredLayout:U,focusConversationTab:Y}=zS(),[ae,z]=l.useState(()=>Qi());l.useEffect(()=>eS(z),[]);const X=l.useMemo(()=>GA({isMobile:$,mobileViewMode:ae}),[$,ae]),[de,re]=l.useState([]),[W,oe]=l.useState({}),[V,ie]=l.useState({});mr("Dashboard",{ideCount:f.length,toastCount:b.length,focusedGroup:T,groupCount:Object.keys(C).length,actionLogCount:de.length});const ke=l.useMemo(()=>f.filter(ot=>ot.type==="adhdev-daemon").sort(Ei),[f]),Se=!!ke[0];l.useEffect(()=>{const{metadataDaemonIds:ot,runtimeDaemonIds:Ut}=zA(ke);for(const Dn of ot)t(Dn,{minFreshMs:3e4}).catch(()=>{});for(const Dn of Ut)n(Dn,{minFreshMs:3e4}).catch(()=>{})},[t,n,ke]);const pe=l.useMemo(()=>xS(f,W),[f,W]),{conversations:G,visibleConversations:O,visibleTabKeys:Z,resolveConversationBySessionId:q,resolveConversationByTarget:me}=DS({ides:pe,connectionStates:v,clearedTabs:V}),Te=l.useMemo(()=>new Map(G.map(ot=>[ot.tabKey,ot])),[G]);Jw(O,X);const _=l.useMemo(()=>uu(f),[f]),te=tp(_,e,l.useCallback(ot=>an(p,`⚠️ ${ot}`),[p])),{notifications:ve,unreadCount:ce}=lC({conversations:G,liveSessionInboxState:_}),{handleMarkDashboardNotificationRead:H,handleMarkDashboardNotificationUnread:fe,handleDeleteDashboardNotification:je}=cC({notifications:ve,sendDaemonCommand:e}),{containerRef:Ce,normalizedGroupAssignments:Be,numGroups:Xe,isSplitMode:dt,groupedConvs:it,moveTabToGroup:he,closeGroup:$e,handleResizeStart:Fe,splitTabRelative:Ie}=ZS({groupAssignments:C,updateGroupAssignments:A,updateFocusedGroup:M,updateGroupActiveTabIds:B,updateGroupTabOrders:R,groupSizes:E,updateGroupSizes:I,isMobile:$,visibleConversations:O,visibleTabKeys:Z}),{activeConv:ye,openDesktopConversation:Oe,requestScrollToBottom:ut,scrollToBottomRequest:at,setDesktopActiveTab:ht}=wC({isMobile:$,conversations:G,visibleConversations:O,groupActiveTabIds:P,focusedGroup:T,groupedConvs:it,setSearchParams:i});CC({activeConv:ye,isMobile:$,liveSessionInboxState:_,sendDaemonCommand:e});const{requestedDesktopTabKey:J,requestedMobileTabKey:ee,consumeRequestedActiveTab:le}=PS({isMobile:$,urlActiveTab:c,resolveConversationBySessionId:q,setSearchParams:i}),{remoteDialogConv:ue,remoteDialogIdeEntry:ge,remoteDialogActiveConv:Ae,setRemoteDialogActiveConv:Pe,openRemoteDialog:Ne,closeRemoteDialog:He,cliStopDialogOpen:Ke,cliStopTargetConv:Ze,requestCliStop:_e,cancelCliStop:Ue,confirmCliStop:et}=AC({isMobile:$,location:r,navigate:o,requestedRemoteTabTarget:u,requestedDesktopTabKey:J,conversations:G,ides:f,resolveConversationByTarget:me,activeConv:ye,sendDaemonCommand:e}),{historyModalOpen:se,openHistoryModal:be,closeHistoryModal:we,historyTargetConv:ze,isSavedSessionHistoryTarget:We,isHistoryCreatingChat:tt,isHistoryRefreshingHistory:qe,handleHistorySwitchSession:Ye,handleHistoryNewChat:Tt,handleHistoryRefresh:Wt,savedHistorySessions:ss,savedHistoryFilters:Me,setSavedHistoryFilters:Qe,missingWorkspaceResumePath:Dt,isSavedHistoryLoading:It,resumingSavedHistorySessionId:qt,handleRefreshSavedHistory:Vt,handleResumeSavedHistorySession:Yt}=jC({activeConv:ye,remoteDialogConv:ue,remoteDialogActiveConv:Ae,ides:f,sendDaemonCommand:e,updateRouteChats:w,setToasts:p,setClearedTabs:ie,setSearchParams:i}),xs=l.useMemo(()=>O,[O]),Re=$&&ae==="chat",rt=l.useMemo(()=>G.filter(ot=>Ds(ot,_).surfaceHidden),[G,_]),jt=l.useCallback(ot=>{const Ut=new URLSearchParams(a);Ut.set("activeTab",ot),i(Ut,{replace:!0})},[a,i]),{trackPendingLaunch:Ot}=gC({ides:f,conversations:G,onOpenSession:jt}),{handleBrowseMachineDirectory:ne,handleSaveMachineWorkspace:Ge,handleLaunchMachineIde:Ee,handleLaunchMachineProvider:vt,handleListMachineMeshes:Jt,handleLaunchMeshCoordinator:Mn,handleListMachineSavedSessions:Oo,setActiveCliViewMode:ys}=xC({sendDaemonCommand:e,trackPendingLaunch:Ot,onOpenSession:jt,activeConv:ye,ides:f,setCliViewModeOverrides:oe});vS({visibleConversations:O,clearedTabs:V,setClearedTabs:ie,setActionLogs:re,isConversationMuted:te.isMuted}),LS({ides:f,sendDaemonCommand:e,setToasts:p,resolveConversationByTarget:me});const rm=Lh(),{isRefreshingHistory:om,handleRefreshHistory:am}=Wh({sendDaemonCommand:e,activeConv:ye,chats:(kl=f.find(ot=>ot.id===(ye==null?void 0:ye.routeId)))==null?void 0:kl.chats,updateRouteChats:w,setToasts:p,setClearedTabs:ie});VS({urlActiveTab:$&&!Re?c:null,conversations:G,resolveConversationBySessionId:q,normalizedGroupAssignments:Be,hasHydratedStoredLayout:$&&!Re?D:!0,hydrateStoredLayout:$&&!Re?U:()=>{},focusConversationTab:Y,setSearchParams:i,historyModalOpen:se,activeConv:ye,isRefreshingHistory:om,ides:f,handleRefreshHistory:am});const im=l.useMemo(()=>!ye||!ct(ye)||lt(ye)?null:Tn(ye),[ye]),{versionMismatchDaemons:lm,hasRequiredVersionDaemons:gl,targetVersion:cm,versionBannerDismissed:dm,setVersionBannerDismissed:um,upgradingDaemons:hm,handleBannerUpgrade:pm}=tC({ides:f,sendDaemonCommand:e}),xl=l.useCallback(ot=>{te.setHidden(ot,!1),Oe(ot)},[Oe,te]),mm=l.useCallback(()=>{for(const ot of rt)te.setHidden(ot,!1)},[rt,te]),fm=l.useCallback(ot=>{te.setHidden(ot,!0)},[te]),bm=l.useCallback(ot=>{te.toggleHidden(ot)},[te]);return s.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[(!dm||gl)&&s.jsx(UA,{daemons:lm,targetVersion:cm,required:gl,upgradingDaemons:hm,onUpgrade:pm,onDismiss:()=>um(!0)}),s.jsx(LA,{showMobileChatMode:Re,isMobile:$,activeConv:ye,wsStatus:j,isConnected:S,onOpenHistory:ot=>{ot&&Pe(ot),be()},onOpenRemote:Ne,onStopCli:_e,activeCliViewMode:im,onSetActiveCliViewMode:ys,mobileChatConversations:xs,ides:f,actionLogs:de,sendDaemonCommand:e,setActionLogs:re,setCliViewModeOverrides:oe,isStandalone:Se,initialDataLoaded:x,userName:m.userName,requestedMobileTabKey:ee,onRequestedMobileTabConsumed:le,requestedMachineId:h,onRequestedMachineConsumed:()=>{o(r.pathname+r.search,{replace:!0,state:null})},requestedMobileSection:d,onRequestedMobileSectionConsumed:()=>{o(r.pathname+r.search,{replace:!0,state:null})},containerRef:Ce,isSplitMode:dt,numGroups:Xe,groupSizes:E,groupedConvs:it,clearedTabs:V,focusedGroup:T,focusGroup:L,moveTabToGroup:he,splitTabRelative:Ie,closeGroup:$e,handleResizeStart:Fe,groupActiveTabIds:P,setGroupActiveTab:K,groupTabOrders:F,setGroupTabOrder:Q,toggleHiddenTab:ot=>{const Ut=Te.get(ot);Ut&&bm(Ut)},visibleConversations:O,hiddenConversations:rt,requestedDesktopTabKey:J,onRequestedDesktopTabConsumed:le,onDesktopActiveTabChange:ht,onRequestScrollToBottom:ut,onHideConversation:fm,onShowHiddenConversation:xl,onShowAllHiddenConversations:mm,scrollToBottomRequest:at,machineEntries:ke,layoutProfile:N,onBrowseMachineDirectory:ne,onSaveMachineWorkspace:Ge,onLaunchMachineIde:Ee,onLaunchMachineProvider:vt,onListMachineMeshes:Jt,onLaunchMeshCoordinator:Mn,onListMachineSavedSessions:Oo,notifications:ve,notificationUnreadCount:ce,liveSessionInboxState:_,onMarkNotificationRead:H,onMarkNotificationUnread:fe,onDeleteNotification:je}),s.jsx("style",{children:`
95
+ body { overflow: hidden; overscroll-behavior: none; }
96
+ `}),s.jsx(OA,{historyModal:{open:se,targetConv:ze,ides:f,isCreatingChat:tt,isRefreshingHistory:We?!1:qe,savedSessions:ss,savedHistoryFilters:Me,missingWorkspaceResumePath:Dt||null,onSavedHistoryFiltersChange:Qe,isSavedSessionsLoading:It,isResumingSavedSessionId:qt,onClose:we,onNewChat:Tt,onSwitchSession:Ye,onRefreshHistory:We?Vt:Wt,onResumeSavedSession:Yt},remoteDialog:{conversation:ue,ideEntry:ge,ides:f,connectionStates:v,actionLogs:de,sendDaemonCommand:e,setActionLogs:re,isStandalone:Se,userName:m.userName,onOpenHistory:ot=>{ot&&Pe(ot),be()},onConversationChange:Pe,onClose:He},cliStopDialog:{open:Ke,targetConv:Ze,onCancel:Ue,onStopNow:async()=>{await et("hard")},onSaveAndStop:async()=>{await et("save")}},connectionBanner:{wsStatus:j,showReconnected:g,loginUrl:m.connectionLoginUrl,onReconnect:m.retryServerConnection},toastOverlay:{toasts:b,onDismiss:ot=>p(Ut=>Ut.filter(Dn=>Dn.id!==ot)),onClick:ot=>{if(ot.targetKey){const Ut=me(ot.targetKey);Ut&&(Y(Ut.tabKey,Be),xl(Ut),ut(Ut.tabKey,"toast-open"))}}},onboarding:{open:y,standalone:Se,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}k(!1)}},interactivePrompt:rm})]})}function VA({machineId:e,registeredMachineId:t,sendDaemonCommand:n,onNicknameSynced:r,logsEndRef:o}){const{launchCli:a}=ko(),[i,c]=l.useState([]),[u,h]=l.useState(null),[d,m]=l.useState(null),[f,x]=l.useState(!1),[w,p]=l.useState(null),[y,k]=l.useState(!1),[b,j]=l.useState(""),S=l.useRef(null),v=l.useCallback(I=>{S.current=I},[]),g=l.useCallback((I,$,D=!1)=>{c(U=>[...U.slice(-100),{timestamp:Date.now(),level:I,message:$}]),setTimeout(()=>{var U;return(U=o.current)==null?void 0:U.scrollIntoView({behavior:"smooth"})},100),D&&pt.showToast($,I==="error"||I==="warn"?"warning":"success")},[o]),N=l.useCallback(I=>{const $=I instanceof Error?I.message:String(I||"");return $.includes("P2P command timeout")||$.includes("P2P not connected")||$.includes("P2P not available")},[]),C=l.useCallback(async(I,$)=>{var D;if(!e||u)return!1;h(I),g("info",`Launching ${$t(I)}${$!=null&&$.workspace?` in ${$.workspace}`:""}...`);try{const U={ideType:I,enableCdp:!0};(D=$==null?void 0:$.workspace)!=null&&D.trim()?U.workspace=$.workspace.trim():$!=null&&$.useDefaultWorkspace&&(U.useDefaultWorkspace=!0);const Y=await n(e,"launch_ide",U);return g(Y!=null&&Y.success?"info":"error",Y!=null&&Y.success?`${$t(I)} launched`:`Failed: ${Y==null?void 0:Y.error}`,!0),!!(Y!=null&&Y.success)}catch(U){return g("error",`Launch error: ${U.message}`,!0),!1}finally{h(null)}},[e,u,g,n]),A=l.useCallback(async I=>{if(!e)return{success:!1};const{cliType:$,dir:D,workspaceId:U,useDefaultWorkspace:Y,useHome:ae,argsStr:z,model:X,resumeSessionId:de}=I;if(!$)return g("warn","Select a CLI or ACP provider first",!0),{success:!1};const re=z?z.split(/\s+/).filter(Boolean):void 0,W=(D==null?void 0:D.trim())||(U?"(saved id)":Y?"(default workspace)":ae?"(home)":"");g("info",`Launching ${$}${W?` in ${W}`:""}${X?` (model: ${X})`:""}...`),m($);try{const oe={cliType:$,cliArgs:re,initialModel:X||void 0};D!=null&&D.trim()?oe.dir=D.trim():U?oe.workspaceId=U:Y?oe.useDefaultWorkspace=!0:ae&&(oe.useHome=!0),de&&(oe.resumeSessionId=de);const V=await a(e,oe),ie=(V==null?void 0:V.result)||V;return V!=null&&V.success?(g("info",`${$} launched`,!0),(ie==null?void 0:ie.launchSource)==="home"?g("info","📂 Running in home directory (explicit choice)"):(ie==null?void 0:ie.launchSource)==="defaultWorkspace"&&g("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:ie==null?void 0:ie.sessionId}):(g("error",`Failed: ${(V==null?void 0:V.error)||(ie==null?void 0:ie.error)}`,!0),(V==null?void 0:V.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&p({cliType:$,argsStr:z,model:X}),{success:!1,sessionId:ie==null?void 0:ie.sessionId})}catch(oe){return N(oe)?(g("warn",`${$} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(g("error",`Launch error: ${oe.message}`,!0),{success:!1})}finally{m(null)}},[e,g,N,n]),T=l.useCallback(async(I,$,D,U)=>e?I?$.trim()?A({cliType:I,dir:$,argsStr:D,model:U}):(p({cliType:I,argsStr:D,model:U}),{success:!1}):(g("warn","Select a provider",!0),{success:!1}):{success:!1},[e,g,A]),M=l.useCallback(async(I,$,D)=>{if(e&&window.confirm(`Stop ${I}?
97
+ This will terminate the process.`))try{const U=await n(e,"stop_cli",{cliType:I,dir:$,targetSessionId:D});U!=null&&U.success?g("info",`${I} stopped`,!0):g("error",`Stop failed: ${(U==null?void 0:U.error)||"Unknown error"}`,!0)}catch(U){g("error",`Stop failed: ${U.message}`,!0)}},[e,g,n]),L=l.useCallback(async I=>{try{await n(I.daemonId,"restart_ide",{ideType:I.type}),g("info",`${$t(I.type)} restart initiated`,!0)}catch($){g("error",`Restart failed: ${$.message}`,!0)}},[g,n]),P=l.useCallback(async I=>{if(window.confirm(`Stop ${$t(I.type)}?
98
+ This will disconnect CDP and optionally kill the process.`))try{const $=await n(I.daemonId,"stop_ide",{ideType:I.type,killProcess:!0});$!=null&&$.success?g("info",`${$t(I.type)} stopped`,!0):g("error",`Stop failed: ${($==null?void 0:$.error)||"Unknown error"}`,!0)}catch($){g("error",`Stop failed: ${$.message}`,!0)}},[g,n]),B=l.useCallback(async()=>{if(e)try{const I=await n(e,"detect_ides",{});g("info",`Found ${((I==null?void 0:I.result)||[]).length} IDE(s)`,!0)}catch(I){g("error",`Detection failed: ${I.message}`,!0)}},[e,g,n]),K=l.useCallback(async I=>{if(!e||!I.trim())return!1;x(!0);try{const $=await n(e,"workspace_add",{path:I.trim()});return $!=null&&$.success?(g("info",`Workspace added: ${I.trim()}`),!0):(g("error",($==null?void 0:$.error)||"workspace_add failed"),!1)}catch($){return g("error",$.message),!1}finally{x(!1)}},[e,g,n]),F=l.useCallback(async I=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){x(!0);try{const $=await n(e,"workspace_remove",{id:I});$!=null&&$.success?g("info","Workspace removed",!0):g("error",($==null?void 0:$.error)||"workspace_remove failed",!0)}catch($){g("error",$.message,!0)}finally{x(!1)}}},[e,g,n]),R=l.useCallback(async I=>{var $;if(e){x(!0);try{const D=await n(e,"workspace_set_default",I===null?{clear:!0}:{id:I});if(D!=null&&D.success){g("info",I?"Default workspace updated":"Default workspace cleared",!0);const U=typeof D.defaultWorkspacePath=="string"?D.defaultWorkspacePath:"";U&&(($=S.current)==null||$.call(S,U))}else g("error",(D==null?void 0:D.error)||"workspace_set_default failed",!0)}catch(D){g("error",D.message,!0)}finally{x(!1)}}},[e,g,n]),Q=l.useCallback(async I=>{var D;if(!e||!I.trim())return;const $=I.trim();x(!0);try{const U=await n(e,"workspace_set_default",{path:$});U!=null&&U.success?(g("info","Default workspace set from history"),(D=S.current)==null||D.call(S,$)):g("error",(U==null?void 0:U.error)||"Could not set default (path missing on disk?)")}catch(U){g("error",U.message)}finally{x(!1)}},[e,g,n]),E=l.useCallback(async()=>{if(e)try{if(await n(e,"set_machine_nickname",{nickname:b}),r)try{await r({machineRuntimeId:e,registeredMachineId:t,nickname:b})}catch(I){g("warn",`Live nickname updated, but account sync failed: ${I.message}`)}g("info",`Nickname set to "${b||"(cleared)"}"`),k(!1)}catch(I){g("error",`Failed: ${I.message}`)}},[e,b,t,g,r,n]);return{logs:i,launchingIde:u,launchingAgentType:d,workspaceBusy:f,launchPick:w,setLaunchPick:p,editingNickname:y,setEditingNickname:k,nicknameInput:b,setNicknameInput:j,addLog:g,handleLaunchIde:C,runLaunchCliCore:A,handleLaunchCli:T,handleStopCli:M,handleRestartIde:L,handleStopIde:P,handleDetectIdes:B,handleWorkspaceAdd:K,handleWorkspaceRemove:F,handleWorkspaceSetDefault:R,handleWorkspaceResumePath:Q,handleSaveNickname:E,setOnDefaultWorkspaceChanged:v}}function YA({machine:e,ideSessions:t,cliSessions:n,acpSessions:r}){var u;const o=typeof e.uptime=="number"||typeof e.freeMem=="number"||typeof e.availableMem=="number"||Array.isArray(e.loadavg)&&e.loadavg.length>0,a=e.availableMem??e.freeMem??e.totalMem,i=o&&e.totalMem>0?Math.min(100,Math.max(0,Math.round((e.totalMem-a)/e.totalMem*100))):0,c=((u=e.loadavg)==null?void 0:u[0])||0;return s.jsxs("div",{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-5",children:[s.jsx(kr,{icon:s.jsx(Jd,{size:16}),label:"Uptime",value:typeof e.uptime=="number"?Ay(e.uptime):"Waiting…"}),s.jsx(kr,{icon:s.jsx(us,{size:16}),label:"IDEs",value:`${t.length}`}),s.jsx(kr,{icon:s.jsx(Ii,{size:16}),label:"CLIs",value:`${n.length}`}),s.jsx(kr,{icon:s.jsx(Bf,{size:16}),label:"ACPs",value:`${r.length}`})]}),s.jsxs(Ss,{padding:"lg",className:"mb-5",children:[s.jsx("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-3",children:"Resource Usage"}),s.jsxs("div",{className:"flex gap-6",children:[s.jsx($l,{value:o?Math.min(Math.round(c/e.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:o?`${c.toFixed(2)} avg / ${e.cpus} cores`:"Polled from machine page"}),s.jsx($l,{value:i,max:100,label:"Memory",color:"#3b82f6",detail:o?`${Xo(e.totalMem-a)} / ${Xo(e.totalMem)}${e.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${Xo(e.totalMem)} total`})]})]})]})}function JA(e){if(!e||typeof e!="object")return null;const t=e,n=t.result&&typeof t.result=="object"?t.result:t;return!n.settings||typeof n.settings!="object"?null:{settings:n.settings,values:n.values&&typeof n.values=="object"?n.values:{}}}function QA(e,t,n){const r=[];for(const[o,a]of Object.entries(e.settings)){const i=n!=null&&n.filterSchema?n.filterSchema(a):a;if(i.length===0)continue;const c=t.find(u=>u.type===o);r.push({type:o,displayName:(c==null?void 0:c.displayName)||o,icon:(c==null?void 0:c.icon)||"",category:(c==null?void 0:c.category)||"unknown",schema:i,values:e.values[o]||{}})}return r}function Ia(e){if(!e||typeof e!="object")return!1;const t=e;return(t.sourceMode==="normal"||t.sourceMode==="no-upstream")&&typeof t.disableUpstream=="boolean"&&(t.explicitProviderDir===null||typeof t.explicitProviderDir=="string")&&typeof t.userDir=="string"&&typeof t.upstreamDir=="string"&&Array.isArray(t.providerRoots)}function md(e){if(!e||typeof e!="object")return null;if(Ia(e))return e;const t=e,n=t.result;return Ia(n)?n:Ia(t.sourceConfig)?t.sourceConfig:null}function XA(e){const t=e.trim();return t||null}function ZA({machineId:e,providers:t,sendDaemonCommand:n,onClose:r,onCreated:o}){var g;const{t:a}=Le("common"),i=t.filter(N=>N.category==="ide"),[c,u]=l.useState(((g=i[0])==null?void 0:g.type)||""),[h,d]=l.useState(""),[m,f]=l.useState(""),[x,w]=l.useState(!1),[p,y]=l.useState(""),[k,b]=l.useState(!1),j=N=>{const C=N.toLowerCase().replace(/[^a-z0-9-]/g,"");d(C),(!m||m===S(h))&&f(S(C))},S=N=>N.split("-").map(C=>C.charAt(0).toUpperCase()+C.slice(1)).join(" "),v=async()=>{if(!(!h||!m||!c)){w(!0),y("");try{const N=await n(e,"provider_clone",{type:h,name:m,category:"ide",location:"user",cloneFrom:c});N!=null&&N.success||N!=null&&N.created?(b(!0),o==null||o(h)):y((N==null?void 0:N.error)||"Failed to create provider")}catch(N){y((N==null?void 0:N.message)||"Connection failed")}w(!1)}};return s.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick:r,children:s.jsxs("div",{className:"w-full max-w-[480px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] rounded-[24px] sm:rounded-2xl bg-bg-primary border border-border-subtle shadow-2xl flex flex-col overflow-hidden",onClick:N=>N.stopPropagation(),children:[s.jsxs("div",{className:"px-5 py-4 border-b border-border-subtle",children:[s.jsx("h2",{className:"text-[15px] font-semibold text-text-primary",children:a("machine.providerClone.title")}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:a("machine.providerClone.subtitle")})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-4",children:k?s.jsxs("div",{className:"text-center py-6",children:[s.jsx("div",{className:"text-3xl mb-2",children:"🎉"}),s.jsx("h3",{className:"text-[14px] font-semibold text-text-primary",children:a("machine.providerClone.createdTitle")}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[a("machine.providerClone.createdDesc",{type:h})," ",s.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",h,"/"]})]}),s.jsx("p",{className:"text-[11px] text-text-muted mt-2",children:a("machine.providerClone.createdRunHint",{type:h})})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:a("machine.providerClone.baseProvider")}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:i.map(N=>s.jsxs("button",{onClick:()=>u(N.type),className:"px-2.5 py-2 rounded-lg border text-center transition-all",style:{borderColor:c===N.type?"color-mix(in srgb, var(--accent-primary) 40%, transparent)":"var(--border-subtle)",background:c===N.type?"color-mix(in srgb, var(--accent-primary) 8%, transparent)":"transparent"},children:[s.jsx("div",{className:"text-lg",children:N.icon}),s.jsx("div",{className:"text-[10px] font-medium mt-0.5",style:{color:c===N.type?"#a78bfa":"var(--text-secondary)"},children:N.displayName})]},N.type))})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:a("machine.providerClone.providerTypeId")}),s.jsx("input",{value:h,onChange:N=>j(N.target.value),placeholder:a("machine.providerClone.typeIdPlaceholder"),className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"}),s.jsxs("p",{className:"text-[10px] text-text-muted mt-1",children:[a("machine.providerClone.typeIdHint")," ",s.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",h||"...","/"]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:a("machine.providerClone.displayName")}),s.jsx("input",{value:m,onChange:N=>f(N.target.value),placeholder:a("machine.providerClone.displayNamePlaceholder"),className:"w-full px-3 py-2 rounded-lg border border-border-subtle bg-bg-secondary text-text-primary text-[12px] placeholder:text-text-muted/50 focus:outline-none focus:border-violet-500/40"})]}),p&&s.jsx("div",{className:"px-3 py-2 rounded-lg bg-red-500/[0.06] border border-red-500/20 text-red-400 text-[11px]",children:p})]})}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-3.5 border-t border-border-subtle flex justify-end gap-2 shrink-0",children:k?s.jsx("button",{onClick:r,className:"machine-btn",children:a("machine.providerClone.close")}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:r,className:"machine-btn",children:a("machine.providerClone.cancel")}),s.jsx("button",{onClick:v,disabled:!h||!m||x,className:"machine-btn",style:{background:h&&m?"rgba(34,197,94,0.12)":void 0,borderColor:h&&m?"rgba(34,197,94,0.3)":void 0,color:h&&m?"#86efac":void 0,opacity:!h||!m||x?.4:1},children:a(x?"machine.providerClone.creating":"machine.providerClone.createProvider")})]})})]})})}const fd={"user-custom":"Custom",trusted:"Official","trusted-with-scripts":"Official · runs JS","external-safe":"External · spec-only","external-untrusted":"⚠ External · untrusted JS"},eT={"user-custom":"bg-violet-500/[0.10] border-violet-500/25 text-violet-300",trusted:"bg-green-500/[0.10] border-green-500/25 text-green-400","trusted-with-scripts":"bg-emerald-500/[0.10] border-emerald-500/25 text-emerald-400","external-safe":"bg-sky-500/[0.10] border-sky-500/25 text-sky-400","external-untrusted":"bg-amber-500/[0.10] border-amber-500/30 text-amber-300"};function tT({trust:e,sourceName:t,description:n}){const r=t&&(e==="external-safe"||e==="external-untrusted")?`${fd[e]} · ${t}`:fd[e];return s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded border whitespace-nowrap ${eT[e]}`,title:n,children:r})}function sT(e){if(typeof e!="string")return null;try{const t=new URL(e);return t.protocol==="https:"||t.protocol==="http:"?t.toString():null}catch{return null}}const bd={detected:"bg-green-500/[0.10] border-green-500/25 text-green-400",not_detected:"bg-red-500/[0.10] border-red-500/25 text-red-400",enabled_unchecked:"bg-yellow-500/[0.10] border-yellow-500/25 text-yellow-400",disabled:"bg-white/[0.04] border-white/[0.10] text-text-muted"},nT={acp:"bg-violet-500/10 text-violet-300 border-violet-500/20",cli:"bg-blue-500/10 text-blue-300 border-blue-500/20",ide:"bg-green-500/10 text-green-300 border-green-500/20",extension:"bg-yellow-500/10 text-yellow-300 border-yellow-500/20"};function gd(e){if(!e)return"—";const t=e.ok?"OK":"Failed",n=e.message||e.path||e.command||"";return n?`${t} — ${n}`:t}function rT(e){return e==="cli"||e==="acp"}function oT({prov:e,providerInfo:t,savingKey:n,onSetSetting:r,onEnableToggle:o,onDetect:a,onResetCommand:i}){const{t:c}=Le("common"),u={detected:c("machine.providerRow.statusDetected"),not_detected:c("machine.providerRow.statusNotDetected"),enabled_unchecked:c("machine.providerRow.statusEnabledUnchecked"),disabled:c("machine.providerRow.statusDisabled")},[h,d]=l.useState(!1),m=(t==null?void 0:t.enabled)===!0||e.values.enabled===!0,f=t==null?void 0:t.machineStatus,x=m&&f==="disabled"?"enabled_unchecked":f||(m?"enabled_unchecked":"disabled"),w=rT(e.category);return s.jsxs(Ss,{padding:"none",children:[s.jsxs("button",{onClick:()=>d(p=>!p),className:"w-full px-4 py-2.5 flex items-center gap-3 text-left",children:[s.jsx("span",{className:"text-base shrink-0",children:e.icon}),s.jsx("span",{className:"text-[13px] font-semibold text-text-primary truncate",children:e.displayName}),s.jsx("span",{className:`text-[9px] font-semibold px-1.5 py-px rounded border ${nT[e.category]??"border-border-subtle text-text-muted"}`,children:e.category.toUpperCase()}),(t==null?void 0:t.trust)&&s.jsx(tT,{trust:t.trust,sourceName:t.sourceName??null,description:t.trustDescription}),w&&s.jsx("span",{className:`text-[9px] font-semibold px-1.5 py-px rounded border ${bd[x]??bd.disabled}`,children:u[x]??x}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[w&&s.jsx("button",{onClick:p=>{p.stopPropagation(),o(e.type,!m)},disabled:n===`${e.type}.enabled`,className:`machine-btn text-[10px] px-2 py-0.5 ${m?"text-red-400 border-red-500/25":"text-green-400 border-green-500/25"}`,children:c(m?"machine.providerRow.disable":"machine.providerRow.enable")}),s.jsx("span",{className:"text-text-muted text-xs",children:h?"▾":"▸"})]})]}),h&&s.jsxs("div",{className:"border-t border-border-subtle px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{className:"grid gap-1 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:c("machine.providerRow.labelType")})," ",s.jsx("span",{className:"font-mono",children:e.type})]}),(t==null?void 0:t.providerVersion)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:c("machine.providerRow.labelVersion")})," ",t.providerVersion]}),(t==null?void 0:t.binary)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:c("machine.providerRow.labelBinary")})," ",s.jsx("span",{className:"font-mono",children:t.binary})]}),(t==null?void 0:t.status)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:c("machine.providerRow.labelStatus")})," ",t.status]}),(t==null?void 0:t.details)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:c("machine.providerRow.labelDetails")})," ",t.details]}),(t==null?void 0:t.sourceLayer)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:c("machine.providerRow.labelSource")})," ",t.sourceLayer,t.sourceName?` · ${t.sourceName}`:""]}),(t==null?void 0:t.trust)&&(t==null?void 0:t.trustDescription)&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:c("machine.providerRow.labelTrust")})," ",t.trustDescription]}),(()=>{const p=t==null?void 0:t.links;if(!p)return null;const y=Object.entries(p).map(([k,b])=>({k,href:sT(b)})).filter(k=>k.href!==null);return y.length===0?null:s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:c("machine.providerRow.labelLinks")})," ",y.map(({k,href:b})=>s.jsx("a",{href:b,target:"_blank",rel:"noopener noreferrer",className:"text-violet-400 hover:underline mr-2",children:k},k))]})})()]}),w&&s.jsxs("div",{className:"grid gap-1 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:c("machine.providerRow.labelDetection")})," ",gd(t==null?void 0:t.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:c("machine.providerRow.labelVerification")})," ",gd(t==null?void 0:t.lastVerification)]})]}),e.schema.length>0&&s.jsx("div",{className:"flex flex-col gap-1.5",children:e.schema.map(p=>s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"flex-1 min-w-0",children:[s.jsxs("div",{className:"text-[11px] font-medium text-text-primary",children:[p.label||p.key,n===`${e.type}.${p.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:c("machine.providerRow.saving")})]}),p.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:p.description})]}),s.jsx("div",{className:"shrink-0",children:p.type==="boolean"?s.jsx("button",{onClick:()=>void r(e.type,p.key,!(e.values[p.key]??p.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:e.values[p.key]??p.default?"#8b5cf6":"var(--border-subtle)"},children:s.jsx("div",{className:"w-4 h-4 rounded-full bg-white absolute top-[3px] transition-[left] duration-200 shadow-[0_1px_3px_rgba(0,0,0,0.3)]",style:{left:e.values[p.key]??p.default?21:3}})}):p.type==="number"?s.jsx("input",{type:"number",value:Number(e.values[p.key]??p.default??0)||0,min:p.min,max:p.max,onChange:y=>{const k=parseInt(y.target.value)||0;p.min!==void 0&&k<p.min||p.max!==void 0&&k>p.max||r(e.type,p.key,k)},className:"machine-input w-20 text-center text-[11px]"}):p.type==="select"&&p.options?s.jsx("select",{value:String(e.values[p.key]??p.default??""),onChange:y=>void r(e.type,p.key,y.target.value),className:"machine-input text-[11px]",children:p.options.map(y=>s.jsx("option",{value:y,children:y},y))}):s.jsx("input",{type:"text",defaultValue:String(e.values[p.key]??p.default??""),onBlur:y=>void r(e.type,p.key,y.target.value),className:"machine-input w-[180px] text-[11px]"})})]},p.key))}),s.jsx("div",{className:"flex gap-1.5 flex-wrap pt-1 border-t border-border-subtle",children:w&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>void a(e.type),disabled:!m||n===`${e.type}.detect`,className:`machine-btn text-[10px] px-2 py-0.5 text-blue-400 border-blue-500/25 ${m?"":"opacity-40 cursor-not-allowed"}`,title:m?"Run detection for the configured executable":"Enable provider before detection",children:c("machine.providerRow.detect")}),s.jsx("button",{onClick:()=>void i(e.type),className:"machine-btn text-[10px] px-2 py-0.5",children:c("machine.providerRow.resetCommand")})]})})]})]})}function Fr(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function aT({machineId:e,sendDaemonCommand:t,onChange:n}){const[r,o]=l.useState([]),[a,i]=l.useState([]),[c,u]=l.useState(!1),[h,d]=l.useState(null),[m,f]=l.useState(!1),[x,w]=l.useState(""),[p,y]=l.useState("main"),[k,b]=l.useState(""),[j,S]=l.useState(!1),[v,g]=l.useState(null),[N,C]=l.useState(null),A=l.useCallback(async()=>{if(e){u(!0),d(null);try{const P=Fr(await t(e,"list_provider_sources",{}));if(!(P!=null&&P.success)){d((P==null?void 0:P.error)||"Failed to load sources");return}o(P.sources||[]),i(P.conflicts||[])}catch(P){d((P==null?void 0:P.message)||String(P))}finally{u(!1)}}},[e,t]);l.useEffect(()=>{A()},[A]);const T=async()=>{if(x.trim()){S(!0),d(null);try{const P=Fr(await t(e,"add_provider_source",{url:x.trim(),ref:p.trim()||"main",...k.trim()?{name:k.trim()}:{}}));P!=null&&P.success?(f(!1),w(""),y("main"),b(""),await A(),n==null||n()):d((P==null?void 0:P.error)||"Failed to add source")}catch(P){d((P==null?void 0:P.message)||String(P))}finally{S(!1)}}},M=async P=>{if(confirm(`Remove provider source ${P}? This deletes the cloned manifests and clears any active-source entries that pointed here.`)){g(P),d(null);try{const B=Fr(await t(e,"remove_provider_source",{name:P}));B!=null&&B.success?(await A(),n==null||n()):d((B==null?void 0:B.error)||"Failed to remove source")}catch(B){d((B==null?void 0:B.message)||String(B))}finally{g(null)}}},L=async(P,B)=>{C(`${P}:${B}`),d(null);try{const K=Fr(await t(e,"set_active_provider_source",{type:P,sourceName:B}));K!=null&&K.success?(await A(),n==null||n()):d((K==null?void 0:K.error)||"Failed to set active source")}catch(K){d((K==null?void 0:K.message)||String(K))}finally{C(null)}};return s.jsxs(Ss,{padding:"none",className:"px-4.5 py-3.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-sky-400",children:"External sources"}),s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:"3rd-party git URLs you've added. Providers here may ship JavaScript the daemon will execute — activation requires a confirmation."})]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsxs("button",{onClick:()=>void A(),disabled:c,className:"machine-btn text-[10px]",children:[c?"⏳":"↻"," Refresh"]}),s.jsx("button",{onClick:()=>f(!0),className:"machine-btn text-[10px] bg-sky-500/[0.08] border-sky-500/20 text-sky-300 hover:bg-sky-500/[0.14]",children:"+ Add source"})]})]}),h&&s.jsx("div",{className:"mb-2 text-[11px] text-red-400 bg-red-500/10 border border-red-500/20 rounded px-2 py-1",children:h}),r.length===0?s.jsx("div",{className:"text-[11px] text-text-muted italic",children:'No external sources registered. Use "+ Add source" to register a 3rd-party provider git URL.'}):s.jsx("ul",{className:"flex flex-col gap-2",children:r.map(P=>s.jsxs("li",{className:"rounded border border-border-subtle bg-bg-primary/40 px-3 py-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"font-mono text-[12px] text-text-primary",children:P.name}),s.jsxs("div",{className:"text-[10px] text-text-muted truncate",children:[P.url," ",s.jsxs("span",{className:"opacity-60",children:["@ ",P.ref]})]})]}),s.jsx("button",{type:"button",onClick:()=>void M(P.name),disabled:v===P.name,className:"machine-btn text-[10px] text-red-400 hover:bg-red-500/[0.10]",children:v===P.name?"…":"Remove"})]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:Object.entries(P.providers).map(([B,K])=>s.jsxs("span",{className:"mr-3",children:[s.jsxs("span",{className:"text-text-secondary",children:[B,":"]})," ",K.length]},B))})]},P.name))}),a.length>0&&s.jsxs("div",{className:"mt-3 rounded border border-amber-500/30 bg-amber-500/[0.06] px-3 py-2",children:[s.jsx("div",{className:"text-[11px] font-semibold text-amber-300 mb-1.5",children:"Conflicts"}),s.jsx("div",{className:"text-[10px] text-text-muted mb-2",children:"Multiple sources expose the same provider type. Pick which source's copy should be active."}),s.jsx("ul",{className:"flex flex-col gap-1.5",children:a.map(P=>s.jsxs("li",{className:"flex items-center justify-between gap-2",children:[s.jsxs("div",{className:"font-mono text-[11px]",children:[P.type," ",s.jsxs("span",{className:"text-text-muted",children:["(",P.category,")"]})]}),s.jsx("div",{className:"flex gap-1.5 flex-wrap",children:P.candidates.map(B=>s.jsxs("button",{type:"button",onClick:()=>void L(P.type,B),disabled:N===`${P.type}:${B}`,className:`text-[10px] px-2 py-0.5 rounded border ${P.active===B?"bg-amber-500/[0.18] border-amber-500/40 text-amber-200":"border-border-subtle text-text-secondary hover:bg-amber-500/[0.06]"}`,title:P.active===B?"Active":`Switch active to ${B}`,children:[P.active===B?"● ":"",B]},B))})]},P.type))})]}),m&&s.jsxs("div",{className:"mt-3 rounded border border-sky-500/30 bg-sky-500/[0.06] px-3 py-3",children:[s.jsx("div",{className:"text-[11px] font-semibold text-sky-300 mb-2",children:"Add external source"}),s.jsxs("div",{className:"grid md:grid-cols-3 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1 text-[10px] text-text-secondary md:col-span-3",children:[s.jsx("span",{children:"Git URL"}),s.jsx("input",{type:"text",value:x,onChange:P=>w(P.target.value),placeholder:"https://github.com/vendor/extra-providers",className:"machine-input text-[11px] font-mono"})]}),s.jsxs("label",{className:"flex flex-col gap-1 text-[10px] text-text-secondary",children:[s.jsx("span",{children:"Ref (branch/tag)"}),s.jsx("input",{type:"text",value:p,onChange:P=>y(P.target.value),placeholder:"main",className:"machine-input text-[11px]"})]}),s.jsxs("label",{className:"flex flex-col gap-1 text-[10px] text-text-secondary md:col-span-2",children:[s.jsx("span",{children:"Name (optional, auto-derived from URL)"}),s.jsx("input",{type:"text",value:k,onChange:P=>b(P.target.value),placeholder:"@vendor-extra-providers",className:"machine-input text-[11px] font-mono"})]})]}),s.jsxs("div",{className:"mt-3 flex items-center justify-end gap-2",children:[s.jsx("button",{type:"button",onClick:()=>f(!1),className:"machine-btn text-[10px]",children:"Cancel"}),s.jsx("button",{type:"button",onClick:()=>void T(),disabled:j||!x.trim(),className:"machine-btn text-[10px] bg-sky-500/[0.10] border-sky-500/30 text-sky-200 hover:bg-sky-500/[0.18]",children:j?"Cloning…":"Clone + register"})]})]})]})}function iT({machineId:e,providers:t,sendDaemonCommand:n}){var Q;const{t:r}=Le("common"),[o,a]=l.useState([]),[i,c]=l.useState(!1),[u,h]=l.useState(null),[d,m]=l.useState("all"),[f,x]=l.useState(!1),[w,p]=l.useState(!1),[y,k]=l.useState(!1),[b,j]=l.useState(null),[S,v]=l.useState("normal"),[g,N]=l.useState(""),[C,A]=l.useState(!1),T=l.useCallback(async()=>{if(e)try{const E=await n(e,"get_provider_source_config",{}),I=md(E);I&&(j(I),v(I.sourceMode),N(I.explicitProviderDir||""))}catch{}},[e,n]),M=l.useCallback(async()=>{if(e){c(!0);try{const E=await n(e,"get_provider_settings",{}),I=JA(E);if(I){const $=QA(I,t,{filterSchema:D=>D.filter(U=>U.key!=="enabled")});$.sort((D,U)=>D.category.localeCompare(U.category)||D.displayName.localeCompare(U.displayName)),a($)}}catch{}c(!1)}},[e,t,n]);l.useEffect(()=>{o.length===0&&M(),b||T()},[]);const L=async(E,I,$)=>{h(`${E}.${I}`),a(D=>D.map(U=>U.type===E?{...U,values:{...U.values,[I]:$}}:U));try{const D=await n(e,"set_provider_setting",{providerType:E,key:I,value:$});D!=null&&D.success||M()}catch{M()}h(null)},P=async(E,I)=>{await L(E,"enabled",I),await M()},B=async E=>{h(`${E}.detect`);try{await n(e,"detect_provider",{providerType:E})}finally{await M(),h(null)}},K=async E=>{await L(E,"executablePath",""),await L(E,"executableArgs",""),await M()},F=async()=>{A(!0);try{const E=await n(e,"set_provider_source_config",{providerSourceMode:S,providerDir:XA(g)}),I=md(E);I?(j(I),v(I.sourceMode),N(I.explicitProviderDir||"")):await T(),await M()}catch{await T()}A(!1)},R=o.filter(E=>d==="all"||E.category===d);return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[s.jsxs("div",{className:"flex gap-1 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-2",children:r("machine.providers.filter")}),["all","acp","cli","ide","extension"].map(E=>s.jsx("button",{onClick:()=>m(E),className:`machine-btn text-[10px] px-2 py-0.5 ${d===E?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:E.toUpperCase()},E))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>p(E=>!E),className:`machine-btn text-[10px] ${w?"bg-sky-500/[0.10] border-sky-500/30 text-sky-300":""}`,title:"Manage 3rd-party provider sources",children:r("machine.providers.sources")}),s.jsx("button",{onClick:()=>x(!0),className:"machine-btn text-[10px]",title:"Create a new provider from an existing one",children:r("machine.providers.create")}),s.jsxs("button",{onClick:M,disabled:i,className:"machine-btn text-[10px]",children:[i?"⏳":"↻"," ",r("machine.providers.refresh")]}),s.jsx("button",{onClick:()=>k(E=>!E),className:"machine-btn text-[10px]",title:"Show source configuration (advanced)",children:r("machine.providers.advanced")})]})]}),w&&s.jsx(aT,{machineId:e,sendDaemonCommand:n,onChange:()=>{M()}}),y&&s.jsxs(Ss,{padding:"none",className:"px-4.5 py-3.5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wider text-violet-400",children:r("machine.providers.sourceConfigTitle")}),s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:r("machine.providers.sourceConfigDesc")})]}),s.jsx("button",{onClick:T,className:"machine-btn text-[10px]",children:"↻ Refresh"})]}),s.jsxs("div",{className:"grid md:grid-cols-[180px_1fr_auto] gap-3 items-end",children:[s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:r("machine.providers.sourceMode")}),s.jsxs("select",{value:S,onChange:E=>v(E.target.value),className:"machine-input text-[11px]",children:[s.jsx("option",{value:"normal",children:"normal"}),s.jsx("option",{value:"no-upstream",children:"no-upstream"})]})]}),s.jsxs("label",{className:"flex flex-col gap-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"font-medium text-text-primary",children:r("machine.providers.explicitProviderDir")}),s.jsx("input",{type:"text",value:g,onChange:E=>N(E.target.value),placeholder:r("machine.providers.providerDirPlaceholder"),className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void F(),disabled:C,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:r(C?"machine.providers.applying":"machine.providers.applyReload")})]}),s.jsxs("div",{className:"mt-3 grid gap-1 text-[10px] text-text-muted",children:[s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:r("machine.providers.userRoot")})," ",(b==null?void 0:b.userDir)||"—"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:r("machine.providers.upstreamRoot")})," ",(b==null?void 0:b.upstreamDir)||"—"]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:r("machine.providers.providerRoots")})," ",((Q=b==null?void 0:b.providerRoots)==null?void 0:Q.join(" → "))||"—"]})]})]}),i&&o.length===0?s.jsx("div",{className:"p-10 text-center text-text-muted",children:r("machine.providers.loadingSettings")}):R.length===0?s.jsx(Ss,{padding:"none",className:"px-4.5 py-8 text-center",children:s.jsx("div",{className:"text-[12px] text-text-muted",children:d==="all"?r("machine.providers.noProviders"):r("machine.providers.noFilteredProviders",{filter:d.toUpperCase()})})}):s.jsx("div",{className:"flex flex-col gap-1.5",children:R.map(E=>s.jsx(oT,{prov:E,providerInfo:t.find(I=>I.type===E.type),savingKey:u,onSetSetting:L,onEnableToggle:P,onDetect:B,onResetCommand:K},E.type))}),f&&s.jsx(ZA,{machineId:e,providers:t,sendDaemonCommand:n,onClose:()=>x(!1),onCreated:()=>{x(!1),M()}})]})}const lT=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function cT({count:e,since:t,category:n}){return{count:e,since:t,...n==="all"?{}:{category:n}}}function dT(e,t){return t==="all"?e:e.filter(n=>n.category===t)}function uT(e){return e.trim().toLowerCase()}function Ho(e,t){const n=uT(t);return n?e.some(r=>String(r??"").toLowerCase().includes(n)):!0}function ml(e){if(!e||Object.keys(e).length===0)return"";try{return JSON.stringify(e)}catch{return"[unserializable payload]"}}function jn(e,t=220){const n=ml(e);return n?n.length>t?`${n.slice(0,t)}…`:n:""}function hT(e){const t=e&&typeof e=="object"&&"logs"in e?e.logs:e;if(Array.isArray(t))return{kind:t.length>0?"structured":"empty",entries:t.map(n=>{const r=n;return{timestamp:Number(r.ts)||0,level:r.level||"info",message:`[${String(r.category||"daemon")}] ${String(r.message||"")}`.trim()}}),rawText:""};if(typeof t=="string"){const n=t.trim();return{kind:n?"text":"empty",entries:[],rawText:n}}return{kind:"empty",entries:[],rawText:""}}function pT(e,t){return e.filter(n=>Ho([n.level,n.message],t))}function xd(e){return`${e.timestamp}:${e.level}:${e.message}`}function mT(e,t,n=300){if(t.entries.length>0){const r=new Map;for(const i of e.entries)r.set(xd(i),i);for(const i of t.entries)r.set(xd(i),i);const o=Array.from(r.values()).sort((i,c)=>i.timestamp-c.timestamp).slice(-n),a=o.reduce((i,c)=>Math.max(i,Number(c.timestamp||0)),e.lastTs);return{entries:o,kind:"structured",rawText:"",lastTs:a}}return t.kind==="text"?e.entries.length>0?e:{entries:[],kind:"text",rawText:t.rawText,lastTs:e.lastTs}:e.entries.length>0||e.rawText?e:{entries:[],kind:"empty",rawText:"",lastTs:e.lastTs}}function fT(e,t,n=120){if(t.length===0)return e;const r=new Map;for(const o of e)r.set(o.id,o);for(const o of t)r.set(o.id,o);return Array.from(r.values()).sort((o,a)=>o.ts-a.ts).slice(-n)}function bT(e,t){return e.split(`
99
+ `).map(n=>n.trimEnd()).filter(Boolean).filter(n=>Ho([n],t))}function gT(e,t){return e.filter(n=>Ho([n.level,n.category,n.stage,n.interactionId,ml(n.payload)],t))}function xT(e,t){return e.filter(n=>Ho([n.kind,n.topic,n.interactionId,ml(n.payload)],t))}function yd(e){return e==="warn"||e==="error"}function yT({daemonLogs:e,daemonRawLines:t,trace:n,webEvents:r}){return{all:e.length+t.length+n.length+r.length,info:e.filter(o=>o.level!=="debug").length+n.filter(o=>o.level!=="debug").length+r.length,issues:e.filter(o=>yd(o.level)).length+n.filter(o=>yd(o.level)).length}}function vT({daemonLogs:e,daemonRawLines:t,trace:n,webEvents:r}){const o=[];return e.length>0?o.push(["[daemon logs]",...e.map(a=>`${new Date(a.timestamp).toISOString()} ${a.level.toUpperCase()} ${a.message}`)].join(`
100
+ `)):t.length>0&&o.push(["[daemon logs]",...t].join(`
101
+ `)),n.length>0&&o.push(["[trace]",...n.map(a=>`${new Date(a.ts).toISOString()} ${a.level.toUpperCase()} ${a.category}.${a.stage} ${jn(a.payload,500)}`.trim())].join(`
102
+ `)),r.length>0&&o.push(["[browser events]",...r.map(a=>`${new Date(a.ts).toISOString()} ${a.kind}${a.topic?` topic=${a.topic}`:""} ${jn(a.payload,500)}`.trim())].join(`
103
+ `)),o.join(`
104
+
105
+ `)}function wT({machineId:e,sendDaemonCommand:t}){const[n,r]=l.useState([]),[o,a]=l.useState("empty"),[i,c]=l.useState(""),[u,h]=l.useState([]),[d,m]=l.useState([]),[f,x]=l.useState(null),[w,p]=l.useState(!0),[y,k]=l.useState("info"),[b,j]=l.useState("all"),[S,v]=l.useState(!0),[g,N]=l.useState(!0),[C,A]=l.useState(""),[T,M]=l.useState(""),[L,P]=l.useState(0),B=l.useRef(0),K=l.useRef(0),F=l.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),R=l.useRef([]),Q=l.useCallback(()=>{const ae={entries:[],kind:"empty",rawText:"",lastTs:0};F.current=ae,B.current=0,r([]),c(""),a("empty"),v(!0)},[]),E=l.useCallback(()=>{R.current=[],K.current=0,h([]),N(!0)},[]),I=l.useCallback(ae=>{ae!==y&&(Q(),k(ae))},[y,Q]),$=l.useCallback(ae=>{j(z=>z===ae?z:ae)},[]),D=l.useCallback(()=>{Q(),E(),m([]),x(null),A(""),M(""),bn.clear()},[Q,E]),U=l.useCallback(()=>{P(ae=>ae+1)},[]),Y=l.useCallback(async()=>{if(!e)return;const ae=B.current,z=K.current,[X,de]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:y,since:ae}),t(e,"get_debug_trace",cT({count:120,since:z,category:b}))]);if(X.status==="fulfilled"){const re=X.value,W=(re==null?void 0:re.result)||re,oe=hT(W),V=mT(F.current,oe,300);F.current=V,B.current=V.lastTs,v(!1),A((re==null?void 0:re.success)===!1?String((re==null?void 0:re.error)||"Could not load daemon logs"):""),a(V.kind),c(V.rawText),r(V.entries)}else v(!1),A(X.reason instanceof Error?X.reason.message:"Could not load daemon logs");if(de.status==="fulfilled"){const re=de.value,W=(re==null?void 0:re.result)||re;if((re==null?void 0:re.success)===!1)M(String((re==null?void 0:re.error)||"Could not load daemon trace"));else if(Array.isArray(W==null?void 0:W.trace)){const oe=W.trace,V=fT(R.current,oe,120),ie=oe.reduce((ke,xe)=>Math.max(ke,Number(xe.ts||0)),z);R.current=V,ie>z&&(K.current=ie),M(""),h(V)}else M("");N(!1)}else N(!1),M(de.reason instanceof Error?de.reason.message:"Could not load daemon trace");m(bn.list({limit:120})),x(Date.now())},[y,e,t,b]);return l.useEffect(()=>{E()},[E,b]),l.useEffect(()=>{if(!e||(Y(),!w))return;const ae=setInterval(()=>{Y()},3e3);return()=>clearInterval(ae)},[w,Y,e,L]),{daemonLogs:n,daemonLogKind:o,daemonRawText:i,debugTrace:u,webEvents:d,lastUpdatedAt:f,autoRefresh:w,logLevel:y,traceCategory:b,daemonLoading:S,traceLoading:g,daemonFetchError:C,traceFetchError:T,setAutoRefresh:p,setLogLevel:I,setTraceCategory:$,refresh:U,clear:D}}function kT({daemonLoading:e,traceLoading:t,daemonFetchError:n,traceFetchError:r,daemonLogKind:o,daemonLogsCount:a,daemonRawLineCount:i,traceCount:c,webEventCount:u}){return[{id:"daemon_logs",label:"Daemon logs",status:n?"error":e?"loading":a>0||i>0?"ok":"empty",detail:n||(o==="text"?`${i} raw file-fallback line(s)`:`${a} structured line(s)`)},{id:"daemon_trace",label:"Daemon trace",status:r?"error":t?"loading":c>0?"ok":"empty",detail:r||`${c} trace event(s)`},{id:"browser_events",label:"Browser debug events",status:u>0?"ok":"empty",detail:u>0?`${u} local browser event(s)`:"No browser events captured"}]}function vd(e){return e==="warn"||e==="error"}function ST(e){const t=e.toLowerCase();return/\[(err|error)\]/i.test(e)||t.includes(" error ")||t.includes(" failed")?"error":/\[(wrn|warn|warning)\]/i.test(e)||t.includes(" warning ")||t.includes(" timeout")?"warn":/\[(dbg|debug)\]/i.test(e)?"debug":"info"}function CT(e,t){const n=e.match(/\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z\b/);if(n){const r=Date.parse(n[0]);if(Number.isFinite(r))return r}return Number.MAX_SAFE_INTEGER-1e5+t}function wd(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function jT(e){const t=jn(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function NT(e){const t=jn(e.payload,320),n=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${n} ${t}`:`${e.kind}${n}`}function AT({daemonLogs:e,daemonRawLines:t,trace:n,webEvents:r}){const o=[];return e.forEach((a,i)=>{o.push({id:`daemon-log-${a.timestamp}-${i}`,source:"daemon_log",ts:Number(a.timestamp||0),severity:a.level,message:a.message,raw:a.message})}),r.forEach(a=>{o.push({id:`browser-event-${a.id}`,source:"browser_event",ts:Number(a.ts||0),severity:"info",message:NT(a),topic:a.topic,interactionId:a.interactionId,payload:a.payload})}),n.forEach(a=>{o.push({id:`daemon-trace-${a.id}`,source:"daemon_trace",ts:Number(a.ts||0),severity:a.level,message:jT(a),category:a.category,stage:a.stage,interactionId:a.interactionId,payload:a.payload})}),t.forEach((a,i)=>{o.push({id:`raw-file-${i}`,source:"raw_file",ts:CT(a,i),severity:ST(a),message:a,raw:a})}),o.sort((a,i)=>a.ts!==i.ts?a.ts-i.ts:wd(a.source)-wd(i.source))}function TT(e){return`${e.source}:${e.severity}:${e.message}`}function IT(e){const t=e.filter(r=>vd(r.severity)).sort((r,o)=>o.ts-r.ts),n=new Map;for(const r of e){if(!vd(r.severity))continue;const o=TT(r),a=n.get(o);a?(a.count+=1,a.firstTs=Math.min(a.firstTs,r.ts),a.lastTs=Math.max(a.lastTs,r.ts)):n.set(o,{key:o,source:r.source,severity:r.severity,message:r.message,count:1,firstTs:r.ts,lastTs:r.ts})}return{totalCount:e.length,issueCount:t.length,latestIssue:t[0]||null,repeatedPatterns:Array.from(n.values()).filter(r=>r.count>1).sort((r,o)=>o.count!==r.count?o.count-r.count:o.lastTs-r.lastTs).slice(0,5)}}function MT(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function kd(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",n=e.interactionId?` ix=${e.interactionId}`:"";return`${MT(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${n} ${e.message}`.trim()}function DT({events:e,summary:t,sources:n,maxTimelineEvents:r=80}){const o=[];o.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
106
+ `)),o.push(["[source status]",...n.map(i=>`${i.label}: ${i.status} - ${i.detail}`)].join(`
107
+ `)),t.latestIssue&&o.push(["[latest issue]",kd(t.latestIssue)].join(`
108
+ `)),t.repeatedPatterns.length>0&&o.push(["[top repeated patterns]",...t.repeatedPatterns.map(i=>`${i.count}x ${i.severity.toUpperCase()} ${i.source} ${i.message}`)].join(`
109
+ `));const a=e.slice(-r);return o.push(["[timeline]",...a.length>0?a.map(kd):["No diagnostic events captured."]].join(`
110
+ `)),o.join(`
111
+
112
+ `)}function PT(e,t){return t==="issues"?e.filter(n=>n.level==="warn"||n.level==="error"):t==="info"?e.filter(n=>n.level!=="debug"):e}function LT(e,t){return t==="issues"?e.filter(n=>n.level==="warn"||n.level==="error"):t==="info"?e.filter(n=>n.level!=="debug"):e}function RT({daemonLogs:e,daemonRawText:t,daemonLogKind:n,debugTrace:r,webEvents:o,traceCategory:a,quickFilter:i,searchQuery:c,daemonLoading:u,traceLoading:h,daemonFetchError:d,traceFetchError:m}){const f=dT(r,a),x=pT(e,c),w=bT(t,c),p=gT(f,c),y=xT(o,c),k=PT(x,i),b=i==="all"?w:[],j=LT(p,i),S=i==="issues"?[]:y,v=yT({daemonLogs:x,daemonRawLines:w,trace:p,webEvents:y}),g=AT({daemonLogs:k,daemonRawLines:b,trace:j,webEvents:S}),N=IT(g),C=kT({daemonLoading:u,traceLoading:h,daemonFetchError:d,traceFetchError:m,daemonLogKind:n,daemonLogsCount:x.length,daemonRawLineCount:w.length,traceCount:p.length,webEventCount:y.length});return{filteredDaemonLogs:x,filteredDaemonRawLines:w,filteredTraceEntries:p,filteredWebEvents:y,visibleDaemonLogs:k,visibleDaemonRawLines:b,visibleTraceEntries:j,visibleWebEvents:S,quickFilterCounts:v,diagnosticEvents:g,diagnosticsSummary:N,sourceStates:C}}function ET(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Jp(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function gi(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 Ma(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 fl(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function _T({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${gi(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:Jp(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:fl(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 $T({quickFilter:e,quickFilterCounts:t,searchQuery:n,autoRefresh:r,onQuickFilterChange:o,onSearchQueryChange:a,onCopyDiagnostics:i,onCopyVisible:c,onToggleAutoRefresh:u,onRefresh:h,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:()=>o(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=>a(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:h,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:d,className:"machine-btn",children:"Clear"})]})]})}function BT({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(o=>s.jsxs("button",{onClick:()=>n(o),className:`machine-btn text-[10px] px-2 py-0.5 ${e===o?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:["Daemon ",o.toUpperCase(),"+"]},o))]}),s.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:lT.map(o=>s.jsx("button",{onClick:()=>r(o.value),className:`machine-btn text-[10px] px-2 py-0.5 ${t===o.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:o.label},o.value))})]})})}function FT({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:n,searchQuery:r,lastUpdatedAt:o,autoRefresh:a,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",h=i||c?"danger":a?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${Ma(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 ${Ma(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:[fl(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:Jp(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 ${Ma(h)}`,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":a?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",ET(o)]}),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 HT({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()," · ",fl(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function WT({streams:e,sectionsOpen:t,setSectionsOpen:n,diagnosticEvents:r,visibleDaemonLogs:o,visibleDaemonRawLines:a,visibleTraceEntries:i,visibleWebEvents:c,quickFilter:u,searchQuery:h}){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(_T,{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"?`${a.length} visible raw line(s) from file fallback`:`${o.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&&o.length===0&&a.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"&&a.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"&&o.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"&&a.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"&&o.map((d,m)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${gi(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:h.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 ${gi(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:h.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 OT({machineId:e,sendDaemonCommand:t}){const n=wT({machineId:e,sendDaemonCommand:t}),[r,o]=l.useState("info"),[a,i]=l.useState(""),[c,u]=l.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),h=l.useRef(null),d=l.useRef(!1),m=l.useMemo(()=>RT({daemonLogs:n.daemonLogs,daemonRawText:n.daemonRawText,daemonLogKind:n.daemonLogKind,debugTrace:n.debugTrace,webEvents:n.webEvents,traceCategory:n.traceCategory,quickFilter:r,searchQuery:a,daemonLoading:n.daemonLoading,traceLoading:n.traceLoading,daemonFetchError:n.daemonFetchError,traceFetchError:n.traceFetchError}),[r,a,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 p;(p=h.current)==null||p.scrollIntoView({behavior:w}),d.current=!0},50)}},[m.diagnosticEvents.length,n.autoRefresh]);const f=l.useCallback(async()=>{var p;const w=vT({daemonLogs:m.visibleDaemonLogs,daemonRawLines:m.visibleDaemonRawLines,trace:m.visibleTraceEntries,webEvents:m.visibleWebEvents});if(!w.trim()){pt.showToast("No visible logs to copy.","info");return}try{await((p=navigator.clipboard)==null?void 0:p.writeText(w)),pt.showToast("Copied visible logs to clipboard.","success")}catch(y){pt.showToast(y instanceof Error?y.message:"Could not copy visible logs","warning")}},[m.visibleDaemonLogs,m.visibleDaemonRawLines,m.visibleTraceEntries,m.visibleWebEvents]),x=l.useCallback(async()=>{var p;const w=DT({events:m.diagnosticEvents,summary:m.diagnosticsSummary,sources:m.sourceStates});try{await((p=navigator.clipboard)==null?void 0:p.writeText(w)),pt.showToast("Copied diagnostic bundle to clipboard.","success")}catch(y){pt.showToast(y instanceof Error?y.message:"Could not copy diagnostic bundle","warning")}},[m.diagnosticEvents,m.diagnosticsSummary,m.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx($T,{quickFilter:r,quickFilterCounts:m.quickFilterCounts,searchQuery:a,autoRefresh:n.autoRefresh,onQuickFilterChange:o,onSearchQueryChange:i,onCopyDiagnostics:()=>{x()},onCopyVisible:()=>{f()},onToggleAutoRefresh:()=>n.setAutoRefresh(w=>!w),onRefresh:n.refresh,onClear:n.clear}),s.jsx(BT,{logLevel:n.logLevel,traceCategory:n.traceCategory,onLogLevelChange:n.setLogLevel,onTraceCategoryChange:n.setTraceCategory}),s.jsx(FT,{diagnosticsSummary:m.diagnosticsSummary,diagnosticEventsCount:m.diagnosticEvents.length,sourceStates:m.sourceStates,searchQuery:a,lastUpdatedAt:n.lastUpdatedAt,autoRefresh:n.autoRefresh,daemonFetchError:n.daemonFetchError,traceFetchError:n.traceFetchError}),s.jsx(HT,{patterns:m.diagnosticsSummary.repeatedPatterns}),s.jsx(WT,{streams:n,sectionsOpen:c,setSectionsOpen:u,diagnosticEvents:m.diagnosticEvents,visibleDaemonLogs:m.visibleDaemonLogs,visibleDaemonRawLines:m.visibleDaemonRawLines,visibleTraceEntries:m.visibleTraceEntries,visibleWebEvents:m.visibleWebEvents,quickFilter:r,searchQuery:a}),s.jsx("div",{ref:h})]})}function UT(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 Qp(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 GT(e){var o;const t=[],n=[],r=[];for(const a of e||[]){const i=String((a==null?void 0:a.lifecycle)||"").trim(),c=Qp((a==null?void 0:a.meta)||void 0),u=((o=a==null?void 0:a.meta)==null?void 0:o.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(i)?t.push(a):(i==="stopped"||i==="failed")&&(u||c)?n.push(a):r.push(a)}return{liveRuntimes:t,recoverySnapshots:n,inactiveRecords:r}}function KT(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Da(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 Pa(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function La(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Sd(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 o=Math.round(r/60);return o<48?`${o}h ago`:`${Math.round(o/24)}d ago`}function zT(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function qT(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 VT(e){var n;const t=new Map;for(const r of e){if(!["starting","running","stopping","interrupted"].includes(r.lifecycle))continue;const o=typeof((n=r.meta)==null?void 0:n.providerSessionId)=="string"?String(r.meta.providerSessionId).trim():"";if(!o)continue;const a=`${r.providerType}::${r.workspace}::${o}`;t.set(a,(t.get(a)||0)+1)}return Array.from(t.values()).filter(r=>r>1).length}function YT({machineId:e,cliSessions:t,sendDaemonCommand:n}){const[r,o]=l.useState(""),[a,i]=l.useState(null),[c,u]=l.useState(!1),h=dS(e,{enabled:!!e,includeSessions:!0,limit:ac,intervalMs:Sw}),d=h.diagnostics,m=h.loading,f=h.applyDiagnostics,x=l.useMemo(()=>UT({diagnostics:d,loading:m,refreshing:c,error:r}),[d,m,c,r]),w=l.useMemo(()=>new Map(t.map(M=>[M.sessionId||M.id,M])),[t]),p=l.useCallback(async()=>{if(e){u(!0);try{const M=await n(e,"session_host_get_diagnostics",{includeSessions:!0,limit:ac}),L=Pa(M);if(!(L!=null&&L.success))throw new Error((L==null?void 0:L.error)||"Could not load hosted runtime diagnostics");f(L.diagnostics||L.result||null),o("")}catch(M){const L=M instanceof Error?M.message:"Could not load hosted runtime diagnostics";o(L)}finally{u(!1)}}},[f,e,n]);l.useEffect(()=>{!e||d||m||c||p()},[d,m,e,p,c]);const y=l.useCallback(async(M,L)=>{const P=`${M}:${L.sessionId}`;if(!(M==="session_host_stop_session"&&!window.confirm(`Stop ${L.displayName}?
113
+ This will terminate the hosted runtime.`))){i(P);try{const B=await n(e,M,{sessionId:L.sessionId}),K=Pa(B);if(!(K!=null&&K.success))throw new Error((K==null?void 0:K.error)||"Session host action failed");const F=M==="session_host_resume_session"?"resumed":M==="session_host_restart_session"?"restarted":"stopped";pt.showToast(`Session host ${F}: ${L.displayName}`,"success"),await p()}catch(B){const K=B instanceof Error?B.message:"Session host action failed";pt.showToast(K,"warning"),o(K)}finally{i(B=>B===P?null:B)}}},[e,p,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 L=await n(e,"session_host_prune_duplicate_sessions",{}),P=Pa(L);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Duplicate prune failed");const B=P.result||{},K=Array.isArray(B.prunedSessionIds)?B.prunedSessionIds.length:0,F=typeof B.duplicateGroupCount=="number"?B.duplicateGroupCount:0;pt.showToast(`Pruned ${K} duplicate runtime(s) across ${F} group(s)`,"success"),await p()}catch(L){const P=L instanceof Error?L.message:"Duplicate prune failed";pt.showToast(P,"warning"),o(P)}finally{i(L=>L==="session_host_prune_duplicate_sessions"?null:L)}}},[e,p,n]),b=l.useMemo(()=>[...(d==null?void 0:d.sessions)||[]].sort((M,L)=>(L.lastActivityAt||0)-(M.lastActivityAt||0)),[d==null?void 0:d.sessions]),j=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)||[]}:GT(b),[d==null?void 0:d.inactiveRecords,d==null?void 0:d.liveRuntimes,d==null?void 0:d.recoverySnapshots,b]),S=j.liveRuntimes,v=j.recoverySnapshots,g=j.inactiveRecords,N=l.useMemo(()=>VT(S),[S]),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(M=>M.level==="warn"||M.level==="error")||null,[d==null?void 0:d.recentLogs]),T=(M,L)=>{var $;const P=a===`session_host_resume_session:${M.sessionId}`,B=a===`session_host_restart_session:${M.sessionId}`,K=a===`session_host_stop_session:${M.sessionId}`,F=Qp(M.meta),R=w.get(M.sessionId),Q=M.attachedClients.length===1?"1 client":`${M.attachedClients.length} clients`,E=L==="recovery"?"Recover":"Resume",I=KT(L);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:M.displayName||(R==null?void 0:R.cliName)||M.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${qT(M.lifecycle)}`,children:M.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:M.workspaceLabel||(R==null?void 0:R.runtimeWorkspaceLabel)||M.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:M.runtimeKey}),M.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",M.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:(($=M.writeOwner)==null?void 0:$.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:zT(M.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(zd,{size:11})," ",Q]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",Sd(M.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",I]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[L==="recovery"&&(M.lifecycle==="interrupted"||M.lifecycle==="failed"||M.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!a,onClick:()=>{y("session_host_resume_session",M)},children:P?`${E}ing…`:E}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!a,onClick:()=>{y("session_host_restart_session",M)},children:B?"Restarting…":"Restart"}),L==="live"&&(M.lifecycle==="running"||M.lifecycle==="starting"||M.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:!!a,onClick:()=>{y("session_host_stop_session",M)},children:K?"Stopping…":"Stop"})]})]})},M.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(Is,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:J0()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[N>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{k()},disabled:a==="session_host_prune_duplicate_sessions",children:a==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${N})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${x.toneClass}`,children:x.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{p()},disabled:m||c,children:[s.jsx(Co,{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:v.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:Sd(d.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:La(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:[La(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:Da("live")}),S.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):s.jsx("div",{className:"space-y-2",children:S.map(M=>T(M,"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(Is,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Da("recovery")}),v.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:v.map(M=>T(M,"recovery"))})]}),g.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:Da("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:g.map(M=>T(M,"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(M=>{var P;const L=b.find(B=>B.sessionId===M.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:(L==null?void 0:L.displayName)||((P=w.get(M.sessionId))==null?void 0:P.cliName)||M.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[M.action,M.lifecycle?` · ${M.lifecycle}`:"",M.detail?` · ${M.detail}`:"",M.error?` · ${M.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${M.success===!1?"text-red-300":"text-text-secondary"}`,children:La(M.timestamp)})]},`${M.sessionId}:${M.timestamp}:${M.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 JT({machine:e,launchPick:t,actions:n}){const{runLaunchCliCore:r,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(a=>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),r({cliType:t.cliType,workspaceId:a.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:a.label||a.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:a.path})]},a.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),r({cliType:t.cliType,useDefaultWorkspace:!0,argsStr:t.argsStr,model:t.model})},children:"Default workspace"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",onClick:()=>{o(null),r({cliType:t.cliType,useHome:!0,argsStr:t.argsStr,model:t.model})},children:"Home directory"}),s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[80px]",onClick:()=>o(null),children:"Cancel"})]})]})})}function QT(e,t){const n=Oh(e),r=dn(e,t),o=Vi(e,r),a=tr(e,r),i=n==="preview"?"Update to preview":"Update daemon";return o?{visible:!0,showButton:!0,title:a?"Daemon update required":"Version mismatch detected",description:a?"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:a,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 Ra({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 Ea({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 XT({machineEntry:e,providers:t,recentLaunches:n,currentConversations:r,onUpgradeDaemon:o,onOpenRecent:a,onOpenConversation:i}){const c=r.slice(0,6),u=n.slice(0,4),d=QT(e,"0.9.82");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:[c.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ra,{icon:s.jsx(Zs,{size:13}),children:"Current Chats"}),s.jsx(Ea,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:c.map(m=>{const f=hi(m);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(m),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(m)}),f>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:jo(f)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:vn(m)})]},m.tabKey)})})})]}),u.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ra,{icon:s.jsx(Jd,{size:13}),children:"Recent Launches"}),s.jsx(Ea,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:u.map(m=>{const{metaText:f,updatedLabel:x}=ep(m);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:()=>a(m),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:m.label}),x&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:x})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:f})]},m.id)})})})]}),d.visible&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ra,{icon:s.jsx(Ys,{size:13}),children:"Daemon Update"}),s.jsx(Ea,{className:d.tone==="good"?"border-emerald-500/20 bg-emerald-500/5":d.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:d.title}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[d.description,d.targetVersion&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",d.targetVersion,d.channel?` (${d.channel})`:""]})]}),d.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:o,children:[s.jsx(Co,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:d.buttonLabel})]}):s.jsx("div",{className:d.tone==="good"?"text-xs font-medium text-emerald-300":"text-xs font-medium text-sky-300",children:"No preview update action is needed."})]})})]})]})}function ZT({machineId:e,machine:t,ideSessions:n,cliSessions:r,acpSessions:o,actions:a,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:u,handleWorkspaceRemove:h,handleWorkspaceSetDefault:d}=a,[m,f]=l.useState(!1),[x,w]=l.useState(""),[p,y]=l.useState([]),[k,b]=l.useState(!1),[j,S]=l.useState(""),v=l.useCallback(async N=>{b(!0),S("");try{const C=await sl(i,e,N);w(C.path),y(C.directories)}catch(C){S(C instanceof Error?C.message:"Could not load folder")}finally{b(!1)}},[e,i]),g=l.useCallback(()=>{f(!0);const N=[...n.map(A=>A.workspace),...r.map(A=>A.workspace),...o.map(A=>A.workspace)],C=tl(t.platform,el(N,t.defaultWorkspacePath,(t.workspaces||[]).map(A=>A.path)));v(C)},[o,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:g,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(N=>{const C=N.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 ${C?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[s.jsx("button",{type:"button",title:C?"Default workspace — click to unset":"Set as default workspace",disabled:c,onClick:()=>void d(C?null:N.id),className:`text-base leading-none shrink-0 transition-colors ${C?"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:xu(N.path,N.label)}),s.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:N.path,children:N.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void h(N.id),children:"Remove"})]},N.id)})})]}),m&&s.jsx(rl,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:x,directories:p,busy:k,error:j,confirmLabel:"Add workspace",onClose:()=>f(!1),onNavigate:N=>{v(N)},onConfirm:N=>{(async()=>{if(!N)return;await u(N)&&f(!1)})()}})]})}function eI({machine:e,machineId:t,ideSessions:n,cliSessions:r,acpSessions:o,actions:a,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(ZT,{machineId:t,machine:e,ideSessions:n,cliSessions:r,acpSessions:o,actions:a,sendDaemonCommand:i})]})}function tI({onNicknameSynced:e}={}){var ke,xe,Se,pe,G,O,Z,q,me,Te;const{id:t}=Wm(),n=pr(),r=ki(),{sendCommand:o}=yt(),a=In(),i=Dh(),c=nh(),u=c.ides||[],h=c.initialLoaded??!0,d=u.find(_=>_.id===t&&_.type==="adhdev-daemon"),m=u.some(_=>_.type==="adhdev-daemon"),f=t?(ke=c.connectionRetryStatuses)==null?void 0:ke[t]:void 0,x=!!(f!=null&&f.blocked),[w,p]=l.useState("workspace"),[y,k]=l.useState(null);l.useCallback((_,te)=>{k({daemonId:_,workspace:te})},[]);const[,b]=l.useState("ide"),j=l.useRef(null),[S,v]=l.useState(null),g=l.useRef("__home__"),[N,C]=l.useState("__home__"),[A,T]=l.useState(!1),M=l.useRef(null);l.useEffect(()=>{!t||!d||!(!d.workspaces||!d.availableProviders||!d.detectedIdes||!d.recentLaunches)||a(t,{minFreshMs:3e4}).catch(()=>{})},[a,d,t]),l.useEffect(()=>{if(!t||!d||w!=="overview")return;const _=d.machine;(typeof(_==null?void 0:_.cpus)!="number"||typeof(_==null?void 0:_.totalMem)!="number"||typeof(_==null?void 0:_.arch)!="string"||typeof(_==null?void 0:_.release)!="string")&&i(t,{minFreshMs:3e4}).catch(()=>{})},[w,i,d,t]),cS(t&&w==="overview"?[t]:[],{enabled:w==="overview",intervalMs:vw});const L=()=>{if(m){n("/dashboard",{state:{mobileSection:"machines"}});return}n("/machines")},P=VA({machineId:t,registeredMachineId:(d==null?void 0:d.machineId)||null,sendDaemonCommand:o,onNicknameSynced:e,logsEndRef:M});l.useEffect(()=>pt.onToast(te=>{c.setToasts(ce=>{if(ce.some(je=>je.message===te.message&&te.timestamp-je.timestamp<3e3))return ce;const fe={id:te.id,message:te.message,type:te.type,timestamp:te.timestamp,targetKey:te.targetKey,actions:te.actions};return[...ce.slice(-4),fe]});const ve=te.duration||5e3;setTimeout(()=>c.setToasts(ce=>ce.filter(H=>H.id!==te.id)),ve)}),[c]);const B=(d==null?void 0:d.availableProviders)||[],K={};for(const _ of B)K[_.type]=_.icon;const F=d?{id:d.id,hostname:yu(d,{fallbackId:d.id}),platform:((xe=d.machine)==null?void 0:xe.platform)||"unknown",arch:((Se=d.machine)==null?void 0:Se.arch)||"",cpus:((pe=d.machine)==null?void 0:pe.cpus)||0,totalMem:((G=d.machine)==null?void 0:G.totalMem)||0,freeMem:(O=d.machine)==null?void 0:O.freeMem,availableMem:(Z=d.machine)==null?void 0:Z.availableMem,loadavg:(q=d.machine)==null?void 0:q.loadavg,uptime:(me=d.machine)==null?void 0:me.uptime,release:((Te=d.machine)==null?void 0:Te.release)||"",cdpConnected:!!d.cdpConnected,machineNickname:d.machineNickname||null,p2p:d.p2p?{screenshotActive:!1,...d.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:d.detectedIdes||[],workspaces:d.workspaces||[],defaultWorkspaceId:d.defaultWorkspaceId??d.activeWorkspaceId??null,defaultWorkspacePath:d.defaultWorkspacePath??d.activeWorkspacePath??null}:null,R=u.filter(_=>_.daemonId===t&&_.type!=="adhdev-daemon").filter(_=>!ir(_)&&!pn(_)).map(_=>({id:_.id,sessionId:_.sessionId,type:_.type,version:_.version||"",instanceId:_.instanceId||"",status:_.status,workspace:_.workspace||null,terminals:_.terminals||0,aiAgents:Ey(_.aiAgents||(_.agents||[]).map(te=>({id:te.name,name:te.name,status:te.status,version:te.version}))),activeChat:_.activeChat||null,chats:_.chats||[],childSessions:_.childSessions||[],cdpConnected:_.cdpConnected||!1,daemonId:t,lastMessageAt:_.lastMessageAt})),Q=u.filter(_=>_.daemonId===t&&ir(_)).map(_=>({id:_.id,sessionId:_.sessionId,type:_.type,cliName:_.cliName||_.type,status:_.status,workspace:_.workspace||"",activeChat:_.activeChat||null,providerSessionId:_.providerSessionId,mode:_.mode,runtimeKey:_.runtimeKey,runtimeDisplayName:_.runtimeDisplayName,runtimeWorkspaceLabel:_.runtimeWorkspaceLabel,runtimeWriteOwner:_.runtimeWriteOwner||null,runtimeAttachedClients:_.runtimeAttachedClients||[],daemonId:t,lastMessageAt:_.lastMessageAt})),E=u.filter(_=>_.daemonId===t&&pn(_)).map(_=>({id:_.id,sessionId:_.sessionId,type:_.type,acpName:_.cliName||_.type,status:_.status,workspace:_.workspace||"",activeChat:_.activeChat||null,providerSessionId:_.providerSessionId,daemonId:t,lastMessageAt:_.lastMessageAt})),I=d?ts(d,{fallbackId:t}):"",$="workspace",D=r.state,U=D==null?void 0:D.initialMachineTab,Y=D==null?void 0:D.initialWorkspaceCategory;D==null||D.initialWorkspaceId,D==null||D.initialWorkspacePath;const ae=U==="ides"||U==="clis"||U==="acps"?"workspace":U||$,z=U==="ides"?"ide":U==="clis"?"cli":U==="acps"?"acp":Y,X=[...R.map(_=>{var te;return{id:`ide:${_.type}:${_.workspace||""}`,label:((te=_.activeChat)==null?void 0:te.title)||_.type,kind:"ide",providerType:_.type,subtitle:_.workspace||void 0,workspace:_.workspace||void 0,lastLaunchedAt:_.lastMessageAt||0}}),...Q.map(_=>{var te;return{id:`cli:${_.type}:${_.workspace||""}`,label:((te=_.activeChat)==null?void 0:te.title)||_.cliName,kind:"cli",providerType:_.type,providerSessionId:_.providerSessionId,subtitle:_.workspace||void 0,workspace:_.workspace||void 0,lastLaunchedAt:_.lastMessageAt||0}}),...E.map(_=>{var te;return{id:`acp:${_.type}:${_.workspace||""}`,label:((te=_.activeChat)==null?void 0:te.title)||_.acpName,kind:"acp",providerType:_.type,providerSessionId:_.providerSessionId,subtitle:Js(_.summaryMetadata)||_.workspace||void 0,workspace:_.workspace||void 0,lastLaunchedAt:_.lastMessageAt||0}})].sort((_,te)=>(te.lastLaunchedAt||0)-(_.lastLaunchedAt||0)),de=((d==null?void 0:d.recentLaunches)||[]).length>0?((d==null?void 0:d.recentLaunches)||[]).map(_=>({id:_.id,label:_.title||_.providerName||_.providerType,kind:_.kind,providerType:_.providerType,providerSessionId:_.providerSessionId,subtitle:Js(_.summaryMetadata)||_.workspace||void 0,workspace:_.workspace,summaryMetadata:_.summaryMetadata,lastLaunchedAt:_.lastLaunchedAt})):X,re=l.useMemo(()=>{var te;const _=((te=c.connectionStates)==null?void 0:te[t||""])||void 0;return u.filter(ve=>ve.daemonId===t&&ve.type!=="adhdev-daemon").flatMap(ve=>qi(ve,{connectionStates:t&&_?{[t]:_}:void 0,defaultConnectionState:_})).filter(ve=>!(ve.transport==="pty"&&ve.mode==="terminal")).sort((ve,ce)=>hi(ce)-hi(ve))},[u,c.connectionStates,t]),W=l.useCallback(_=>{const te=zh(_);te&&n(dr(te))},[n]),oe=l.useCallback(()=>{j.current&&(T(!0),j.current().finally(()=>{j.current=null,T(!1),v(null)}))},[]),V=l.useCallback(_=>{if(!F)return;const{options:te,selectedKey:ve}=Zh({machine:F,currentWorkspacePath:_.workspace}),ce=async()=>{b(_.kind),p("workspace")};j.current=async()=>{const H=te.find(Ce=>Ce.key===g.current),fe=(H==null?void 0:H.workspacePath)??null,je=(H==null?void 0:H.workspaceId)??null;if(_.kind==="ide"&&_.providerType){await P.handleLaunchIde(_.providerType,fe?{workspace:fe}:void 0);return}if((_.kind==="cli"||_.kind==="acp")&&_.providerType){await P.runLaunchCliCore({cliType:_.providerType,dir:je?void 0:fe||"",workspaceId:je||void 0,model:_.kind==="acp"&&wu(_.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:_.providerSessionId});return}await ce()},g.current=ve,C(ve),v({title:_.kind==="ide"?uo("restart-ide",_.label):_.providerSessionId?mh(_.label):uo("start-fresh",_.label),description:_.kind==="ide"?ho("restart-ide"):_.providerSessionId?fh():ho("start-fresh"),confirmLabel:_.kind==="ide"?po("restart-ide"):_.providerSessionId?oi(!0):po("start-fresh"),busyLabel:_.kind==="ide"?mo("restart-ide"):_.providerSessionId?ph(!0):mo("start-fresh"),workspaceOptions:te,details:[{label:"Mode",value:_.kind.toUpperCase()},..._.providerType?[{label:"Provider",value:_.providerType}]:[]]})},[P,F]);if(l.useEffect(()=>{p(ae)},[$,ae,t]),l.useEffect(()=>{z&&b(z)},[z,t]),!F)return h?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:"Machine not found"}),s.jsx("p",{className:"mt-3",children:"The machine may be offline or not yet connected."}),s.jsx("button",{onClick:L,className:"machine-btn-back",children:"← Back"})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:"⏳ Loading machine..."})});const ie=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(us,{size:14})," Workspace"]}),count:R.length+Q.length+E.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Is,{size:14})," Hosted Runtimes"]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(So,{size:14})," Providers"]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ef,{size:14})," System"]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Vd,{size:14})," Logs"]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:L,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:[P.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:P.nicknameInput,onChange:_=>P.setNicknameInput(_.target.value),onKeyDown:_=>{_.key==="Enter"&&P.handleSaveNickname(),_.key==="Escape"&&P.setEditingNickname(!1)},placeholder:"Machine nickname...",className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:P.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:"Save"}),s.jsx("button",{onClick:()=>P.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:"Cancel"})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{P.setEditingNickname(!0),P.setNicknameInput(F.machineNickname||"")},title:"Click to set nickname",children:I}),x?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),c.retryConnection&&t&&s.jsx("button",{onClick:()=>c.retryConnection(t),className:"px-2.5 py-0.5 rounded text-[11px] font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:"Reconnect"})]}):s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[F.platform," · ",F.arch]}),s.jsxs("span",{children:[F.cpus," cores"]}),(d==null?void 0:d.version)&&s.jsxs("span",{children:["v",d.version]}),F.p2p.available&&s.jsxs("span",{children:["P2P ",F.p2p.state==="connected"?"connected":F.p2p.state]}),F.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:F.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:ie.map(_=>s.jsxs("button",{onClick:()=>p(_.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${w===_.id?"border-accent-primary text-accent-primary":"border-transparent text-text-secondary hover:text-text-primary"}`,children:[_.label,_.count!==void 0&&s.jsx("span",{className:`px-1.5 py-0.5 rounded-full text-[10px] ml-1 ${w===_.id?"bg-accent-primary/20 text-accent-primary":"bg-[#ffffff10] text-text-muted"}`,children:_.count})]},_.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:[w==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(XT,{machineEntry:d,providers:B,recentLaunches:de,currentConversations:re,onUpgradeDaemon:async()=>{try{await o(t,"daemon_upgrade",Uh(d))}catch{}},onOpenRecent:V,onOpenConversation:W}),s.jsx(eI,{machine:F,machineId:t,ideSessions:R,cliSessions:Q,acpSessions:E,actions:P,sendDaemonCommand:o})]}),w==="providers"&&s.jsx(iT,{machineId:t,providers:B,sendDaemonCommand:o}),w==="overview"&&s.jsx(YA,{machine:F,ideSessions:R,cliSessions:Q,acpSessions:E}),w==="session-host"&&s.jsx(YT,{machineId:t,cliSessions:Q,sendDaemonCommand:o}),w==="logs"&&s.jsx(OT,{machineId:t,sendDaemonCommand:o})]})})}),P.launchPick&&F&&s.jsx(JT,{machine:F,launchPick:P.launchPick,actions:P}),S&&s.jsx(Xh,{title:S.title,description:S.description,details:S.details,workspaceOptions:S.workspaceOptions,selectedWorkspaceKey:N,onWorkspaceChange:_=>{g.current=_,C(_)},confirmLabel:S.confirmLabel,busyLabel:S.busyLabel,busy:A,onConfirm:oe,onCancel:()=>{j.current=null,v(null)}}),y&&s.jsx(Yp,{daemonId:y.daemonId,workspace:y.workspace,onClose:()=>k(null)}),s.jsx(gh,{toasts:c.toasts||[],onDismiss:_=>c.setToasts(te=>te.filter(ve=>ve.id!==_)),onClickToast:_=>{_.targetKey&&n(dr(_.targetKey))}}),s.jsx("style",{children:`
115
+ @keyframes toast-in {
116
+ from { opacity: 0; transform: translateX(40px); }
117
+ to { opacity: 1; transform: translateX(0); }
118
+ }
119
+ `})]})}function sI({daemonIds:e,meshId:t,sendData:n,onRevisionAdvance:r}){const o=l.useRef(new Map),a=l.useRef(r);a.current=r;const i=[...new Set(e.filter(Boolean))].sort().join(",");l.useEffect(()=>{o.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(h=>ls.subscribe({sendData:n},h,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${h}`,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 x=o.current.get(h);o.current.set(h,f),x!==void 0&&f>x&&a.current()}));return()=>{for(const h of u)h()}},[i,t,n])}const nI={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,queueSection:!0,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},Xp=l.createContext(null);function rI(){const e=l.useContext(Xp);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}function oI({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 aI({size:e=14}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[s.jsx("line",{x1:"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 iI({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 lI({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 cI({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 dI(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function uI({meshes:e,loading:t,error:n,onDismissError:r,daemons:o,features:a,showCreate:i,onToggleCreate:c,createName:u,onCreateNameChange:h,createRepoIdentity:d,onCreateRepoIdentityChange:m,createRepoRemoteUrl:f,onCreateRepoRemoteUrlChange:x,newMeshDaemonId:w,onNewMeshDaemonIdChange:p,newMeshWorkspace:y,onNewMeshWorkspaceChange:k,createPickerWorkspaces:b,onSelectMesh:j,onCreate:S,onCancelCreate:v}){const{t:g}=Le("common");return s.jsxs(gr,{icon:s.jsx(es,{}),title:g("repoMesh.list.title"),subtitle:g("repoMesh.list.count",{count:e.length}),widthClassName:"max-w-5xl",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:c,children:g("repoMesh.list.createMesh")}),children:[n&&s.jsx(Gt,{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:g("repoMesh.list.createTitle")}),a.createDaemonPicker&&s.jsx(Ct,{label:g("repoMesh.list.createOnMachine"),hint:g("repoMesh.list.createOnMachineHint"),children:s.jsx("select",{className:"input w-full",value:w,onChange:N=>p(N.target.value),disabled:!o.length,children:o.length===0?s.jsx("option",{value:"",children:g("repoMesh.list.noConnectedDaemon")}):o.map(N=>s.jsx("option",{value:N.id,children:dI(N)},N.id))})}),a.createDaemonPicker&&s.jsx(Ct,{label:g("repoMesh.list.workspace"),hint:g("repoMesh.list.workspaceHint"),children:s.jsx("select",{className:"input w-full",value:y,onChange:N=>k(N.target.value),disabled:!w||!b.length,children:w?b.length===0?s.jsx("option",{value:"",children:g("repoMesh.list.noRegisteredWorkspaces")}):b.map(N=>s.jsx("option",{value:N.path,children:N.label?`${N.label} · ${N.path}`:N.path},N.id||N.path)):s.jsx("option",{value:"",children:g("repoMesh.list.selectMachineFirst")})})}),s.jsx(Ct,{label:g("repoMesh.list.name"),children:s.jsx(is,{value:u,onChange:N=>h(N.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(Ct,{label:g("repoMesh.list.remoteUrl"),hint:g("repoMesh.list.remoteUrlHint"),children:s.jsx(is,{value:f,onChange:N=>x(N.target.value),placeholder:"https://github.com/user/repo"})}),s.jsx(Ct,{label:g("repoMesh.list.repoIdentity"),hint:g("repoMesh.list.remoteUrlHint"),children:s.jsx(is,{value:d,onChange:N=>m(N.target.value),placeholder:"github.com/user/repo"})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{className:"btn btn-primary btn-sm",onClick:S,disabled:!u.trim()||!f.trim()&&!d.trim()||a.createDaemonPicker&&(!w||!y),children:g("repoMesh.list.create")}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:v,children:g("repoMesh.list.cancel")})]})]}),t?s.jsx("div",{className:"text-sm text-text-muted p-4",children:g("repoMesh.list.loading")}):e.length===0?s.jsx(Ro,{icon:s.jsx(es,{}),title:g("repoMesh.list.emptyTitle"),description:o.length>0?g("repoMesh.list.emptyWithDaemons"):g("repoMesh.list.emptyNoDaemons"),action:s.jsx("button",{className:"btn btn-primary btn-sm",disabled:!o.length,onClick:c,children:g("repoMesh.list.createFirst")})}):s.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(N=>{var C;return s.jsx("button",{type:"button",onClick:()=>j(N.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:N.name})]}),s.jsxs("div",{className:"text-[12px] text-text-muted flex items-center gap-2",children:[s.jsx("span",{className:"font-mono",children:N.repoIdentity||N.repo_identity||g("repoMesh.list.noRepoIdentity")}),(N.defaultBranch||N.default_branch)&&s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(aI,{size:11}),N.defaultBranch||N.default_branch]})]})]}),s.jsxs("div",{className:"text-right text-[11px] text-text-muted shrink-0 ml-4",children:[s.jsx("div",{children:new Date(N.createdAt||N.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})}),s.jsxs("div",{className:"text-text-muted/60",children:[((C=N.nodes)==null?void 0:C.length)??N.nodeCount??0," ",g("repoMesh.list.nodesSuffix")]})]})]})},N.id)})})]})}const hI=["claude-cli","codex-cli","gemini-cli","hermes-cli","antigravity-cli"],pI=[{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 mI(){return{nodeId:"",provider:"",model:"",n:""}}function Cd(e){var t;return(t=e.providers)!=null&&t.length?e.providers.filter(Boolean):(e.providerPriority??[]).filter(Boolean)}function fI(e){return{nodeId:e.nodeId??"",provider:e.provider??"",model:e.model??"",n:e.n!=null?String(e.n):""}}function bI(e){const t=[];for(let n=0;n<e.length;n++){const r=e[n],o=r.provider.trim();if(!o)return{error:{code:"provider_required",slot:n+1}};const a=r.nodeId.trim(),i=r.model.trim(),c=r.n.trim();let u;if(c){const h=Number(c);if(!Number.isFinite(h)||h<1)return{error:{code:"replica_min",slot:n+1}};u=Math.floor(h)}t.push({provider:o,...a?{nodeId:a}:{},...i?{model:i}:{},...u!==void 0?{n:u}:{}})}return t.length===0?{error:{code:"no_slot"}}:{slots:t}}function gI({status:e,daemonId:t,sendDaemonCommand:n,availableProviders:r}){const{t:o}=Le(),{theme:a}=Ls(),i=l.useMemo(()=>Rs(a),[a]),c=l.useMemo(()=>kh(r),[r]),[u,h]=l.useState({}),[d,m]=l.useState(!1),[f,x]=l.useState(null),[w,p]=l.useState({}),[y,k]=l.useState(null),b=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(I=>({nodeId:I.nodeId,machineLabel:I.machineLabel,providers:I.providers,providerPriority:I.providerPriority})),[e==null?void 0:e.nodes]),j=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(I=>I.nodeId),[e==null?void 0:e.nodes]),S=l.useMemo(()=>Object.fromEntries(((e==null?void 0:e.nodes)??[]).map(I=>[I.nodeId,I.machineLabel||I.nodeId])),[e==null?void 0:e.nodes]),v=l.useMemo(()=>{const I={};for(const $ of b)I[$.nodeId]=Cd($);return I},[b]),g=l.useMemo(()=>{const I=[...new Set(b.flatMap(Cd).filter(Boolean))];return[...new Set([...I,...hI])].sort()},[b]),N=!!t&&!!n,C=I=>I&&typeof I=="object"&&"result"in I?I.result:I,A=l.useCallback(async()=>{if(!(!t||!n)){m(!0),x(null);try{const I=await n(t,"magi_kind_panel_list",{}),$=C(I);if(($==null?void 0:$.success)===!1)throw new Error($.error||o("meshGraph.magiKind.errorLoad"));h($!=null&&$.kindPanels&&typeof $.kindPanels=="object"?$.kindPanels:{}),p({})}catch(I){x((I==null?void 0:I.message)||o("meshGraph.magiKind.errorLoad"))}finally{m(!1)}}},[t,n,o]);l.useEffect(()=>{A()},[A]);const T=l.useCallback(I=>{if(w[I])return w[I];const $=u[I];return $?$.map(fI):[]},[w,u]),M=(I,$)=>{p(D=>({...D,[I]:$}))},L=(I,$,D)=>{const U=T(I);M(I,U.map((Y,ae)=>ae===$?{...Y,...D}:Y))},P=I=>{M(I,[...T(I),mI()])},B=(I,$)=>{M(I,T(I).filter((D,U)=>U!==$))},K=l.useCallback(async I=>{if(!t||!n)return;const $=bI(T(I));if("error"in $){const D=$.error,U=D.code==="provider_required"?o("meshGraph.magiKind.errorSlotProvider",{slot:D.slot}):D.code==="replica_min"?o("meshGraph.magiKind.errorSlotReplica",{slot:D.slot}):o("meshGraph.magiKind.errorNoSlot");x(`${I}: ${U}`);return}k(I),x(null);try{const D=await n(t,"magi_kind_panel_set",{kind:I,slots:$.slots}),U=C(D);if((U==null?void 0:U.success)===!1)throw new Error(U.error||o("meshGraph.magiKind.errorSave"));await A()}catch(D){x((D==null?void 0:D.message)||o("meshGraph.magiKind.errorSave"))}finally{k(null)}},[t,n,T,A,o]),F=l.useCallback(async I=>{if(!(!t||!n)&&confirm(o("meshGraph.magiKind.removeConfirm",{kind:I}))){k(I),x(null);try{const $=await n(t,"magi_kind_panel_remove",{kind:I}),D=C($);if((D==null?void 0:D.success)===!1)throw new Error(D.error||o("meshGraph.magiKind.errorRemove"));await A()}catch($){x(($==null?void 0:$.message)||o("meshGraph.magiKind.errorRemove"))}finally{k(null)}}},[t,n,A,o]),R=`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"}`,Q="btn btn-primary btn-sm",E="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:o("meshGraph.magiKind.intro")}),s.jsx("div",{className:"ml-auto flex items-center gap-2",children:s.jsx("button",{type:"button",className:E,onClick:()=>void A(),disabled:d||!N,children:o(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:o("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:pI.map(({kind:I,labelKey:$,hint:D})=>{const U=T(I),Y=!!u[I],ae=y===I;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:o($)}),s.jsx("span",{className:`font-mono text-[10px] ${i.textMuted}`,children:D}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${Y?"border-emerald-400/30 bg-emerald-500/10 text-emerald-300":"border-slate-400/20 bg-slate-500/10 text-slate-300"}`,children:Y?o("meshGraph.magiKind.agentCount",{count:u[I].length}):o("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:o("meshGraph.magiKind.noAgents")}),U.map((z,X)=>{const de=z.nodeId?v[z.nodeId]??[]:[],re=z.nodeId&&de.length?de:g;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:o("meshGraph.magiKind.machine")}),s.jsxs("select",{className:R,value:z.nodeId,onChange:W=>L(I,X,{nodeId:W.target.value}),title:o("meshGraph.magiKind.machineTitle"),children:[s.jsx("option",{value:"",children:o("meshGraph.magiKind.anyMachine")}),j.map(W=>s.jsx("option",{value:W,children:S[W]??W},W)),z.nodeId&&!j.includes(z.nodeId)&&s.jsx("option",{value:z.nodeId,children:o("meshGraph.magiKind.offlineSuffix",{label:S[z.nodeId]??z.nodeId})})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsxs("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:[o("meshGraph.magiKind.provider")," *"]}),s.jsxs("select",{className:R,value:z.provider,onChange:W=>L(I,X,{provider:W.target.value}),title:o("meshGraph.magiKind.providerTitle"),children:[s.jsx("option",{value:"",children:o("meshGraph.magiKind.selectProvider")}),re.map(W=>s.jsx("option",{value:W,children:W},W)),z.provider&&!re.includes(z.provider)&&s.jsx("option",{value:z.provider,children:z.provider})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:o("meshGraph.magiKind.model")}),(()=>{var V;const W=(z.provider?(V=c.get(z.provider))==null?void 0:V.models:void 0)??[],oe=!!z.model&&W.length>0&&!W.includes(z.model);return W.length>0&&!oe?s.jsxs("select",{className:R,value:W.includes(z.model)?z.model:"",title:o("meshGraph.magiKind.modelTitle"),onChange:ie=>L(I,X,{model:ie.target.value==="__custom__"?" ":ie.target.value}),children:[s.jsx("option",{value:"",children:o("meshGraph.magiKind.modelDefault")}),W.map(ie=>s.jsx("option",{value:ie,children:ie},ie)),s.jsx("option",{value:"__custom__",children:o("meshGraph.magiKind.modelCustom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:R,value:z.model.trim(),placeholder:o("meshGraph.magiKind.modelDefault"),title:o("meshGraph.magiKind.modelTitle"),onChange:ie=>L(I,X,{model:ie.target.value})}),W.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:()=>L(I,X,{model:""}),children:o("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:o("meshGraph.magiKind.copies")}),s.jsx("input",{className:`${R} sm:w-16`,value:z.n,placeholder:"1",inputMode:"numeric",title:o("meshGraph.magiKind.copiesTitle"),onChange:W=>L(I,X,{n:W.target.value})})]}),s.jsx("button",{type:"button",className:`${E} sm:mt-[18px] inline-flex h-8 w-8 items-center justify-center p-0`,onClick:()=>B(I,X),"aria-label":o("meshGraph.magiKind.removeAgent"),title:o("meshGraph.magiKind.removeAgent"),children:"✕"})]},X)}),s.jsx("div",{children:s.jsx("button",{type:"button",className:E,onClick:()=>P(I),disabled:!N,children:o("meshGraph.magiKind.addAgent")})})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:Q,onClick:()=>void K(I),disabled:ae||!N,children:o(ae?"meshGraph.magiKind.saving":"meshGraph.magiKind.save")}),s.jsx("button",{type:"button",className:E,onClick:()=>void F(I),disabled:ae||!N||!Y,title:o(Y?"meshGraph.magiKind.removeBindingTitle":"meshGraph.magiKind.removeBindingDisabledTitle"),children:o("meshGraph.magiKind.removeBinding")})]})]},I)})})]})}function xI({daemonId:e,meshId:t,cliType:n,sendCommand:r}){const{t:o}=Le(),[a,i]=l.useState(!1),[c,u]=l.useState(!1),[h,d]=l.useState(null),[m,f]=l.useState(null),[x,w]=l.useState(null),p=l.useCallback(async()=>{if(!e||!t){d(o("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)||o("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,o]),y=l.useCallback(()=>{const k=!a;i(k),k&&m===null&&!c&&p()},[a,m,c,p]);return s.jsxs("div",{className:"mt-2",children:[s.jsxs("button",{type:"button",onClick:y,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 ${a?"rotate-90":""}`,"aria-hidden":!0,children:"▸"}),o(a?"repoMesh.promptPreview.hide":"repoMesh.promptPreview.view"),s.jsxs("span",{className:"text-text-muted",children:["(",n,")"]})]}),a&&s.jsxs("div",{className:"mt-2",children:[c&&s.jsx("div",{className:"text-[12px] text-text-muted",children:o("repoMesh.promptPreview.rendering")}),h&&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:[h,s.jsx("button",{type:"button",onClick:()=>void p(),className:"ml-2 underline bg-transparent border-none cursor-pointer text-amber-300",children:o("repoMesh.promptPreview.retry")})]}),!c&&!h&&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:o("repoMesh.promptPreview.info")}),x!==null&&s.jsxs("span",{children:[(x/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 yI=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function vI(e){const t=yI(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function wI(e){const t=e==null?void 0:e.missions;return Array.isArray(t)?t:[]}function kI(e){return typeof e.goal=="string"&&e.goal?{text:e.goal,truncated:!1}:{text:e.goalPreview??"",truncated:e.goalTruncated===!0}}const SI=["active","paused","completed","abandoned"];function jd(e){return(e.status||"active").toLowerCase()}const CI=8;function jI({status:e,daemonId:t,meshId:n,sendCommand:r}){const{t:o}=Le("common"),a=l.useMemo(()=>wI(e),[e]),[i,c]=l.useState({}),[u,h]=l.useState({}),[d,m]=l.useState(!1),[f,x]=l.useState(null),[w,p]=l.useState("active"),[y,k]=l.useState(!1),b=l.useMemo(()=>{const A={};for(const T of a){const M=jd(T);A[M]=(A[M]||0)+1}return A},[a]),j=l.useMemo(()=>w==="all"?a:a.filter(A=>jd(A)===w),[a,w]),S=y?j:j.slice(0,CI),v=j.length-S.length,g=!!t&&a.length>0,N=l.useCallback(async()=>{if(t){m(!0),x(null);try{const A=await r(t,"mesh_status",{meshId:n,verbose:!0}),T=vI(A),M=Array.isArray(T==null?void 0:T.missions)?T.missions:[],L={};for(const P of M)P.id&&typeof P.goal=="string"&&P.goal&&(L[P.id]=P.goal);c(P=>({...P,...L}))}catch(A){x(A instanceof Error?A.message:o("repoMesh.missions.errorFetch"))}finally{m(!1)}}},[t,n,r,o]),C=l.useCallback(A=>{h(T=>({...T,[A]:!T[A]})),!u[A]&&!i[A]&&N()},[u,i,N]);return a.length===0?null:s.jsxs(bt,{title:o("repoMesh.missions.title"),description:o("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:[SI.filter(A=>(b[A]||0)>0).map(A=>s.jsxs("button",{type:"button",onClick:()=>{p(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:()=>{p("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 ",a.length]})]}),j.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:o("repoMesh.missions.empty",{status:w})}),s.jsx("div",{className:"flex flex-col gap-2",children:S.map(A=>{var F;const T=u[A.id]===!0,M=i[A.id],L=kI(A),P=T&&M?M:L.text,B=T&&!M&&L.truncated,K=((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}),K>0&&s.jsx("span",{className:"shrink-0 text-[11px] text-text-muted",children:o("repoMesh.missions.taskCount",{count:K})})]}),P&&s.jsxs("div",{className:`mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-text-secondary ${T?"max-h-72 overflow-y-auto":"line-clamp-2"}`,children:[P,B&&s.jsx("span",{className:"text-text-muted",children:o("repoMesh.missions.goalUnavailable")})]}),(L.truncated||M)&&g&&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:o(T?"repoMesh.missions.showLess":d&&!M?"repoMesh.missions.loading":"repoMesh.missions.showFullGoal")})]},A.id)})}),v>0&&s.jsx("button",{type:"button",className:"mt-2 text-[12px] text-accent-primary hover:underline",onClick:()=>k(!0),children:o("repoMesh.missions.showMore",{count:v})})]})}const NI=["","low","medium","high"],AI={easy:"Easy",medium:"Medium",difficult:"Difficult",freeform:"Freeform"};function Nd(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 Ad(e){const t=e.provider.trim();if(!t)return null;const n=e.model.trim(),r=e.thinkingLevel.trim()||void 0,o=Number(e.maxParallel),a=Number.isFinite(o)&&o>0?Math.floor(o):void 0;return{provider:t,...n?{model:n}:{},...r?{thinkingLevel:r}:{},...e.difficulty.length?{difficulty:e.difficulty}:{},...e.capability.length?{capability:e.capability}:{},...a!==void 0?{maxParallel:a}:{}}}function TI(){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 II({slots:e,availableProviders:t,saving:n,onSave:r}){const{t:o}=Le("common"),[a,i]=l.useState(()=>e.map(Nd)),c=l.useMemo(()=>JSON.stringify(e),[e]);l.useEffect(()=>{i(e.map(Nd))},[c]);const u=l.useMemo(()=>[...new Set(t.map(b=>b.type).filter(Boolean))],[t]),h=l.useMemo(()=>kh(t),[t]),d=l.useMemo(()=>{const b=a.map(Ad).filter(Boolean);return JSON.stringify(b)!==JSON.stringify(e)},[a,e]),m=(b,j)=>i(S=>S.map((v,g)=>g===b?{...v,...j}:v)),f=(b,j)=>i(S=>S.map((v,g)=>{var A;if(g!==b)return v;const N=((A=h.get(j))==null?void 0:A.models)??[],C=!v.model||N.length===0||N.includes(v.model);return{...v,provider:j,...C?{}:{model:""}}})),x=b=>i(j=>j.filter((S,v)=>v!==b)),w=()=>i(b=>[...b,TI()]),p=(b,j)=>i(S=>{const v=b+j;if(v<0||v>=S.length)return S;const g=[...S];return[g[b],g[v]]=[g[v],g[b]],g}),y=(b,j)=>i(S=>S.map((v,g)=>{if(g!==b)return v;const N=v.difficulty.includes(j);return{...v,difficulty:N?v.difficulty.filter(C=>C!==j):[...v.difficulty,j]}})),k=()=>r(a.map(Ad).filter(Boolean));return s.jsxs("div",{className:"flex flex-col gap-2",onClick:b=>b.stopPropagation(),children:[a.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:o("repoMesh.slotEditor.empty")}),a.map((b,j)=>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:["#",j+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:j===0,onClick:()=>p(j,-1),title:o("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:j===a.length-1,onClick:()=>p(j,1),title:o("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:()=>x(j),"aria-label":o("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:o("repoMesh.slotEditor.provider")}),u.length>0?s.jsxs("select",{className:_s,value:b.provider,onChange:S=>f(j,S.target.value),children:[s.jsx("option",{value:"",children:o("repoMesh.slotEditor.select")}),u.map(S=>s.jsx("option",{value:S,children:S},S)),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:S=>m(j,{provider:S.target.value})})]}),(()=>{var C;const S=h.get(b.provider),v=(S==null?void 0:S.models)??[],g=(C=S==null?void 0:S.thinking)!=null&&C.length?["",...S.thinking]:NI,N=!!b.model&&v.length>0&&!v.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:o("repoMesh.slotEditor.model")}),v.length>0&&!N?s.jsxs("select",{className:_s,value:v.includes(b.model)?b.model:"",onChange:A=>m(j,{model:A.target.value==="__custom__"?" ":A.target.value}),children:[s.jsx("option",{value:"",children:o("repoMesh.slotEditor.providerDefault")}),v.map(A=>s.jsx("option",{value:A,children:A},A)),s.jsx("option",{value:"__custom__",children:o("repoMesh.slotEditor.custom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:_s,value:b.model.trim(),placeholder:b.provider?`${b.provider} model`:o("repoMesh.slotEditor.modelPlaceholder"),onChange:A=>m(j,{model:A.target.value})}),v.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(j,{model:""}),children:o("repoMesh.slotEditor.backToModelList")})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:o("repoMesh.slotEditor.thinking")}),s.jsx("select",{className:_s,value:b.thinkingLevel,onChange:A=>m(j,{thinkingLevel:A.target.value}),children:g.map(A=>s.jsx("option",{value:A,children:A||o("repoMesh.slotEditor.thinkingDefault")},A||"_default"))})]})]})})()]}),s.jsxs("div",{className:"mt-2",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:o("repoMesh.slotEditor.difficulty")}),s.jsx("div",{className:"mt-1 flex flex-wrap gap-1.5",children:ky.map(S=>{const v=b.difficulty.includes(S);return s.jsx("button",{type:"button",className:`rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors ${v?"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:()=>y(j,S),children:AI[S]},S)})})]}),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:o("repoMesh.slotEditor.capabilityTags")}),s.jsx("input",{className:_s,value:b.capability.join(", "),placeholder:"worktree, os=darwin",onChange:S=>m(j,{capability:S.target.value.split(",").map(v=>v.trim()).filter(Boolean)})})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:o("repoMesh.slotEditor.maxParallel")}),s.jsx("input",{type:"number",inputMode:"numeric",min:1,className:_s,value:b.maxParallel,placeholder:o("repoMesh.slotEditor.maxParallelPlaceholder"),onChange:S=>m(j,{maxParallel:S.target.value})})]})]})]},j)),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(Mi,{size:13})," ",o("repoMesh.slotEditor.addSlot")]}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:k,disabled:!!n||!d,children:o(n?"repoMesh.slotEditor.saving":"repoMesh.slotEditor.saveSlots")})]})]})}function MI(e){const t=new Map;for(const n of e)n!=null&&n.id&&t.set(n.id,wn(n.availableProviders||[]));return t}function DI(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 PI(e){var u,h,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 o=(((u=t.userOverrides)==null?void 0:u.platform)||t.reportedPlatform||"").toString().trim(),a=(((h=t.userOverrides)==null?void 0:h.arch)||t.reportedArch||"").toString().trim();o&&n.push({tag:`os=${o}`,custom:!1}),a&&n.push({tag:`arch=${a}`,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 LI(e){const t=e.capabilities;return Array.isArray(t)?t.map(n=>typeof n=="string"?n.trim():"").filter(Boolean):[]}const RI=["os=","arch=","provider=","worktree=","converge="];function EI({node:e,saving:t,onSave:n}){const{t:r}=Le("common"),o=l.useMemo(()=>PI(e).filter(p=>!p.custom),[e]),a=l.useMemo(()=>LI(e),[e]),[i,c]=l.useState(a),[u,h]=l.useState(""),d=JSON.stringify(i)!==JSON.stringify(a),f=(p=>{const y=p.trim();return y?/\s/.test(y)?r("repoMesh.tagEditor.noSpaces"):RI.some(k=>y.toLowerCase().startsWith(k))?r("repoMesh.tagEditor.reservedPrefix"):i.includes(y)?r("repoMesh.tagEditor.alreadyAdded"):null:null})(u);function x(){const p=u.trim();!p||f||(c(y=>[...y,p]),h(""))}function w(p){c(y=>y.filter(k=>k!==p))}return s.jsxs("div",{className:"mt-2",onClick:p=>p.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")}),o.map(p=>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:p.tag},p.tag)),i.map(p=>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:[p,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(p),disabled:t,"aria-label":r("repoMesh.tagEditor.remove",{tag:p}),children:"×"})]},p))]}),s.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:p=>h(p.target.value),onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),x())},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:x,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&&o.length===0&&s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:r("repoMesh.tagEditor.empty")})]})}function _I(e,t){return t.filter(n=>n.status!=="assigned"?!1:(n.assignedNodeId||n.nodeId)===e.id)}function $I(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 BI(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(o=>typeof o=="string"?o.trim():"").filter(Boolean).filter(o=>n.has(o)?!1:(n.add(o),!0))}function FI(e){const t=BI(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 HI(e){return e.isLocalWorktree===!0}function WI(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(o=>{var a;return((a=o==null?void 0:o.settings)==null?void 0:a.meshNodeId)===e.id||(o==null?void 0:o.workspace)===e.workspace}).map(o=>{var a;return{id:o.sessionId||o.id||o.instanceId||"unknown",provider:o.providerType||o.cliType||o.acpType||o.type||"unknown",status:o.status||((a=o.activeChat)==null?void 0:a.status)||"unknown"}})}function Td(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function OI(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 UI({nodes:e,meshQueue:t,activeDaemon:n,daemons:r,selectedMeshId:o,userName:a,features:i,coordinatorDaemonId:c,availableCliProviders:u,savingNodeSlotsId:h,onUpdateNodeSlots:d,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:f,nodeSystemPromptDrafts:x,onNodeSystemPromptDraftChange:w,savingNodeSystemPromptId:p,onSaveNodeSystemPrompt:y,selectedNodeId:k,onSelectNode:b,showAddNode:j,onShowAddNode:S,onCancelAddNode:v,nodeWorkspace:g,onNodeWorkspaceChange:N,nodeProviderPriority:C,onNodeProviderPriorityChange:A,nodeDaemonId:T,onNodeDaemonIdChange:M,nodeCustomPath:L,onNodeCustomPathChange:P,nodePickerWorkspaces:B,nodePickerProviders:K,attachableDaemons:F,onAddNode:R,onRemoveNode:Q}){const{t:E}=Le("common"),I=l.useMemo(()=>MI(r),[r]),$=l.useMemo(()=>e.filter(D=>!HI(D)),[e]);return s.jsxs(bt,{title:i.addNodeDaemonPicker?E("repoMesh.nodeList.title",{count:$.length}):E("repoMesh.nodeList.titleNoCount"),description:i.addNodeDaemonPicker?E("repoMesh.nodeList.descriptionCloud"):E("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:E("repoMesh.nodeList.daemonCandidates")}),s.jsx("div",{className:"text-[12px] text-text-muted",children:E("repoMesh.nodeList.daemonCandidatesHint")})]}),s.jsx("span",{className:"text-[11px] text-text-muted",children:E("repoMesh.nodeList.available",{count:F.length})})]}),r.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:E("repoMesh.nodeList.noDaemonsAvailable")}):F.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:E("repoMesh.nodeList.allDaemonsAttached")}):s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:F.map(D=>s.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors ${D.id===c?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{M(D.id),N(""),P(!1),A(cr(wn(D.availableProviders||[]))),S()},children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-medium truncate",children:Td(D)}),D.id===c&&s.jsx("span",{className:"text-[10px] text-accent-primary",children:E("repoMesh.nodeList.selectedHost")})]}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted font-mono truncate",children:D.id}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:E("repoMesh.nodeList.workspacesDetected",{count:(D.workspaces||[]).length})})]},D.id))})]}),!j&&s.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:S,children:[s.jsx(lI,{size:13})," ",i.addNodeDaemonPicker?E("repoMesh.nodeList.attachMachine"):E("repoMesh.nodeList.addNode")]}),j&&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?E("repoMesh.nodeList.attachMachineTitle"):E("repoMesh.nodeList.addNodeTitle")}),s.jsx("button",{onClick:()=>{v(),M(""),P(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(At,{size:16})})]}),i.addNodeDaemonPicker&&s.jsx(Ct,{label:E("repoMesh.nodeList.machine"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:T,onChange:D=>{var U;M(D.target.value),N(""),P(!1),A(cr(wn(((U=r.find(Y=>Y.id===D.target.value))==null?void 0:U.availableProviders)||[])))},children:[s.jsx("option",{value:"",children:E("repoMesh.nodeList.selectMachine")}),r.map(D=>s.jsx("option",{value:D.id,children:Td(D)},D.id))]})}),(i.addNodeDaemonPicker?T:!0)&&s.jsx(Ct,{label:E("repoMesh.nodeList.workspacePath"),children:i.addNodeDaemonPicker&&!L&&B.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:B.map(D=>s.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${g===D.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(D.path),children:[s.jsx("span",{className:"font-medium block truncate",children:D.label||D.path.split("/").pop()}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:D.path})]},D.id||D.path))}),s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0",onClick:()=>{P(!0),N("")},children:E("repoMesh.nodeList.enterCustomPath")})]}):s.jsx(s.Fragment,{children:i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[s.jsx(is,{value:g,onChange:D=>N(D.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:D=>{D.key==="Enter"&&R()}}),B.length>0&&s.jsx("button",{type:"button",className:"text-[11px] text-accent-primary bg-transparent border-none cursor-pointer p-0 mt-1",onClick:()=>{P(!1),N("")},children:E("repoMesh.nodeList.pickFromSaved")})]}):(()=>{var Y;const D=Array.isArray(n==null?void 0:n.workspaces)?n.workspaces:[],U=`mesh-add-node-workspaces-${o||"new"}`;return s.jsxs(s.Fragment,{children:[s.jsx(is,{value:g,onChange:ae=>N(ae.target.value),placeholder:((Y=D[0])==null?void 0:Y.path)||"/Users/dev/projects/myapp",list:D.length>0?U:void 0,autoFocus:!0}),D.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:U,children:D.map(ae=>s.jsx("option",{value:ae.path,children:ae.label||ae.path},ae.id||ae.path))}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:D.slice(0,6).map(ae=>s.jsx("button",{type:"button",onClick:()=>N(ae.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:ae.path,children:ae.label||ae.path.split("/").filter(Boolean).pop()||ae.path},ae.id||ae.path))})]})]})})()})}),s.jsx(Ct,{label:E("repoMesh.nodeList.preferredTools"),hint:E("repoMesh.nodeList.preferredToolsHint"),children:s.jsx(mk,{value:C,availableProviders:i.addNodeDaemonPicker?K:u,onChange:A})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:R,disabled:!g.trim()||i.addNodeDaemonPicker&&!T,className:"btn btn-primary btn-sm",children:E("repoMesh.nodeList.add")}),s.jsx("button",{onClick:()=>{v(),M(""),P(!1)},className:"btn btn-secondary btn-sm",children:E("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:E("repoMesh.nodeList.setupInventoryWarning")}),$.length===0?s.jsx(Ro,{icon:s.jsx(xn,{}),title:E("repoMesh.nodeList.emptyTitle"),description:E("repoMesh.nodeList.emptyDescription")}):s.jsx("div",{className:"flex flex-col gap-2",children:$.map(D=>{var de;const U=FI(D),Y=_I(D,t),ae=WI(D,n),z=k===D.id,X=D.status||D.machine_status||(Y.length>0||ae.length>0?"active":"enabled");return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary transition-colors ${i.addNodeDaemonPicker?"bg-bg-glass border-border-subtle rounded-xl px-5 py-4":`cursor-pointer ${z?"border-accent-primary/60":"border-border-subtle hover:border-accent-primary/35"}`}`,role:i.addNodeDaemonPicker?void 0:"button",tabIndex:i.addNodeDaemonPicker?void 0:0,onClick:i.addNodeDaemonPicker?void 0:()=>b(z?null:D.id),onKeyDown:i.addNodeDaemonPicker?void 0:re=>{(re.key==="Enter"||re.key===" ")&&(re.preventDefault(),b(z?null:D.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:D.machine_label||D.machine_nickname||D.hostname||D.workspace}):s.jsx("span",{className:"text-sm font-medium",children:D.workspace.split("/").pop()}),i.addNodeDaemonPicker&&s.jsx(cI,{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:E("repoMesh.nodeList.setupInventory")})]}),i.addNodeDaemonPicker&&s.jsx("div",{className:"text-[11px] text-text-muted",children:E("repoMesh.nodeList.ownerMachine",{owner:OI(r.find(re=>re.id===String(D.daemon_id||"")),a),machine:D.machine_label||D.daemon_id||D.workspace})}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:D.workspace}),s.jsx(EI,{node:D,saving:m===D.id,onSave:re=>f(D,re)}),i.addNodeDaemonPicker&&s.jsx("div",{className:"mt-2 text-[11px] text-amber-300",children:E("repoMesh.nodeList.liveDetailGraphOwned")}),s.jsxs("div",{className:"mt-3 max-w-2xl",onClick:re=>re.stopPropagation(),children:[s.jsx(Ct,{label:E("repoMesh.nodeList.slotsLabel"),hint:E("repoMesh.nodeList.slotsHint"),children:s.jsx(II,{slots:Array.isArray((de=D.policy)==null?void 0:de.slots)?D.policy.slots:[],availableProviders:DI(D,I),saving:h===D.id,onSave:re=>d(D,re)})}),i.nodeInstruction&&s.jsxs(Ct,{label:E("repoMesh.nodeList.nodeInstruction"),hint:E("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:x[D.id]??"",onChange:re=>{const W=re.target.value;w(D.id,W)},onClick:re=>re.stopPropagation(),disabled:p===D.id,placeholder:E("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:re=>{re.stopPropagation(),y(D)},disabled:p===D.id,children:p===D.id?E("repoMesh.nodeList.saving"):E("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:re=>{re.stopPropagation(),Q(D.id)},title:E("repoMesh.nodeList.removeNode"),children:s.jsx(iI,{size:14})})]}),s.jsxs("details",{className:"mt-3 group",onClick:re=>re.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:"▸"})," ",E("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:E("repoMesh.nodeList.nodeId")})," ",s.jsx("span",{className:"font-mono break-all",children:D.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:E("repoMesh.nodeList.launchReady")})," ",s.jsx("span",{className:U.configured?"text-green-400":"text-amber-400",children:U.configured?E("repoMesh.nodeList.launchReadyYes"):E("repoMesh.nodeList.launchReadyNo")})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:E("repoMesh.nodeList.repoRoot")})," ",s.jsx("span",{className:"font-mono break-all",children:D.repoRoot||D.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:E("repoMesh.nodeList.activeSessionsLabel")})," ",ae.length]}),i.addNodeDaemonPicker&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:E("repoMesh.nodeList.added")})," ",new Date(D.created_at||D.createdAt||Date.now()).toLocaleDateString()]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:E("repoMesh.nodeList.activeQueueAssignments")}),Y.length===0?s.jsx("div",{children:E("repoMesh.nodeList.noActiveAssignment")}):s.jsx("ul",{className:"m-0 pl-4",children:Y.map(re=>s.jsx("li",{className:"font-mono",children:$I(re)},re.id))})]}),ae.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:E("repoMesh.nodeList.activeSessions")}),s.jsx("ul",{className:"m-0 pl-4",children:ae.map(re=>s.jsxs("li",{className:"font-mono",children:[re.provider," / ",re.status," / ",re.id]},re.id))})]})]})]})]},D.id)})})]})}function Hr(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function GI({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:n,coordinatorCliType:r,onCoordinatorCliTypeChange:o,launchingCoordinator:a,launchResult:i,isHostNodeAttached:c,selectedHostNode:u,hostPinned:h,hostLabel:d,hostOnline:m,hostRebindDaemonId:f,onHostRebindDaemonIdChange:x,onLaunchCoordinator:w}){const{t:p}=Le("common"),y=s.jsx(Ct,{label:p("repoMesh.host.coordinatorProvider"),hint:p("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:j=>o(j.target.value),children:[s.jsx("option",{value:"",children:p("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(h)return s.jsxs(bt,{title:p("repoMesh.host.title"),description:p("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:p("repoMesh.host.hostLabel")}),s.jsx("span",{className:"font-medium",children:d||p("repoMesh.host.unknown")}),s.jsxs("span",{className:m?"text-text-muted":"text-amber-400",children:["· ",p(m?"repoMesh.host.online":"repoMesh.host.offline")]})]}),(u==null?void 0:u.workspace)&&s.jsxs("span",{className:"text-[12px] text-text-muted",children:[p("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(Gt,{variant:"warning",className:"mb-3",children:[s.jsx("strong",{children:p("repoMesh.host.hostOffline")})," ",p("repoMesh.host.hostOfflineText")]}),e.length>0?s.jsx(Ct,{label:p("repoMesh.host.reconnectToCommand"),hint:p("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:j=>x(j.target.value),children:[s.jsx("option",{value:"",children:p("repoMesh.host.waitForHost")}),e.map(j=>s.jsx("option",{value:j.id,children:Hr(j)},j.id))]})}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:p("repoMesh.host.noDaemonsToRoute")})]}),s.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-[180px_auto] items-end",children:[y,s.jsx("button",{className:"btn btn-primary btn-sm",onClick:w,disabled:a||!t,title:t?void 0:p("repoMesh.host.noCommandTarget"),children:p(a?"repoMesh.host.launching":"repoMesh.host.launchHost")})]}),k]});const b=e.find(j=>j.id===t);return s.jsxs(bt,{title:p("repoMesh.host.title"),description:p("repoMesh.host.descriptionUnset"),children:[s.jsxs(Gt,{variant:"info",className:"mb-4",children:[s.jsx("strong",{children:p("repoMesh.host.setHostBanner")})," ",p("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:Hr(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:Hr(b)}),". Attach one of its workspaces as a node first, then launch to set the host."]})}):s.jsx(Ct,{label:p("repoMesh.host.hostDaemon"),hint:p("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:j=>n(j.target.value),children:[s.jsx("option",{value:"",children:p("repoMesh.host.resolvingHost")}),e.map(j=>s.jsx("option",{value:j.id,children:Hr(j)},j.id))]})}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-[180px_auto] items-end mt-3",children:[y,s.jsx("button",{className:"btn btn-primary btn-sm",onClick:w,disabled:!t||!c||a,title:t?c?void 0:p("repoMesh.host.attachNodeFirst"):p("repoMesh.host.pickHostFirst"),children:p(a?"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:p("repoMesh.host.noDaemonsToHost")}),k]})}function KI({meshId:e,availableCliAgents:t}){const{t:n}=Le(),r=t.find(a=>{const i=a.id.toLowerCase();return i==="hermes-cli"||i.includes("hermes")||a.name.toLowerCase().includes("hermes")}),o=Kh(r==null?void 0:r.meshCoordinator,{meshId:e});return o?s.jsx(bt,{title:n("repoMesh.hermesMcp.title"),description:n("repoMesh.hermesMcp.description"),children:s.jsx(fp,{setup:o,providerName:(r==null?void 0:r.name)||n("repoMesh.hermesMcp.fallbackProvider")})}):null}const _a=[{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."}],zI=[{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 qI(e){return e==="smart"?"fitness":e==="spread"?"least_loaded":"first_eligible"}function VI(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 YI={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,schedulingStrategy:"first_eligible",sessionCleanupOnNodeRemove:"preserve"};function xi(e){return{...YI,...(e==null?void 0:e.policy)||{}}}function JI(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 QI({selectedMesh:e,error:t,onDismissError:n,onBack:r,onDelete:o,displayedMeshStatus:a,graphLoading:i,graphError:c,onRefreshGraph:u,savingPolicy:h,onUpdatePolicy:d,coordinatorPromptDraft:m,onCoordinatorPromptDraftChange:f,savingCoordinatorPrompt:x,onSaveCoordinatorPrompt:w,daemons:p,coordinatorDaemonId:y,onCoordinatorDaemonIdChange:k,coordinatorCliType:b,onCoordinatorCliTypeChange:j,launchingCoordinator:S,launchResult:v,isHostNodeAttached:g,selectedHostNode:N,hostPinned:C,hostLabel:A,hostOnline:T,hostRebindDaemonId:M,onHostRebindDaemonIdChange:L,onLaunchCoordinator:P,activeDaemon:B,activeDaemonId:K,meshQueue:F,userName:R,availableCliProviders:Q,savingNodeSlotsId:E,onUpdateNodeSlots:I,savingNodeCapabilitiesId:$,onUpdateNodeCapabilities:D,nodeSystemPromptDrafts:U,onNodeSystemPromptDraftChange:Y,savingNodeSystemPromptId:ae,onSaveNodeSystemPrompt:z,selectedNodeId:X,onSelectNode:de,showAddNode:re,onShowAddNode:W,onCancelAddNode:oe,nodeWorkspace:V,onNodeWorkspaceChange:ie,nodeProviderPriority:ke,onNodeProviderPriorityChange:xe,nodeDaemonId:Se,onNodeDaemonIdChange:pe,nodeCustomPath:G,onNodeCustomPathChange:O,nodePickerWorkspaces:Z,nodePickerProviders:q,attachableDaemons:me,onAddNode:Te,onRemoveNode:_,availableCliAgents:te,features:ve,sendCommand:ce}){var Fe;const{t:H}=Le("common"),fe=xi(e),je=e.nodes||[],Ce=je.some(Ie=>{var Oe;const ye=Number((Oe=Ie.policy)==null?void 0:Oe.schedulingPriority);return Number.isFinite(ye)&&ye!==0}),Be=!fe.schedulingStrategy,Xe=l.useMemo(()=>je.some(Ie=>{var ye;return Array.isArray((ye=Ie.policy)==null?void 0:ye.slots)&&Ie.policy.slots.length>0}),[je]),dt=Be?Xe?"smart":je.length>=2?"spread":null:null,[it,he]=l.useState(!1),$e=!!K&&!!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:H("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(oI,{size:13}),H(i?"repoMesh.detail.probing":"repoMesh.detail.refresh")]}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>o(e.id),children:H("repoMesh.detail.delete")})]}),children:[t&&s.jsx(Gt,{variant:"error",onDismiss:n,className:"mb-4",children:t}),ve.meshHostDaemonSection&&s.jsx(GI,{daemons:p,coordinatorDaemonId:y,onCoordinatorDaemonIdChange:k,coordinatorCliType:b,onCoordinatorCliTypeChange:j,launchingCoordinator:S,launchResult:v,isHostNodeAttached:g,selectedHostNode:N,hostPinned:C,hostLabel:A,hostOnline:T,hostRebindDaemonId:M,onHostRebindDaemonIdChange:Ie=>{L(Ie),u()},onLaunchCoordinator:P}),s.jsxs(bt,{title:H("repoMesh.detail.observabilityTitle"),description:H("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:H($e?"repoMesh.detail.observabilityOpenTitle":"repoMesh.detail.observabilityDisabledTitle"),children:[s.jsx(es,{size:14}),H("repoMesh.detail.observabilityOpen")]}),s.jsx("span",{className:"text-[12px] text-text-muted",children:H("repoMesh.detail.observabilityHint")})]})]}),s.jsx(UI,{nodes:je,meshQueue:F,activeDaemon:B,daemons:p,selectedMeshId:e.id,userName:R,features:{addNodeDaemonPicker:ve.addNodeDaemonPicker,nodeInstruction:ve.nodeInstruction},coordinatorDaemonId:y,availableCliProviders:Q,savingNodeSlotsId:E,onUpdateNodeSlots:I,savingNodeCapabilitiesId:$,onUpdateNodeCapabilities:D,nodeSystemPromptDrafts:U,onNodeSystemPromptDraftChange:Y,savingNodeSystemPromptId:ae,onSaveNodeSystemPrompt:z,selectedNodeId:X,onSelectNode:de,showAddNode:re,onShowAddNode:W,onCancelAddNode:oe,nodeWorkspace:V,onNodeWorkspaceChange:ie,nodeProviderPriority:ke,onNodeProviderPriorityChange:xe,nodeDaemonId:Se,onNodeDaemonIdChange:pe,nodeCustomPath:G,onNodeCustomPathChange:O,nodePickerWorkspaces:Z,nodePickerProviders:q,attachableDaemons:me,onAddNode:Te,onRemoveNode:_}),s.jsxs(bt,{title:H("repoMesh.detail.schedulingTitle"),description:H("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:H("repoMesh.detail.distribution")}),s.jsx("div",{className:"flex flex-col gap-2",children:zI.map(Ie=>{const Oe=VI(fe.schedulingStrategy,{priorityConfigured:Ce})===Ie.value;return s.jsxs("label",{className:`flex items-start gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${Oe?"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:Ie.value,checked:Oe,disabled:h,onChange:()=>d({schedulingStrategy:qI(Ie.value)})}),s.jsxs("span",{className:"min-w-0",children:[s.jsxs("span",{className:"flex items-center gap-2 text-sm text-text-primary",children:[Ie.label,dt===Ie.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:H("repoMesh.detail.recommended")})]}),s.jsx("span",{className:"block text-[12px] text-text-muted",children:Ie.description})]})]},Ie.value)})})]}),h&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:H("repoMesh.detail.saving")})]}),s.jsx(bt,{title:H("repoMesh.detail.visibilityTitle"),description:H("repoMesh.detail.visibilityDescription"),children:s.jsx(Ct,{label:H("repoMesh.detail.visibilityLabel"),hint:H("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:fe.spawnedSessionVisibility==="visible"?"visible":"hidden",onChange:Ie=>d({spawnedSessionVisibility:Ie.target.value==="visible"?"visible":"hidden"}),disabled:h,children:[s.jsx("option",{value:"hidden",children:H("repoMesh.detail.visibilityHidden")}),s.jsx("option",{value:"visible",children:H("repoMesh.detail.visibilityVisible")})]})})}),a&&s.jsx(bt,{title:H("repoMesh.detail.magiTitle"),description:H("repoMesh.detail.magiDescription"),children:s.jsx(gI,{status:a,daemonId:K,sendDaemonCommand:ce,availableProviders:Q})}),s.jsx(jI,{status:a,daemonId:K,meshId:e.id,sendCommand:ce}),ve.coordinatorPrompt&&s.jsxs(bt,{title:H("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:H("repoMesh.detail.advanced")}),description:H("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:H("repoMesh.detail.thisMesh")}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:H("repoMesh.detail.thisMeshHint",{name:e.name})}),s.jsxs(Ct,{label:H("repoMesh.detail.overrideLabel"),hint:H("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:Ie=>f({...m,override:Ie.target.value}),disabled:x,placeholder:H("repoMesh.detail.overridePlaceholder")}),s.jsx(xI,{daemonId:K,meshId:e.id,cliType:b,sendCommand:ce})]}),s.jsx(Ct,{label:H("repoMesh.detail.appendLabel"),hint:H("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:Ie=>f({...m,append:Ie.target.value}),disabled:x,placeholder:H("repoMesh.detail.appendPlaceholder")})}),s.jsxs("details",{className:"mt-2 text-[12px] text-text-muted",children:[s.jsx("summary",{className:"cursor-pointer select-none",children:H("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:x,children:H(x?"repoMesh.detail.saving":"repoMesh.detail.saveCoordinatorPrompt")}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>f({override:"",append:""}),disabled:x,title:H("repoMesh.detail.clearTitle"),children:H("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:H("repoMesh.detail.userLevel")}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:H("repoMesh.detail.userLevelDescription")}),s.jsx(Uk,{daemonId:K||void 0})]})]}),s.jsxs(bt,{title:H("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:H("repoMesh.detail.advanced")}),description:H("repoMesh.detail.safetyDescription"),children:[s.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:[{label:H("repoMesh.detail.checkpointBefore"),key:"requirePreTaskCheckpoint",opts:[["no","No"],["yes","Yes"]],val:Ie=>Ie?"yes":"no",parse:Ie=>Ie==="yes"},{label:H("repoMesh.detail.checkpointAfter"),key:"requirePostTaskCheckpoint",opts:[["yes","Yes"],["no","No"]],val:Ie=>Ie?"yes":"no",parse:Ie=>Ie==="yes"},{label:H("repoMesh.detail.pushApproval"),key:"requireApprovalForPush",opts:[["required",H("repoMesh.detail.requireApprovalBeforePush")],["not_required",H("repoMesh.detail.doNotRequireApproval")]],val:Ie=>Ie?"required":"not_required",parse:Ie=>Ie==="required"},{label:H("repoMesh.detail.destructiveGitApproval"),key:"requireApprovalForDestructiveGit",opts:[["required",H("repoMesh.detail.requireApproval")],["not_required",H("repoMesh.detail.doNotRequireApproval")]],val:Ie=>Ie?"required":"not_required",parse:Ie=>Ie==="required"},{label:H("repoMesh.detail.uncommittedChanges"),key:"dirtyWorkspaceBehavior",opts:[["warn",H("repoMesh.detail.warnAndContinue")],["block",H("repoMesh.detail.blockTask")],["checkpoint_then_continue",H("repoMesh.detail.checkpointThenContinue")]],val:Ie=>Ie||"warn",parse:Ie=>Ie},{label:H("repoMesh.detail.autoPublishSubmodule"),key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled",H("repoMesh.detail.requireExplicitApproval")],["enabled",H("repoMesh.detail.allowRefineryPublish")]],val:Ie=>Ie?"enabled":"disabled",parse:Ie=>Ie==="enabled"}].map(({label:Ie,key:ye,opts:Oe,val:ut,parse:at})=>s.jsx(Ct,{label:Ie,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(fe[ye]),onChange:ht=>d({[ye]:at(ht.target.value)}),disabled:h,children:Oe.map(([ht,J])=>s.jsx("option",{value:ht,children:J},ht))})},ye))}),(()=>{const Ie=fe.autoFastForward&&typeof fe.autoFastForward=="object"?fe.autoFastForward:{},ye=Ie.enabled!==!1,Oe=Ie.remoteNodes===!0,ut=Ie.mode==="continuous"?"continuous":"idle",at=ht=>d({autoFastForward:{...Ie,...ht}});return s.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[s.jsx(Ct,{label:H("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:ye?"enabled":"disabled",onChange:ht=>at({enabled:ht.target.value==="enabled"}),disabled:h,children:[s.jsx("option",{value:"enabled",children:H("repoMesh.detail.ffEnabled")}),s.jsx("option",{value:"disabled",children:H("repoMesh.detail.ffDisabled")})]})}),s.jsx(Ct,{label:H("repoMesh.detail.includeRemoteNodes"),hint:H("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:Oe?"yes":"no",onChange:ht=>at({remoteNodes:ht.target.value==="yes"}),disabled:h||!ye,children:[s.jsx("option",{value:"no",children:H("repoMesh.detail.remoteNo")}),s.jsx("option",{value:"yes",children:H("repoMesh.detail.remoteYes")})]})}),s.jsx(Ct,{label:H("repoMesh.detail.detectionMode"),hint:H("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:ht=>at({mode:ht.target.value==="continuous"?"continuous":"idle"}),disabled:h||!ye||!Oe,children:[s.jsx("option",{value:"idle",children:H("repoMesh.detail.idleEdgeOnly")}),s.jsx("option",{value:"continuous",children:H("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:H("repoMesh.detail.sessionCleanupLabel"),hint:H("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:fe.sessionCleanupOnNodeRemove||"preserve",onChange:Ie=>d({sessionCleanupOnNodeRemove:Ie.target.value}),disabled:h,children:_a.map(Ie=>s.jsx("option",{value:Ie.value,children:Ie.label},Ie.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((Fe=_a.find(Ie=>Ie.value===fe.sessionCleanupOnNodeRemove))==null?void 0:Fe.description)||_a[0].description})]}),h&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:H("repoMesh.detail.saving")})]}),ve.hermesMcpConfig&&s.jsx(KI,{meshId:e.id,availableCliAgents:te}),ve.meshHostDaemonSection&&s.jsxs(Gt,{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(qp,{activeConv:JI({meshId:e.id,daemonId:K,meshName:e.name}),sendDaemonCommand:ce,onClose:()=>he(!1)})]})}const Un=new Map;function XI({daemons:e,primaryDaemonId:t,sendCommand:n,unwrapResult:r,normalizeMesh:o,features:a,loadDaemonMetadata:i}){const c=e.map(I=>I.id).filter(Boolean).sort().join(","),[u,h]=l.useState(()=>Un.get(c)??[]),[d,m]=l.useState(null),[f,x]=l.useState(()=>!Un.has(c)),[w,p]=l.useState(null),[y,k]=l.useState(!1),[b,j]=l.useState(""),[S,v]=l.useState(""),[g,N]=l.useState(""),[C,A]=l.useState(""),[T,M]=l.useState(""),L=l.useMemo(()=>e.find(I=>I.id===C),[e,C]),P=(L==null?void 0:L.workspaces)||[],B=l.useMemo(()=>wn((L==null?void 0:L.availableProviders)||[]),[L]);l.useEffect(()=>{!a.createDaemonPicker||!i||!C||!L||!(!L.workspaces||!L.availableProviders)||Promise.resolve(i(C,{minFreshMs:3e4})).catch(()=>{})},[a.createDaemonPicker,i,C,L]);const K=l.useMemo(()=>e.map(I=>I.id).filter(Boolean).sort().join(","),[e]),F=l.useCallback(async(I=!1)=>{const $=I||Un.has(K);x(D=>$?D:!0);try{if(a.createDaemonPicker){const D=await Promise.allSettled(e.map(async ae=>{if(!ae.id)return[];const z=await n(ae.id,"list_meshes",{}),X=r(z);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=>o(de,ae.id)).filter(de=>de.id)})),U=new Map;for(const ae of D)if(ae.status==="fulfilled")for(const z of ae.value)U.has(z.id)||U.set(z.id,z);const Y=Array.from(U.values());h(Y),Un.set(K,Y),p(null)}else{if(!t)return;const D=await n(t,"list_meshes");if(D!=null&&D.success){const U=(D.meshes||[]).map(Y=>o(Y,t));h(U),Un.set(K,U),p(null)}else p((D==null?void 0:D.error)||"Failed to load meshes")}}catch(D){p((D==null?void 0:D.message)||"Failed to load meshes")}finally{x(!1)}},[K,t,n,r,o,a.createDaemonPicker]);async function R(){var U,Y;const I=a.createDaemonPicker?C:t;if(!I||!b.trim())return;const $=g.trim(),D=S.trim();if(!(!$&&!D))try{const ae={name:b.trim()};$&&(ae.repoRemoteUrl=$),D&&(ae.repoIdentity=D);const z=await n(I,"create_mesh",ae),X=r(z);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&&a.createDaemonPicker&&T){const re=await n(I,"add_mesh_node",{meshId:de,daemonId:I,machineId:L==null?void 0:L.machineId,workspace:T,role:"host",providerPriority:cr(B)}),W=r(re);if((W==null?void 0:W.success)===!1)throw new Error(W.error||"Mesh created but failed to attach workspace")}k(!1),j(""),v(""),N(""),M(""),await F(),(Y=X==null?void 0:X.mesh)!=null&&Y.id&&m(X.mesh.id)}catch(ae){p((ae==null?void 0:ae.message)||"Create failed")}}async function Q(I){var D;if(!confirm("Delete this mesh? This cannot be undone."))return;const $=((D=u.find(U=>U.id===I))==null?void 0:D.__sourceDaemonId)||t;try{const U=await n($,"delete_mesh",{meshId:I}),Y=r(U);if((Y==null?void 0:Y.success)===!1)throw new Error(Y.error||"Failed to delete");d===I&&m(null),await F()}catch(U){p((U==null?void 0:U.message)||"Delete failed")}}function E(){k(!1),j(""),v(""),N("")}return{meshes:u,setMeshes:h,selectedMeshId:d,setSelectedMeshId:m,loading:f,error:w,setError:p,showCreate:y,setShowCreate:k,createName:b,setCreateName:j,createRepoIdentity:S,setCreateRepoIdentity:v,createRepoRemoteUrl:g,setCreateRepoRemoteUrl:N,newMeshDaemonId:C,setNewMeshDaemonId:A,newMeshWorkspace:T,setNewMeshWorkspace:M,createPickerWorkspaces:P,createPickerProviders:B,loadMeshes:F,handleCreate:R,handleDelete:Q,cancelCreate:E}}function ZI({selectedMesh:e,selectedMeshId:t,primaryDaemonId:n,activeDaemonId:r,daemons:o,sendCommand:a,unwrapResult:i,loadLiveMesh:c,resolveCommandTarget:u,launchCoordinator:h,features:d,loadMeshes:m,loadQueue:f,queueSection:x,setError:w}){const[p,y]=l.useState({}),[k,b]=l.useState(null),[j,S]=l.useState(null),[v,g]=l.useState(!1),[N,C]=l.useState(""),[A,T]=l.useState([]),[M,L]=l.useState(""),[P,B]=l.useState(!1),[K,F]=l.useState(""),[R,Q]=l.useState(!1),[E,I]=l.useState(null),[$,D]=l.useState(!1),[U,Y]=l.useState({override:"",append:""}),[ae,z]=l.useState(!1),[X,de]=l.useState({}),[re,W]=l.useState(null),oe=l.useMemo(()=>o.find(ce=>ce.id===M),[o,M]),V=(oe==null?void 0:oe.workspaces)||[],ie=l.useMemo(()=>wn((oe==null?void 0:oe.availableProviders)||[]),[oe]);async function ke(){const ce=(e==null?void 0:e.__sourceDaemonId)||n;if(!t||!ce)return;const H=N.trim();if(H)try{const fe={meshId:t,workspace:H};d.addNodeDaemonPicker&&M&&(fe.daemonId=M,fe.machineId=oe==null?void 0:oe.machineId),fe.providerPriority=kn(A);const je=await a(ce,"add_mesh_node",fe),Ce=i(je);if((Ce==null?void 0:Ce.success)===!1)throw new Error(Ce.error||"Add node failed");g(!1),C(""),T([]),L(""),B(!1),await m(),x||await f(t)}catch(fe){w((fe==null?void 0:fe.message)||"Add node failed")}}async function xe(ce){var Ce;if(!e)return;const H=xi(e),fe=((Ce=[{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(Be=>Be.value===H.sessionCleanupOnNodeRemove))==null?void 0:Ce.label)||"Preserve history and runtimes";if(!confirm(`Remove this node?
120
+
121
+ Node removal cleanup policy: ${fe}`))return;const je=e.__sourceDaemonId||n;try{const Be=await a(je,"remove_mesh_node",{meshId:e.id,nodeId:ce}),Xe=i(Be);if((Xe==null?void 0:Xe.success)===!1)throw new Error(Xe.error||"Remove failed");j===ce&&S(null),await m(),x||await f(t)}catch(Be){w((Be==null?void 0:Be.message)||"Remove node failed")}}async function Se(ce){if(!e)return;const H={...xi(e),...ce},fe=e.__sourceDaemonId||n;try{D(!0),w(null);const je=await a(fe,"update_mesh",{meshId:e.id,policy:H}),Ce=i(je);if((Ce==null?void 0:Ce.success)===!1)throw new Error(Ce.error||"Policy update failed");await m()}catch(je){w((je==null?void 0:je.message)||"Policy update failed")}finally{D(!1)}}async function pe(ce){if(!t)return;const H=(e==null?void 0:e.__sourceDaemonId)||n,fe=p[ce.id]||eM(ce),je=kn(fe),Ce={...ce.policy||{}};delete Ce.provider_priority,je.length?Ce.providerPriority=je:delete Ce.providerPriority;try{b(ce.id),w(null);const Be=await a(H,"update_mesh_node",{meshId:t,nodeId:ce.id,policy:Ce,providerPriority:je}),Xe=i(Be);if((Xe==null?void 0:Xe.success)===!1){w(Xe.error||"Node policy update failed");return}await m()}catch(Be){w((Be==null?void 0:Be.message)||"Node policy update failed")}finally{b(null)}}const[G,O]=l.useState(null);async function Z(ce,H){if(!t)return;const fe=(e==null?void 0:e.__sourceDaemonId)||n;try{O(ce.id),w(null);const je=await a(fe,"update_mesh_node",{meshId:t,nodeId:ce.id,policy:{slots:H}}),Ce=i(je);if((Ce==null?void 0:Ce.success)===!1){w(Ce.error||"Node slots update failed");return}await m()}catch(je){w((je==null?void 0:je.message)||"Node slots update failed")}finally{O(null)}}const[q,me]=l.useState(null);async function Te(ce,H){if(!t)return;const fe=(e==null?void 0:e.__sourceDaemonId)||n,je=H.map(Ce=>Ce.trim()).filter(Boolean);try{me(ce.id),w(null);const Ce=await a(fe,"update_mesh_node",{meshId:t,nodeId:ce.id,capabilities:je}),Be=i(Ce);if((Be==null?void 0:Be.success)===!1){w(Be.error||"Node tag update failed");return}await m()}catch(Ce){w((Ce==null?void 0:Ce.message)||"Node tag update failed")}finally{me(null)}}async function _(){if(!n||!t)return;const H={...(e==null?void 0:e.coordinator)||{}};U.override.trim()?H.systemPromptOverride=U.override:delete H.systemPromptOverride,U.append.trim()?H.systemPromptAppend=U.append:delete H.systemPromptAppend,delete H.systemPromptSuffix;try{z(!0),w(null);const fe=await a(n,"update_mesh",{meshId:t,coordinator:H}),je=i(fe);if((je==null?void 0:je.success)===!1){w(je.error||"Coordinator prompt save failed");return}await m()}catch(fe){w((fe==null?void 0:fe.message)||"Coordinator prompt save failed")}finally{z(!1)}}async function te(ce){if(!n||!t)return;const H=(X[ce.id]||"").trim();try{W(ce.id),w(null);const fe=await a(n,"update_mesh_node",{meshId:t,nodeId:ce.id,systemPrompt:H}),je=i(fe);if((je==null?void 0:je.success)===!1){w(je.error||"Node instruction save failed");return}await m()}catch(fe){w((fe==null?void 0:fe.message)||"Node instruction save failed")}finally{W(null)}}async function ve(){if(e){w(null),I(null);try{Q(!0);const ce=c?await c(r,e.id,e):null,H=u(r,e.id,e,e.nodes||[],ce);if("error"in H)throw new Error(H.error);const fe=await h(H.targetDaemonId,{meshId:e.id,inlineMesh:H.inlineMesh,coordinatorNodeId:H.coordinatorNodeId,cliType:K.trim()||void 0});I(fe.message)}catch(ce){w((ce==null?void 0:ce.message)||"Coordinator launch failed")}finally{Q(!1)}}}return{nodeProviderPriorityDrafts:p,setNodeProviderPriorityDrafts:y,savingNodePolicyId:k,selectedNodeId:j,setSelectedNodeId:S,showAddNode:v,setShowAddNode:g,nodeWorkspace:N,setNodeWorkspace:C,nodeProviderPriority:A,setNodeProviderPriority:T,nodeDaemonId:M,setNodeDaemonId:L,nodeCustomPath:P,setNodeCustomPath:B,nodePickerWorkspaces:V,nodePickerProviders:ie,coordinatorCliType:K,setCoordinatorCliType:F,launchingCoordinator:R,launchResult:E,savingPolicy:$,coordinatorPromptDraft:U,setCoordinatorPromptDraft:Y,savingCoordinatorPrompt:ae,nodeSystemPromptDrafts:X,setNodeSystemPromptDrafts:de,savingNodeSystemPromptId:re,savingNodeSlotsId:G,savingNodeCapabilitiesId:q,handleAddNode:ke,handleRemoveNode:xe,handleUpdatePolicy:Se,handleUpdateNodeProviderPriority:pe,handleUpdateNodeSlots:Z,handleUpdateNodeCapabilities:Te,handleSaveCoordinatorPrompt:_,handleSaveNodeSystemPrompt:te,handleLaunchCoordinator:ve}}function eM(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(o=>typeof o=="string"?o.trim():"").filter(Boolean).filter(o=>n.has(o)?!1:(n.add(o),!0))}function tM(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 sM({primaryDaemonId:e,activeDaemonId:t,sendCommand:n,unwrapResult:r,loadLiveMesh:o,resolveCommandTarget:a}){const[i,c]=l.useState([]),[u,h]=l.useState(null),[d,m]=l.useState(!1),[f,x]=l.useState(null),w=l.useCallback(async y=>{if(!e||!y){c([]);return}try{const k=await n(e,"get_mesh_queue",{meshId:y});c(k!=null&&k.success?Array.isArray(k.queue)?k.queue:[]:[])}catch{c([])}},[e,n]);async function p(y){var k,b;if(y){m(!0),x(null);try{const j=o?await o(t,y.id,y):null,S=a(t,y.id,y,y.nodes||[],j);if("error"in S)throw new Error(S.error);const v=await n(S.targetDaemonId,"get_mesh_queue",{meshId:y.id}),g=r(v);if((g==null?void 0:g.success)===!1)throw new Error(g.error||"Queue load failed");const N=Array.isArray(((k=g==null?void 0:g.result)==null?void 0:k.rows)??(g==null?void 0:g.rows)??(g==null?void 0:g.queue))?((b=g==null?void 0:g.result)==null?void 0:b.rows)??(g==null?void 0:g.rows)??(g==null?void 0:g.queue):[];h(tM(N))}catch(j){x((j==null?void 0:j.message)||"Queue load failed")}finally{m(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:u,queueLoading:d,queueError:f,loadQueue:w,handleLoadQueue:p}}function nM(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}const Zp=new Map;function em(e){return e?Zp.get(e)??null:null}function rM(e,t){!e||!t||Zp.set(e,t)}function oM({selectedMeshId:e,loadMeshStatus:t,extractStatus:n,normalizeNode:r,gateIncompleteGraph:o}){const[a,i]=l.useState(()=>em(e)),[c,u]=l.useState(!1),[h,d]=l.useState(null),[m,f]=l.useState("idle"),[x,w]=l.useState(!1),p=l.useRef(!1);async function y(k,b=e,j=!1){if(!(!k||!b))try{u(!j&&a===null),f(j?"settling":"first_paint"),d(null);const S=await t(k,b,{refresh:j,retryProfile:j?"settled":"interactive"});w(nM(S));const v=n(S),g=r&&v?{...v,nodes:(v.nodes??[]).map(N=>r(N,v.meshId??b,""))}:v;if(g){if(o&&!j&&a!==null&&!Cj(Mp(g))){f("settling"),p.current||(p.current=!0,Promise.resolve().then(()=>y(k,b,!0)).finally(()=>{p.current=!1}));return}i(g),rM(b,g),f("settled")}else i(null),d("mesh_status returned an unexpected payload."),f("idle")}catch(S){a||i(null),d((S==null?void 0:S.message)||"Failed to load mesh graph"),f("idle")}finally{u(!1)}}return{meshGraphStatus:a,setMeshGraphStatus:i,graphLoading:c,graphError:h,setGraphError:d,graphProvenance:m,graphBootstrapFallback:x,loadGraph:y}}function aM(e,t,n,r,o){if(!e.length)return"";const a=String(o||"");if(a){const u=e.find(h=>Ws(h.id,a));return u?u.id:a}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(h=>Ws(h.id,c));if(u)return u.id}return""}const iM=7e3,lM=45e3;function cM(){const e=rI(),{sendCommand:t,sendData:n,daemons:r,userName:o,loadMeshStatus:a,launchCoordinator:i,loadLiveMesh:c,extractStatus:u,unwrapResult:h,normalizeMesh:d,normalizeNode:m,resolveCommandTarget:f,features:x,gateIncompleteGraph:w}=e,p=In(),y=r[0],k=(y==null?void 0:y.id)||"",b=l.useMemo(()=>((y==null?void 0:y.availableProviders)||[]).filter(rt=>rt.category==="cli").map(rt=>({id:rt.type||rt.id,name:rt.displayName||rt.name||rt.type,meshCoordinator:rt.meshCoordinator})),[y]),j=l.useMemo(()=>wn((y==null?void 0:y.availableProviders)||[]),[y]),{meshes:S,selectedMeshId:v,setSelectedMeshId:g,loading:N,error:C,setError:A,showCreate:T,setShowCreate:M,createName:L,setCreateName:P,createRepoIdentity:B,setCreateRepoIdentity:K,createRepoRemoteUrl:F,setCreateRepoRemoteUrl:R,newMeshDaemonId:Q,setNewMeshDaemonId:E,newMeshWorkspace:I,setNewMeshWorkspace:$,createPickerWorkspaces:D,loadMeshes:U,handleCreate:Y,handleDelete:ae,cancelCreate:z}=XI({daemons:r,primaryDaemonId:k,sendCommand:t,unwrapResult:h,normalizeMesh:d,features:x,loadDaemonMetadata:p}),X=S.find(Re=>Re.id===v)||null,{meshGraphStatus:de,setMeshGraphStatus:re,graphLoading:W,graphError:oe,setGraphError:V,loadGraph:ie}=oM({selectedMeshId:v,loadMeshStatus:a,extractStatus:u,normalizeNode:m,gateIncompleteGraph:w}),[ke,xe]=l.useState(""),[Se,pe]=l.useState(""),G=x.meshHostDaemonSection&&ke||k,{meshQueue:O,loadQueue:Z}=sM({primaryDaemonId:k,activeDaemonId:G,sendCommand:t,unwrapResult:h,loadLiveMesh:c,resolveCommandTarget:f}),{setNodeProviderPriorityDrafts:q,selectedNodeId:me,setSelectedNodeId:Te,showAddNode:_,setShowAddNode:te,nodeWorkspace:ve,setNodeWorkspace:ce,nodeProviderPriority:H,setNodeProviderPriority:fe,nodeDaemonId:je,setNodeDaemonId:Ce,nodeCustomPath:Be,setNodeCustomPath:Xe,nodePickerWorkspaces:dt,nodePickerProviders:it,coordinatorCliType:he,setCoordinatorCliType:$e,launchingCoordinator:Fe,launchResult:Ie,savingPolicy:ye,coordinatorPromptDraft:Oe,setCoordinatorPromptDraft:ut,savingCoordinatorPrompt:at,nodeSystemPromptDrafts:ht,setNodeSystemPromptDrafts:J,savingNodeSystemPromptId:ee,savingNodeSlotsId:le,savingNodeCapabilitiesId:ue,handleAddNode:ge,handleRemoveNode:Ae,handleUpdatePolicy:Pe,handleUpdateNodeSlots:Ne,handleUpdateNodeCapabilities:He,handleSaveCoordinatorPrompt:Ke,handleSaveNodeSystemPrompt:Ze,handleLaunchCoordinator:_e}=ZI({selectedMesh:X,selectedMeshId:v,primaryDaemonId:k,activeDaemonId:G,daemons:r,availableCliProviders:j,sendCommand:t,unwrapResult:h,loadLiveMesh:c,resolveCommandTarget:f,launchCoordinator:i,features:{addNodeDaemonPicker:x.addNodeDaemonPicker},loadMeshes:U,loadQueue:Z,queueSection:x.queueSection,setError:A}),Ue=l.useMemo(()=>r.find(Re=>Re.id===G)||y,[r,G,y]),et=l.useMemo(()=>new Set(((X==null?void 0:X.nodes)||[]).map(Re=>String(Re.daemon_id||Re.daemonId||""))),[X]),se=l.useMemo(()=>r.filter(Re=>Re.id&&!et.has(Re.id)),[r,et]),be=(X==null?void 0:X.nodes)||[],we=l.useMemo(()=>be.find(Re=>Ws(String(Re.daemon_id||Re.daemonId||""),ke)),[be,ke]),ze=x.meshHostDaemonSection?!!we:!0,We=l.useMemo(()=>{if(!x.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,Ot=String((jt==null?void 0:jt.hostDaemonId)||""),ne=be.find(ys=>ys.role==="host"),Ge=String((jt==null?void 0:jt.hostNodeId)||(ne==null?void 0:ne.id)||""),Ee=Ge?be.find(ys=>String(ys.id)===Ge):void 0,vt=String((Ee==null?void 0:Ee.daemon_id)||(Ee==null?void 0:Ee.daemonId)||""),Jt=Ot||vt;if(!Jt)return{pinned:!1,daemonId:"",label:"",online:!1};const Mn=r.find(ys=>Ot&&Ws(ys.id,Ot))||(vt?r.find(ys=>Ws(ys.id,vt)):void 0);if(Mn)return{pinned:!0,daemonId:Mn.id,label:dM(Mn),online:!0};const Oo=String((Ee==null?void 0:Ee.machineLabel)||"")||String((Ee==null?void 0:Ee.workspace)||"")||Jt;return{pinned:!0,daemonId:Jt,label:Oo,online:!1}},[X,be,r,de,x.meshHostDaemonSection]),tt=We.daemonId,qe=We.online,Ye=l.useMemo(()=>!x.meshHostDaemonSection||!We.pinned?"":!qe&&Se&&r.some(Re=>Re.id===Se)?Se:tt,[x.meshHostDaemonSection,We.pinned,qe,Se,r,tt]),Tt=l.useMemo(()=>de?[...new Set((de.nodes??[]).map(Re=>String(Re.daemonId||Re.daemon_id||"")).filter(Boolean))]:[],[de]),Wt=zp({status:de,daemonId:G||null,extraDaemonIds:Tt,meshId:v,sendData:n});l.useEffect(()=>{q(Object.fromEntries(((X==null?void 0:X.nodes)||[]).map(Re=>[Re.id,uM(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:""}),J(Object.fromEntries(((X==null?void 0:X.nodes)||[]).map(rt=>[rt.id,typeof rt.systemPrompt=="string"?rt.systemPrompt:""])))},[X]),l.useEffect(()=>{const Re=x.addNodeDaemonPicker?cr(it):cr(j);_&&H.length===0&&Re.length>0&&fe(Re)},[_,j,it,H.length,x.addNodeDaemonPicker]),l.useEffect(()=>{const Re=new Set(((X==null?void 0:X.nodes)||[]).map(rt=>rt.id));me&&!Re.has(me)&&Te(null)},[X,me]);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]),Me=l.useMemo(()=>aM(r,be,G,k,ss),[r,be,G,k,ss]);l.useEffect(()=>{if(!x.meshHostDaemonSection)return;if(!r.length&&!We.pinned){xe("");return}const Re=We.pinned?Ye:Me;Re&&!Ws(Re,ke)&&xe(Re)},[r,ke,We.pinned,Ye,Me,x.meshHostDaemonSection]),l.useEffect(()=>{Se&&(qe||!r.some(Re=>Re.id===Se))&&pe("")},[qe,Se,r]),l.useEffect(()=>{if(x.createDaemonPicker){if(!r.length){E("");return}(!Q||!r.some(Re=>Re.id===Q))&&E(r[0].id)}},[r,Q,x.createDaemonPicker]),l.useEffect(()=>{var Re;if(!x.createDaemonPicker||!Q){$("");return}if(!D.length){$("");return}D.some(rt=>rt.path===I)||$(((Re=D[0])==null?void 0:Re.path)||"")},[Q,I,D,x.createDaemonPicker]);const Qe=l.useRef(null);l.useEffect(()=>{if(!v)return;const Re=Qe.current!==v;if(Qe.current=v,Re){const rt=em(v);re(rt),V(null),ie(G,v,rt!==null)}else V(null),ie(G,v,!0)},[v,G]);const Dt=l.useRef(ie);Dt.current=ie;const It=l.useRef(!1),qt=l.useRef(()=>{});qt.current=()=>{It.current||!v||!G||(It.current=!0,Promise.resolve(Dt.current(G,v,!0)).finally(()=>{It.current=!1}))};const Vt=x.meshStatePushRefresh?lM:iM;sI({daemonIds:l.useMemo(()=>[G,...Tt].filter(Boolean),[G,Tt]),meshId:v,sendData:n,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||qt.current()}}),l.useEffect(()=>{if(!v||!G||typeof document>"u")return;let Re=null;const rt=()=>{document.visibilityState==="visible"&&qt.current()},jt=()=>{Re===null&&(Re=setInterval(rt,Vt))},Ot=()=>{Re!==null&&(clearInterval(Re),Re=null)},ne=()=>{document.visibilityState==="visible"?jt():Ot()};return document.visibilityState==="visible"&&jt(),document.addEventListener("visibilitychange",ne),()=>{Ot(),document.removeEventListener("visibilitychange",ne)}},[v,G,Vt]),l.useEffect(()=>{x.queueSection||Z(v)},[v,x.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(QI,{selectedMesh:X,error:C,onDismissError:()=>A(null),onBack:()=>{g(null),re(null)},onDelete:ae,displayedMeshStatus:Wt,graphLoading:W,graphError:oe,onRefreshGraph:()=>ie(G,v,!0),savingPolicy:ye,onUpdatePolicy:Pe,coordinatorPromptDraft:Oe,onCoordinatorPromptDraftChange:ut,savingCoordinatorPrompt:at,onSaveCoordinatorPrompt:Ke,daemons:r,coordinatorDaemonId:ke,onCoordinatorDaemonIdChange:xe,coordinatorCliType:he,onCoordinatorCliTypeChange:$e,launchingCoordinator:Fe,launchResult:Ie,isHostNodeAttached:ze,selectedHostNode:we,hostPinned:We.pinned,hostLabel:We.label,hostOnline:qe,hostRebindDaemonId:Se,onHostRebindDaemonIdChange:Re=>pe(Re),onLaunchCoordinator:_e,activeDaemon:Ue,activeDaemonId:G,meshQueue:O,userName:o,availableCliProviders:j,savingNodeSlotsId:le,onUpdateNodeSlots:Ne,savingNodeCapabilitiesId:ue,onUpdateNodeCapabilities:He,nodeSystemPromptDrafts:ht,onNodeSystemPromptDraftChange:(Re,rt)=>J(jt=>({...jt,[Re]:rt})),savingNodeSystemPromptId:ee,onSaveNodeSystemPrompt:Ze,selectedNodeId:me,onSelectNode:Te,showAddNode:_,onShowAddNode:()=>te(!0),onCancelAddNode:()=>te(!1),nodeWorkspace:ve,onNodeWorkspaceChange:ce,nodeProviderPriority:H,onNodeProviderPriorityChange:fe,nodeDaemonId:je,onNodeDaemonIdChange:Ce,nodeCustomPath:Be,onNodeCustomPathChange:Xe,nodePickerWorkspaces:dt,nodePickerProviders:it,attachableDaemons:se,onAddNode:ge,onRemoveNode:Ae,availableCliAgents:b,features:{coordinatorPrompt:x.coordinatorPrompt,meshHostDaemonSection:x.meshHostDaemonSection,hermesMcpConfig:x.hermesMcpConfig,addNodeDaemonPicker:x.addNodeDaemonPicker,nodeInstruction:x.nodeInstruction},sendCommand:t}):s.jsx(uI,{meshes:S,loading:N,error:C,onDismissError:()=>A(null),daemons:r,features:{createDaemonPicker:x.createDaemonPicker},showCreate:T,onToggleCreate:()=>M(!T),createName:L,onCreateNameChange:P,createRepoIdentity:B,onCreateRepoIdentityChange:K,createRepoRemoteUrl:F,onCreateRepoRemoteUrlChange:R,newMeshDaemonId:Q,onNewMeshDaemonIdChange:E,newMeshWorkspace:I,onNewMeshWorkspaceChange:$,createPickerWorkspaces:D,onSelectMesh:g,onCreate:Y,onCancelCreate:z}):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 dM(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function uM(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(o=>typeof o=="string"?o.trim():"").filter(Boolean).filter(o=>n.has(o)?!1:(n.add(o),!0))}function hM({children:e}){const{sendCommand:t,sendData:n}=yt(),{ides:r}=gs(),o=l.useMemo(()=>r.filter(i=>i.daemonMode||i.type==="adhdev-daemon").map(i=>i),[r]),a=l.useMemo(()=>({sendCommand:t,sendData:n,daemons:o,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 h=await t(i,"launch_mesh_coordinator",u),d=(h==null?void 0:h.result)??h;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:Hi,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,u)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:nI}),[t,n,o]);return s.jsx(Xp.Provider,{value:a,children:e})}function bl(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function pM(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=bl();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 ms(e,t){return await fetch(pM(e),{credentials:"same-origin",...t})}function tm(){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 mM{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(o=>o(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,o=!1,a,i){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:r,text:n,truncated:o,cols:a,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 o=this.runtimeListeners.get(t);o&&(o.delete(n),o.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,n,r){if(!n)return{success:!1,error:"sessionId is required"};const o=new URL(`/api/v1/runtime/${encodeURIComponent(n)}/snapshot`,window.location.origin);typeof(r==null?void 0:r.sinceSeq)=="number"&&o.searchParams.set("sinceSeq",String(r.sinceSeq));const a=await ms(`${o.pathname}${o.search}`);if(!a.ok){let c=`Runtime snapshot unavailable (${a.status})`;try{const u=await a.json();u!=null&&u.error&&(c=u.error)}catch{}return{success:!1,error:c}}const i=await a.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(o=>o(n))}}const ps=new mM;function fM(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=bl();return n?`${t}?token=${encodeURIComponent(n)}`:t}const Wr=fM(),Id=3e3,bM=3e4;let os=null,gM=0;const wo=new Map;let $s=null,nr=null;function Md(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 xM(e){return e==="connected"?"connected":e}async function rr(e,t,n){const r=Sh(e,n||{}),o=os;if(o&&o.readyState===WebSocket.OPEN){const a=`req_${++gM}_${Date.now()}`;return new Promise((i,c)=>{const u=setTimeout(()=>{wo.delete(a),c(new Error(`WS command timeout: ${t}`))},3e4);wo.set(a,{resolve:h=>{clearTimeout(u),i(h)},reject:h=>{clearTimeout(u),c(h)}}),o.send(JSON.stringify({type:"command",requestId:a,data:{type:t,payload:r.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function yi(e,t){const n=os;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 sm(e,t,n){const r=os;if(!r||r.readyState!==WebSocket.OPEN)return!1;const o=Sh(e,{sessionId:t,targetSessionId:t,data:n});try{return r.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:o.payload}})),!0}catch{return!1}}ps.registerPtyInputSender(sm);class yM{constructor(t){st(this,"daemonId");st(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(os==null?void 0:os.readyState)===WebSocket.OPEN}get connectionState(){return(os==null?void 0:os.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,$s&&(clearInterval($s),$s=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 o=await fetch(`data:image/jpeg;base64,${r.base64}`).then(a=>a.blob());ps.emitScreenshot(this.daemonId,o)}}catch{}};n(),$s=setInterval(n,2e3)}stopScreenshots(t){$s&&(clearInterval($s),$s=null)}}let Xt=null;function vM(e){return(!Xt||Xt.daemonId!==e)&&(Xt=new yM(e)),Xt}function wM({children:e}){const t=l.useRef(or()),n=or();t.current=n;const{setUserName:r}=gs(),o=l.useRef(r);o.current=r;const a=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),u=l.useCallback((p,y)=>{c(p),nr==null||nr(p,y)},[]),h=l.useRef(null),d=l.useRef(),m=l.useRef(Id),f=l.useRef(!0),x=l.useRef(!1),w=l.useRef("initial_connect");return l.useEffect(()=>{f.current=!0,x.current=!1;function p(){var b,j;if(!f.current||((b=h.current)==null?void 0:b.readyState)===WebSocket.OPEN||((j=h.current)==null?void 0:j.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(S){console.error("[Standalone WS] Failed to create WebSocket:",S),y();return}h.current=k,k.onopen=()=>{if(!f.current){k.close();return}u("connected"),m.current=Id,Gn("open",{url:Wr,reason:w.current}),ls.resubscribeAll({sendData:yi}),console.log("[Standalone WS] Connected")},os=k,k.onmessage=S=>{var v,g;try{const N=JSON.parse(S.data);if((N.type==="command_result"||N.type==="error")&&N.requestId){const C=wo.get(N.requestId);C&&(wo.delete(N.requestId),N.type==="error"?C.reject(new Error(((v=N.data)==null?void 0:v.message)||"Command failed")):C.resolve(N.data));return}if(N.type==="session_output"){const C=N.sessionId||N.cliId||N.cliType;C&&ps.emitSessionOutput(C,typeof N.data=="string"?N.data:"",typeof N.seq=="number"?N.seq:void 0);return}if(N.type==="runtime_snapshot"){ps.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:T,getIdes:M}=t.current,L=C.instanceId||"standalone",P=M().find(F=>F.id===L),B=vM(L);ps.register(L,B),ps.setState(L,"connected"),u("connected",L),ps.emitStatus(L,C);const K=ao(C,{daemonId:L,existingDaemon:P,existingEntries:M()});Md("ws_status",{type:N.type,daemonId:L,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}))}),Md("entries",{daemonId:L,entries:K.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}))}),K.length>0&&A(K,{authoritativeDaemonIds:[L]}),T(),i.current!==L&&((g=a.current)==null||g.call(a),i.current=L,a.current=ls.subscribe({sendData:yi},L,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${L}`,params:{includeSessions:!0}},F=>{if(F.topic!=="daemon.metadata")return;const R=t.current.getIdes(),Q=R.find(I=>I.id===L),E=ao(F.status,{daemonId:L,existingDaemon:Q,existingEntries:R,timestamp:F.timestamp});E.length>0&&t.current.injectEntries(E,{authoritativeDaemonIds:[L]}),F.userName&&o.current&&o.current(F.userName)}))}}catch(N){console.error("[Standalone WS] Parse error:",N)}},k.onclose=S=>{f.current&&(Xt==null||Xt.stopScreenshots(),Xt&&ps.setState(Xt.daemonId,"disconnected"),u("disconnected"),h.current=null,w.current=`close:${S.code}${S.wasClean?":clean":":unclean"}`,Gn("close",{code:S.code,reason:S.reason||"",wasClean:S.wasClean}),y())},k.onerror=S=>{x.current||!f.current||(w.current="error",Gn("error",{message:S instanceof Event?"event":String(S),readyState:k.readyState}),console.warn("[Standalone WS] Error, will reconnect:",S))}}function y(){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,bM),p()},k)}return p(),()=>{var k;f.current=!1,x.current=!0,(k=a.current)==null||k.call(a),a.current=null,i.current=null,clearTimeout(d.current),h.current&&(h.current.onerror=null,h.current.onclose=null,h.current.close(),h.current=null,os=null),Xt&&(Xt.stopScreenshots(),ps.unregister(Xt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function kM({children:e}){const[t,n]=l.useState("disconnected"),[r,o]=l.useState(null);l.useEffect(()=>(nr=(i,c)=>{n(i),c&&o(c)},()=>{nr=null}),[]);const a=l.useMemo(()=>{const i=t==="connected",c=xM(t),u={};return r&&(u[r]=c),u.standalone=c,{wsStatus:t,isConnected:i,connectionStates:u}},[t,r]);return s.jsx(of,{connectionOverrides:a,children:s.jsx(wM,{children:e})})}const nm="adhdev_standalone_font_preferences",Vs={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Wo=[{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"}],hr=[{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"}],SM=new Set(Wo.map(e=>e.id)),CM=new Set(hr.map(e=>e.id));function fs(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{chat:Zr("chat",t.chat),code:Zr("code",t.code),terminal:Zr("terminal",t.terminal)}}function Zr(e,t){const n=Vs[e],r=t&&typeof t=="object"&&!Array.isArray(t)?t:{},o=typeof r.preset=="string"?r.preset.trim():"",a=typeof r.customFamily=="string"?r.customFamily.trim():"";return(e==="chat"?SM:CM).has(o)?o==="custom"?a?{preset:"custom",customFamily:a}:n:{preset:o}:n}function eo(e,t){var o;const n=Zr(e,t);if(n.preset==="custom"&&n.customFamily)return n.customFamily;const r=e==="chat"?Wo:hr;return((o=r.find(a=>a.id===n.preset))==null?void 0:o.family)||r[0].family}function jM(e){const t=fs(e),n=eo("chat",t.chat),r=eo("code",t.code),o=eo("terminal",t.terminal);return{"--chat-font-family":n,"--chat-code-font-family":r,"--chat-terminal-font-family":o,"--chat-tool-font-family":o}}function Hs(e,t=document.documentElement){const n=fs(e),r=jM(n);t.setAttribute("data-standalone-fonts","custom");for(const[o,a]of Object.entries(r))t.style.setProperty(o,a);return n}function vi(e){const t=fs(e);try{localStorage.setItem(nm,JSON.stringify(t))}catch{}return t}function NM(){try{const e=localStorage.getItem(nm);if(e)return fs(JSON.parse(e))}catch{}return Vs}function AM(){return Hs(NM())}function Kn(e,t){var r;const n=e==="chat"?Wo:hr;return((r=n.find(o=>o.id===t))==null?void 0:r.label)||n[0].label}function TM({children:e}){const t=pr(),n=ki(),{t:r}=Le("common"),o=l.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:s.jsx(Kd,{}),label:r("standalone.nav.dashboard"),active:n.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:s.jsx(Is,{}),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(So,{}),label:r("standalone.nav.settings"),active:n.pathname.startsWith("/settings"),onSelect:()=>t("/settings")}],[n.pathname,t,r]),a=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(Ni,{}),active:n.pathname==="/about",onSelect:()=>t("/about"),title:r("standalone.nav.about")}],[n.pathname,t,r]);return s.jsx(Ak,{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:o,footerItems:a,footerInfo:({collapsed:i})=>i?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","0.9.82"]}),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 IM=[{icon:s.jsx(Is,{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(Yd,{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(ar,{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."}],MM=[{icon:s.jsx($f,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(Kd,{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(Mf,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(zd,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Lf,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],DM=[{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 PM(){const{t:e}=Le("common");return s.jsxs(gr,{icon:s.jsx(Ni,{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","0.9.82"]}),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:IM.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:Ch.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:Nh.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:jh.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:MM.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:DM.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(Ro,{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(zf,{size:14,className:"mr-1"}),e("standalone.about.discord")]})]})})]})}function $a(e,t,n){return{...e,[t]:n}}function Ba({surface:e,title:t,description:n,value:r,options:o,onChange:a}){const{t:i}=Le("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(Dk,{value:r.preset,onChange:c=>{const u=c.target.value;a(u==="custom"?{preset:"custom",customFamily:r.customFamily||""}:{preset:u})},children:o.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=>a({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:eo(e,r)})]})]})]})}function LM({value:e,savedValue:t,saving:n=!1,error:r,notice:o,onChange:a,onSave:i,onResetToSaved:c,onResetToDefaults:u}){const{t:h}=Le("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:h("standalone.fonts.fontOverridesNotice")}),r&&s.jsx(Gt,{variant:"error",children:r}),o&&s.jsx(Gt,{variant:"success",children:o}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(Ba,{surface:"chat",title:h("standalone.fonts.chat"),description:h("standalone.fonts.chatDescription"),value:e.chat,options:Wo,onChange:m=>a($a(e,"chat",m))}),s.jsx(Ba,{surface:"code",title:h("standalone.fonts.code"),description:h("standalone.fonts.codeDescription"),value:e.code,options:hr,onChange:m=>a($a(e,"code",m))}),s.jsx(Ba,{surface:"terminal",title:h("standalone.fonts.terminal"),description:h("standalone.fonts.terminalDescription"),value:e.terminal,options:hr,onChange:m=>a($a(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:h("standalone.fonts.livePreview")}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",Kn("chat",e.chat.preset)," · Code: ",Kn("code",e.code.preset)," · Terminal: ",Kn("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[h("standalone.fonts.defaults")," ",Kn("chat",Vs.chat.preset)," / ",Kn("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:h(n?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),s.jsx(ks,{type:"button",variant:"secondary",size:"sm",onClick:c,disabled:n||!d,children:h("standalone.fonts.revertToSaved")}),s.jsx(ks,{type:"button",variant:"secondary",size:"sm",onClick:u,disabled:n,children:h("standalone.fonts.resetToDefaults")})]})]})}function RM(){const{t:e}=Le("common"),{ides:t}=gs(),n=t.find(W=>W.type==="adhdev-daemon"),r=(n==null?void 0:n.detectedIdes)||[],{sendCommand:o}=yt(),{userName:a}=gs(),[i,c]=l.useState(a||""),[u,h]=l.useState(null),[d,m]=l.useState(null),[f,x]=l.useState(Vs),[w,p]=l.useState(!1),[y,k]=l.useState(""),[b,j]=l.useState(""),[S,v]=l.useState("127.0.0.1"),[g,N]=l.useState(""),[C,A]=l.useState(""),[T,M]=l.useState(""),[L,P]=l.useState(""),[B,K]=l.useState(""),[F,R]=l.useState(!1),Q=async()=>{const oe=await(await ms("/auth/session")).json();h(oe)},E=async()=>{const oe=await(await ms("/api/v1/standalone/preferences")).json();m(oe),v(oe.standaloneBindHost);const V=fs(oe.standaloneFontPreferences);x(V),Hs(V),vi(V)};l.useEffect(()=>{a!==void 0&&c(a)},[a]),l.useEffect(()=>{Promise.all([Q(),E()]).catch(W=>{P(W instanceof Error?W.message:String(W))})},[]),l.useEffect(()=>{Hs(f)},[f]);const I=W=>{const oe=W.target.value.trim();n!=null&&n.id&&oe!==a&&o(n.id,"set_user_name",{userName:oe}).catch(console.error)},[$,D]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),U=W=>{D(W);try{localStorage.setItem("adhdev_sound",W?"1":"0")}catch{}},Y=async()=>{k(""),j(""),p(!0);try{const W=fs(f),oe=await ms("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:W})}),V=await oe.json();if(!oe.ok)throw new Error((V==null?void 0:V.error)||"Failed to save standalone font preferences");const ie=fs(V.standaloneFontPreferences);m(V),x(ie),Hs(ie),vi(ie),j(e("standalone.settings.fontsSaved"))}catch(W){k(W instanceof Error?W.message:String(W))}finally{p(!1)}},ae=()=>{const W=fs(d==null?void 0:d.standaloneFontPreferences);k(""),j(""),x(W),Hs(W)},z=()=>{k(""),j(""),x(Vs),Hs(Vs)},X=async()=>{P(""),K(""),R(!0);try{const W=await ms("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:S})}),oe=await W.json();if(!W.ok)throw new Error((oe==null?void 0:oe.error)||"Failed to save standalone network preference");m(oe),v(oe.standaloneBindHost),K(oe.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(W){P(W instanceof Error?W.message:String(W))}finally{R(!1)}},de=async()=>{if(P(""),K(""),C.trim().length<4){P(e("standalone.settings.passwordTooShort"));return}if(C!==T){P(e("standalone.settings.passwordMismatch"));return}R(!0);try{const W=await ms("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:g,newPassword:C})}),oe=await W.json();if(!W.ok)throw new Error((oe==null?void 0:oe.error)||"Failed to save password");h(oe),await E(),N(""),A(""),M(""),K(u!=null&&u.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),tm()}catch(W){P(W instanceof Error?W.message:String(W))}finally{R(!1)}},re=async()=>{P(""),K(""),R(!0);try{const W=await ms("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:g,clear:!0})}),oe=await W.json();if(!W.ok)throw new Error((oe==null?void 0:oe.error)||"Failed to clear password");h(oe),await E(),N(""),A(""),M(""),K(e("standalone.settings.passwordDisabled"))}catch(W){P(W instanceof Error?W.message:String(W))}finally{R(!1)}};return s.jsxs(gr,{icon:s.jsx(So,{className:"text-text-primary"}),title:e("standalone.settings.title"),subtitle:e("standalone.settings.subtitle"),widthClassName:"max-w-5xl",children:[s.jsx(Gt,{variant:"info",children:e("standalone.settings.infoNotice")}),(u==null?void 0:u.publicHostWarning)&&s.jsx(Gt,{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","0.9.82"]}),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:S==="127.0.0.1",onChange:()=>v("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:S==="0.0.0.0",onChange:()=>v("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")}),L&&s.jsx(Gt,{variant:"error",children:L}),B&&s.jsx(Gt,{variant:"success",children:B}),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:g,onChange:W=>N(W.target.value)}),s.jsx(is,{type:"password",placeholder:u!=null&&u.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:C,onChange:W=>A(W.target.value)}),s.jsx(is,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:T,onChange:W=>M(W.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:()=>{re()},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(W=>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 ${W.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:W.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:W.type})]},W.type))})}),s.jsx(bt,{title:e("standalone.settings.machineSection"),description:e("standalone.settings.machineDescription"),children:s.jsx(Fk,{ides:t,emptyMessage:e("standalone.settings.daemonNotConnected")})}),s.jsx(bt,{title:e("standalone.settings.appearanceSection"),description:e("standalone.settings.appearanceDescription"),children:s.jsx(oS,{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(LM,{value:f,savedValue:fs(d==null?void 0:d.standaloneFontPreferences),saving:w,error:y,notice:b,onChange:x,onSave:()=>{Y()},onResetToSaved:ae,onResetToDefaults:z})]})})}),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(Ek,{}),s.jsx(Fs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Kf,{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(If,{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:W=>c(W.target.value),onBlur:I,onKeyDown:W=>{W.key==="Enter"&&W.currentTarget.blur()}})]})})})]})}const EM=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],Yn="adhdev_onboarding_done",_M=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],$M={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function BM({onDone:e}){const{t}=Le("common"),[n,r]=l.useState([]),[o,a]=l.useState(new Set(EM)),[i,c]=l.useState(!0),[u,h]=l.useState(null),[d,m]=l.useState(!1),[f,x]=l.useState(null),[w,p]=l.useState("all");l.useEffect(()=>{let g=!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=>{g||r(C.providers??[])}).catch(C=>{g||h(C instanceof Error?C.message:String(C))}).finally(()=>{g||c(!1)}),()=>{g=!0}},[]);const y=n.filter(g=>w==="all"||g.category===w),k=["cli","ide","extension","acp"].map(g=>({category:g,items:y.filter(N=>N.category===g)})).filter(g=>g.items.length>0),b=l.useCallback(g=>{a(N=>{const C=new Set(N);return C.has(g)?C.delete(g):C.add(g),C})},[]),j=l.useCallback(async()=>{if(o.size===0){localStorage.setItem(Yn,"1"),e();return}m(!0);const g=[];for(const N of o)try{const A=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:N})})).json().catch(()=>({}));g.push({type:N,ok:!!A.success,error:A.error})}catch(C){g.push({type:N,ok:!1,error:C instanceof Error?C.message:String(C)})}x(g),m(!1),g.every(N=>N.ok)&&localStorage.setItem(Yn,"1")},[o,e]),S=l.useCallback(()=>{localStorage.setItem(Yn,"1"),e()},[e]),v=l.useCallback(()=>{f&&f.every(g=>g.ok)?e():d||S()},[f,d,e,S]);return s.jsx(Du,{open:!0,onClose:v,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(o.size!==1?"standalone.onboarding.selectedCount_other":"standalone.onboarding.selectedCount_one",{count:o.size})}),s.jsxs("div",{className:"ml-auto flex gap-2",children:[s.jsx(ks,{variant:"secondary",size:"sm",onClick:S,disabled:d,children:t("standalone.onboarding.skip")}),s.jsx(ks,{variant:"primary",size:"sm",onClick:()=>{f?(localStorage.setItem(Yn,"1"),e()):j()},disabled:d||!f&&o.size===0,children:d?t("standalone.onboarding.installing"):f?t("standalone.onboarding.done"):t("standalone.onboarding.installCount",{count:o.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:_M.map(g=>{const N=g.key==="all"?n.length:n.filter(C=>C.category===g.key).length;return N===0&&g.key!=="all"?null:s.jsxs("button",{onClick:()=>p(g.key),className:`machine-btn text-[10px] px-2 py-0.5 ${w===g.key?"bg-accent-primary/12 border-accent-primary/40 text-accent-primary":""}`,children:[g.label," ",s.jsxs("span",{className:"opacity-60",children:["(",N,")"]})]},g.key)})}),i&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.loadingRegistry")}),!i&&u&&s.jsx(Gt,{variant:"error",children:t("standalone.onboarding.loadError",{error:u})}),!i&&!u&&y.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.noProviders")}),!i&&!u&&y.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:k.map(g=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:$M[g.category]??g.category}),s.jsx("div",{className:"grid gap-1.5",children:g.items.map(N=>{var L,P;const C=o.has(N.type),A=f==null?void 0:f.find(B=>B.type===N.type),T=((L=N.manifest)==null?void 0:L.icon)??"📦",M=((P=N.manifest)==null?void 0:P.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:T}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"text-[13px] font-medium text-text-primary truncate",children:N.displayName}),M&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:M})]}),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)})})]},g.category))})]})})}function FM(){try{return localStorage.getItem(Yn)==="1"}catch{return!1}}wk();Qk();dy();AM();const HM=Bd({baseUrl:"",getToken:bl});function WM({children:e}){const{t}=Le("common"),[n,r]=l.useState(null),[o,a]=l.useState(!0),[i,c]=l.useState(""),[u,h]=l.useState(""),[d,m]=l.useState(!1),f=async()=>{a(!0),h("");try{const p=await(await ms("/auth/session")).json();r(p)}catch(w){h(w instanceof Error?w.message:String(w))}finally{a(!1)}};l.useEffect(()=>{f()},[]),l.useEffect(()=>{if(!n||n.required&&!n.authenticated)return;let w=!1;return(async()=>{try{const p=await ms("/api/v1/standalone/preferences");if(!p.ok)return;const y=await p.json();if(w)return;const k=fs(y.standaloneFontPreferences);Hs(k),vi(k)}catch{}})(),()=>{w=!0}},[n==null?void 0:n.authenticated,n==null?void 0:n.required]);const x=async w=>{w.preventDefault(),m(!0),h("");try{const p=await ms("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),y=await p.json();if(!p.ok)throw new Error((y==null?void 0:y.error)||"Login failed");r(y),c(""),tm()}catch(p){h(p instanceof Error?p.message:String(p))}finally{m(!1)}};return o?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:x,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(Gt,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),u&&s.jsx(Gt,{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 Dd(){const{t:e}=Le("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(o=>o.daemonMode||o.type==="adhdev-daemon");return r?s.jsx(Wa,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Wa,{to:"/dashboard",replace:!0})}function OM(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let n=!1;if(!FM())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(BM,{onDone:()=>t(!1)}):null}function UM(){const{t:e}=Le("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:o,responseError:a,isSubmitting:i,submit:c,cancel:u,reopen:h}=Lh(n);return o?s.jsxs("div",{className:"relative",children:[!r&&s.jsx("button",{type:"button",onClick:h,className:"fixed bottom-4 right-4 z-[79] btn btn-primary btn-sm shadow-lg",children:e("standalone.machine.awaitingInput")}),s.jsx(cu,{promptSession:r,isSubmitting:i,error:a,onSubmit:c,onCancel:u})]}):null}function GM(){const e=l.useMemo(()=>({sendCommand:rr,sendData:yi,sendPtyInput:sm}),[]);return s.jsx(Om,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(cf,{client:HM,children:s.jsx(WM,{children:s.jsx(kM,{children:s.jsx(uf,{value:e,children:s.jsxs(ff,{sendDaemonCommand:rr,children:[s.jsx(UM,{}),s.jsxs(TM,{children:[s.jsx(OM,{}),s.jsxs(Um,{children:[s.jsx(js,{path:"/dashboard",element:s.jsx(qA,{})}),s.jsx(js,{path:"/machine",element:s.jsx(Dd,{})}),s.jsx(js,{path:"/machines/:id",element:s.jsx(tI,{})}),s.jsx(js,{path:"/machines",element:s.jsx(Dd,{})}),s.jsx(js,{path:"/about",element:s.jsx(PM,{})}),s.jsx(js,{path:"/settings",element:s.jsx(RM,{})}),s.jsx(js,{path:"/mesh",element:s.jsx(hM,{children:s.jsx(cM,{})})}),s.jsx(js,{path:"*",element:s.jsx(Wa,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}m0({connectionManager:ps});Gm(document.getElementById("root")).render(s.jsx(GM,{}));