@adhdev/daemon-standalone 0.9.82-rc.565 → 0.9.82-rc.566

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-CqjiB824.js","assets/vendor-B6OqYKvq.js","assets/terminal-6GBZ9nXN.css"])))=>i.map(i=>d[i]);
2
+ var xh=Object.defineProperty;var vh=(e,t,n)=>t in e?xh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var st=(e,t,n)=>vh(e,typeof t!="symbol"?t+"":t,n);import{r as l,j as s,u as Ne,M as ki,a as yh,b as wh,c as kh,t as Sh,d as Ch,i as wt,e as jh,f as fn,R as Rt,T as Bo,g as mr,h as Fo,k as Oo,D as Nh,E as Ah,l as Ih,C as Th,m as Mh,B as Dh,n as Ph,o as Lh,p as Rh,H as yr,P as Cs,q as Eh,s as _h,v as $h,w as Hh,x as Bh,y as Fh,z as Si,A as Oh,F as Wh,G as Uh,I as Gh,J as js,N as Wo,K as qh}from"./vendor-B6OqYKvq.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const o of a)if(o.type==="childList")for(const i of o.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&r(i)}).observe(document,{childList:!0,subtree:!0});function n(a){const o={};return a.integrity&&(o.integrity=a.integrity),a.referrerPolicy&&(o.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?o.credentials="include":a.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(a){if(a.ep)return;a.ep=!0;const o=n(a);fetch(a.href,o)}})();function zh(e={}){const t=Math.max(1,Math.floor(e.capacity||200)),n=[];return{record(r){const a={id:`webdbg_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,ts:Date.now(),...r,payload:r.payload?{...r.payload}:{}};return n.push(a),n.length>t&&n.splice(0,n.length-t),a},list(r={}){const a=Math.max(1,Math.floor(r.limit||100));return n.filter(o=>!r.interactionId||o.interactionId===r.interactionId).filter(o=>!r.topic||o.topic===r.topic).filter(o=>!r.kind||o.kind===r.kind).slice(-a).map(o=>({...o,payload:o.payload?{...o.payload}:{}}))},clear(){n.splice(0,n.length)}}}const bn=zh();function Cl(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 Kh(e,t){return typeof e=="string"&&e.trim().length>0&&e!==t}function jl(e){return Array.isArray(e)?[...e]:[]}function Ld(e,t){if(!e)return t??null;const n=Object.prototype.hasOwnProperty.call(e,"messages"),r=Object.prototype.hasOwnProperty.call(e,"activeModal"),a=typeof e.id=="string"?e.id.trim():"",o=typeof(t==null?void 0:t.id)=="string"?t.id.trim():"",i=!!a&&!!o&&a!==o;return t?{...t,...e,messages:n?jl(e.messages):i?[]:t.messages,activeModal:r?e.activeModal??null:t.activeModal,inputContent:e.inputContent??t.inputContent}:{...e,...n?{messages:jl(e.messages)}:{},...r?{activeModal:e.activeModal??null}:{}}}function zn(e,t){const n=Kh(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:Ld(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 Rd(e,t,n){if(!(t!=null&&t.length))return(n==null?void 0:n.preserveMissing)===!1&&Array.isArray(t)?t:e;if(!(e!=null&&e.length))return t;const r=t.map(a=>{const o=e.find(i=>i.id===a.id);return o?zn(a,o):a});if((n==null?void 0:n.preserveMissing)!==!1){const a=new Set(t.map(o=>o.id));for(const o of e)a.has(o.id)||r.push(o)}return r}function Nl(e){return!!e&&typeof e=="object"&&"text"in e}function Ci(e,t){const n=(t==null?void 0:t.joiner)??" ",r=(t==null?void 0:t.normalizeWhitespace)??!1;let a="";return typeof e=="string"?a=e:Array.isArray(e)?a=e.map(o=>typeof o=="string"?o:Nl(o)?String(o.text||""):"").join(n):Nl(e)?a=String(e.text||""):a=String(e||""),r?a.replace(/\s+/g," ").trim():a}function gn(e){return Ci(e,{normalizeWhitespace:!0})}function Vh(e){let t="";for(let n=0;n<e.length;n++){const r=e[n],a=e.charCodeAt(n);if(!(a<=31&&r!==`
3
+ `&&r!==" ")&&!(a>=127&&a<=159)&&!(a>=8203&&a<=8207||a>=8234&&a<=8238||a===8288||a===65279)&&a!==65533){if(a===65038||a===65039){const o=t.length>0?t[t.length-1]:"";if(!o||o===`
4
+ `||o===" "||o===" ")continue}t+=r}}return t}function Al(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 Ed(e,t,n){if(n.type!=="adhdev-daemon")return n;const r={...n},a=t.version??n.version??e.version,o=t.serverVersion??e.serverVersion??n.serverVersion,i=t.versionMismatch===!0||e.versionMismatch===!0,c=t.versionUpdateRequired===!0||e.versionUpdateRequired===!0,d=t.versionUpdateReason??e.versionUpdateReason??n.versionUpdateReason;return a&&(r.version=a),o&&(r.serverVersion=o),d&&(r.versionUpdateReason=d),a&&o&&a===o?(delete r.versionMismatch,delete r.serverVersion,delete r.versionUpdateRequired,delete r.versionUpdateReason,r):((t.versionMismatch===!0||i&&a&&o&&a!==o)&&(r.versionMismatch=!0),c&&(r.versionUpdateRequired=!0),r)}function Yh(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 Wa(e){if(!e||typeof e!="object")return"";const t=e,n=Yh(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 Jh(e,t){if(!Array.isArray(e))return e;if(t!=null&&t.has(e))return{count:e.length,sharedRef:!0};let n=2166136261;for(const r of e){const a=Wa(r);for(let o=0;o<a.length;o+=1)n^=a.charCodeAt(o),n=Math.imul(n,16777619)>>>0}return{count:e.length,hash:n.toString(16).padStart(8,"0"),first:Wa(e[0]),last:Wa(e[e.length-1])}}function Uo(e){return!!e&&typeof e=="object"&&"messages"in e&&("activeModal"in e||"inputContent"in e||"status"in e)}function Go(e,t,n){if(!e||!t||typeof e!="object"||typeof t!="object")return;if(Uo(e)&&Uo(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)Go(e[c],t[c],n);return}const r=e,a=t,o=new Set([...Object.keys(r),...Object.keys(a)]);for(const i of o)i!=="messages"&&Go(r[i],a[i],n)}function Jn(e,t){return Array.isArray(e)?e.map(n=>Jn(n,t)):!e||typeof e!="object"?e:Uo(e)?Object.fromEntries(Object.entries(e).filter(([r])=>r!=="timestamp"&&r!=="_lastUpdate").sort(([r],[a])=>r.localeCompare(a)).map(([r,a])=>[r,r==="messages"?Jh(a,t):Jn(a,t)])):Object.fromEntries(Object.entries(e).filter(([n])=>n!=="timestamp"&&n!=="_lastUpdate").sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>[n,Jn(r,t)]))}function Qh(e,t){try{const n=new WeakSet;return Go(e,t,n),JSON.stringify(Jn(e,n))===JSON.stringify(Jn(t,n))}catch{return!1}}function qo(e,t,n){return Qh(e,t)?(e._lastUpdate=n,typeof t.timestamp=="number"&&(e.timestamp=t.timestamp),e):t}function _d(e){var t;return e.daemonId||((t=e.id)==null?void 0:t.split(":")[0])||e.id}function Xh(e,t,n){t[n]!==void 0&&(e[n]=t[n])}function Il(e,t,n,r){var d;const a=(d=t.chats)!=null&&d.length?t.chats:e.chats,o=Rd(e.childSessions,t.childSessions,{preserveMissing:r}),i=Ld(t.activeChat,e.activeChat),c=t.workspace||e.workspace;return Ed(e,t,{...e,...t,chats:a,childSessions:o,activeChat:i,workspace:c,_lastUpdate:n})}function Zh(e,t,n){var a,o;const r={};t.status&&t.status!==e.status&&(r.status=t.status),t.cdpConnected!==void 0&&(r.cdpConnected=t.cdpConnected),t.childSessions!==void 0&&(r.childSessions=Rd(e.childSessions,t.childSessions,{preserveMissing:n})),(a=t.chats)!=null&&a.length&&!((o=e.chats)!=null&&o.length)&&(r.chats=t.chats),t.workspace&&(r.workspace=t.workspace);for(const i of["title","providerSessionId","parentSessionId","sessionKind","sessionCapabilities","controlValues","providerControls","summaryMetadata","activeInteractivePrompt","lastMessagePreview","lastMessageRole","lastMessageAt","lastMessageHash","lastUpdated","unread","lastSeenAt","inboxBucket","completionMarker","seenCompletionMarker","surfaceHidden","muted","runtimeKey","runtimeDisplayName","runtimeWorkspaceLabel","runtimeWriteOwner","runtimeAttachedClients","version","serverVersion","versionUpdateReason","versionUpdateRequired","updateCommand","updatePolicy","updateChannel","releaseChannel"])Xh(r,t,i);return t.machineNickname!==void 0&&t.machineNickname!==e.machineNickname&&(r.machineNickname=t.machineNickname),t.versionMismatch===!0&&(r.versionMismatch=!0),r}function ef(e,t,n,r){const a=Zh(e,t,r),o=Object.keys(a).length>0?Ed(e,t,{...e,...a,_lastUpdate:n}):{...e,_lastUpdate:n};return qo(e,o,n)}function tf(e){const t=new Set(e.map(o=>o.id)),n=new Set,r=new Set,a=new Set;for(const o of e){const i=_d(o);i&&n.add(i),i&&o.type!=="adhdev-daemon"&&r.add(i),i&&o.type==="adhdev-daemon"&&o._sessionListAuthoritative&&a.add(i)}return{incomingIds:t,incomingDaemonIds:n,daemonIdsWithSessionEntries:r,daemonIdsWithAuthoritativeSessionList:a}}function sf(e,t,n,r,a,o){return!a.has(t)||!o.has(t)||r.has(e.id)?!1:e.transport==="pty"||e.transport==="acp"?n>1e4:e.transport==="cdp-page"?n>3e4:!1}function nf(e,t,n,r,a){return e.transport?n.has(t)&&!r.has(t)?!0:a.has(t):!1}function rf(e,t,n){var u,m;const r=Date.now(),a=new Set((n==null?void 0:n.authoritativeDaemonIds)||[]);if(t.length===0)return e.map(f=>({...f,_lastUpdate:r}));const o=new Map;for(const f of t)o.set(f.id,f);const{incomingIds:i,incomingDaemonIds:c,daemonIdsWithSessionEntries:d,daemonIdsWithAuthoritativeSessionList:p}=tf(e);for(const f of e){const g=o.get(f.id);if(!g){o.set(f.id,{...f,_lastUpdate:r});continue}const C=Al(f),h=Al(g),x=_d(f),y=!a.has(x);if(C>h){const k=Il(g,f,r,y);o.set(f.id,qo(g,k,r));continue}if(C<h){o.set(f.id,ef(g,f,r,y));continue}const b=f.timestamp||r,S=g._lastUpdate||g.timestamp||0;if(b>=S){const k=Il(g,f,r,y);o.set(f.id,qo(g,k,r));continue}(u=f.chats)!=null&&u.length&&!((m=g.chats)!=null&&m.length)&&o.set(f.id,{...g,chats:f.chats})}for(const[f,g]of o){const C=g.daemonId||f.split(":")[0];if(!c.has(C))continue;if(a.has(C)&&p.has(C)&&!i.has(f)){o.delete(f);continue}const h=r-(g._lastUpdate||g.timestamp||0);sf(g,C,h,i,a,d)&&o.delete(f)}for(const[f,g]of o){const C=g.daemonId||f.split(":")[0];if(nf(g,C,c,d,o))continue;r-(g._lastUpdate||g.timestamp||0)>3e5&&g.status!=="online"&&o.delete(f)}return Array.from(o.values())}function af(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}),Hd=l.createContext({injectEntries:()=>{},markLoaded:()=>{},getIdes:()=>[]});function of({children:e,connectionOverrides:t}){const[n,r]=l.useState([]),[a,o]=l.useState(!1),[i,c]=l.useState([]),[d,p]=l.useState(void 0),u=l.useRef(n);l.useEffect(()=>{u.current=n},[n]);const m=l.useCallback((y,b)=>{r(S=>{let k=!1;const w=S.map(v=>v.id!==y||v.chats===b?v:(k=!0,{...v,chats:b}));return k?w:S})},[]),f=l.useCallback((y,b)=>{r(S=>{const k=S.length===0?y:rf(y,S,b),w=!af(S,k);return w&&bn.record({kind:"dashboard.entries_applied",payload:{incoming:Cl(y),next:Cl(k)}}),w?k:S})},[]),g=l.useCallback(()=>o(!0),[]),C=l.useMemo(()=>({injectEntries:f,markLoaded:g,getIdes:()=>u.current}),[f,g]),h=t,x=l.useMemo(()=>({ides:n,updateRouteChats:m,initialLoaded:a,toasts:i,setToasts:c,wsStatus:(h==null?void 0:h.wsStatus)??"connected",isConnected:(h==null?void 0:h.isConnected)??!0,connectionStates:(h==null?void 0:h.connectionStates)??{},connectionTransports:(h==null?void 0:h.connectionTransports)??{},showReconnected:(h==null?void 0:h.showReconnected)??!1,retryConnection:h==null?void 0:h.retryConnection,retryServerConnection:h==null?void 0:h.retryServerConnection,connectionLoginUrl:h==null?void 0:h.connectionLoginUrl,isP2PActive:(h==null?void 0:h.isP2PActive)??!1,p2pStates:(h==null?void 0:h.p2pStates)??{},userRole:h==null?void 0:h.userRole,connectionRetryStatuses:h==null?void 0:h.connectionRetryStatuses,userName:d,setUserName:p}),[n,m,a,i,h==null?void 0:h.wsStatus,h==null?void 0:h.isConnected,h==null?void 0:h.connectionStates,h==null?void 0:h.connectionTransports,h==null?void 0:h.showReconnected,h==null?void 0:h.retryConnection,h==null?void 0:h.retryServerConnection,h==null?void 0:h.connectionLoginUrl,h==null?void 0:h.isP2PActive,h==null?void 0:h.p2pStates,h==null?void 0:h.userRole,h==null?void 0:h.connectionRetryStatuses,d]);return s.jsx(Hd.Provider,{value:C,children:s.jsx($d.Provider,{value:x,children:e})})}function gs(){return l.useContext($d)}function ar(){return l.useContext(Hd)}function Bd(e){const{baseUrl:t,getToken:n,onUnauthorized:r}=e;function a(c){return c.startsWith("http")?c:`${t}${c.startsWith("/")?"":"/"}${c}`}function o(c){const d=n==null?void 0:n(),p=a(c),u=c.startsWith("http")?new URL(p):new URL(p,typeof window<"u"?window.location.origin:"http://localhost");return d&&u.searchParams.set("token",d),!c.startsWith("http")&&!t?`${u.pathname}${u.search}${u.hash}`:u.toString()}async function i(c,d={}){const p={"Content-Type":"application/json",...d.headers||{}},u=n==null?void 0:n();u&&(p.Authorization=`Bearer ${u}`);const m=a(c),f=new AbortController,g=setTimeout(()=>f.abort(),15e3);try{const C=await fetch(m,{...d,headers:p,signal:f.signal});if(C.status===401)throw r==null||r(),new Error("Unauthorized");if(!C.ok){const h=await C.json().catch(()=>({error:C.statusText}));throw new Error(h.error||`API Error: ${C.status}`)}return C.json()}finally{clearTimeout(g)}}return{getDaemons:()=>i("/api/v1/daemons"),getDaemonStatus:c=>i(`/api/v1/daemons/${c}/status`),sendCommand:(c,d,p={})=>i(`/api/v1/daemons/${c}/command`,{method:"POST",body:JSON.stringify({type:d,payload:p})}),execTerminal:(c,d,p)=>i(`/api/v1/daemons/${c}/terminal`,{method:"POST",body:JSON.stringify({command:d,name:p})}),sendAgentMessage:(c,d,p)=>i(`/api/v1/shortcuts/${c}/chat`,{method:"POST",body:JSON.stringify({agentType:d,message:p})}),getAgentStatus:c=>i(`/api/v1/shortcuts/${c}/status`),approveAgent:(c,d,p)=>i(`/api/v1/shortcuts/${c}/approve`,{method:"POST",body:JSON.stringify({agentType:d,action:p?"approve":"reject"})}),getMuxState:c=>i(`/api/v1/mux/${encodeURIComponent(c)}/state`),getMuxSocketInfo:c=>i(`/api/v1/mux/${encodeURIComponent(c)}/socket-info`),controlMux:(c,d,p={})=>i(`/api/v1/mux/${encodeURIComponent(c)}/control`,{method:"POST",body:JSON.stringify({type:d,payload:p})}),getMuxEventsUrl:c=>o(`/api/v1/mux/${encodeURIComponent(c)}/events`),getRuntimeEventsUrl:c=>o(`/api/v1/runtime/${encodeURIComponent(c)}/events`),request:i}}const lf=Bd({baseUrl:"http://localhost:3847"}),cf=l.createContext(lf);function df({client:e,children:t}){return s.jsx(cf.Provider,{value:e,children:t})}const uf={sendCommand:async()=>{throw new Error("TransportContext not initialized")}},Fd=l.createContext(uf);function pf({value:e,children:t}){return s.jsx(Fd.Provider,{value:e,children:t})}function vt(){return l.useContext(Fd)}function Od(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function mf(e){const t=Od(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 hf(e){const[t,n]=l.useState(null),r=l.useCallback(async(i,c)=>{const d=m=>e(i,"launch_cli",{...c,...m}),p=await d({}),u=mf(p);return u?new Promise(m=>{n({providerType:u.providerType||String(c.cliType??"?"),sourceName:u.sourceName,description:u.description,retry:()=>d({confirmExternalUntrusted:!0}),resolve:f=>{f.cancelled?m({success:!1,error:"user_cancelled_untrusted_launch"}):m(f.response)}})}):p},[e]),a=l.useCallback(async()=>{const i=t;if(i){n(null);try{const c=await i.retry(),d=Od(c);d!=null&&d.success?i.resolve({ok:!0,response:c}):i.resolve({ok:!1,error:(d==null?void 0:d.error)||"launch failed after confirm",response:c})}catch(c){i.resolve({ok:!1,error:(c==null?void 0:c.message)||String(c)})}}},[t]),o=l.useCallback(()=>{const i=t;i&&(n(null),i.resolve({ok:!1,cancelled:!0}))},[t]);return{launchCli:r,pending:t,confirm:a,cancel:o}}function ff({providerType:e,sourceName:t,description:n,onConfirm:r,onCancel:a}){const{t:o}=Ne("common"),i=l.useRef(null);return l.useEffect(()=>{var c;(c=i.current)==null||c.focus()},[]),l.useEffect(()=>{const c=d=>{d.key==="Escape"&&a()};return window.addEventListener("keydown",c),()=>window.removeEventListener("keydown",c)},[a]),s.jsx("div",{role:"dialog","aria-modal":"true","aria-label":o("machine.confirmExternal.dialogAria"),className:"fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4",onClick:a,style:{pointerEvents:"auto"},children:s.jsxs("div",{className:"bg-[var(--surface-primary)] text-text-primary border border-amber-500/40 rounded-lg shadow-xl max-w-lg w-full",onClick:c=>c.stopPropagation(),children:[s.jsxs("div",{className:"px-4 py-3 border-b border-border-subtle flex items-center gap-2",children:[s.jsx("span",{"aria-hidden":!0,className:"text-amber-400 text-base",children:"⚠"}),s.jsx("h2",{className:"text-sm font-semibold",children:o("machine.confirmExternal.title")})]}),s.jsxs("div",{className:"px-4 py-3 text-[12px] flex flex-col gap-3",children:[s.jsxs("p",{children:["You're about to activate ",s.jsx("span",{className:"font-mono",children:e}),t?s.jsxs(s.Fragment,{children:[" from ",s.jsx("span",{className:"font-mono",children:t})]}):null,"."]}),s.jsx("p",{className:"text-text-secondary",children:n??o("machine.confirmExternal.description")}),s.jsx("p",{className:"text-text-secondary",children:o("machine.confirmExternal.proceedWarning")})]}),s.jsxs("div",{className:"px-4 py-2 border-t border-border-subtle flex justify-end gap-2",children:[s.jsx("button",{ref:i,type:"button",onClick:a,className:"px-3 py-1 text-sm rounded border border-border-default hover:bg-surface-secondary",children:o("machine.confirmExternal.cancel")}),s.jsx("button",{type:"button",onClick:r,className:"px-3 py-1 text-sm rounded bg-amber-500 text-black font-semibold hover:opacity-90",children:o("machine.confirmExternal.activate")})]})]})})}const Wd=l.createContext(null);function bf({sendDaemonCommand:e,children:t}){const n=hf(e),r=l.useMemo(()=>({launchCli:n.launchCli}),[n.launchCli]);return s.jsxs(Wd.Provider,{value:r,children:[t,n.pending&&s.jsx(ff,{providerType:n.pending.providerType,sourceName:n.pending.sourceName,description:n.pending.description,onConfirm:n.confirm,onCancel:n.cancel})]})}function wa(){const e=l.useContext(Wd);return e||{launchCli:async()=>{throw new Error("useLaunchCli must be used inside <LaunchCliProvider>")}}}function Ud(e){return e?new Date(e).toLocaleTimeString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0}):""}function gf(e,t,n){return Number(e.receivedAt||n[ta(e)]||0)||0}function Gd(e){return/[`*_#[\]()>-]|https?:\/\/|\n\s*[-*]\s|\n\s*\d+\.\s|\|/.test(e)}function xf(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 Ua(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 vf(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 ta(e,t){const n=e,r=Ci(e.content,{joiner:`
5
+ `}),a=[e.id?`id:${e.id}`:"",n._localId?`local:${n._localId}`:"",n._turnKey?`turn:${n._turnKey}`:"",e.bubbleId?`bubble:${e.bubbleId}`:"",e.providerUnitKey?`unit:${e.providerUnitKey}`:"",typeof e.index=="number"?`msgIndex:${e.index}`:"",typeof e.sequence=="number"?`seq:${e.sequence}`:""].filter(Boolean);if(a.length>0)return a.join("|");const o=e.receivedAt||e.timestamp||0;return[e.role?`role:${e.role}`:"role:",`chash:${vf(r)}`,o?`ts:${o}`:""].filter(Boolean).join("|")}function yf(e){let t=2166136261;for(const n of e){const r=String(n||"");for(let a=0;a<r.length;a+=1)t^=r.charCodeAt(a),t=Math.imul(t,16777619)>>>0;t^=255,t=Math.imul(t,16777619)>>>0}return t.toString(16).padStart(8,"0")}function wf(e){try{return JSON.stringify(e??"")}catch{return String(e??"")}}function qd(e){return e?yf([String(e.id||""),String(e.index??""),String(e.role||""),String(e.receivedAt??e.timestamp??""),wf(e.content)]):""}const ji=200,kf=80,Tl=650,Ln=new Map;function sa(e,t){if(!e)return!1;const n=String(e.messageFingerprint||"");return n?n===String(t||""):!0}function Sf(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}:${qd(r)}`}function Cf(e,t,n,r){return e||!t?!1:sa(n,r)}function jf({scrollTop:e,scrollHeight:t,clientHeight:n,topThresholdPx:r=kf,bottomThresholdPx:a=ji}){const o=Math.max(0,Number(e)||0),i=Math.max(0,Number(t)||0),c=Math.max(0,Number(n)||0);return Math.max(0,i-c)<=0?{showTop:!1,showBottom:!1}:{showTop:o>r,showBottom:Math.max(0,i-o-c)>a}}function Nf(e){return jf({scrollTop:e.scrollTop,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight})}function Kn(e,t=ji){return!!e&&e.fromBottom>=t}function Af(e,t){return sa(e,t)?!Kn(e):!0}function If({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 Ga(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 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("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 Ni({size:e=Je.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polyline",{points:"15 18 9 12 15 6"})})}function Ts({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"2",y:"2",width:"20",height:"8",rx:"2"}),s.jsx("rect",{x:"2",y:"14",width:"20",height:"8",rx:"2"}),s.jsx("circle",{cx:"6",cy:"6",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("circle",{cx:"6",cy:"18",r:"1",fill:"currentColor",stroke:"none"}),s.jsx("line",{x1:"10",y1:"6",x2:"18",y2:"6"}),s.jsx("line",{x1:"10",y1:"18",x2:"18",y2:"18"})]})}function 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("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 Mf({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 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:"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 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:"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 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:"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 Pf({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 ka({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 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("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 Lf({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("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 Rf({size:e=Je.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("path",{d:"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 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("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 Sa({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("polyline",{points:"23 4 23 10 17 10"}),s.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}function Ys({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),s.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),s.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}function or({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M12 22v-5"}),s.jsx("path",{d:"M9 8V2"}),s.jsx("path",{d:"M15 8V2"}),s.jsx("path",{d:"M18 8v5a6 6 0 0 1-12 0V8z"})]})}function es({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("circle",{cx:"12",cy:"5",r:"2"}),s.jsx("circle",{cx:"5",cy:"19",r:"2"}),s.jsx("circle",{cx:"19",cy:"19",r:"2"}),s.jsx("line",{x1:"12",y1:"7",x2:"5",y2:"17"}),s.jsx("line",{x1:"12",y1:"7",x2:"19",y2:"17"}),s.jsx("line",{x1:"5",y1:"19",x2:"19",y2:"19"})]})}function 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("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 Jd({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"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 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("circle",{cx:"12",cy:"12",r:"10"}),s.jsx("polyline",{points:"12 6 12 12 16 14"})]})}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("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 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("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 Xd({size:e=Je.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})}function Di({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),s.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function At({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.9",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),s.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})}function 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("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 Of({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"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 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:"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 Uf({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 Gf({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("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 eu({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),s.jsx("polyline",{points:"22 4 12 14.01 9 11.01"})]})}function qf({size:e=Je.size,className:t}){return s.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:s.jsx("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})})}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("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 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("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 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("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 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("polyline",{points:"9 14 4 9 9 4"}),s.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]})}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:"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 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:"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 Xf({size:e=Je.size,className:t}){return s.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.75",strokeLinecap:"round",strokeLinejoin:"round",className:t,children:[s.jsx("rect",{x:"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 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("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 tu="adhdev_chat_activity_visible",Ml=new Set(["hidden","debug","internal"]),Dl=new Set(["visible","user","chat"]),eb=new Set(["debug","trace","internal"]),tb=new Set(["tool_call","terminal_command","runtime_activity"]),sb=new Set(["runtime_status","provider_chrome","control"]),nb=new Set(["thought","tool","terminal"]);function su(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 qa(e,t,n){return e[n]??(t==null?void 0:t[n])}function Pl(e,t,n){const r=e;return n.some(a=>r[a]===!0||(t==null?void 0:t[a])===!0)}function rb(e,t){const n=rn(e.kind);return n||(t==="tool"?"tool":"standard")}function za(e,t,n){const r=su(e),a=typeof(r==null?void 0:r.label)=="string"?r.label.trim():"";return a||(t==="terminal"||n==="terminal_command"?"Terminal":t==="tool"||n==="tool_call"?"Tool":t==="thought"?"Thought":n==="runtime_activity"?"Runtime":"Activity")}function ab(e){const t=e.content;return Array.isArray(t)&&t.some(n=>!!n&&typeof n=="object"&&n.type!=="text")}function Pi(e){if(!e)return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:"",kind:"standard",label:"Internal"};const t=su(e),n=rn(e.role),r=rb(e,n),a=rn(qa(e,t,"visibility")),o=rn(e.transcriptVisibility??(t==null?void 0:t.transcriptVisibility)??a),i=rn(qa(e,t,"audience")),c=rn(qa(e,t,"source")),d=Ml.has(a)||Ml.has(o)||eb.has(i)||Pl(e,t,["internal","isInternal","debug","statusOnly","controlOnly"]),p=Dl.has(a)||Dl.has(o)||i==="chat"||Pl(e,t,["userFacing"]),u=nb.has(r)||tb.has(c);if(d)return{surface:u?"activity":"internal",isUserFacing:!1,isActivityFacing:u,isInternal:!u,role:n,kind:r,label:za(e,r,c)};if(p)return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:n,kind:r,label:za(e,r,c)};if((n==="system"||r==="system")&&ab(e))return{surface:"chat",isUserFacing:!0,isActivityFacing:!1,isInternal:!1,role:n,kind:r,label:"Chat"};if(sb.has(c)||n==="system"||r==="system")return{surface:"internal",isUserFacing:!1,isActivityFacing:!1,isInternal:!0,role:n,kind:r,label:"Internal"};if(u)return{surface:"activity",isUserFacing:!1,isActivityFacing:!0,isInternal:!1,role:n,kind:r,label:za(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=>Pi(t).isUserFacing)}function nu(e){return(Array.isArray(e)?e:[]).filter(t=>Pi(t).isActivityFacing)}function ru(e){const t=e.content;return typeof t=="string"?t:(()=>{try{return JSON.stringify(t??"")}catch{return String(t??"")}})()}function ib(e){return`${String(e.role||"")}::${ru(e)}`}function lb(e){if(e.length<2)return e;const t=[];let n="";for(const r of e){const a=ib(r);ru(r).trim().length>0&&a===n||(t.push(r),n=a)}return t}function cb(e,t,n){return!n||t.length===0?e:[...e,...t].sort((r,a)=>{const o=Number(r.receivedAt??r.timestamp??0)||0,i=Number(a.receivedAt??a.timestamp??0)||0;if(o!==i)return o-i;const c=Number(r.index??0)||0,d=Number(a.index??0)||0;return c-d})}function Ll(e=typeof localStorage<"u"?localStorage:void 0){try{return(e==null?void 0:e.getItem(tu))==="1"}catch{return!1}}function db({text:e}){const{t}=Ne("common"),[n,r]=l.useState(!1),a=l.useCallback(()=>{navigator.clipboard.writeText(e).catch(()=>{}),r(!0),setTimeout(()=>r(!1),1500)},[e]);return s.jsx("button",{type:"button",onClick:a,"aria-label":t("chat.copyMessage"),className:"chat-copy-btn",children:n?s.jsx(Pf,{size:11}):s.jsx(Yd,{size:11})})}const au=[yh,{singleTilde:!1}],ou=[au,wh,kh],ub=[au];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 Rl(e,t){return e?t?s.jsx("pre",{className:"chat-preformatted",children:e}):Gd(e)?s.jsx(ki,{remarkPlugins:ou,children:e}):s.jsx("div",{style:{whiteSpace:"pre-wrap"},children:e}):null}const pb=l.memo(function({content:t,renderAsPreformatted:n,renderAsMarkdown:r}){return n?s.jsx("pre",{className:"chat-preformatted",children:t}):r?s.jsx(ki,{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:Rl(String(n.text||""),t)},`text-${r}`);if(n.type==="image"){const a=Ua(n),o=n.alt||n.description||Pn(n.uri,"image");return a?s.jsx("img",{src:a,alt:o,className:"max-w-full rounded-md border border-border-subtle"},`image-${r}`):s.jsx("div",{children:wr("Image",o,n.mimeType)},`image-fallback-${r}`)}if(n.type==="audio"){const a=Ua(n);return a?s.jsxs("div",{className:"flex flex-col gap-1",children:[s.jsx("audio",{controls:!0,src:a,className:"max-w-full"}),n.transcript?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:n.transcript}):null]},`audio-${r}`):s.jsx("div",{children:wr("Audio",Pn(n.uri,"audio"),n.transcript||n.mimeType)},`audio-fallback-${r}`)}if(n.type==="video"){const a=Ua(n),o=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:[a?s.jsx("video",{controls:!0,src:a,poster:n.posterUri,className:"max-w-full rounded-md border border-border-subtle"}):wr("Video",o,i),a&&i?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:i}):null]},`video-${r}`)}if(n.type==="resource_link"){const a=n.title||n.name||Pn(n.uri,"resource"),o=[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:a}):wr("Resource",a,o),n.uri&&o?s.jsx("div",{className:"text-sm opacity-80",style:{whiteSpace:"pre-wrap"},children:o}):null]},`resource-link-${r}`)}if(n.type==="resource"&&n.resource){const a=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:a}),Rl(n.resource.text,!0)]},`resource-${r}`);if(n.resource.uri)return s.jsx("a",{href:n.resource.uri,target:"_blank",rel:"noreferrer",className:"underline break-all",children:a},`resource-uri-${r}`)}return null})})}const mb=l.memo(function({log:t}){return s.jsxs("div",{className:"self-center chat-msg-action",children:[s.jsx(ki,{remarkPlugins:ub,children:t.text}),s.jsx("span",{className:"action-time",children:Ud(t.timestamp)})]})},(e,t)=>e.log===t.log);function El(e){const t=e.meta;return[qd(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 hb=l.memo(function({message:t,receivedAt:n,agentName:r,userName:a,isCliMode:o,isTextExpanded:i,onToggleTextExpanded:c}){var j,A,I;const d=(t.role||"").toLowerCase(),p=d==="user"||d==="human",u=t.kind||(d==="tool"?"tool":"standard"),m=Pi(t),f=xf(t.content)?t.content:null,g=!!(f!=null&&f.some(D=>D.type!=="text")),C=Ci(t.content,{joiner:`
8
+ `});if(m.isActivityFacing&&u!=="thought"&&u!=="tool"&&u!=="terminal"){const D=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:D})]}),g&&f?s.jsx("div",{className:"chat-msg-activity-body",children:s.jsx(Rn,{parts:f,renderAsPreformatted:!1})}):s.jsx("div",{className:"chat-msg-activity-body",style:{whiteSpace:"pre-wrap"},children:C})]})}if(u==="thought"){const D=typeof((j=t.meta)==null?void 0:j.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:D})]}),s.jsx("div",{className:"chat-msg-body",children:C})]})}if(u==="tool")return s.jsxs("div",{className:"self-start chat-msg-tool","data-chat-activity-row":m.isActivityFacing?"true":void 0,children:[s.jsxs("div",{className:"chat-msg-tool-meta","aria-label":"Tool message",children:[s.jsx("span",{className:"tool-icon",children:"⏺"}),s.jsx("span",{className:"tool-label",children:"Tool"})]}),g&&f?s.jsx("div",{className:"tool-text w-full",children:s.jsx(Rn,{parts:f,renderAsPreformatted:!1})}):s.jsx("div",{className:"tool-text w-full",style:{whiteSpace:"pre-wrap"},children:C})]});if(u==="terminal"){const D=(A=t.meta)!=null&&A.isRunning?"⏳":"✅",L=typeof((I=t.meta)==null?void 0:I.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:D}),s.jsx("span",{children:L})]}),g&&f?s.jsx("div",{className:"chat-msg-body",children:s.jsx(Rn,{parts:f,renderAsPreformatted:!0})}):s.jsx("pre",{className:"chat-msg-body",children:C})]})}if(u==="system")return s.jsx("div",{className:"self-center chat-msg-system",children:g&&f?s.jsx(Rn,{parts:f,renderAsPreformatted:!1}):C.slice(0,100)});const h=t.meta,y=(typeof(h==null?void 0:h.renderMode)=="string"?h.renderMode.trim():"")==="preformatted",b=C,S=!1,k=b,w=y,v=!p&&!w&&Gd(k),N=["chat-message-row",p?"chat-message-row-user self-end":"chat-message-row-assistant self-start"].join(" ");return s.jsx("div",{className:N,children:(b||g||p)&&s.jsxs("div",{className:`chat-bubble ${p?"chat-bubble-user":"chat-bubble-assistant"}`,children:[s.jsxs("div",{className:`chat-bubble-header ${b||g?"mb-1.5":"mb-0"}`,children:[s.jsx("span",{className:"chat-sender",children:p?a||"You":t.senderName||r}),s.jsxs("span",{className:"chat-bubble-header-end",children:[(b||g)&&s.jsx(db,{text:C}),n!=null&&s.jsx("span",{className:"chat-time",children:Ud(n)})]})]}),(b||g)&&s.jsx("div",{className:"chat-markdown",children:g&&f?s.jsx(Rn,{parts:f,renderAsPreformatted:w}):s.jsx(pb,{content:k,renderAsPreformatted:w,renderAsMarkdown:v})}),S]})})},(e,t)=>(e.message===t.message||El(e.message)===El(t.message))&&e.receivedAt===t.receivedAt&&e.agentName===t.agentName&&e.userName===t.userName&&e.isCliMode===t.isCliMode&&e.isTextExpanded===t.isTextExpanded),fb=l.forwardRef(function({messages:t,actionLogs:n,agentName:r="Agent",userName:a,isCliMode:o=!1,isWorking:i=!1,contextKey:c="",receivedAtMap:d={},lastMessageHash:p,showActivityMessages:u=!1,emptyState:m,onLoadMore:f,isLoadingMore:g,hasMoreHistory:C,hiddenLiveCount:h=0,loadError:x,scrollToBottomRequestNonce:y,isVisible:b=!0},S){const{t:k}=Ne("common"),w=l.useRef(null),v=l.useRef(null),N=l.useRef(null),j=l.useRef(0),A=l.useRef(""),I=l.useRef(""),D=l.useRef(!1),L=l.useRef(null),P=l.useRef(!1),_=l.useRef(null),q=l.useRef(!1),[B,E]=l.useState(new Set),[K,R]=l.useState({showTop:!1,showBottom:!1}),T=l.useRef(!1),H=l.useRef(!1),M=l.useRef(b),W=l.useRef(b),J=l.useRef(null);W.current=b;const re=()=>{const ce=w.current;return ce?ce.scrollHeight-ce.scrollTop-ce.clientHeight<ji:!0},V=l.useCallback(()=>{const ce=w.current,$=ce?Nf(ce):{showTop:!1,showBottom:!1};R(pe=>pe.showTop===$.showTop&&pe.showBottom===$.showBottom?pe:$)},[]),X=l.useCallback((ce="auto")=>{var pe;const $=w.current;$&&($.scrollTo({top:$.scrollHeight,behavior:ce}),(pe=$.ownerDocument.defaultView)==null||pe.requestAnimationFrame(()=>V()))},[V]),de=l.useCallback((ce="auto")=>{var pe;const $=w.current;$&&($.scrollTo({top:0,behavior:ce}),(pe=$.ownerDocument.defaultView)==null||pe.requestAnimationFrame(()=>V()))},[V]),ne=l.useCallback(()=>{var F;const ce=w.current,$=(F=window.getSelection)==null?void 0:F.call(window);if(!ce||!$||$.rangeCount===0||$.isCollapsed){q.current=!1;return}const pe=$.anchorNode,le=$.focusNode;q.current=!!(pe&&le&&ce.contains(pe)&&ce.contains(le))},[]),O=l.useMemo(()=>{const ce=ob(t),$=nu(t);return lb(cb(ce,$,u))},[t,u]),ie=O.length===t.length?p:void 0,z=Sf(O,ie),ae=l.useCallback(()=>{const ce=w.current;if(!ce||!c||!W.current)return;const $={top:ce.scrollTop,fromBottom:Math.max(0,ce.scrollHeight-ce.scrollTop-ce.clientHeight),messageFingerprint:z};J.current={contextKey:c,snapshot:$},Ln.set(c,$)},[c,z]),Ce=l.useCallback((ce="auto")=>{L.current!=null&&cancelAnimationFrame(L.current),L.current=requestAnimationFrame(()=>{L.current=null,X(ce)})},[X]),ye=l.useCallback(()=>{T.current=!1,P.current=!0,H.current=!0,_.current!=null&&window.clearTimeout(_.current),_.current=window.setTimeout(()=>{P.current=!1,_.current=null},Tl)},[]);l.useEffect(()=>{const ce=!D.current,$=I.current!==c;if(I.current=c,ce||$){D.current=!0;const le=c?Ln.get(c):null,F=!!le&&sa(le,z);T.current=F?Kn(le):!1,P.current=Af(le,z),q.current||(F?requestAnimationFrame(()=>{const be=w.current;be&&(Ga(be,le),T.current=Kn(le),V(),H.current=!0)}):Ce("auto")),j.current=O.length,A.current=z;return}O.length>j.current;const pe=z!==A.current;If({hasSelection:q.current,userScrolledUp:T.current,hasChatContentChanged:pe})&&Ce("auto"),j.current=O.length,A.current=z},[z,c,O.length,Ce,V]),l.useEffect(()=>{y&&(ye(),q.current||Ce("auto"))},[ye,Ce,y]),l.useEffect(()=>{const ce=M.current;ce&&!b&&ae(),W.current=b,M.current=b;const $=c?Ln.get(c):null;if(Cf(ce,b,$,z)){if(!$)return;T.current=Kn($),P.current=!1,q.current||requestAnimationFrame(()=>{const pe=w.current;pe&&(Ga(pe,$),V())});return}},[b,c,z,ye,ae,Ce,V]),l.useEffect(()=>()=>{const ce=J.current;ce&&Ln.set(ce.contextKey,ce.snapshot),L.current!=null&&cancelAnimationFrame(L.current),_.current!=null&&window.clearTimeout(_.current)},[]),l.useEffect(()=>{const ce=v.current,$=w.current;if(!ce||!$)return;const pe=()=>{_.current!=null&&window.clearTimeout(_.current),_.current=window.setTimeout(()=>{P.current=!1,_.current=null},Tl)},le=new ResizeObserver(()=>{V();const F=P.current;Tf({hasSelection:q.current,userScrolledUp:T.current,contextAutoScrollActive:F})&&(Ce("auto"),F&&pe())});return le.observe(ce),$!==ce&&le.observe($),()=>{le.disconnect(),_.current!=null&&(window.clearTimeout(_.current),_.current=null)}},[Ce,c,V]),l.useImperativeHandle(S,()=>({scrollToBottom:(ce="smooth")=>{X(ce)}}),[X]),l.useEffect(()=>{const ce=w.current;if(!ce)return;let $;const pe=()=>{ae(),clearTimeout($),$=setTimeout(()=>{T.current=!re(),V()},50)};return ce.addEventListener("scroll",pe,{passive:!0}),()=>{ce.removeEventListener("scroll",pe),clearTimeout($)}},[ae,V]),l.useEffect(()=>(document.addEventListener("selectionchange",ne),()=>document.removeEventListener("selectionchange",ne)),[ne]);const ke=l.useRef(0),me=l.useRef(!1);l.useEffect(()=>{const ce=w.current;if(!ce||!me.current||ke.current===0)return;const $=ce.scrollHeight-ke.current;$>0&&(ce.scrollTop=$),V(),ae(),ke.current=0,me.current=!1},[O.length,ae,V]),l.useEffect(()=>{if(H.current||!c)return;const ce=Ln.get(c),$=w.current;if(!(!ce||!$)){if(!sa(ce,z)){X("auto"),H.current=!0;return}Ga($,ce),T.current=Kn(ce),V(),H.current=!0}},[c,z,O.length,X,V]);const G=()=>{const ce=w.current;ce&&(ke.current=ce.scrollHeight),me.current=!0,f==null||f()},U=()=>{T.current=!0,de("smooth"),ae()},Z=()=>{ye(),X("smooth"),ae()},Y=l.useMemo(()=>{const ce=O.map((F,be)=>({type:"message",data:F,index:be,ts:gf(F,be,d)}));if(!n||n.length===0)return ce;const $=[...n].sort((F,be)=>F.timestamp-be.timestamp).map((F,be)=>({type:"action",data:F,index:be,ts:F.timestamp})),pe=[];let le=0;for(const F of ce){for(;le<$.length&&F.ts>0&&$[le].ts<F.ts;)pe.push($[le++]);pe.push(F)}for(;le<$.length;)pe.push($[le++]);return pe},[O,n,d]),fe=h>0||!!C,Te=h>0?h>80?k("chatList.showEarlierMessagesHidden",{count:Math.min(h,80),total:h}):k("chatList.showEarlierMessages",{count:Math.min(h,80)}):x?k("chatList.loadErrorRetry",{error:x}):k("chatList.loadOlderMessages");return s.jsxs("div",{className:"chat-scroll-frame",children:[s.jsx("div",{ref:w,"data-chat-scroll":!0,className:"chat-container",children:s.jsxs("div",{ref:v,className:"chat-container-content",children:[g&&s.jsx("div",{className:"text-center py-3 text-text-muted text-xs opacity-60 animate-pulse",children:k("chatList.loadingOlderMessages")}),fe&&!g&&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 ${x&&h===0?"bg-transparent border-yellow-500/30 text-yellow-400 opacity-80 hover:opacity-100":"bg-transparent border-border-subtle text-text-muted opacity-70 hover:opacity-100 hover:border-accent/40"}`,children:Te})}),Y.length===0&&!fe&&(m||s.jsx("div",{className:"text-center mt-16 opacity-20 text-[13px]",children:k("chatList.waitingForMessages")})),Y.map(ce=>{if(ce.type==="action"){const je=ce.data;return s.jsx(mb,{log:je},`action-${ce.index}`)}const $=ce.data;ce.index;const pe=ta($),le=$.receivedAt||d[pe],F=`${c}-${pe}`,be=B.has(F);return s.jsx(hb,{message:$,receivedAt:le,agentName:r,userName:a,isCliMode:o,isTextExpanded:be,onToggleTextExpanded:()=>E(je=>{const Se=new Set(je);return be?Se.delete(F):Se.add(F),Se})},`msg-${pe}`)}),i&&s.jsx("div",{className:"self-start chat-typing-wrapper",children:s.jsxs("div",{className:"typing-indicator",children:[s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("div",{className:"dot"}),s.jsx("span",{className:"text-[11px] text-text-muted ml-1",children:k("chatList.agentGenerating")})]})}),s.jsx("div",{className:"min-h-10",ref:N})]})}),(K.showTop||K.showBottom)&&s.jsxs("div",{className:"chat-scroll-jump-controls","aria-label":k("chatList.jumpToTop"),children:[K.showTop&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button",onClick:U,"aria-label":k("chatList.jumpToOldestMessages"),title:k("chatList.jumpToTop"),children:k("chatList.top")}),K.showBottom&&s.jsx("button",{type:"button",className:"chat-scroll-jump-button chat-scroll-jump-button-primary",onClick:Z,"aria-label":k("chatList.jumpToLatestMessages"),title:k("chatList.jumpToBottom"),children:k("chatList.latest")})]})]})}),bb=l.memo(fb,(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),gb="modulepreload",xb=function(e){return"/"+e},_l={},vb=function(t,n,r){let a=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const i=document.querySelector("meta[property=csp-nonce]"),c=(i==null?void 0:i.nonce)||(i==null?void 0:i.getAttribute("nonce"));a=Promise.allSettled(n.map(d=>{if(d=xb(d),d in _l)return;_l[d]=!0;const p=d.endsWith(".css"),u=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${u}`))return;const m=document.createElement("link");if(m.rel=p?"stylesheet":gb,p||(m.as="script"),m.crossOrigin="",m.href=d,c&&m.setAttribute("nonce",c),document.head.appendChild(m),p)return new Promise((f,g)=>{m.addEventListener("load",f),m.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(i){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=i,window.dispatchEvent(c),!c.defaultPrevented)throw i}return a.then(i=>{for(const c of i||[])c.status==="rejected"&&o(c.reason);return t().catch(o)})};let $l=!1;const iu=l.forwardRef(({onInput:e,onViewportMetrics:t,onScrollMetrics:n,fontSize:r=13,readOnly:a=!1,sizingMode:o="measured"},i)=>{const c=l.useRef(null),[d,p]=l.useState(null),u=l.useRef([]),m=l.useRef(!1),f=l.useRef(!1),g=l.useRef(!1),C=l.useRef(!1),h=()=>{const x=c.current;if(x){m.current&&(x.clear(),m.current=!1);for(const y of u.current)x.write(y.data,y.onProcessed);u.current=[],f.current&&(x.fit(),f.current=!1),g.current&&(x.bumpResize(),g.current=!1),C.current&&(x.scrollToTop(),C.current=!1)}};return l.useImperativeHandle(i,()=>({write:(x,y)=>{c.current?c.current.write(x,y):u.current.push({data:x,onProcessed:y})},clear:()=>{c.current?c.current.clear():(u.current=[],m.current=!0)},reset:()=>{c.current&&typeof c.current.reset=="function"?c.current.reset():(u.current=[],m.current=!0)},resize:(x,y)=>{c.current&&typeof c.current.resize=="function"&&c.current.resize(x,y)},fit:()=>{c.current?c.current.fit():f.current=!0},bumpResize:()=>{c.current?c.current.bumpResize():g.current=!0},scrollToTop:()=>{c.current?c.current.scrollToTop():C.current=!0},getSelection:()=>{var x,y;return((y=(x=c.current)==null?void 0:x.getSelection)==null?void 0:y.call(x))||""},getVisibleText:()=>{var x,y;return((y=(x=c.current)==null?void 0:x.getVisibleText)==null?void 0:y.call(x))||""}}),[]),l.useEffect(()=>{d&&h()},[d]),l.useEffect(()=>{let x=!1;return vb(()=>import("./terminal-CqjiB824.js"),__vite__mapDeps([0,1,2])).then(y=>{$l||($l=!0,console.info("[CliTerminal] renderer module loaded: terminal-render-web")),x||p(()=>y.GhosttyTerminalView)}).catch(y=>{console.error("[CliTerminal] failed to load terminal renderer",y)}),()=>{x=!0}},[]),d?s.jsx(d,{ref:c,onInput:e,onViewportMetrics:t,onScrollMetrics:n,fontSize:r,readOnly:a,sizingMode:o,className:"w-full h-full rounded-lg overflow-hidden"}):s.jsx("div",{className:"w-full h-full rounded-lg overflow-hidden animate-pulse",style:{background:"#0f1117"}})});iu.displayName="CliTerminal";function Ft(...e){return Sh(Ch(e))}const yb={lg:"rounded-lg",xl:"rounded-xl","2xl":"rounded-2xl"},wb={none:"",sm:"p-3",md:"px-4 py-3.5",lg:"px-5 py-4"},Ss=l.forwardRef(function({radius:t="xl",padding:n="md",className:r,...a},o){return s.jsx("div",{ref:o,className:Ft("border border-border-subtle bg-bg-secondary",yb[t],wb[n],r),...a})});function kr({label:e,value:t,sub:n,icon:r}){return s.jsxs(Ss,{children:[s.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[s.jsx("span",{className:"text-base flex items-center",children:r}),s.jsx("span",{className:"text-[10px] text-text-muted uppercase tracking-wide font-semibold",children:e})]}),s.jsx("div",{className:"text-[22px] font-bold text-text-primary tracking-tight",children:t}),n&&s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:n})]})}function Hl({value:e,max:t,label:n,color:r="#8b5cf6",detail:a,compact:o=!1}){const i=t>0?Math.min(Math.round(e/t*100),100):0,c=i>85?"#ef4444":i>60?"var(--status-warning)":r;return o?s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-0.5",children:[s.jsx("span",{className:"text-[9px] text-text-muted uppercase tracking-wide font-semibold",children:n}),s.jsxs("span",{className:"text-[10px] text-text-secondary font-semibold",children:[i,"%"]})]}),s.jsx("div",{className:"h-1 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-500",style:{width:`${i}%`,background:c}})})]}):s.jsxs("div",{className:"flex-1",children:[s.jsxs("div",{className:"flex justify-between mb-1.5",children:[s.jsx("span",{className:"text-[11px] text-text-secondary font-medium",children:n}),s.jsxs("span",{className:"text-[13px] text-text-primary font-bold",children:[i,"%"]})]}),s.jsx("div",{className:"h-1.5 bg-white/[0.04] rounded-sm overflow-hidden",children:s.jsx("div",{className:"h-full rounded-sm transition-[width] duration-[600ms]",style:{width:`${i}%`,background:`linear-gradient(90deg, ${c}, ${c}cc)`}})}),a&&s.jsx("div",{className:"text-[10px] text-text-muted mt-0.5",children:a})]})}function kb({cursorPos:e,viewportRef:t,imgRef:n}){var b;if(!e||!n.current)return null;const r=n.current,a=r.getBoundingClientRect(),o=(b=t.current)==null?void 0:b.getBoundingClientRect();if(!o)return null;const i=r.naturalWidth||a.width,c=r.naturalHeight||a.height,d=i/c,p=a.width/a.height;let u,m,f,g;d>p?(u=a.width,m=a.width/d,f=0,g=(a.height-m)/2):(m=a.height,u=a.height*d,f=(a.width-u)/2,g=0);const C=a.left-o.left+f+u*e.nx,h=a.top-o.top+g+m*e.ny,x=Math.max(8,Math.min(o.width-8,C)),y=Math.max(8,Math.min(o.height-8,h));return s.jsxs("div",{style:{position:"absolute",left:x-8,top:y-8,width:16,height:16,pointerEvents:"none",zIndex:100},children:[s.jsx("div",{style:{position:"absolute",left:7,top:0,width:2,height:16,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:0,top:7,width:16,height:2,background:"rgba(59,130,246,0.8)"}}),s.jsx("div",{style:{position:"absolute",left:5,top:5,width:6,height:6,borderRadius:"50%",background:"#3b82f6",boxShadow:"0 0 8px rgba(59,130,246,0.6)"}})]})}function Sb({inputMode:e,onToggleInputMode:t,isImeOpen:n,setIsImeOpen:r,isMenuOpen:a,setIsMenuOpen:o,imeText:i,setImeText:c,handleImeSubmit:d,isConnActive:p,zoom:u,isMobile:m,mobileFillZoom:f,onZoomOut:g,onZoomReset:C,onZoomIn:h,transportType:x,screenshotUsage:y,lastActionStatus:b}){const{t:S}=Ne("common");return s.jsxs(s.Fragment,{children:[s.jsxs("div",{onTouchStart:k=>k.stopPropagation(),className:"absolute bottom-0 left-0 right-0 z-20 flex items-center justify-center gap-1.5 px-3 py-2 bg-black/75 backdrop-blur-xl border-t border-white/[0.08] touch-none",children:[s.jsxs("div",{onClick:t,className:`h-8 px-2.5 rounded-lg flex items-center gap-[5px] cursor-pointer ${e==="mouse"?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:[s.jsx("span",{className:"text-sm",children:e==="mouse"?"🖱️":"👆"}),s.jsx("span",{className:`text-[10px] font-bold ${e==="mouse"?"text-blue-400":"text-slate-400"}`,children:S(e==="mouse"?"remote.mouse":"remote.touch")})]}),s.jsxs("div",{className:"relative",children:[s.jsx("div",{onClick:()=>{r(k=>!k),o(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${n?"bg-emerald-500/25 border border-emerald-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⌨️"})}),n&&s.jsx("div",{className:"absolute bottom-10 left-1/2 -translate-x-1/2 w-[220px] bg-neutral-950/[0.98] backdrop-blur-[30px] rounded-xl border border-white/20 p-[10px_12px] shadow-[0_10px_30px_rgba(0,0,0,0.8)] flex flex-col gap-2 z-20",style:{animation:"slideUp 0.15s ease-out"},children:s.jsx("input",{type:"text",placeholder:S("remote.typeAndEnter"),value:i,autoFocus:!0,onTouchStart:k=>k.stopPropagation(),onChange:k=>c(k.target.value),onKeyDown:k=>{d(k)},className:"w-full bg-black/60 border border-white/15 rounded-lg px-2.5 py-2 text-white text-[13px] outline-none"})})]}),s.jsx("div",{className:"relative",children:s.jsx("div",{onClick:()=>{o(k=>!k),r(!1)},className:`w-8 h-8 rounded-lg flex items-center justify-center cursor-pointer ${a?"bg-blue-500/25 border border-blue-500/40":"bg-white/[0.08] border border-white/10"}`,children:s.jsx("span",{className:"text-sm",children:"⚙️"})})}),s.jsx("div",{className:"w-px h-[18px] bg-white/10"}),s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("div",{className:"flex items-center gap-0.5 px-1.5 py-0.5 rounded-md",style:{background:p?"rgba(34,197,94,0.12)":"rgba(234,179,8,0.12)"},children:[s.jsx("div",{className:"w-1 h-1 rounded-full",style:{background:p?"#22c55e":"#eab308",boxShadow:p?"0 0 4px #22c55e80":"0 0 4px #eab30880"}}),s.jsx("span",{className:"text-[8px] font-extrabold",style:{color:p?"#22c55e":"#eab308"},children:S(p?"remote.connected":"remote.ws")})]}),u>1&&s.jsxs("span",{className:"text-[8px] font-bold text-indigo-400",children:[Math.round(u*100),"%"]}),x==="direct"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"#22c55e",background:"rgba(34,197,94,0.12)"},title:S("remote.directP2PTitle"),children:S("remote.direct")}),x==="relay"&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:"var(--status-warning)",background:"color-mix(in srgb, var(--status-warning) 12%, transparent)"},title:S("remote.turnRelayTitle"),children:S("remote.relay")}),y&&y.dailyBudgetMinutes>0&&s.jsx("span",{className:"text-[8px] font-bold px-1 py-0.5 rounded",style:{color:y.budgetExhausted?"#ef4444":"#c4b5fd",background:y.budgetExhausted?"rgba(239,68,68,0.1)":"rgba(139,92,246,0.14)"},title:S("remote.dailyTurnTitle"),children:y.budgetExhausted?S("remote.turnBlocked"):S("remote.turnUsage",{used:y.dailyUsedMinutes,budget:y.dailyBudgetMinutes})}),b&&s.jsx("span",{className:"text-[8px] text-neutral-500 font-semibold max-w-[100px] overflow-hidden text-ellipsis whitespace-nowrap",children:b})]})]}),a&&s.jsxs("div",{onTouchStart:k=>k.stopPropagation(),style:{position:"absolute",bottom:56,left:"50%",transform:"translateX(-50%)",width:220,background:"rgba(23, 23, 23, 0.95)",backdropFilter:"blur(25px)",borderRadius:14,border:"1px solid rgba(255,255,255,0.1)",padding:14,boxShadow:"0 12px 40px rgba(0,0,0,0.6)",display:"flex",flexDirection:"column",gap:12,zIndex:20,touchAction:"none",animation:"slideUpSidebar 0.15s ease-out"},children:[s.jsx("div",{style:{fontSize:9,fontWeight:900,color:"#3b82f6",letterSpacing:1.5},children:S("remote.settings")}),s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.jsxs("div",{style:{fontSize:10,color:"#888",fontWeight:700},children:[S("remote.zoom")," ",u<=(m?f:1)+.01?S(m?"remote.fill":"remote.fit"):`${Math.round(u*100)}%`]}),s.jsxs("div",{style:{display:"flex",gap:4},children:[s.jsx("button",{onClick:k=>{k.stopPropagation(),g()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"−"}),s.jsx("button",{onClick:k=>{k.stopPropagation(),C()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:9,fontWeight:800,cursor:"pointer"},children:S(m?"remote.fill":"remote.fit")}),s.jsx("button",{onClick:k=>{k.stopPropagation(),h()},style:{flex:1,background:"rgba(255,255,255,0.1)",color:"#fff",border:"none",padding:"6px",borderRadius:6,fontSize:12,fontWeight:800,cursor:"pointer"},children:"+"})]})]})]})]})}function Cb({waitingLabel:e,waitingHint:t,transportType:n}){const{t:r}=Ne("common");return s.jsxs("div",{className:"text-center flex flex-col items-center gap-3 px-6",children:[s.jsx("div",{className:"w-14 h-14 rounded-2xl flex items-center justify-center border border-white/10 bg-white/[0.04] shadow-[0_10px_30px_rgba(0,0,0,0.35)]",style:{animation:"remote-float 2.8s ease-in-out infinite"},children:s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-8 h-8 opacity-90"})}),s.jsx("div",{className:"text-white/85 text-[13px] font-semibold tracking-wide",children:e}),s.jsx("div",{className:"text-[11px] text-white/40",children:t}),n==="relay"&&s.jsx("div",{className:"text-[10px] font-medium",style:{color:"var(--status-warning)",opacity:.8},children:r("remote.waitingState.turnRelayActive")})]})}function jb(){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 hr(e,t){const n=l.useRef(null),r=l.useRef(0);l.useEffect(()=>{if(!jb())return;r.current+=1;const a=n.current;if(!a){console.debug(`[render-trace] ${e}#${r.current}`,{changed:["mount"],snapshot:Object.fromEntries(Object.entries(t).map(([i,c])=>[i,Bl(c)]))}),n.current=t;return}const o=Object.keys({...a,...t}).filter(i=>!Object.is(a[i],t[i]));o.length>0&&console.debug(`[render-trace] ${e}#${r.current}`,{changed:o,snapshot:Object.fromEntries(o.map(i=>[i,Bl(t[i])]))}),n.current=t})}function Nb({containerRef:e,viewportRef:t,imgRef:n,inputMode:r,setInputMode:a,minZoom:o,zoomRef:i,panXRef:c,panYRef:d,setPanX:p,setPanY:u,setZoom:m,lastWheelTimeRef:f,onAction:g,setLastActionStatus:C,spawnRippleFromNormalized:h,clampPan:x,isMobile:y,mobileFillZoom:b}){const[S,k]=l.useState(null),w=l.useRef(null),v=l.useRef(null),N=l.useRef(null),j=l.useRef(!1),A=l.useRef(null),I=l.useRef(0),D=l.useRef(null),L=l.useRef(1),P=l.useRef({x:0,y:0}),_=l.useRef(!1),q=l.useRef(r),B=l.useRef(g),E=30,K=550,R=18,T=60,H=400,M=12,W=()=>{if(w.current)return;const V={nx:.5,ny:.5};w.current=V,k(V)};return l.useEffect(()=>{q.current=r,r==="mouse"&&W()},[r]),l.useEffect(()=>{B.current=g},[g]),l.useEffect(()=>{const V=e.current;if(!V)return;const X=ae=>{if(!n.current)return null;const Ce=n.current.getBoundingClientRect();return!Ce.width||!Ce.height?null:{nx:Math.max(0,Math.min(1,(ae.clientX-Ce.left)/Ce.width)),ny:Math.max(0,Math.min(1,(ae.clientY-Ce.top)/Ce.height))}},de=(ae,Ce)=>{if(!n.current)return{dnx:0,dny:0};const ye=n.current,ke=ye.getBoundingClientRect(),me=ye.naturalWidth||ke.width,G=ye.naturalHeight||ke.height,U=me/G,Z=ke.width/ke.height;let Y,fe;return U>Z?(Y=ke.width,fe=ke.width/U):(fe=ke.height,Y=ke.height*U),{dnx:ae/Y,dny:Ce/fe}},ne=(ae,Ce,ye)=>{if(ye<=1.05)return;const ke=-(ae-.5)*100,me=-(Ce-.5)*100,G=x(ke,me,ye);(Math.abs(G.x-c.current)>.1||Math.abs(G.y-d.current)>.1)&&(p(G.x),u(G.y),c.current=G.x,d.current=G.y)},O=ae=>{const Ce=t.current;if(Ce&&ae.target instanceof Node&&Ce.contains(ae.target))ae.preventDefault();else return;if(ae.touches.length===1){const ye=ae.touches[0];v.current={x:ye.clientX,y:ye.clientY,time:Date.now()},N.current={x:ye.clientX,y:ye.clientY},_.current||(j.current=!1),A.current=setTimeout(()=>{if(!j.current&&!_.current)if(j.current=!0,q.current==="mouse"){const ke=w.current||{nx:.5,ny:.5};C("Right Click"),h(ke.nx,ke.ny,"right"),B.current("input_click",{...ke,button:"right"}).catch(()=>{})}else{const ke=X(ye);ke&&(C("Right Click"),h(ke.nx,ke.ny,"right"),B.current("input_click",{...ke,button:"right"}).catch(()=>{}))}},500);return}if(ae.touches.length===2){A.current&&clearTimeout(A.current),j.current=!0,_.current=!0;const ye=ae.touches[1].clientX-ae.touches[0].clientX,ke=ae.touches[1].clientY-ae.touches[0].clientY;D.current=Math.sqrt(ye*ye+ke*ke),L.current=i.current,P.current={x:(ae.touches[0].clientX+ae.touches[1].clientX)/2,y:(ae.touches[0].clientY+ae.touches[1].clientY)/2}}},ie=ae=>{const Ce=t.current;if(Ce&&ae.target instanceof Node&&Ce.contains(ae.target)&&ae.preventDefault(),ae.touches.length===1&&N.current){const ye=ae.touches[0],ke=ye.clientX-N.current.x,me=ye.clientY-N.current.y;if(!j.current&&v.current){const G=ye.clientX-v.current.x,U=ye.clientY-v.current.y;Math.sqrt(G*G+U*U)>8&&(j.current=!0,A.current&&clearTimeout(A.current))}if(j.current)if(q.current==="mouse"){const G=de(ke,me),U=w.current||{nx:.5,ny:.5},Z=Math.max(0,Math.min(1,U.nx+G.dnx)),Y=Math.max(0,Math.min(1,U.ny+G.dny));w.current={nx:Z,ny:Y},k({nx:Z,ny:Y}),C(`Cursor: ${Math.round(Z*100)}%, ${Math.round(Y*100)}%`),ne(Z,Y,i.current);const fe=Date.now();fe-f.current>=30&&(f.current=fe,B.current("input_mouseMoved",{nx:Z,ny:Y}).catch(()=>{}))}else if(i.current>1){const G=t.current;if(G){const U=G.clientWidth,Z=G.clientHeight,Y=c.current+ke/U*100,fe=d.current+me/Z*100,Te=x(Y,fe,i.current);p(Te.x),u(Te.y),c.current=Te.x,d.current=Te.y}}else{const G=X(ye);if(G){const U=Date.now();U-f.current>=40&&(f.current=U,C("Scroll"),B.current("input_wheel",{nx:G.nx,ny:G.ny,deltaX:Math.round(-ke*2.5),deltaY:Math.round(-me*2.5)}).catch(()=>{}))}}N.current={x:ye.clientX,y:ye.clientY};return}if(ae.touches.length===2&&D.current!==null){const ye=ae.touches[1].clientX-ae.touches[0].clientX,ke=ae.touches[1].clientY-ae.touches[0].clientY,G=Math.sqrt(ye*ye+ke*ke)/D.current,U=(ae.touches[0].clientX+ae.touches[1].clientX)/2,Z=(ae.touches[0].clientY+ae.touches[1].clientY)/2,Y=U-P.current.x,fe=Z-P.current.y,Te=Math.abs(G-1)>.03;if(q.current==="mouse"){if(Te){const ce=Math.max(o,Math.min(5,L.current*G));m(ce),i.current=ce}else if(Math.abs(Y)>2||Math.abs(fe)>2){const ce=w.current||{nx:.5,ny:.5},$=Date.now();$-f.current>=30&&(f.current=$,C("Scroll"),B.current("input_wheel",{nx:ce.nx,ny:ce.ny,deltaX:Math.round(-Y*3),deltaY:Math.round(-fe*3)}).catch(()=>{}))}}else{const ce=Math.max(o,Math.min(5,L.current*G));m(ce),i.current=ce;const $=t.current;if($&&ce>1){const pe=$.clientWidth,le=$.clientHeight,F=c.current+Y/pe*100,be=d.current+fe/le*100,je=x(F,be,ce);p(je.x),u(je.y),c.current=je.x,d.current=je.y}}P.current={x:U,y:Z}}},z=ae=>{var Ce;if(A.current&&clearTimeout(A.current),D.current=null,ae.touches.length===1&&_.current){const ye=ae.touches[0];v.current={x:ye.clientX,y:ye.clientY,time:Date.now()},N.current={x:ye.clientX,y:ye.clientY},j.current=!0;return}if(ae.touches.length===0){if(_.current){_.current=!1,j.current=!1;return}if(ae.changedTouches.length===1){const ye=ae.changedTouches[0],ke=Date.now(),me=ke-(((Ce=v.current)==null?void 0:Ce.time)||0),G=v.current?ye.clientX-v.current.x:0,U=v.current?ye.clientY-v.current.y:0,Z=Math.sqrt(G*G+U*U);if(q.current==="mouse"){if(me<E||me>K||Z>R){j.current=!1;return}const Y=w.current||X(ye);Y&&(C(`Click: ${Math.round(Y.nx*100)}%, ${Math.round(Y.ny*100)}%`),h(Y.nx,Y.ny,"left"),B.current("input_click",{...Y}).catch(()=>{}))}else{if(j.current){j.current=!1;return}if(me<T||me>H||Z>M){j.current=!1;return}const Y=X(ye);if(!Y)return;ke-I.current<300?(C("Double tap"),h(Y.nx,Y.ny,"double"),B.current("input_click",{...Y,clickCount:2}).catch(()=>{}),I.current=0):(C(`Tap: ${Math.round(Y.nx*100)}%, ${Math.round(Y.ny*100)}%`),h(Y.nx,Y.ny,"left"),B.current("input_click",{...Y}).catch(()=>{}),I.current=ke)}}j.current=!1}};return V.addEventListener("touchstart",O,{passive:!1}),V.addEventListener("touchmove",ie,{passive:!1}),V.addEventListener("touchend",z,{passive:!1}),()=>{V.removeEventListener("touchstart",O),V.removeEventListener("touchmove",ie),V.removeEventListener("touchend",z),A.current&&clearTimeout(A.current)}},[e,t,n,o,i,c,d,p,u,m,f,C,h,x]),{cursorPos:S,cursorPosRef:w,handleToggleInputMode:()=>{a(V=>{const X=V==="touch"?"mouse":"touch";return X==="mouse"&&W(),X})},handleZoomReset:()=>{const V=y?b:1;m(V),i.current=V,p(0),u(0),c.current=0,d.current=0}}}function lu({onAction:e,addLog:t,connState:n,connScreenshot:r,screenshotUsage:a,transportType:o}){const i=l.useRef(null),c=l.useRef(null),d=l.useRef(null),[p,u]=l.useState(null),[m,f]=l.useState(""),[,g]=l.useState(!1),[C,h]=l.useState([]),x=l.useRef(0),[y,b]=l.useState(!1),[S,k]=l.useState(!1),w=typeof window<"u"&&window.matchMedia("(max-width: 768px)").matches,[v,N]=l.useState(w?"mouse":"touch"),[j,A]=l.useState(1),I=l.useRef(!1),[D,L]=l.useState(1),[P,_]=l.useState(0),[q,B]=l.useState(0);hr("RemoteView",{connState:n,hasScreenshot:!!r,inputMode:v,zoom:D,panX:P,panY:q,isMenuOpen:y,isImeOpen:S});const E=l.useRef(0),K=l.useRef(D),R=l.useRef(P),T=l.useRef(q);l.useEffect(()=>{K.current=D},[D]),l.useEffect(()=>{R.current=P},[P]),l.useEffect(()=>{T.current=q},[q]),l.useEffect(()=>{var me;(me=i.current)==null||me.focus()},[]);const H=n==="connected",M=r,W=H?"Connected. Waiting for first frame...":n==="connecting"?"Connecting to Host...":"Reconnecting to Host...",J=H?"The remote stream is warming up":"Waiting for the remote stream to catch up";l.useEffect(()=>{if(!w||I.current||!M)return;const me=d.current,G=c.current;if(!me||!G)return;const U=()=>{const Z=G.clientWidth,Y=G.clientHeight,fe=me.naturalWidth,Te=me.naturalHeight;if(!fe||!Te||!Z||!Y)return;const ce=Math.min(Z/fe,Y/Te),pe=Math.max(Z/fe,Y/Te)/ce;pe>1.01&&(A(pe),L(pe),K.current=pe),I.current=!0};me.complete&&me.naturalWidth?U():me.addEventListener("load",U,{once:!0})},[M,w]);const re=.5;l.useEffect(()=>{D<=re&&(_(0),B(0))},[D,re]);const V=(me,G,U)=>{if(U<=re)return{x:0,y:0};const Z=(U-1)/(2*U)*100,Y=(U-1)/(2*U)*100;return{x:Math.max(-Z,Math.min(Z,me)),y:Math.max(-Y,Math.min(Y,G))}},X=(me,G)=>{if(!d.current)return null;const U=d.current.getBoundingClientRect();return!U.width||!U.height?null:{nx:Math.max(0,Math.min(1,(me-U.left)/U.width)),ny:Math.max(0,Math.min(1,(G-U.top)/U.height))}},de=(me,G,U)=>{const Z=c.current;if(!Z)return;const Y=Z.getBoundingClientRect(),fe=++x.current;h(Te=>[...Te,{id:fe,x:me-Y.left,y:G-Y.top,type:U}]),setTimeout(()=>h(Te=>Te.filter(ce=>ce.id!==fe)),600)},ne=(me,G,U)=>{const Z=d.current,Y=c.current;if(!Z||!Y)return;const fe=Z.getBoundingClientRect(),Te=Y.getBoundingClientRect(),ce=Z.naturalWidth||fe.width,$=Z.naturalHeight||fe.height,pe=ce/$,le=fe.width/fe.height;let F,be,je,Se;pe>le?(F=fe.width,be=fe.width/pe,je=0,Se=(fe.height-be)/2):(be=fe.height,F=fe.height*pe,je=(fe.width-F)/2,Se=0);const He=fe.left-Te.left+je+F*me,Xe=fe.top-Te.top+Se+be*G,dt=++x.current;h(it=>[...it,{id:dt,x:He,y:Xe,type:U}]),setTimeout(()=>h(it=>it.filter(he=>he.id!==dt)),600)},O=async me=>{var U;const G=X(me.clientX,me.clientY);if(G){u(`Click: ${Math.round(G.nx*100)}%, ${Math.round(G.ny*100)}%`),de(me.clientX,me.clientY,"left"),(U=i.current)==null||U.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}`)}}},ie=async(me,G,U,Z=0)=>{try{await e("input_key",{type:U?"char":"keyDown",key:me,code:G,text:U?me:void 0,unmodifiedText:U?me:void 0,modifiers:Z})}catch(Y){t(`❌ Key error: ${Y.message||Y}`)}},z=async me=>{if(me.target.tagName==="INPUT")return;["ArrowUp","ArrowDown","ArrowLeft","ArrowRight","Backspace","Tab","Enter","Escape"].includes(me.key)&&me.preventDefault();let U=0;me.altKey&&(U|=1),me.ctrlKey&&(U|=2),me.metaKey&&(U|=4),me.shiftKey&&(U|=8),u(`Key: ${me.key}`),await ie(me.key,me.code,me.key.length===1,U)},ae=async me=>{if(me.key==="Enter"){if(me.nativeEvent.isComposing)return;if(m){const G=m;f(""),u(`IME Sent: ${G}`);try{const U=await e("input_type",{text:G});U!=null&&U.success||t(`❌ IME error: ${U==null?void 0:U.error}`)}catch(U){t(`❌ IME error: ${U.message}`)}}else u("Key: Enter"),await ie("Enter","Enter",!1)}};l.useEffect(()=>{const me=i.current;if(!me)return;const G=U=>{var Z;if((Z=d.current)!=null&&Z.contains(U.target)){U.preventDefault();const Y=Date.now();if(Y-E.current<40)return;E.current=Y;const fe=X(U.clientX,U.clientY);if(!fe)return;u(`Scroll: ${Math.round(U.deltaY)}`),e("input_wheel",{nx:fe.nx,ny:fe.ny,deltaX:Math.round(U.deltaX),deltaY:Math.round(U.deltaY)}).catch(()=>{})}};return me.addEventListener("wheel",G,{passive:!1}),()=>me.removeEventListener("wheel",G)},[e]);const{cursorPos:Ce,handleToggleInputMode:ye,handleZoomReset:ke}=Nb({containerRef:i,viewportRef:c,imgRef:d,inputMode:v,setInputMode:N,minZoom:re,zoomRef:K,panXRef:R,panYRef:T,setPanX:_,setPanY:B,setZoom:L,lastWheelTimeRef:E,onAction:e,setLastActionStatus:u,spawnRippleFromNormalized:ne,clampPan:V,isMobile:w,mobileFillZoom:j});return s.jsxs("div",{ref:i,className:"flex-1 flex flex-col bg-black relative overflow-hidden outline-none touch-none",onKeyDown:z,onContextMenu:me=>me.preventDefault(),onFocus:()=>g(!0),onBlur:()=>g(!1),tabIndex:0,children:[s.jsxs("div",{ref:c,className:"flex-1 relative overflow-hidden flex items-center justify-center bg-black",children:[M?s.jsx("img",{ref:d,src:M,alt:"Remote View",style:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",transform:`scale(${D}) translate(${P}%, ${q}%)`,transformOrigin:"center center",cursor:v==="mouse"?"default":"crosshair",userSelect:"none",WebkitTouchCallout:"none"},onClick:O,onContextMenu:me=>me.preventDefault(),onDragStart:me=>me.preventDefault()}):s.jsx(Cb,{waitingLabel:W,waitingHint:J,transportType:o}),v==="mouse"&&M&&s.jsx(kb,{cursorPos:Ce,viewportRef:c,imgRef:d}),C.map(me=>{const U={left:"59,130,246",right:"239,68,68",double:"34,197,94"}[me.type];return s.jsxs("div",{style:{position:"absolute",left:me.x,top:me.y,pointerEvents:"none",zIndex:200,transform:"translate(-50%, -50%)"},children:[s.jsx("div",{style:{width:40,height:40,borderRadius:"50%",border:`2px solid rgba(${U}, 0.8)`,animation:"click-ripple-ring 0.5s ease-out forwards",position:"absolute",left:-20,top:-20}}),s.jsx("div",{style:{width:8,height:8,borderRadius:"50%",background:`rgba(${U}, 0.9)`,boxShadow:`0 0 12px rgba(${U}, 0.6)`,animation:"click-ripple-dot 0.4s ease-out forwards",position:"absolute",left:-4,top:-4}})]},me.id)})]}),s.jsx(Sb,{inputMode:v,onToggleInputMode:ye,isImeOpen:S,setIsImeOpen:k,isMenuOpen:y,setIsMenuOpen:b,imeText:m,setImeText:f,handleImeSubmit:ae,isConnActive:H,zoom:D,isMobile:w,mobileFillZoom:j,onZoomOut:()=>L(me=>Math.max(.5,me-.25)),onZoomReset:ke,onZoomIn:()=>L(me=>Math.min(5,me+.25)),transportType:o,screenshotUsage:a,lastActionStatus:p}),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 Ab(e){var t;return Fl(e.activeInteractivePrompt)||Fl((t=e.activeChat)==null?void 0:t.activeInteractivePrompt)}function Ib(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 a=Ab(r);if(!a)continue;const o=Ib(r);if(n&&n!==o&&n!==r.id)continue;return{daemonId:r.daemonId||r.id.split(":")[0]||r.id,sessionId:o,routeId:r.id,providerType:r.type,title:r.title||r.cliName||r.type,prompt:a}}return null}function cu(e,t){var r;const n={};for(const a of e.questions){const o=t[a.questionId]||{},i=Array.from(new Set((o.selectedLabels||[]).map(d=>d.trim()).filter(Boolean))),c=(r=o.freeformText)==null?void 0:r.trim();n[a.questionId]={selectedLabels:i,...c?{freeformText:c}:{}}}return{promptId:e.promptId,answers:n}}const Mb=200;function Ol(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 Db({label:e,description:t,selected:n,multiSelect:r,disabled:a,onClick:o}){return s.jsx("button",{type:"button",disabled:a,role:r?"checkbox":"radio","aria-checked":n,onClick:o,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"} ${a?"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(eu,{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 du({promptSession:e,isSubmitting:t=!1,error:n,onSubmit:r,onCancel:a}){var D;const{t:o}=Ne("common"),[i,c]=l.useState(()=>Ol(e)),[d,p]=l.useState(0),[u,m]=l.useState(!1),f=l.useRef(!1);l.useEffect(()=>{if(c(Ol(e)),p(0),m(!1),f.current=!1,!(e==null?void 0:e.prompt.promptId))return;const P=setTimeout(()=>{f.current=!0,m(!0)},Mb);return()=>clearTimeout(P)},[e==null?void 0:e.prompt.promptId]);const g=(e==null?void 0:e.prompt.questions)||[],C=g.length,h=d===C-1,x=C===1,y=g[d],b=y?i[y.questionId]:void 0,S=y?Wl(y,b):!1,k=l.useMemo(()=>e?e.prompt.questions.every(L=>Wl(L,i[L.questionId])):!1,[e,i]);if(!e)return null;const w=(L,P)=>{c(_=>{const q=_[L.questionId]||{selectedLabels:[]},B=q.selectedLabels||[],E=L.multiSelect?B.includes(P)?B.filter(K=>K!==P):[...B,P]:[P];return{..._,[L.questionId]:{...q,selectedLabels:E}}})},v=(L,P)=>{c(_=>({..._,[L]:{..._[L]||{selectedLabels:[]},freeformText:P}}))},N=()=>{d<C-1&&p(L=>L+1)},j=()=>{d>0&&p(L=>L-1)},A=()=>{!k||t||!f.current||r(i)},I=cu(e.prompt,i);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:[!x&&s.jsxs("span",{className:"text-xs text-text-muted",children:[d+1," / ",C]}),s.jsx("button",{type:"button",onClick:a,className:"btn btn-ghost btn-sm h-8 w-8 p-0","aria-label":"Cancel interactive prompt",children:s.jsx(At,{size:16})})]})]}),!x&&s.jsx("div",{className:"flex shrink-0 gap-1.5 px-5 pt-3",children:g.map((L,P)=>s.jsx("div",{className:`h-1.5 flex-1 rounded-full transition-colors ${P<d?"bg-accent-primary":P===d?"bg-accent-primary/60":"bg-border-default"}`},L.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:[x?"":`${d+1}. `,y.question]}),y.multiSelect&&y.options.length>0&&s.jsx("div",{className:"mt-0.5 text-xs text-text-muted",children:o("interactivePrompt.selectAllThatApply")})]}),s.jsx("div",{className:"grid gap-2",role:y.multiSelect?"group":"radiogroup","aria-label":y.question,children:y.options.map(L=>{var P;return s.jsx(Db,{label:L.label,description:L.description||L.preview,selected:(((P=I.answers[y.questionId])==null?void 0:P.selectedLabels)||[]).includes(L.label),multiSelect:y.multiSelect,disabled:t,onClick:()=>w(y,L.label)},L.label)})}),y.allowFreeform&&s.jsxs("label",{className:"block",children:[s.jsx("span",{className:"mb-1 block text-xs font-semibold text-text-muted",children:o("interactivePrompt.other")}),s.jsx("textarea",{value:((D=i[y.questionId])==null?void 0:D.freeformText)||"",disabled:t,onChange:L=>v(y.questionId,L.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:!x&&d>0&&s.jsx("button",{type:"button",className:"btn btn-ghost btn-sm",onClick:j,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:a,disabled:t,children:"Cancel"}),x||h?s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:A,disabled:!k||t||!u,children:t?"Submitting...":"Submit"}):s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:N,disabled:!S||t,children:"Next"})]})]})]})})}function Ca(e,t={}){if(!e)return"";const{suffix:n="",nowLabel:r="now",nowThreshold:a=60}=t,o=Date.now()-e,i=Math.floor(o/1e3);if(i<a)return r;const c=Math.floor(i/60);if(c<60)return`${c}m${n}`;const d=Math.floor(c/60);if(d<24)return`${d}h${n}`;const p=Math.floor(d/24);return p<7?`${p}d${n}`:new Date(e).toLocaleDateString()}const uu=e=>Ca(e);function Pb(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",a=e.status==="waiting_approval";return{isReconnecting:t,isConnecting:n,isGenerating:r,isWaiting:a}}function pu(e){const t=new Map,n=(r,a)=>{r&&t.set(r,{sessionId:r,...Pb(a)})};for(const r of e)if(r.type!=="adhdev-daemon"){n(r.sessionId,r);for(const a of r.childSessions||[])n(a.id,a)}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 ja(e,t,n){const r=Ds(e,t),a=An(e),o=a.isReconnecting,i=a.isConnecting,c=a.isGenerating,d=a.isWaiting,p=r.inboxBucket==="needs_attention"||e.status==="needs_attention"||e.status==="waiting_for_user_input"||d,u=r.inboxBucket==="working"||c,f=!!(r.inboxBucket==="task_complete"&&r.unread&&!(n!=null&&n.hideOpenTaskCompleteUnread&&(n!=null&&n.isOpenConversation)));return{unread:f,requiresAction:p,isWorking:u,isReconnecting:o,isConnecting:i,isGenerating:c,isWaiting:d,inboxBucket:p?"needs_attention":u?"working":f?"task_complete":"idle"}}function Lb(e,t,n){return ja(e,t,{hideOpenTaskCompleteUnread:!0,isOpenConversation:n==null?void 0:n.isOpenConversation}).unread}function mu({activeConv:e,onModalButton:t}){const{t:n}=Ne(),[r,a]=l.useState(null);if(l.useEffect(()=>{a(null)},[e.modalMessage,e.status,e.connectionState]),!An(e).isWaiting||!e.modalButtons)return null;const i=d=>{r||(a(d),t(d))},c=d=>d.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((d,p)=>{const u=c(d).toLowerCase(),m=/^(run|approve|accept|yes|allow|always)/.test(u),f=/^(reject|deny|delete|remove|abort)/.test(u),g=r===d,C=r!==null;return s.jsx("button",{onClick:()=>i(d),disabled:C,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"} ${C&&!g?"opacity-40":"opacity-100"} ${C?"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:g?"⏳ ...":c(d)},p)})})]})]})}const Li="adhdev_controls_bar_visible",zo="adhdev:controlsbarvisibilitychange";function Ka(e){if(!e)return!1;try{return e.getItem(Li)==="1"}catch{return!1}}function Rb(e,t){if(t)try{t.setItem(Li,e?"1":"0")}catch{}}function Eb(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(zo,{detail:{visible:e}}))}function Ri(){const[e,t]=l.useState(()=>typeof window>"u"?!1:Ka(window.localStorage)),n=l.useRef(e),r=l.useCallback((i,c=!0)=>{n.current=i,t(i),typeof window<"u"&&Rb(i,window.localStorage),c&&Eb(i)},[]);l.useEffect(()=>{const i=d=>{const p=d.detail,u=typeof(p==null?void 0:p.visible)=="boolean"?p.visible:Ka(window.localStorage);n.current=u,t(u)},c=d=>{if(d.key!==Li)return;const p=Ka(window.localStorage);n.current=p,t(p)};return window.addEventListener(zo,i),window.addEventListener("storage",c),()=>{window.removeEventListener(zo,i),window.removeEventListener("storage",c)}},[]);const a=l.useCallback(i=>{r(i)},[r]),o=l.useCallback(()=>{r(!n.current)},[r]);return{isVisible:e,setVisibility:a,toggleVisibility:o}}const hu=["en","ko","ja","zh-CN","es"],Qn="en",Va=[{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"&&hu.includes(e)}function _b(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"},Hb={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"},Ob={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"},Ub={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."},metaChips:{meshNode:"Mesh Node"},versionBanner:{required:"required",retry:"retry"},remoteDialog:{history:"History"},sourceTimeline:{colWhen:"When",colEvent:"Event",colFrom:"From",colTo:"To",colCause:"Cause"}},Gb={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"},qb={processing:"PROCESSING...",actionRequired:"ACTION REQUIRED"},zb={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"},Kb={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)"},Vb={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",tooltipLocalChanges:"Local changes",tooltipHasConflicts:"Has conflicts",tooltipOutOfSync:"Out of sync",tooltipNeedsFollowUp:"Needs follow-up",tooltipUpstreamUnverified:"Upstream unverified",tooltipStartedNotReported:"Started: not reported",tooltipRefineCompleted:"refine completed",tooltipRefinedBranch:"refined {{branch}}",tooltipP2PRelayed:"P2P link relayed through TURN (slower path)",tooltipP2PRtt:"P2P round-trip latency",tooltipPrefixStatus:"Status:",tooltipPrefixBranch:"Branch:",tooltipPrefixNote:"Note:"},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"},dialog:{kicker:"Mesh observability",showDetails:"Show mesh details",hideDetails:"Hide mesh details",refreshedAt:"Refreshed {{time}}",liveMetadata:"Live daemon metadata",metadataUnavailable:"Metadata subscription unavailable",refreshTitle:"Refresh live mesh graph",refresh:"Refresh",refreshing:"Refreshing…",loadingStatus:"Loading live mesh status…",noGraph:"No live mesh graph is available for this coordinator yet.",errorNoMeshId:"This coordinator does not expose a live mesh id.",errorUnexpectedPayload:"mesh_status returned an unexpected payload."},health:{panelTitle:"Mesh Health Panel",lastActivity:"Last activity",refineJobs:"Refine jobs",failedTasks:"Failed tasks",staleWork:"Stale work",sessions:"Sessions"}},Yb={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"}},Jb={copyMessage:"Copy message"},Qb={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..."},Xb={attachImage:"Attach image",placeholder:"Send message to {{panel}}... (Shift+Enter for newline)",sendMessage:"Send message",dropImage:"Drop image here"},Zb={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.",noTabsInGroup:"No tabs in this group",pressEscToCancel:"Press Esc to cancel"},eg={loadOlderOutput:"Load older terminal output",loadingOlder:"Loading older...",debug:"Debug",copy:"Copy",openControlKeys:"Open terminal control keys",closeControlKeys:"Close terminal control keys"},tg={muteThis:"Mute this chat",unmuteThis:"Unmute this chat",mutedTitle:"Muted — notifications silenced. Click to unmute.",muteTitle:"Mute notifications for this chat"},sg={switchToTerminal:"Switch to Terminal view",switchToChat:"Switch to Chat view"},ng={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."},rg={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…"}},ag={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",frozenFeatureTitle:"Frozen — this feature is paused and not available. See docs/FROZEN_SURFACES.md"},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 →",frozenFeatureTitle:"Frozen — this feature is paused. See docs/FROZEN_SURFACES.md"},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.",defaultMemberName:"team member",defaultMemberNameCapitalized:"Team member",sessionFallback:"Session",timeNow:"now",yourSession:"Your session",viewSessionTitle:"{{action}} {{sessionName}} session",viewingRestricted:"Viewing restricted by policy"},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",unknownError:"Unknown error"},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"},announcementBanner:{eyebrow:"System Notice",visibleUntil:"Visible until {{time}}",dismiss:"Dismiss"},upgradeBanner:{button:"Upgrade →"},push:{title:"Push Notifications",descUnsupported:"Not supported in this browser",descDenied:"Blocked — enable in browser settings",descEnabled:"Server-side push enabled",descDefault:"Get alerts even when tab is closed",docs:"Docs",docsLink:"Push Notifications docs",sent:"Sent",test:"Test",docsHintPrefix:"Setup steps, iPhone PWA requirements, and browser compatibility are documented in ",docsHintSuffix:".",iosHint:"On iPhone and iPad, push only works from the installed Safari PWA. A normal Safari tab cannot receive ADHDev push notifications.",budget:"Current plan push budget: {{used}}/{{limit}} used today{{remaining}}{{resets}}.",budgetRemaining:", {{count}} remaining",budgetResets:" • Resets at {{time}}",unsupportedWarning:"This browser does not support Web Push here. Use Safari PWA on iPhone/iPad or a Chromium browser on desktop/Android.",deniedWarning:"Notifications are blocked in browser or site settings. Re-enable them there, then turn Push Notifications on again.",registeredDevices:"Registered devices: {{count}}",noDevices:"No active push devices found.",deviceLabel:"Device {{number}}",thisDevice:"This device",lastActive:"Last active:",removing:"Removing...",removeHere:"Remove here",remove:"Remove"},mesh:{manualMcpSetup:"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",couldNotLoadMeshes:"Could not load meshes",untitledMesh:"Untitled mesh",chooseMachineFirst:"Choose a machine first.",launchFailed:"Launch failed",coordinatorLaunchFailed:"Coordinator launch failed",coordinatorLaunched:"Coordinator launched ({{sessionId}})",coordinatorLaunchSent:"Coordinator launch command sent"},plans:{free:"Free",pro:"Pro",ultra:"Ultra",team:"Team",enterprise:"Enterprise"},adminAudit:{title:"Global Audit",subtitle:"System-wide event tracking",allActions:"All Actions",allSources:"All Sources",filter:"Filter",noLogs:"No logs found",loading:"Loading...",loadMore:"Load More ↓"},adminDashboard:{failedToLoad:"Failed to load admin data",title:"Admin Dashboard",subtitle:"Service overview & management",accessDenied:"Admin access denied",backToDashboard:"Back to Dashboard",loading:"Loading admin dashboard",loadingDesc:"Collecting service stats and recent audit activity.",totalUsers:"Total Users",todayCommands:"Today Commands",activeApiKeys:"Active API Keys",todayLogins:"Today Logins",planDistribution:"Plan Distribution",quickActions:"Quick Actions",manageUsers:"Manage Users",apiKeys:"API Keys",auditLogs:"Audit Logs",systemConfig:"System Config",recentActivity:"Recent Activity",viewAll:"View All",noRecentActivity:"No recent activity"},adminSystem:{error:"Error: {{message}}",announcementSent:"Announcement sent",announcementCleared:"Announcement cleared",registrationOpened:"Registration opened — anyone can sign up",registrationClosed:"Registration closed",title:"System Settings",subtitle:"Announcements & system configuration",loading:"Loading system settings",loadingDesc:"Fetching registration policy and current announcement state.",registration:"Registration",registrationOpenState:"Open — anyone can sign up",registrationClosedState:"Closed — only allowed emails",registrationDesc:"When closed, only emails added to the allowed list can create a new account. Existing users are never affected.",closeRegistration:"Close registration",openRegistration:"Open registration",announcement:"Announcement",current:"Current:",untilTime:"(until {{time}})",untilCleared:"(until cleared)",announcementPlaceholder:"Enter announcement message...",severityInfo:"Info",severityWarning:"Warning",severityCritical:"Critical",duration1h:"1 hour",duration6h:"6 hours",duration24h:"24 hours",duration7d:"7 days",durationUntilCleared:"Until cleared",send:"Send"},adminUsers:{error:"Error: {{message}}",roleUpdated:"Role updated",planUpdated:"Plan updated",suspensionReasonPrompt:"Enter suspension reason:",userSuspended:"User suspended",userUnsuspended:"User unsuspended",title:"User Management",subtitle:"Manage users, roles, and suspension",usersTotal:"users total",searchPlaceholder:"Search email or name...",allRoles:"All Roles",roleUser:"User",roleAdmin:"Admin",roleSuperAdmin:"Super Admin",allPlans:"All Plans",search:"Search",colUser:"User",colRole:"Role",colPlan:"Plan",colStatus:"Status",colCreated:"Created",colActions:"Actions",noName:"No name",statusSuspended:"Suspended",statusActive:"Active",unsuspend:"Unsuspend",suspend:"Suspend",loading:"Loading...",prev:"← Prev",next:"Next →"}},og={openMenu:"Open menu",closeMenu:"Close menu"},ig={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}}"},lg={zoomOut:"Zoom Out",zoomIn:"Zoom In",resetZoom:"Reset Zoom",toggleFullscreen:"Toggle Fullscreen"},cg={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",waitingState:{turnRelayActive:"TURN relay active"}},dg={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"},ug={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"}},pg={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..."},card:{sectionIDEs:"IDEs",sectionCLIs:"CLIs",sectionACPAgents:"ACP Agents",emptyHeadline:"Welcome to ADHDev",emptyBody:"Connect your first machine to the dashboard. Run setup once, then start ADHDev on that machine:",emptyDocsLink:"📚 Read the documentation →",hidden:"Hidden",pageTitle:"Burrows",burrowCount_one:"{{count}} burrow",burrowCount_other:"{{count}} burrows",onlineCount_one:"{{count}} online",onlineCount_other:"{{count}} online",agentsActive_one:"{{count}} agent active",agentsActive_other:"{{count}} agents active",activeNow:"Active Now",generating:"generating",connectionFailed:"Connection failed",reconnect:"Reconnect",connecting:"Connecting...",runtimePolling:"Runtime polling",transportRelay:"TURN relay — direct connection failed",transportDirect:"Direct connection (STUN/host)",noAgentsRunning:"No agents running yet",launchCta:"Launch →"},detail:{notFound:"Machine not found",save:"Save",cancel:"Cancel",loading:"⏳ Loading machine...",offlineHint:"The machine may be offline or not yet connected.",back:"← Back",tabWorkspace:"Workspace",tabHostedRuntimes:"Hosted Runtimes",tabProviders:"Providers",tabSystem:"System",tabLogs:"Logs",clickToSetNickname:"Click to set nickname",nicknamePlaceholder:"Machine nickname...",reconnect:"Reconnect",coresCount_one:"{{count}} core",coresCount_other:"{{count}} cores",p2pState:"P2P {{state}}",p2pConnected:"connected"},commandCenter:{currentChats:"Current Chats",recentLaunches:"Recent Launches",daemonUpdate:"Daemon Update"},workspaceBrowse:{currentFolder:"Current folder"},managedWorkspaces:{remove:"Remove"}},mg={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"},providerPriority:{available:"available",notOnMachine:"not on this machine",remove:"Remove",addCliLabel:"Add available CLI provider",addProvider:"Add provider"},coordinatorPrompts:{overrideDesc:"<strong>Override</strong> replaces the daemon's built-in base prompt for that CLI.",appendDesc:"<strong>Append</strong> stacks after whichever base wins.",overrideLabel:"Override",appendLabel:"Append"},appearance:{modeLabel:"Mode",themeLabel:"Theme",mobileLabel:"Mobile"}},hg={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..."},fg={nav:{home:"ADHDev Home",mesh:"Mesh",what:"What",agents:"Agents",pricing:"Pricing",install:"Install",github:"GitHub",docs:"Docs",getStarted:"Get started",toggleMenu:"Toggle menu",mainNavigation:"Main navigation"},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."}},bg={selectAllThatApply:"Select all that apply",other:"Other"},gg={changeList:{binaryBadge:"bin",truncatedNote:"File list truncated — run <code>git status</code> locally for full output."},statusDialog:{conflicts:"conflicts",clean:"clean"}},xg={header:{back:"Back"}},vg={title:"Notifications",subtitle:"Alerts, auto-approve & provider settings",sectionBrowserAlerts:"Browser alerts",masterToggleLabel:"Notifications",masterToggleDesc:"Master toggle for all alerts",browserNotificationsLabel:"Browser Notifications",browserNotificationsDesc:"Desktop alerts when tab is inactive",browserBackgroundInfo:"Browser alerts only fire while this dashboard tab stays open in the background.",browserBackgroundInfoWithPush:"Browser alerts only fire while this dashboard tab stays open in the background. If you close the tab, use Push Notifications instead.",standaloneBackgroundInfo:"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.",permissionDefault:"This browser has not granted notification permission yet. Allow it to receive browser alerts.",standalonePermissionDefault:"This browser has not granted notification permission yet. Allow it to receive local browser alerts.",allowNotifications:"Allow notifications",permissionDenied:"Browser notifications are blocked in site or browser settings. Re-enable them there to receive desktop alerts.",standalonePermissionUnsupported:"This browser cannot show desktop notifications here. Keep the dashboard visible, or use another supported browser on this device.",permissionUnsupported:"This browser cannot show desktop notifications here. Use a supported desktop browser, or rely on Push Notifications where available.",completionAlertsLabel:"Completion Alerts",completionAlertsDesc:"Notify when agent finishes a task",approvalAlertsLabel:"Approval Alerts",approvalAlertsDesc:"Notify when agent needs approval",connectionAlertsLabel:"Connection Alerts",connectionAlertsDesc:"Alert when a machine disconnects",allDisabled:"All notifications are disabled. Enable the master toggle to configure.",sectionProviderAlerts:"Provider alert rules",loading:"⏳ Loading...",refresh:"↻ Refresh",noOnlineMachines:"No online machines. Start ADHDev on a machine to configure provider alerts.",loadingProviderSettings:"Loading provider settings...",providerCount_one:"{{count}} provider",providerCount_other:"{{count}} providers",keyStatAutoApprove:"Auto Approve",keyStatApprovalAlert:"Approval Alert",keyStatNoProgressAlert:"No Progress Alert",bulkEnabledAll:"Enabled for all {{total}} providers",bulkDisabledAll:"Disabled for all {{total}} providers",bulkEnabledSome:"Enabled for {{onCount}} of {{total}} providers",hideDetails:"▾ Hide details",showDetails:"▸ Show per-provider details ({{count}})",soundEffectsLabel:"Sound Effects",soundEffectsDesc:"Play a sound when agent completes or needs approval"},yg={language:$b,common:Hb,connection:Bb,toast:Fb,notification:Ob,event:Wb,dashboard:Ub,cliStop:Gb,approval:qb,newSession:zb,mobileInbox:Kb,meshGraph:Vb,repoMesh:Yb,chat:Jb,chatPane:Qb,chatInput:Xb,paneGroup:Zb,terminal:eg,conversation:tg,cliView:sg,launch:ng,standalone:rg,cloud:ag,app:og,chatList:ig,screenshot:lg,remote:cg,sessionInfo:dg,mesh:ug,machine:pg,settings:mg,historyModal:hg,landing:fg,interactivePrompt:bg,git:gg,ide:xg,notifications:vg},wg={label:"언어",select:"언어 선택"},kg={cancel:"취소"},Sg={disconnected:"연결 끊김",connected:"연결됨",connectedToDashboard:"대시보드에 연결됨",connectingToMachine:"머신에 연결 중...",networkOffline:"네트워크 오프라인",reconnecting:"재연결 중",sessionExpired:"세션이 만료되었습니다.",logInAgain:"다시 로그인",connectionFailed:"연결에 실패했습니다 — 페이지를 새로고침하거나 잠시 후 다시 시도하세요.",reconnectNow:"지금 재연결"},Cg={label:{success:"완료",warning:"주의",info:"업데이트"},dismiss:"닫기"},jg={actionNeeded:"조치 필요",taskComplete:"작업 완료",markRead:"읽음 표시",markUnread:"읽지 않음 표시",delete:"삭제"},Ng={taskCompleted:"{{label}} 에이전트 작업 완료",taskCompletedWithDuration:"{{label}} 에이전트 작업 완료 ({{duration}}초)",approvalNeeded:"{{label}} 승인 필요",noProgress:"{{label}} 에이전트 진행 없음",noProgressWithDuration:"{{label}} 에이전트 진행 없음 ({{minutes}}분)",noProgressTitle:"{{label}} — 진행 없음",noProgressBody:"에이전트가 {{duration}} 넘게 진행이 없습니다",viewRequest:"{{requester}}님이 세션 보기를 요청합니다",viewRequestTitle:"보기 요청",viewRequestApproved:"보기 요청이 승인되었습니다",viewRequestDeclined:"{{target}}님이 보기 요청을 거절했습니다",someoneRequester:"팀 멤버",someoneTarget:"팀 멤버"},Ag={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:"대기 중인 활동이 없습니다."},metaChips:{meshNode:"Mesh 노드"},versionBanner:{required:"필수 업데이트",retry:"재시도"},remoteDialog:{history:"히스토리"},sourceTimeline:{colWhen:"시간",colEvent:"이벤트",colFrom:"출발",colTo:"도착",colCause:"원인"}},Ig={title:"{{agent}}을(를) 중지할까요?",gracefulDescription:"중지는 지원되는 경우 프로바이더에게 정상 종료를 요청합니다. 강제 중지는 런타임을 즉시 종료합니다.",forceOnlyDescription:"이 프로바이더는 정상 중지를 지원하지 않습니다. 강제 중지는 런타임을 즉시 종료합니다.",stop:"중지",forceStop:"강제 중지"},Tg={processing:"처리 중...",actionRequired:"조치 필요"},Mg={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:"세션을 재개할 수 없습니다"},Dg={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:"세션 중지 (에이전트를 종료합니다)"},Pg={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:"정제됨",tooltipLocalChanges:"로컬 변경 사항",tooltipHasConflicts:"충돌 있음",tooltipOutOfSync:"미동기화",tooltipNeedsFollowUp:"후속 작업 필요",tooltipUpstreamUnverified:"업스트림 미확인",tooltipStartedNotReported:"시작됨: 미보고",tooltipRefineCompleted:"refine 완료",tooltipRefinedBranch:"refined {{branch}}",tooltipP2PRelayed:"P2P 링크가 TURN을 통해 중계됨 (느린 경로)",tooltipP2PRtt:"P2P 왕복 지연",tooltipPrefixStatus:"상태:",tooltipPrefixBranch:"브랜치:",tooltipPrefixNote:"메모:"},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:"알 수 없는 프로바이더"},dialog:{kicker:"Mesh 관측",showDetails:"메시 세부 정보 표시",hideDetails:"메시 세부 정보 숨기기",refreshedAt:"{{time}} 갱신됨",liveMetadata:"라이브 데몬 메타데이터",metadataUnavailable:"메타데이터 구독 불가",refreshTitle:"라이브 메시 그래프 새로 고침",refresh:"새로 고침",refreshing:"새로 고침 중…",loadingStatus:"라이브 메시 상태 로딩 중…",noGraph:"이 코디네이터에 대한 라이브 메시 그래프가 아직 없습니다.",errorNoMeshId:"이 코디네이터는 라이브 메시 ID를 노출하지 않습니다.",errorUnexpectedPayload:"mesh_status가 예상치 못한 응답을 반환했습니다."},health:{panelTitle:"메시 헬스 패널",lastActivity:"마지막 활동",refineJobs:"Refine 작업",failedTasks:"실패한 작업",staleWork:"지연된 작업",sessions:"세션"}},Lg={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"}},Rg={copyMessage:"메시지 복사"},Eg={connectingToMachine:"머신에 연결 중",establishingP2P:"P2P 연결 설정 중",agentNotMonitored:"에이전트 모니터링 안 됨",clickToSwitchMonitoring:"이 에이전트로 모니터링 전환하려면 클릭하세요",agentPanelHidden:"에이전트 패널이 아직 표시되지 않습니다",openPanelHint:"사용 중인 앱에서 에이전트 패널이나 채팅 보기를 열어 메시지를 확인하세요",noMessagesYet:"아직 메시지가 없습니다",loadingChat:"채팅 불러오는 중...",openPanel:"{{label}} 패널 열기",switchingPanel:"전환 중...",openingPanel:"여는 중..."},_g={attachImage:"이미지 첨부",placeholder:"{{panel}}에 메시지 전송... (줄바꿈은 Shift+Enter)",sendMessage:"메시지 전송",dropImage:"여기에 이미지를 놓으세요"},$g={noConversations:"아직 대화가 없습니다",waitingForDaemon:"데몬을 기다리는 중",connectYourMachines:"머신을 연결하세요",daemonDescription:"ADHDev 데몬을 시작하여 이 대시보드에 연결하세요. 온라인이 되면 설치된 프로바이더로 세션을 실행할 수 있습니다.",installDescription:"머신에 ADHDev를 설치하고 로그인하면 여기에 표시됩니다.",newSession:"새 세션",newSessionDescription:"연결된 머신이 준비되었습니다. CLI, ACP, IDE 중 설치된 프로바이더로 새 세션을 시작하세요.",noTabsInGroup:"이 그룹에 탭이 없습니다",pressEscToCancel:"Esc를 눌러 취소"},Hg={loadOlderOutput:"이전 터미널 출력 불러오기",loadingOlder:"이전 항목 불러오는 중...",debug:"디버그",copy:"복사",openControlKeys:"터미널 제어 키 열기",closeControlKeys:"터미널 제어 키 닫기"},Bg={muteThis:"이 채팅 음소거",unmuteThis:"이 채팅 음소거 해제",mutedTitle:"음소거됨 — 알림이 차단되었습니다. 클릭하여 해제하세요.",muteTitle:"이 채팅 알림 음소거"},Fg={switchToTerminal:"터미널 보기로 전환",switchToChat:"채팅 보기로 전환"},Og={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:"저장된 기록을 재개하기 전에 대상 워크스페이스를 확인하거나 변경하세요."},Wg={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:"저장 중…"}},Ug={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}}일 전",frozenFeatureTitle:"동결됨 — 이 기능은 일시 중지되어 사용할 수 없습니다. docs/FROZEN_SURFACES.md 참고"},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 레퍼런스 →",frozenFeatureTitle:"동결됨 — 이 기능은 일시 중지되었습니다. docs/FROZEN_SURFACES.md 참고"},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:"정말 이 워크스페이스를 나가시겠습니까? 플랜이 다운그레이드될 수 있습니다.",defaultMemberName:"팀 멤버",defaultMemberNameCapitalized:"팀 멤버",sessionFallback:"세션",timeNow:"방금",yourSession:"내 세션",viewSessionTitle:"{{sessionName}} 세션 {{action}}",viewingRestricted:"정책에 의해 보기가 제한됨"},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:"제어 공유에는 인증이 필요합니다",unknownError:"알 수 없는 오류"},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:"닫기"},announcementBanner:{eyebrow:"시스템 공지",visibleUntil:"{{time}}까지 표시",dismiss:"닫기"},upgradeBanner:{button:"업그레이드 →"},push:{title:"푸시 알림",descUnsupported:"이 브라우저에서는 지원되지 않습니다",descDenied:"차단됨 — 브라우저 설정에서 허용하세요",descEnabled:"서버 푸시 활성화됨",descDefault:"탭이 닫혀 있어도 알림을 받으세요",docs:"문서",docsLink:"푸시 알림 문서",sent:"전송됨",test:"테스트",docsHintPrefix:"설정 단계, iPhone PWA 요구사항, 브라우저 호환성은 ",docsHintSuffix:"에 정리되어 있습니다.",iosHint:"iPhone과 iPad에서는 설치된 Safari PWA에서만 푸시가 동작합니다. 일반 Safari 탭은 ADHDev 푸시 알림을 받을 수 없습니다.",budget:"현재 플랜 푸시 한도: 오늘 {{used}}/{{limit}} 사용{{remaining}}{{resets}}.",budgetRemaining:", {{count}}개 남음",budgetResets:" • {{time}}에 초기화",unsupportedWarning:"이 브라우저는 여기서 웹 푸시를 지원하지 않습니다. iPhone/iPad에서는 Safari PWA를, 데스크톱/Android에서는 Chromium 계열 브라우저를 사용하세요.",deniedWarning:"브라우저 또는 사이트 설정에서 알림이 차단되어 있습니다. 그곳에서 다시 허용한 뒤 푸시 알림을 다시 켜세요.",registeredDevices:"등록된 기기: {{count}}",noDevices:"활성 푸시 기기가 없습니다.",deviceLabel:"기기 {{number}}",thisDevice:"이 기기",lastActive:"마지막 활동:",removing:"제거 중...",removeHere:"여기서 제거",remove:"제거"},mesh:{manualMcpSetup:"이 프로바이더는 Repo Mesh 코디네이터로 동작하려면 수동 MCP 설정이 필요합니다.",couldNotLoadMeshes:"메시를 불러오지 못했습니다",untitledMesh:"제목 없는 메시",chooseMachineFirst:"먼저 머신을 선택하세요.",launchFailed:"실행 실패",coordinatorLaunchFailed:"코디네이터 실행 실패",coordinatorLaunched:"코디네이터 실행됨 ({{sessionId}})",coordinatorLaunchSent:"코디네이터 실행 명령을 보냈습니다"},plans:{free:"Free",pro:"Pro",ultra:"Ultra",team:"Team",enterprise:"Enterprise"},adminAudit:{title:"전역 감사",subtitle:"시스템 전역 이벤트 추적",allActions:"모든 작업",allSources:"모든 소스",filter:"필터",noLogs:"로그가 없습니다",loading:"불러오는 중...",loadMore:"더 보기 ↓"},adminDashboard:{failedToLoad:"관리자 데이터를 불러오지 못했습니다",title:"관리자 대시보드",subtitle:"서비스 개요 및 관리",accessDenied:"관리자 접근이 거부되었습니다",backToDashboard:"대시보드로 돌아가기",loading:"관리자 대시보드 불러오는 중",loadingDesc:"서비스 통계와 최근 감사 활동을 수집하는 중입니다.",totalUsers:"전체 사용자",todayCommands:"오늘 명령",activeApiKeys:"활성 API 키",todayLogins:"오늘 로그인",planDistribution:"플랜 분포",quickActions:"빠른 작업",manageUsers:"사용자 관리",apiKeys:"API 키",auditLogs:"감사 로그",systemConfig:"시스템 설정",recentActivity:"최근 활동",viewAll:"전체 보기",noRecentActivity:"최근 활동 없음"},adminSystem:{error:"오류: {{message}}",announcementSent:"공지가 전송되었습니다",announcementCleared:"공지가 해제되었습니다",registrationOpened:"가입이 열렸습니다 — 누구나 가입할 수 있습니다",registrationClosed:"가입이 닫혔습니다",title:"시스템 설정",subtitle:"공지 및 시스템 구성",loading:"시스템 설정 불러오는 중",loadingDesc:"가입 정책과 현재 공지 상태를 가져오는 중입니다.",registration:"가입",registrationOpenState:"열림 — 누구나 가입 가능",registrationClosedState:"닫힘 — 허용된 이메일만",registrationDesc:"닫혀 있으면 허용 목록에 추가된 이메일만 새 계정을 만들 수 있습니다. 기존 사용자는 영향을 받지 않습니다.",closeRegistration:"가입 닫기",openRegistration:"가입 열기",announcement:"공지",current:"현재:",untilTime:"({{time}}까지)",untilCleared:"(해제될 때까지)",announcementPlaceholder:"공지 메시지를 입력하세요...",severityInfo:"정보",severityWarning:"경고",severityCritical:"심각",duration1h:"1시간",duration6h:"6시간",duration24h:"24시간",duration7d:"7일",durationUntilCleared:"해제될 때까지",send:"전송"},adminUsers:{error:"오류: {{message}}",roleUpdated:"역할이 변경되었습니다",planUpdated:"플랜이 변경되었습니다",suspensionReasonPrompt:"정지 사유를 입력하세요:",userSuspended:"사용자가 정지되었습니다",userUnsuspended:"사용자 정지가 해제되었습니다",title:"사용자 관리",subtitle:"사용자, 역할, 정지 관리",usersTotal:"명 전체",searchPlaceholder:"이메일 또는 이름 검색...",allRoles:"모든 역할",roleUser:"사용자",roleAdmin:"관리자",roleSuperAdmin:"슈퍼 관리자",allPlans:"모든 플랜",search:"검색",colUser:"사용자",colRole:"역할",colPlan:"플랜",colStatus:"상태",colCreated:"생성일",colActions:"작업",noName:"이름 없음",statusSuspended:"정지됨",statusActive:"활성",unsuspend:"정지 해제",suspend:"정지",loading:"불러오는 중...",prev:"← 이전",next:"다음 →"}},Gg={openMenu:"메뉴 열기",closeMenu:"메뉴 닫기"},qg={loadingOlderMessages:"이전 메시지 불러오는 중...",waitingForMessages:"메시지를 기다리는 중...",agentGenerating:"에이전트가 응답 중...",jumpToTop:"맨 위로 이동",jumpToOldestMessages:"가장 오래된 메시지로 이동",top:"↑ 맨 위",latest:"↓ 최신",jumpToLatestMessages:"최신 메시지로 이동",jumpToBottom:"맨 아래로 이동",showEarlierMessages:"↑ 이전 메시지 {{count}}개 표시...",showEarlierMessagesHidden:"↑ 이전 메시지 {{count}}개 표시... ({{total}}개 숨김)",loadOlderMessages:"↑ 이전 메시지 불러오기",loadErrorRetry:"↻ {{error}}"},zg={zoomOut:"축소",zoomIn:"확대",resetZoom:"확대/축소 초기화",toggleFullscreen:"전체화면 전환"},Kg={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 릴레이 사용량",waitingState:{turnRelayActive:"TURN 릴레이 활성"}},Vg={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:"연결된 클라이언트"},Yg={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:"워크스페이스"}},Jg={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:"연결 중..."},card:{sectionIDEs:"IDEs",sectionCLIs:"CLIs",sectionACPAgents:"ACP 에이전트",emptyHeadline:"ADHDev에 오신 것을 환영합니다",emptyBody:"대시보드에 첫 번째 머신을 연결하세요. 한 번만 설정하면 해당 머신에서 ADHDev를 시작할 수 있습니다:",emptyDocsLink:"📚 문서 읽기 →",hidden:"숨김",pageTitle:"Burrows",burrowCount_one:"버로우 {{count}}개",burrowCount_other:"버로우 {{count}}개",onlineCount_one:"{{count}}개 온라인",onlineCount_other:"{{count}}개 온라인",agentsActive_one:"에이전트 {{count}}개 활성",agentsActive_other:"에이전트 {{count}}개 활성",activeNow:"활성 중",generating:"생성 중",connectionFailed:"연결 실패",reconnect:"재연결",connecting:"연결 중...",runtimePolling:"런타임 폴링 중",transportRelay:"TURN 릴레이 — 직접 연결 실패",transportDirect:"직접 연결 (STUN/host)",noAgentsRunning:"실행 중인 에이전트 없음",launchCta:"실행 →"},detail:{notFound:"머신을 찾을 수 없습니다",save:"저장",cancel:"취소",loading:"⏳ 머신 불러오는 중...",offlineHint:"머신이 오프라인이거나 아직 연결되지 않았을 수 있습니다.",back:"← 뒤로",tabWorkspace:"워크스페이스",tabHostedRuntimes:"호스팅 런타임",tabProviders:"프로바이더",tabSystem:"시스템",tabLogs:"로그",clickToSetNickname:"클릭하여 닉네임 설정",nicknamePlaceholder:"머신 닉네임...",reconnect:"재연결",coresCount_one:"{{count}}코어",coresCount_other:"{{count}}코어",p2pState:"P2P {{state}}",p2pConnected:"연결됨"},commandCenter:{currentChats:"현재 채팅",recentLaunches:"최근 실행",daemonUpdate:"데몬 업데이트"},workspaceBrowse:{currentFolder:"현재 폴더"},managedWorkspaces:{remove:"제거"}},Qg={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:"🎨 커스텀"},providerPriority:{available:"사용 가능",notOnMachine:"이 머신에 없음",remove:"제거",addCliLabel:"사용 가능한 CLI 프로바이더 추가",addProvider:"프로바이더 추가"},coordinatorPrompts:{overrideDesc:"<strong>Override</strong>는 해당 CLI의 데몬 내장 기본 프롬프트를 대체합니다.",appendDesc:"<strong>Append</strong>는 선택된 기본 프롬프트 뒤에 추가됩니다.",overrideLabel:"Override",appendLabel:"Append"},appearance:{modeLabel:"모드",themeLabel:"테마",mobileLabel:"모바일"}},Xg={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:"⌛ 새로고침 중..."},Zg={nav:{home:"ADHDev 홈",mesh:"Mesh",what:"소개",agents:"에이전트",pricing:"요금제",install:"설치",github:"GitHub",docs:"문서",getStarted:"시작하기",toggleMenu:"메뉴 토글",mainNavigation:"주 내비게이션"},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."}},ex={selectAllThatApply:"해당하는 항목을 모두 선택하세요",other:"기타"},tx={changeList:{binaryBadge:"bin",truncatedNote:"파일 목록이 잘렸습니다 — 전체 출력은 로컬에서 <code>git status</code>를 실행하세요."},statusDialog:{conflicts:"충돌 있음",clean:"변경 없음"}},sx={header:{back:"뒤로"}},nx={title:"알림",subtitle:"알림, 자동 승인 및 프로바이더 설정",sectionBrowserAlerts:"브라우저 알림",masterToggleLabel:"알림",masterToggleDesc:"모든 알림의 마스터 토글",browserNotificationsLabel:"브라우저 알림",browserNotificationsDesc:"탭이 비활성 상태일 때 데스크톱 알림",browserBackgroundInfo:"브라우저 알림은 이 대시보드 탭이 백그라운드에서 열려 있는 동안에만 발생합니다.",browserBackgroundInfoWithPush:"브라우저 알림은 이 대시보드 탭이 백그라운드에서 열려 있는 동안에만 발생합니다. 탭을 닫으면 푸시 알림을 사용하세요.",standaloneBackgroundInfo:"브라우저 알림은 이 대시보드 탭이 백그라운드에서 열려 있는 동안에만 발생합니다. 탭을 닫으면 스탠드얼론은 호스팅 푸시 알림을 전달할 수 없습니다.",permissionDefault:"이 브라우저는 아직 알림 권한을 허용하지 않았습니다. 브라우저 알림을 받으려면 허용하세요.",standalonePermissionDefault:"이 브라우저는 아직 알림 권한을 허용하지 않았습니다. 로컬 브라우저 알림을 받으려면 허용하세요.",allowNotifications:"알림 허용",permissionDenied:"사이트 또는 브라우저 설정에서 알림이 차단되었습니다. 데스크톱 알림을 받으려면 해당 설정에서 다시 활성화하세요.",standalonePermissionUnsupported:"이 브라우저에서는 데스크톱 알림을 표시할 수 없습니다. 대시보드를 계속 열어두거나 지원되는 다른 브라우저를 사용하세요.",permissionUnsupported:"이 브라우저에서는 데스크톱 알림을 표시할 수 없습니다. 지원되는 데스크톱 브라우저를 사용하거나 가능한 경우 푸시 알림을 이용하세요.",completionAlertsLabel:"완료 알림",completionAlertsDesc:"에이전트가 작업을 완료하면 알림",approvalAlertsLabel:"승인 알림",approvalAlertsDesc:"에이전트가 승인을 요청하면 알림",connectionAlertsLabel:"연결 알림",connectionAlertsDesc:"머신 연결이 끊기면 알림",allDisabled:"모든 알림이 비활성화되었습니다. 마스터 토글을 활성화하여 설정하세요.",sectionProviderAlerts:"프로바이더 알림 규칙",loading:"⏳ 불러오는 중...",refresh:"↻ 새로고침",noOnlineMachines:"온라인 머신이 없습니다. 프로바이더 알림을 설정하려면 머신에서 ADHDev를 시작하세요.",loadingProviderSettings:"프로바이더 설정 불러오는 중...",providerCount_one:"프로바이더 {{count}}개",providerCount_other:"프로바이더 {{count}}개",keyStatAutoApprove:"자동 승인",keyStatApprovalAlert:"승인 알림",keyStatNoProgressAlert:"진행 없음 알림",bulkEnabledAll:"전체 {{total}}개 프로바이더에 활성화됨",bulkDisabledAll:"전체 {{total}}개 프로바이더에 비활성화됨",bulkEnabledSome:"{{total}}개 중 {{onCount}}개 프로바이더에 활성화됨",hideDetails:"▾ 상세 숨기기",showDetails:"▸ 프로바이더별 상세 보기 ({{count}})",soundEffectsLabel:"사운드 효과",soundEffectsDesc:"에이전트가 완료하거나 승인이 필요할 때 사운드 재생"},rx={language:wg,common:kg,connection:Sg,toast:Cg,notification:jg,event:Ng,dashboard:Ag,cliStop:Ig,approval:Tg,newSession:Mg,mobileInbox:Dg,meshGraph:Pg,repoMesh:Lg,chat:Rg,chatPane:Eg,chatInput:_g,paneGroup:$g,terminal:Hg,conversation:Bg,cliView:Fg,launch:Og,standalone:Wg,cloud:Ug,app:Gg,chatList:qg,screenshot:zg,remote:Kg,sessionInfo:Vg,mesh:Yg,machine:Jg,settings:Qg,historyModal:Xg,landing:Zg,interactivePrompt:ex,git:tx,ide:sx,notifications:nx},ax={label:"言語",select:"言語を選択"},ox={cancel:"キャンセル"},ix={disconnected:"切断されました",connected:"接続済み",connectedToDashboard:"ダッシュボードに接続しました",connectingToMachine:"マシンに接続しています...",networkOffline:"ネットワークがオフラインです",reconnecting:"再接続しています",sessionExpired:"セッションの有効期限が切れました。",logInAgain:"再度ログイン",connectionFailed:"接続に失敗しました — ページを更新するか、しばらくしてからもう一度お試しください。",reconnectNow:"今すぐ再接続"},lx={label:{success:"完了",warning:"注意",info:"お知らせ"},dismiss:"閉じる"},cx={actionNeeded:"対応が必要です",taskComplete:"タスク完了",markRead:"既読にする",markUnread:"未読にする",delete:"削除"},dx={taskCompleted:"{{label}} エージェントのタスクが完了しました",taskCompletedWithDuration:"{{label}} エージェントのタスクが完了しました({{duration}}秒)",approvalNeeded:"{{label}} の承認が必要です",noProgress:"{{label}} エージェントに進捗がありません",noProgressWithDuration:"{{label}} エージェントに進捗がありません({{minutes}}分)",noProgressTitle:"{{label}} — 進捗なし",noProgressBody:"エージェントは {{duration}} を超えて進捗がありません",viewRequest:"{{requester}} があなたのセッションの閲覧をリクエストしています",viewRequestTitle:"閲覧リクエスト",viewRequestApproved:"閲覧リクエストが承認されました",viewRequestDeclined:"{{target}} があなたの閲覧リクエストを拒否しました",someoneRequester:"チームメンバー",someoneTarget:"チームメンバー"},ux={header:{title:"ダッシュボード",guide:"ダッシュボードガイド",guideOpen:"ダッシュボードガイドを開く",guideShort:"ガイド",openGitStatus:"git ステータスを開く",openMeshGraph:"ライブ Repo Mesh グラフを開く",meshGraph:"Mesh グラフ",stopAcpSession:"ACP セッションを停止",stopCliProcess:"CLI プロセスを停止",chatHistory:"チャット履歴",remoteControl:"リモートコントロール",generating:"生成中",activityInbox:"アクティビティ受信箱"},hidden:{title:"非表示のタブ",dragHint:"タブをここにドラッグして非表示にします。",resetPanels:"パネルをリセット",restoreAll:"すべて復元",hideCurrentTab:"現在のタブを非表示",empty:"非表示のタブはありません。"},inbox:{unread:"未読",read:"既読",empty:"保留中のアクティビティはありません。"},metaChips:{meshNode:"Mesh ノード"},versionBanner:{required:"必須",retry:"再試行"},remoteDialog:{history:"履歴"},sourceTimeline:{colWhen:"日時",colEvent:"イベント",colFrom:"変更前",colTo:"変更後",colCause:"原因"}},px={title:"{{agent}} を停止しますか?",gracefulDescription:"「停止」はサポートされている場合にプロバイダーへ正常な終了を要求します。「強制停止」はランタイムを即座に終了します。",forceOnlyDescription:"このプロバイダーは正常な停止をサポートしていません。「強制停止」はランタイムを即座に終了します。",stop:"停止",forceStop:"強制停止"},mx={processing:"処理中...",actionRequired:"対応が必要です"},hx={title:"セッションを開始",close:"新規セッションダイアログを閉じる",category:"カテゴリ",detectedLocally:"ローカルで検出済み",availableToOpen:"開くことができます",machine:"マシン",selectMachine:"マシン {{name}} を選択",workspace:"ワークスペース",browse:"参照…",launchTargetType:"起動ターゲットタイプ",modeWorkspace:"ワークスペース",modeWorkspaceDesc:"通常のセッション",modeMesh:"Mesh",modeMeshDesc:"コーディネーターセッション",homeDirectory:"ホームディレクトリ",customFolder:"カスタムフォルダー…",launchWithoutWorkspace:"ワークスペースなしで起動します。",selectWorkspaceFolder:"ワークスペースフォルダーを選択してください。",selectFolder:"フォルダーを選択",saving:"保存中…",saveWorkspace:"ワークスペースを保存",loadingMeshes:"メッシュを読み込み中…",noMeshes:"このマシンには Repo Mesh が構成されていません。先にメッシュを作成または同期してから、このピッカーを再度開いてください。",mesh:"Mesh",repoMesh:"Repo mesh",nodeCount_one:"{{count}} ノード",nodeCount_other:"{{count}} ノード",coordinatorWorkspace:"コーディネーターワークスペース: {{path}}",chooseIde:"IDE を選択",chooseCliProvider:"CLI プロバイダーを選択",chooseAcpProvider:"ACP プロバイダーを選択",noProviders:"選択したマシンではこのカテゴリで使用できるものがありません。バイナリがデフォルトの場所以外にある場合は、Providers でカスタム実行パスを設定してください。",startupArguments:"起動引数",optionalFlags:"オプションのフラグ...",modelAndThinking:"モデルと思考(任意)",model:"モデル",providerDefault:"(プロバイダーのデフォルト)",custom:"カスタム…",typeModelName:"モデル名を入力",backToModelList:"← モデル一覧に戻る",thinkingLevel:"思考レベル",selectWorkspaceTitle:"ワークスペースを選択",selectWorkspaceDescription:"この新しいセッションで使用するフォルダーを選択してください。",start:"開始",starting:"開始中…",startMeshCoordinator:"Mesh コーディネーターを開始",startingCoordinator:"コーディネーターを開始中…",startIde:"IDE を起動",startingIde:"IDE を起動しています…",startAcpSession:"ACP セッションを開始",startingAcpSession:"ACP セッションを開始しています…",startFresh:"新規に開始",startingFresh:"新規に開始しています…",resumeSavedHistory:"保存した履歴を再開",resumingSavedHistory:"保存した履歴を再開しています…",errorLoadMeshes:"メッシュを読み込めませんでした",errorLoadFolder:"フォルダを読み込めませんでした",errorLoadSavedSessions:"保存済みセッションを読み込めませんでした",errorSaveWorkspace:"ワークスペースを保存できませんでした",workspaceSaved:"ワークスペースを保存しました。マシンの状態が更新されると一覧に表示されます。",errorManualMcpSetup:"このプロバイダーをメッシュコーディネーターとして使用するには、事前に手動での MCP セットアップが必要です。",errorStartMeshCoordinator:"メッシュコーディネーターを起動できませんでした",errorStartSession:"セッションを開始できませんでした",errorResumeSession:"セッションを再開できませんでした"},fx={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:"ライブの repo mesh グラフを開く",unmute:"{{title}} のミュートを解除",mute:"{{title}} をミュート",mutedTitle:"ミュート中 — 通知が停止されています。タップしてミュートを解除します。",muteNotifications:"通知をミュート",hideConversationAria:"{{title}} を非表示",hideConversationTitle:"会話を非表示",stopSessionAria:"{{title}} セッションを停止",stopSessionTitle:"セッションを停止(エージェントを終了します)"},bx={help:{toggleAria:"メッシュのヘルプ",toggleTitle:"メッシュの概念ヘルプ",regionAria:"メッシュの概念ヘルプ",kicker:"ヘルプ",title:"メッシュの概念を一目で",close:"ヘルプを閉じる",sections:{node:{term:"ノード",summary:"メッシュに参加しているワークスペース — リポジトリのチェックアウト、または分離された git worktree です。",details:["ベースノードと worktree クローンノード — クローンは並行作業を競合なく分離します。","健全性(オンライン/オフライン)と git の状態(ブランチ · ahead/behind · dirty)を併せて表示します。","複数のノードが同じデーモンを共有できます。"]},p2p:{term:"P2P 接続",summary:"選択したコーディネーターが WebRTC を介して各リモートノードに到達する方法です。",details:["direct — 直接のホスト/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:"1 つのゴールを目指すマルチタスクのバッチであり、その取り組みの永続的な記録です。",details:["状態: active / paused / completed / abandoned。","進捗は構成タスクの状態から導出されます。"]},refinery:{term:"Refinery(refine)",summary:"worktree ブランチを安全にベースへ収束・マージするプロセスです。",details:["設定駆動(.adhdev/refine.*)— パッチ等価性のプリフライトと no-op ガードで保護されます。","原則として ff-only。force-push は行いません。","submodule のコミットが 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:["各メンバーは 1 つのプロバイダー(AI)で、任意でノード(マシン)にピン留めでき、レプリカ数を持ちます。","independent — 2 つ以上のプロバイダーかつ 2 つ以上のマシンにまたがるため、一致が真の確信度を高めます。","coupled — 1 つの AI または 1 つのマシンに収束します。重複したメンバーは同じ間違いを繰り返します。","「Panels」タブからマシンローカルに管理し、~/.adhdev/meshes.json で定義します。"]},convergence:{term:"ブランチ収束の状態",summary:"worktree での作業後、各ブランチはちょうど 1 つの最終状態に分類されます。",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:"daemon: {{id}}",run:"run: {{id}}",session:"session: {{id}}"},difficulty:{intro:"各タスクの難易度をブレインに対応付けます。コーディネーターはタスクの難易度を分類し、簡単な作業は低コストのモデルで低い effort で実行し、難しい作業はより強力なモデルで高い effort で実行します。ルーティングのデフォルトを維持するにはフィールドを空欄のままにしてください。",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:"各タスクタイプをレビューするエージェントを選択します。エージェントごとに1行追加してください。",refresh:"更新",loading:"読み込み中…",connectPrompt:"kind → パネルのバインディングを管理するには、コーディネーターデーモンに接続してください。",errorLoad:"kind パネルの読み込みに失敗しました",errorSave:"kind バインディングの保存に失敗しました",errorRemove:"kind バインディングの削除に失敗しました",errorSlotProvider:"スロット {{slot}}: プロバイダーは必須です",errorSlotReplica:"スロット {{slot}}: レプリカ数は 1 以上である必要があります",errorNoSlot:"kind バインディングには少なくとも 1 つのスロットが必要です",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:"未検証(フェッチ失敗)",upstreamUnverified:"未検証",upstreamUnavailable:"利用不可",needsFollowUp:"フォローアップが必要",refined:"精緻化済み",tooltipLocalChanges:"ローカルの変更",tooltipHasConflicts:"コンフリクトあり",tooltipOutOfSync:"同期ずれ",tooltipNeedsFollowUp:"フォローアップが必要",tooltipUpstreamUnverified:"アップストリーム未検証",tooltipStartedNotReported:"開始: 報告なし",tooltipRefineCompleted:"精緻化完了",tooltipRefinedBranch:"{{branch}} をリファイン済み",tooltipP2PRelayed:"P2P リンクは TURN 経由でリレーされています(低速経路)",tooltipP2PRtt:"P2P ラウンドトリップ遅延",tooltipPrefixStatus:"ステータス:",tooltipPrefixBranch:"ブランチ:",tooltipPrefixNote:"メモ:"},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:"プロバイダー不明"},dialog:{kicker:"メッシュの可観測性",showDetails:"メッシュの詳細を表示",hideDetails:"メッシュの詳細を非表示",refreshedAt:"{{time}} に更新",liveMetadata:"ライブデーモンメタデータ",metadataUnavailable:"メタデータのサブスクリプションは利用できません",refreshTitle:"ライブメッシュグラフを更新",refresh:"更新",refreshing:"更新中…",loadingStatus:"ライブメッシュステータスを読み込み中…",noGraph:"このコーディネーターにはまだ利用可能なライブメッシュグラフがありません。",errorNoMeshId:"このコーディネーターはライブメッシュ ID を公開していません。",errorUnexpectedPayload:"mesh_status が予期しないペイロードを返しました。"},health:{panelTitle:"メッシュヘルスパネル",lastActivity:"最終アクティビティ",refineJobs:"リファインジョブ",failedTasks:"失敗したタスク",staleWork:"古い作業",sessions:"セッション"}},gx={page:{title:"Repo Mesh",subtitle:"マルチワークスペースのオーケストレーション",waitingForDaemon:"デーモン接続を待機中...",observabilitySecondary:"メッシュの可観測性"},list:{title:"Repo Mesh 一覧",count_one:"{{count}} 個のメッシュ",count_other:"{{count}} 個のメッシュ",createMesh:"+ メッシュを作成",createTitle:"Repo Mesh を作成",createOnMachine:"マシン上に作成",createOnMachineHint:"メッシュ設定は選択したデーモンに保存されます。",noConnectedDaemon:"接続されているデーモンがありません",workspace:"ワークスペース",workspaceHint:"選択したデーモンに登録されたワークスペースから選びます。",selectMachineFirst:"先にマシンを選択してください",noRegisteredWorkspaces:"登録されたワークスペースがありません",name:"名前",remoteUrl:"リポジトリのリモート URL(任意)",remoteUrlHint:"リモート URL または安定した識別子を指定してください。",repoIdentity:"リポジトリ識別子(任意)",create:"作成",cancel:"キャンセル",loading:"メッシュを読み込み中...",emptyTitle:"Repo Mesh がありません",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:"コーディネーターセッションのシステムプロンプトをカスタマイズします。メッシュ単位のオーバーライドはこのメッシュにのみ適用され、ユーザーレベルのオーバーライドはこの daemon が調整するすべてのメッシュに適用されます。",thisMesh:"このメッシュ",thisMeshHint:"{{name}} のコーディネーターセッションにのみ適用されます。空のままにすると、ユーザーレベル / daemon のデフォルトにフォールスルーします。",overrideLabel:"オーバーライド(デフォルトを置き換え)",overrideHint:"設定すると、daemon のデフォルトのベースプロンプトを置き換えます。デフォルトを維持するには空のままにしてください。",overridePlaceholder:"(空 — daemon のデフォルトが適用されます)",appendLabel:"追記(ベースの後に追加)",appendHint:"採用されたベースプロンプトの後に常に追加されます。",appendPlaceholder:"(空 — 何も追記されません)",availablePlaceholders:"使用可能なプレースホルダー",saveCoordinatorPrompt:"コーディネータープロンプトを保存",clear:"クリア",clearTitle:"両方のフィールドをクリアします。保存をクリックして確定してください。",userLevel:"ユーザーレベル(この daemon)",userLevelDescription:"コーディネーター daemon 上のマシン単位のプロンプトファイルです。この daemon が調整するすべてのメッシュに適用され、daemon 間で同期されません。上記のメッシュ単位のオーバーライドがこれらより優先されます。",safetyTitle:"安全性と Git",safetyDescription:"コーディネーター主導のタスクに対するチェックポイント、承認ゲート、git の安全性動作。",checkpointBefore:"各タスクの前にチェックポイントを自動コミット",checkpointAfter:"各タスクの後にチェックポイントを自動コミット",pushApproval:"プッシュの承認",requireApprovalBeforePush:"プッシュ前に承認を必須にする",doNotRequireApproval:"承認を必須にしない",destructiveGitApproval:"破壊的な git 操作の承認",requireApproval:"承認を必須にする",uncommittedChanges:"ワークスペースに未コミットの変更がある場合",warnAndContinue:"警告して続行",blockTask:"タスクをブロック",checkpointThenContinue:"チェックポイントを作成して続行",autoPublishSubmodule:"サブモジュールのコミットを自動公開(詳細設定)",requireExplicitApproval:"明示的な承認を必須にする",allowRefineryPublish:"Refinery の非強制公開を許可",autoFastForward:"アイドルノードを自動 fast-forward",ffEnabled:"有効(オンライン・クリーン・遅れているノードを追いつかせる)",ffDisabled:"無効",includeRemoteNodes:"リモートノードを含める",includeRemoteNodesHint:"オフ = コーディネーターのローカルワークスペースのみが自動 fast-forward されます。",remoteNo:"いいえ(ローカルワークスペースのみ)",remoteYes:"はい(リモートの所有 daemon に委任)",detectionMode:"検出モード",detectionModeHint:"アイドル = ノードのアイドルエッジで実行。継続 = 定期的にもスキャン(ベースノードのみ)。",idleEdgeOnly:"アイドルエッジのみ",continuousScan:"継続(定期スキャン)",sessionCleanupLabel:"ノードを削除するとき、そのセッションは…",sessionCleanupHint:"トランスクリプトのクリーンアップをランタイム/プロセスのクリーンアップと分離します。",mcpMode:"MCP モード:",mcpDescription:"· メッシュ MCP サーバーは CLI エージェントから直接使用できます。"},nodeList:{title:"ノードとプロバイダー({{count}})",descriptionCloud:"このメッシュのワークスペースと優先 AI ツール。セットアップインベントリのみ — ライブなグラフ/git/セッションの真実は上記の Mesh Host のステータスが管理します。",descriptionStandalone:"このメッシュに参加しているワークスペースと優先 AI ツール。",daemonCandidates:"マシン daemon の候補",daemonCandidatesHint:"選択した Mesh Host のセットアップに接続する、接続済みの daemon を選択してください。",available:"{{count}} 件が利用可能",noDaemonsAvailable:"現在、接続済みのマシン daemon はありません。",allDaemonsAttached:"接続済みのマシン daemon はすべてすでにアタッチされています。",selectedHost:"選択されたホスト",attachMachine:"マシンをアタッチ",addNode:"ノードを追加",attachMachineTitle:"マシン daemon をアタッチ",addNodeTitle:"ノードを追加",machine:"マシン",selectMachine:"マシンを選択…",workspacePath:"ワークスペースパス",enterCustomPath:"またはカスタムパスを入力 →",preferredTools:"優先 AI ツール(順序)",preferredToolsHint:"明示的なプロバイダーなしで起動する際に使用される順序です。",add:"追加",cancel:"キャンセル",setupInventoryWarning:"セットアップインベントリのみ — ライブな git/セッション/ブランチの詳細は、Mesh Host から直接集約された mesh_status の真実が利用可能になった後、グラフのポップアップに表示されます。",emptyTitle:"ノードなし",emptyDescription:"このメッシュにワークスペースを追加してください。",setupInventory:"セットアップインベントリ",liveDetailGraphOwned:"ライブなブランチ/git/セッションの詳細はグラフが管理します。上記のライブグラフのノードポップアップを使用してください。",slotsLabel:"優先 AI ツール(能力スロット)",slotsHint:"各スロット = プロバイダー + モデル + thinking + 処理するタスクの難易度/能力 + スロットごとの並列上限。タスクは最適なスロットにマッチングされます(順序 = 優先度)。スロットがない場合、このノードは従来のプロバイダー順を使用します。",nodeInstruction:"ノード指示(任意)",nodeInstructionHint:"コーディネーターのシステムプロンプトに 📌 ノード指示として表示されます。",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:"Mesh Host daemon",descriptionSet:"このメッシュのコーディネーターとライブな真実(ステータス、キュー、グラフ、ノード詳細)を所有する daemon です。メッシュ作成時に固定され、ここでは再割り当てできません。",descriptionUnset:"このメッシュにはまだホストがありません。接続済みの daemon でコーディネーターを起動すると、その daemon がメッシュホストとして固定されます(1:1 のピン留め)。以降、その daemon がライブな真実を所有します。",hostLabel:"ホスト:",hostNode:"ホストノード:",unknown:"不明",hostOffline:"ホストがオフラインです。",hostOfflineText:"ピン留めされたホスト daemon が接続されていません。再接続するまでライブなステータス/キュー/グラフは読み込まれません。下記の別の接続済み daemon を通じて一時的にコマンドをルーティングできます — これはルーティングのフォールバックであり、ホストの再割り当てではありません。",reconnectToCommand:"コマンドに再接続",reconnectToCommandHint:"ホストが復帰するまで、この接続済み daemon を通じてコマンドをルーティングします。メッシュホストは変更されません。",waitForHost:"ホストの再接続を待つ",noDaemonsToRoute:"コマンドをルーティングできる接続済みの daemon がありません。ホスト(または別の daemon)をオンラインにしてください。",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:"これは、Override が空のときにコーディネーターセッションに渡される内容です。"},hermesMcp:{title:"Hermes MCP 設定",description:"Hermes はリポジトリローカルの .mcp.json を自動インポートしません。この YAML を Hermes 設定の mcp_servers 配下に追加してから、新しい Hermes セッションを開始してください。",fallbackProvider:"Hermes CLI"}},xx={copyMessage:"メッセージをコピー"},vx={connectingToMachine:"マシンに接続中",establishingP2P:"P2P 接続を確立中",agentNotMonitored:"エージェントは監視されていません",clickToSwitchMonitoring:"クリックして、このエージェントに監視を切り替えます",agentPanelHidden:"エージェントパネルはまだ表示されていません",openPanelHint:"メッセージの表示を開始するには、使用中のアプリでエージェントパネルまたはチャットビューを開いてください",noMessagesYet:"メッセージはまだありません",loadingChat:"チャットを読み込み中...",openPanel:"{{label}} パネルを開く",switchingPanel:"切り替え中...",openingPanel:"オープン中..."},yx={attachImage:"画像を添付",placeholder:"{{panel}} にメッセージを送信...(改行は Shift+Enter)",sendMessage:"メッセージを送信",dropImage:"ここに画像をドロップ"},wx={noConversations:"会話はまだありません",waitingForDaemon:"デーモンを待機中",connectYourMachines:"マシンを接続",daemonDescription:"ADHDev デーモンを起動して、このダッシュボードを接続してください。オンラインになると、インストール済みの任意のプロバイダーでセッションを起動できます。",installDescription:"マシンに ADHDev をインストールしてサインインすると、ここに表示されます。",newSession:"新しいセッション",newSessionDescription:"接続済みのマシンが準備できています。インストール済みの任意のプロバイダー(CLI、ACP、または IDE)で新しいセッションを開始してください。",noTabsInGroup:"このグループにタブはありません",pressEscToCancel:"Esc を押してキャンセル"},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:"ダッシュボード",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:"Anonymous"},onboarding:{title:"ADHDev へようこそ",selectedCount_one:"{{count}} 個のプロバイダーを選択中",selectedCount_other:"{{count}} 個のプロバイダーを選択中",skip:"スキップ",installing:"インストール中…",done:"完了",installCount:"{{count}} 件をインストール",intro:"使用したいプロバイダーを選択してください。既定では公式サポートの 4 つの CLI プロバイダーが選ばれます。IDE、ACP、拡張機能のプロバイダーは下のタブから、または後で Burrow → Providers → Add provider からインストールできます。",loadingRegistry:"レジストリを読み込み中…",loadError:"レジストリの読み込みに失敗しました: {{error}}",noProviders:"このカテゴリにはプロバイダーがありません。",installed:"✓ インストール済み",installFailed:"✗ {{error}}"},about:{title:"概要",subtitle:"セルフホスト版 ADHDev の概要、組み込み機能、Cloud での違い",selfHostedEdition:"セルフホスト版",headline:"同じダッシュボード体験のまま、ランタイムを完全にデバイス上で実行できます。",description:"Standalone は、ブラウザ、デーモン、スクリーンショット、制御経路をご自身のマシン上に保持します。リモートネットワークやチームレイヤーがないだけで、Cloud と同じコア製品の形をしています。",docs:"Docs ↗",github:"GitHub ↗",tryCloud:"Cloud を試す ↗",includedSection:"Standalone に含まれるもの",includedDescription:"クラウド制御プレーンなしで利用できるローカルファーストの機能セット。",inventorySection:"組み込みインベントリ",inventoryDescription:"Standalone ダッシュボードで公開されるバンドル済みエディターとエージェント機能。これらのリストはインベントリを示すものであり、検証済みのサポートを保証するものではありません。",cloudExtrasSection:"Cloud 専用機能",cloudExtrasDescription:"ホスト型の制御プレーンまたはチームインフラを必要とする機能。",comparisonSection:"セルフホスト vs Cloud",comparisonDescription:"製品の違いを一目で確認できます。",featureHeader:"機能",selfhostHeader:"セルフホスト",cloudHeader:"Cloud",cloudOptional:"Cloud は任意であり、必須ではありません",cloudOptionalDescription:"Standalone で完全にローカルのまま利用でき、ダッシュボードの使い方を変えることなく後から Cloud へ移行できます。",compareCloud:"Cloud を比較 ↗",discord:"Discord ↗"},fonts:{fontOverridesNotice:"Standalone 専用のフォント上書き設定です。クラウドダッシュボードには影響しません。チャットバブル、Markdown 本文、コードブロック、ツール行、ターミナル出力はすべて以下の設定を使用します。",chat:"チャットテキスト",chatDescription:"アシスタント/ユーザーの本文、Markdown テキスト、思考カード、システムノート。",code:"コードブロック",codeDescription:"Markdown のコードフェンス、インラインコード、整形済みのコマンド出力。",terminal:"ターミナル",terminalDescription:"ターミナルのトランスクリプトカードと、チャットモードのツール/コマンド行。",livePreview:"ライブプレビュー",resolvedStack:"解決されたスタック:",defaults:"既定値:",saveFontSettings:"フォント設定を保存",revertToSaved:"保存済みに戻す",resetToDefaults:"既定値にリセット",saving:"保存中…"}},Ax={login:{eyebrow:"Cloud サインイン",title:"ADHDev にサインイン",subtitle:"マシンを接続し、承認と完了の通知を受け取り、デスクを離れているときもコーディングエージェントを動かし続けましょう。",continueWith:"{{provider}} で続行",connecting:"接続中...",devDivider:"dev",devLogin:"Dev ログイン (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}}日前",frozenFeatureTitle:"凍結中 — この機能は一時停止されており利用できません。docs/FROZEN_SURFACES.md を参照してください"},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:"{{used}} / {{total}} シート使用中",pricePerMonth:"${{price}}/月",cannotReduceSeats:"{{count}} シート未満には減らせません(現在使用中)。先にメンバーを削除してください。",removeSeat:"− シートを削除",addSeat:"+ シートを追加",cancelSubscription:"サブスクリプションを解約",cancelRetainAccess:"現在の請求期間の終了まで {{plan}} の機能へのアクセスを維持できます。",cancelTeamDowngrade:" すべてのチームメンバーは個人プランにダウングレードされます。"},about:{title:"概要",subtitle:"クラウドの概要、対応サーフェス、プランごとの機能",cloudEdition:"クラウドエディション",heroTitle:"ローカルの CLI エージェントをどこからでも操作 — Web またはモバイルで。",heroDesc:"ADHDev Cloud は、あなたのマシンで動作するエージェントをブラウザに表示します。プロンプトの送信、アクションの承認、複数マシンにまたがる作業の調整、スマートフォンへの通知が可能です。コードは P2P で直接デーモンへ流れ、サーバーを経由することはありません。",openDashboard:"ダッシュボードを開く",viewMachines:"マシンを表示",docs:"ドキュメント ↗",whyTitle:"ADHDev Cloud を選ぶ理由",whyDesc:"マシンをクラウドのコントロールプレーン経由で接続したときに利用できる主要機能。",howTitle:"仕組み",howDesc:"インストールからリモート操作までのクラウドオンボーディングの流れ。",repoMeshTitle:"Repo Mesh",repoMeshDesc:"複数のマシンにまたがってエージェントを調整 — クラウド限定。",meshCard1Title:"1 つのコーディネーター、多数のエージェント",meshCard1Desc:"ミッションに対してタスクをキューに追加し、アイドル状態のノードにローカルファーストのプル型キューから作業を取得させます。複数のマシンとプロバイダーにファンアウト — 一方で Claude Code、もう一方で Codex を動かし、1 つのコーディネーターセッションから結果を集約します。",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 エージェントの Web 操作",webControlDesc:"任意のローカル CLI エージェント — Claude Code、Codex、Gemini — をブラウザから操作。ターミナルに触れることなく、プロンプトの送信、アクションの承認、セッションの制御が可能です。",chatRelayTitle:"エージェントチャットリレー",chatRelayDesc:"モバイルを含め、どこからでもエージェントとの会話を読んで返信できます。",liveViewTitle:"ライブセッションビュー",liveViewDesc:"エージェントの動作をリアルタイムで確認。IDE セッションでは、ウィンドウを切り替えることなく P2P で画面を表示・操作できます。",mobileTitle:"モバイル対応",mobileDesc:"開発マシンから離れているときでも、承認を受け取り、進捗を確認できます。",secureTitle:"デフォルトで安全",secureDesc:"チャット、コマンド、スクリーンショットは WebRTC を介してブラウザとデーモンの間を直接流れます。クラウドは認証とシグナリングのメタデータのみを扱います。あなたのコードがサーバーを経由することはありません。"},steps:{step1Title:"ワンライナーインストール",step1Desc:"操作したいマシンで 1 つのコマンドを実行します。ADHDev デーモンと adhdev CLI がインストールされます。",step2Title:"サインイン",step2Desc:"GitHub または Google でサインインすると、デーモンが自動的にアカウントとペアリングされます — トークンをコピーする必要はありません。",step3Title:"どこからでもエージェントを操作",step3Desc:"マシンはすぐにダッシュボードに表示されます。Claude Code、Codex、Gemini などの CLI エージェントを Web から起動・制御 — IDE セッションも同様です。"},plans:{freeName:"Free",proName:"Pro",ultraName:"Ultra",freePer:"/月",proPer:"/月",ultraPer:"/月",freeFeature1:"1 マシン",freeFeature2:"リアルタイムチャットリレー",freeFeature3:"ローカルエージェントの Web 操作",freeFeature4:"コミュニティサポート",proFeature1:"2 マシン",proFeature2:"AI エージェント無制限",proFeature3:"P2P リモートビュー",proFeature4:"7 日間無料トライアル",ultraFeature1:"5 マシン — シート単位ではなく定額",ultraFeature2:"Pro のすべての機能",ultraFeature3:"より高い同時実行数と使用上限",ultraFeature4:"1 日あたりのスクリーンショット時間無制限"}},layout:{navDashboard:"ダッシュボード",navBurrows:"Burrows",navNotifications:"通知",navMesh:"Mesh",navMarketplace:"マーケットプレイス",navTeam:"チーム",navApi:"API",navWebhooks:"Webhooks",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:"{{count}} TURN 分/日",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:"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:"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:"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 リファレンス →",frozenFeatureTitle:"凍結中 — この機能は一時停止しています。docs/FROZEN_SURFACES.md を参照してください"},auditLogs:{title:"監査ログ",subtitle:"セキュリティイベントと API 履歴",refresh:"更新",filterPlaceholder:"アクション、リソース、ソースで絞り込み...",loading:"読み込み中...",noLogs:"ログがありません",noMatchingLogs:"一致するログが見つかりません。",logsWillAppear:"アクションが発生するとここに表示されます。",colAction:"アクション",colResource:"リソース",colSource:"ソース",colTime:"時刻",logCount:"{{count}} 件のログ",logCountFiltered:"({{total}} 件中の絞り込み結果)"},inviteModal:{title:"チームメンバーを招待",subtitle:"メールで招待リンクを送信します",manageSeats:"→ Billing でシートを管理",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:"開発環境を本サービスに接続すると、ローカルの daemon が次の情報を送信することがあります:",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:"支払い処理は、当社の Merchant of Record である Paddle(Paddle.com Market Limited)が全面的に取り扱います。当社はクレジットカード番号、銀行口座情報、その他の金融情報を直接収集または保存することはありません。データの取り扱いについては次をご参照ください。",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:"daemon 認証のための接続ごとのトークン",s3l4:"すべての API エンドポイントでのレート制限",s3l5:"セキュリティ上重要な操作に対する監査ログ",s4Title:"4. データの共有",s4p1:"当社はお客様の個人データを第三者に販売しません。当社は次の相手とデータを共有することがあります:",s4l1:"Merchant of Record としての支払い処理",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. Cookie",s7p1:"当社は、認証(セッショントークン)およびユーザー設定(テーマ、通知設定)のためにのみ必須の Cookie を使用します。広告やトラッキングの Cookie は使用しません。",s8Title:"8. 子どものプライバシー",s8p1:"本サービスは 16 歳未満のユーザーを対象としていません。当社は 16 歳未満の子どもから個人情報を故意に収集することはありません。",s9Title:"9. 国際的なデータ移転",s9p1:"お客様のデータは、Cloudflare のグローバルネットワークを通じてさまざまな場所で処理される場合があります。本サービスを利用することにより、お客様はこれらの場所でのデータの移転および処理に同意するものとします。",s10Title:"10. 本ポリシーの変更",s10p1:"当社は、本プライバシーポリシーを随時更新することがあります。重要な変更については、メールまたは本サービスを通じてお客様に通知します。変更後も継続して利用された場合、更新されたポリシーに同意したものとみなされます。",s11Title:"11. お問い合わせ",s11p1:"本プライバシーポリシーまたはデータの取り扱いに関するお問い合わせ:",s11l1Prefix:"メール:",s11l2Prefix:"ウェブサイト:"},terms:{title:"利用規約",lastUpdated:"最終更新日: 2026年4月11日",intro:"RacoLab(以下「当社」)が運営する ADHDev(以下「本サービス」)へようこそ。次の場所で当社の本サービスにアクセスまたは利用することにより、",introSuffix:"お客様は本利用規約(以下「本規約」)に拘束されることに同意するものとします。同意されない場合は、本サービスを利用しないでください。",s1Title:"1. サービスの説明",s1p1:"ADHDev は、AI コーディングエージェント(Cursor、VS Code、Antigravity、Claude Code など)を、ウェブおよびモバイルのダッシュボード画面を通じてリモートで監視・制御するクラウド開発者ツールです。本サービスには、ローカルの daemon、リモートダッシュボード、REST API アクセス、ブラウザおよびプッシュ通知が含まれます。",s2Title:"2. アカウント登録",s2p1:"本サービスを利用するにはアカウントを作成する必要があります。お客様はアカウント認証情報の機密を保持する責任を負います。お客様は、登録時に正確かつ完全な情報を提供し、アカウント情報を最新の状態に保つことに同意するものとします。",s2p2:"本サービスを利用するには 16 歳以上である必要があります。アカウントを作成することにより、お客様はこの年齢要件を満たしていることを表明するものとします。",s3Title:"3. サブスクリプションプランと請求",s3p1:"本サービスは次のプランを提供します:",s3l1:"機能制限あり、接続マシン 1 台",s3l2:"接続マシン 2 台、無制限のエージェント、P2P リモートビュー、7 日間の無料トライアル",s3l3:"接続マシン 5 台、Pro のすべての機能に加えて、より高い同時接続数と利用上限(定額制、シートごとではありません)",s3p2:"有料サブスクリプションは、月単位または年単位で前払いにて請求されます。すべての支払いは、すべての取引において Merchant of Record として機能する当社の決済パートナー Paddle(Paddle.com Market Limited)によって処理されます。",s4Title:"4. 返金ポリシー",s4p1:"当社はすべての有料プランについて 14 日間の返金保証を提供します。本サービスにご満足いただけない場合は、最初のご購入から 14 日以内に次までご連絡いただくことで全額返金を請求できます。",s4p2:"更新分の返金は、個別のケースごとに対応します。Paddle が Merchant of Record であるため、Paddle の返金ポリシーも適用されます。",s5Title:"5. 許容される利用",s5p1:"お客様は次の行為を行わないことに同意するものとします:",s5l1:"違法な目的または適用される法律に違反して本サービスを利用すること",s5l2:"他のユーザーのアカウントまたはデータへの不正アクセスを試みること",s5l3:"本サービスのサーバーコンポーネントのソースコードをリバースエンジニアリング、逆コンパイル、または抽出しようと試みること",s5l4:"本サービスを利用してマルウェア、スパム、その他の有害なコンテンツを送信すること",s5l5:"当社の書面による同意なしに本サービスを再販または再配布すること",s5l6:"本サービスの完全性またはパフォーマンスを妨害または中断すること",s6Title:"6. 知的財産権",s6p1:"本サービスは、そのオリジナルコンテンツ、機能、仕組みを含め、RacoLab が所有し、適用される知的財産権法によって保護されています。ローカルデーモンコンポーネントは、プロジェクトリポジトリで規定されたオープンソースライセンスのもとで利用できます。",s6p2:"お客様が本サービスを通じて送信するすべてのデータおよびコンテンツの所有権は、お客様が保持します。",s7Title:"7. データとプライバシー",s7p1:"お客様による本サービスの利用は、当社の以下にも準拠します",s7PrivacyLink:"プライバシーポリシー",s7p1Suffix:"本サービスは、リモート監視および操作を目的として、IDE の操作、チャットメッセージ、スクリーンショットを処理します。当社はお客様のデータを第三者に販売することはありません。",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 が運営しています。すべての支払いは、当社の販売者(Merchant of Record)である以下によって処理されます",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:"Team",subtitle:"シート単位のチーム管理 — $15/シート/月、一元化された請求",planRequired:"Team プランが必要です",planDesc:`Team ワークスペースは Team プラン($15/シート/月)でご利用いただけます。
34
+ シートの管理、チームメンバーの招待、組織の請求の一元管理ができます。`,upgradeBtn:"Team にアップグレード →",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:"このメンバーを削除しますか? Team プランへのアクセス権を失います。",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:"この Team ワークスペースを削除しますか? すべてのメンバーが Team プランの特典を失います。",leaveWorkspace:"ワークスペースを退出",leaveWorkspaceConfirm:"本当にこのワークスペースを退出しますか? プランがダウングレードされる場合があります。",defaultMemberName:"チームメンバー",defaultMemberNameCapitalized:"チームメンバー",sessionFallback:"セッション",timeNow:"たった今",yourSession:"あなたのセッション",viewSessionTitle:"{{sessionName}} セッションを{{action}}",viewingRestricted:"ポリシーにより閲覧が制限されています"},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:"コントロール共有には認証が必要です",unknownError:"不明なエラー"},apiPlayground:{title:"API Playground",history:"履歴 ({{count}})",apiRelayWarning:"デーモン API リレーはオプトイン方式です。REST コマンド/チャットプロキシのルートは、そのデーモンが `adhdev daemon:api enable` で明示的に有効化しない限り無効のままです。",authBearer:"Authorization: Bearer {{key}}",copyAsCurl:"cURL",copied:"コピーしました",targetDaemon:"対象デーモン",quickActions:"クイックアクション",requestBody:"リクエストボディ (JSON)",recentRequests:"最近のリクエスト",clearHistory:"クリア",noDaemonsWarning:"デーモンが接続されていません。まずデーモンを起動するか、{daemonId} を手動で置き換えてください。",send:"▶ 送信",sending:"⏳",close:"閉じる"},announcementBanner:{eyebrow:"システム通知",visibleUntil:"{{time}} まで表示",dismiss:"閉じる"},upgradeBanner:{button:"アップグレード →"},push:{title:"プッシュ通知",descUnsupported:"このブラウザではサポートされていません",descDenied:"ブロック中 — ブラウザ設定で有効にしてください",descEnabled:"サーバー側プッシュが有効です",descDefault:"タブを閉じていても通知を受け取れます",docs:"ドキュメント",docsLink:"プッシュ通知のドキュメント",sent:"送信済み",test:"テスト",docsHintPrefix:"セットアップ手順、iPhone の PWA 要件、ブラウザ互換性については、次を参照してください: ",docsHintSuffix:"。",iosHint:"iPhone と iPad では、プッシュはインストール済みの Safari PWA からのみ機能します。通常の Safari タブでは ADHDev のプッシュ通知を受信できません。",budget:"現在のプランのプッシュ枠: 本日 {{used}}/{{limit}} 使用済み{{remaining}}{{resets}}。",budgetRemaining:"、残り {{count}}",budgetResets:" • {{time}} にリセット",unsupportedWarning:"このブラウザはここでの Web Push をサポートしていません。iPhone/iPad では Safari PWA を、デスクトップ/Android では Chromium ブラウザをご利用ください。",deniedWarning:"通知がブラウザまたはサイトの設定でブロックされています。そこで再度有効にしてから、プッシュ通知をもう一度オンにしてください。",registeredDevices:"登録済みデバイス: {{count}}",noDevices:"アクティブなプッシュデバイスが見つかりません。",deviceLabel:"デバイス {{number}}",thisDevice:"このデバイス",lastActive:"最終アクティブ:",removing:"削除中...",removeHere:"ここで削除",remove:"削除"},mesh:{manualMcpSetup:"このプロバイダーが Repo Mesh のコーディネーターとして動作するには、事前に手動で MCP をセットアップする必要があります。",couldNotLoadMeshes:"メッシュを読み込めませんでした",untitledMesh:"無題のメッシュ",chooseMachineFirst:"先にマシンを選択してください。",launchFailed:"起動に失敗しました",coordinatorLaunchFailed:"コーディネーターの起動に失敗しました",coordinatorLaunched:"コーディネーターを起動しました ({{sessionId}})",coordinatorLaunchSent:"コーディネーター起動コマンドを送信しました"},plans:{free:"Free",pro:"Pro",ultra:"Ultra",team:"Team",enterprise:"Enterprise"},adminAudit:{title:"グローバル監査",subtitle:"システム全体のイベント追跡",allActions:"すべてのアクション",allSources:"すべてのソース",filter:"フィルター",noLogs:"ログが見つかりません",loading:"読み込み中...",loadMore:"さらに読み込む ↓"},adminDashboard:{failedToLoad:"管理データの読み込みに失敗しました",title:"管理ダッシュボード",subtitle:"サービス概要と管理",accessDenied:"管理者アクセスが拒否されました",backToDashboard:"ダッシュボードに戻る",loading:"管理ダッシュボードを読み込み中",loadingDesc:"サービス統計と最近の監査アクティビティを収集しています。",totalUsers:"総ユーザー数",todayCommands:"本日のコマンド",activeApiKeys:"アクティブな API キー",todayLogins:"本日のログイン",planDistribution:"プラン分布",quickActions:"クイックアクション",manageUsers:"ユーザー管理",apiKeys:"API キー",auditLogs:"監査ログ",systemConfig:"システム設定",recentActivity:"最近のアクティビティ",viewAll:"すべて表示",noRecentActivity:"最近のアクティビティはありません"},adminSystem:{error:"エラー: {{message}}",announcementSent:"お知らせを送信しました",announcementCleared:"お知らせをクリアしました",registrationOpened:"登録を開放しました — 誰でもサインアップできます",registrationClosed:"登録を締め切りました",title:"システム設定",subtitle:"お知らせとシステム構成",loading:"システム設定を読み込み中",loadingDesc:"登録ポリシーと現在のお知らせ状態を取得しています。",registration:"登録",registrationOpenState:"開放中 — 誰でもサインアップできます",registrationClosedState:"締め切り中 — 許可されたメールのみ",registrationDesc:"締め切り中は、許可リストに追加されたメールのみが新しいアカウントを作成できます。既存のユーザーには影響しません。",closeRegistration:"登録を締め切る",openRegistration:"登録を開放する",announcement:"お知らせ",current:"現在:",untilTime:"({{time}}まで)",untilCleared:"(クリアするまで)",announcementPlaceholder:"お知らせメッセージを入力...",severityInfo:"情報",severityWarning:"警告",severityCritical:"重大",duration1h:"1時間",duration6h:"6時間",duration24h:"24時間",duration7d:"7日間",durationUntilCleared:"クリアするまで",send:"送信"},adminUsers:{error:"エラー: {{message}}",roleUpdated:"ロールを更新しました",planUpdated:"プランを更新しました",suspensionReasonPrompt:"停止理由を入力してください:",userSuspended:"ユーザーを停止しました",userUnsuspended:"ユーザーの停止を解除しました",title:"ユーザー管理",subtitle:"ユーザー、ロール、停止を管理",usersTotal:"人のユーザー",searchPlaceholder:"メールまたは名前で検索...",allRoles:"すべてのロール",roleUser:"ユーザー",roleAdmin:"管理者",roleSuperAdmin:"スーパー管理者",allPlans:"すべてのプラン",search:"検索",colUser:"ユーザー",colRole:"ロール",colPlan:"プラン",colStatus:"ステータス",colCreated:"作成日",colActions:"操作",noName:"名前なし",statusSuspended:"停止中",statusActive:"有効",unsuspend:"停止解除",suspend:"停止",loading:"読み込み中...",prev:"← 前へ",next:"次へ →"}},Ix={openMenu:"メニューを開く",closeMenu:"メニューを閉じる"},Tx={loadingOlderMessages:"以前のメッセージを読み込み中...",waitingForMessages:"メッセージを待機中...",agentGenerating:"エージェントが生成中...",jumpToTop:"先頭へ移動",jumpToOldestMessages:"最も古いメッセージへ移動",top:"↑ 先頭",latest:"↓ 最新",jumpToLatestMessages:"最新のメッセージへ移動",jumpToBottom:"末尾へ移動",showEarlierMessages:"↑ 以前の{{count}}件のメッセージを表示...",showEarlierMessagesHidden:"↑ 以前の{{count}}件のメッセージを表示...({{total}}件非表示)",loadOlderMessages:"↑ 以前のメッセージを読み込む",loadErrorRetry:"↻ {{error}}"},Mx={zoomOut:"縮小",zoomIn:"拡大",resetZoom:"ズームをリセット",toggleFullscreen:"全画面表示の切り替え"},Dx={mouse:"マウス",touch:"タッチ",connected:"接続済み",ws:"WS",direct:"直接",relay:"リレー",turnBlocked:"TURN がブロックされました",turnUsage:"TURN {{used}}/{{budget}}m",typeAndEnter:"入力して Enter...",settings:"設定",zoom:"ズーム:",fill:"フィル",fit:"フィット",directP2PTitle:"P2P 直接接続",turnRelayTitle:"TURN リレーを使用中",dailyTurnTitle:"1日の TURN リレー使用量",waitingState:{turnRelayActive:"TURN リレー有効"}},Px={title:"セッション情報",loading:"読み込み中…",refresh:"更新",close:"閉じる",failedToLoad:"セッション情報の読み込みに失敗しました",notCoordinatorSession:"これは Repo Mesh コーディネーターセッションではないため、コーディネーター固有のプロンプトは挿入されていません。エージェントは CLI が標準で備えるデフォルト設定で実行されます。",stampedToNode:"このセッションは、コーディネーターがもう報告しないメッシュノードに紐付けられています。",sectionSession:"セッション",sectionLaunch:"起動",sectionMeshNode:"メッシュノード",sectionMeshCoordinator:"メッシュコーディネーター",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:"ワークツリー",rowLaunchReady:"起動準備完了",rowGit:"Git",rowProviders:"プロバイダー",rowProviderPriority:"プロバイダー優先度",rowMeshId:"Mesh ID",rowCoordinatorCli:"コーディネーター CLI",rowStartedAt:"開始時刻",rowPromptInjection:"プロンプト注入",rowMcpConfig:"MCP 設定",rowRuntimeId:"ランタイムID",rowLifecycle:"ライフサイクル",rowSurface:"サーフェス",rowRecoveryState:"復旧状態",rowRestoredFromStorage:"ストレージから復元",rowAttachedClients:"接続中のクライアント"},Lx={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:"ワークスペース"}},Rx={launchConfirm:{workspace:"ワークスペース",languageModel:"言語モデル(任意)",autoDetect:"自動検出またはデフォルト",cliArgs:"CLI 引数(任意)",cliArgsPlaceholder:"例: --experimental",cancel:"キャンセル",closeAria:"起動確認を閉じる",launch:"起動",launching:"起動中…"},confirmExternal:{dialogAria:"信頼されていない外部プロバイダーを確認",title:"信頼されていない外部プロバイダーを有効化しますか?",description:"このマニフェストにはデーモンが実行する JavaScript が含まれています。信頼されていないコードとして扱い、有効化する前にソースを確認してください。",proceedWarning:"追加したソース URL を信頼し、マニフェストを確認済みの場合のみ続行してください。",cancel:"キャンセル",activate:"有効化"},workspace:{noWorkspace:"(ワークスペースなし — ホームで起動)",selectWorkspace:"📁 ワークスペースを選択…",customPath:"✏️ カスタムパス…",noWorkspacesSaved:"(保存されたワークスペースなし — Overview タブで追加)",selectWorkspaceBtn:"ワークスペースを選択…",enterAbsolutePath:"絶対パスを入力…",browseHint:"起動先のフォルダーを参照してください。",absolutePathHint:"起動先の絶対パスを入力してください。",defaultWorkspace:"デフォルトのワークスペース",selectedWorkspace:"選択したワークスペース",noWorkspaceSelected:"ワークスペースが選択されていません。ホームディレクトリで起動します。"},agentTab:{selectToLaunch:"起動する {{label}} を選択",launchSettings:"起動設定",noIdesDetected:"IDE が検出されませんでした。",scanSystem:"システムをスキャン",noProviders:"利用可能な {{category}} プロバイダーがありません。",noProvidersHint:"バイナリを既定の場所以外にインストールしている場合は、Providers でカスタムの実行パスを設定してください。",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:"デーモンがプロバイダーマニフェストを探す場所です。解決とリロードに影響します。",sourceMode:"ソースモード",explicitProviderDir:"明示的な providerDir",providerDirPlaceholder:"空欄にすると ~/.adhdev/providers を使用します",applying:"適用中…",applyReload:"適用 + リロード",userRoot:"ユーザールート:",upstreamRoot:"アップストリームルート:",providerRoots:"プロバイダールート:",loadingSettings:"プロバイダー設定を読み込んでいます…",noProviders:"まだプロバイダーがインストールされていません。上の「Add provider」を開いてインストールしてください。",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:"接続中..."},card:{sectionIDEs:"IDE",sectionCLIs:"CLI",sectionACPAgents:"ACP エージェント",emptyHeadline:"ADHDev へようこそ",emptyBody:"最初のマシンをダッシュボードに接続しましょう。セットアップを一度実行してから、そのマシンで ADHDev を起動してください:",emptyDocsLink:"📚 ドキュメントを読む →",hidden:"非表示",pageTitle:"Burrows",burrowCount_one:"{{count}} 個の burrow",burrowCount_other:"{{count}} 個の burrow",onlineCount_one:"{{count}} 台オンライン",onlineCount_other:"{{count}} 台オンライン",agentsActive_one:"{{count}} 個のエージェントがアクティブ",agentsActive_other:"{{count}} 個のエージェントがアクティブ",activeNow:"現在アクティブ",generating:"生成中",connectionFailed:"接続に失敗しました",reconnect:"再接続",connecting:"接続中...",runtimePolling:"ランタイムポーリング",transportRelay:"TURN リレー — 直接接続に失敗しました",transportDirect:"直接接続 (STUN/host)",noAgentsRunning:"実行中のエージェントはまだありません",launchCta:"起動 →"},detail:{notFound:"マシンが見つかりません",save:"保存",cancel:"キャンセル",loading:"⏳ マシンを読み込み中...",offlineHint:"マシンがオフラインか、まだ接続されていない可能性があります。",back:"← 戻る",tabWorkspace:"ワークスペース",tabHostedRuntimes:"ホスト型ランタイム",tabProviders:"プロバイダー",tabSystem:"システム",tabLogs:"ログ",clickToSetNickname:"クリックしてニックネームを設定",nicknamePlaceholder:"マシンのニックネーム...",reconnect:"再接続",coresCount_one:"{{count}} コア",coresCount_other:"{{count}} コア",p2pState:"P2P {{state}}",p2pConnected:"接続済み"},commandCenter:{currentChats:"現在のチャット",recentLaunches:"最近の起動",daemonUpdate:"デーモンの更新"},workspaceBrowse:{currentFolder:"現在のフォルダー"},managedWorkspaces:{remove:"削除"}},Ex={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:"🎨 カスタム"},providerPriority:{available:"利用可能",notOnMachine:"このマシンにはありません",remove:"削除",addCliLabel:"利用可能な CLI プロバイダーを追加",addProvider:"プロバイダーを追加"},coordinatorPrompts:{overrideDesc:"<strong>Override</strong> は、その CLI のデーモン組み込みベースプロンプトを置き換えます。",appendDesc:"<strong>Append</strong> は、いずれかのベースが選ばれた後に積み重ねられます。",overrideLabel:"Override",appendLabel:"Append"},appearance:{modeLabel:"モード",themeLabel:"テーマ",mobileLabel:"モバイル"}},_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:"⌛ 更新中..."},$x={nav:{home:"ADHDev ホーム",mesh:"Mesh",what:"特徴",agents:"エージェント",pricing:"料金",install:"インストール",github:"GitHub",docs:"ドキュメント",getStarted:"始める",toggleMenu:"メニューを切り替え",mainNavigation:"メインナビゲーション"},hero:{badge:"マルチベンダー・マルチマシン対応のエージェント制御プレーン",title:"10体のエージェントは誰でも動かせます。ADHDev は成果を main に着地させます。",subtitle:"Claude Code、Codex、Cursor など、あらゆるローカルコーディングエージェントをブラウザから操作し、完了した作業を Refinery が<em>無人</em>で main にマージし直します。リポジトリ独自のゲート、パッチ等価性チェック、fast-forward のみ、force-push なし。あなたは 1 つのコーディネーターと対話するだけで、コーディネーターが自分のマシン全体で並列エージェントを非同期に実行します。世話を焼くセッションはありません。コードはあなたのマシン上に留まります — P2P、エンドツーエンドで。",selectOs:"OS を選択",osUnix:"macOS / Linux",osWindows:"Windows",copyInstall:"インストールコマンドをコピー: {{cmd}}",copied:"コピーしました",copy:"コピー",getStarted:"始める",openSource:"GitHub でオープンソース",joinDiscord:"Discord に参加",selfHost:"自分でセルフホスト",demoDesktop:"複数のマシンにまたがるライブエージェントセッションを操作する ADHDev コマンドセンター",demoPush:"ADHDev モバイルプッシュ通知とワンタップ承認"},mesh:{sectionTitle:"彼らは並列化する。私たちは着地させる。",sectionSubtitle:"並列エージェントの起動は簡単な部分で、いまやどのツールでもできます。難しいのはその後です。検証してマージしなければならない 10 個のブランチ。Refinery がそれを無人で代行するので、完了した作業はレビュー待ち行列ではなく main に届きます。",refineryHighlight:"Refinery",refineryTitle:"完了した作業が main に着地します — 無人で",refineryDesc:"10 体の並列エージェントは誰でも起動できます。Refinery は各ワークツリーをリポジトリ独自のゲート(typecheck、テスト、lint)に照らして検証し、パッチ等価性を確認し、サブモジュールのコミットを公開し、main を fast-forward し、後始末まで自動で行います。force-push は一切ありません。あいまいなものはマージされず、レビューに差し戻されます。",asyncHighlight:"非同期オーケストレーション",asyncTitle:"1 か所に話すだけ。残りは自動で動きます。",asyncDesc:"作業を 1 つのコーディネーターに渡すと、それが多数のマシンにまたがる多数のワーカーをイベントループ上で駆動します — 完了、承認、ステータスのイベントが届いたときだけ反応します。ポーリングも、世話を焼くエージェントごとのウィンドウもありません。各エージェントセッションを見張るデスクトップアプリとは異なり、ここではコーディネーターがイベントを待つので、あなたが何かの前に同期的に座り続ける必要はありません。",monoHighlight:"モノレポ対応",monoTitle:"git submodule があっても安全",monoDesc:"実際の本番リポジトリはサブモジュールをネストします — そしてそこがまさに素朴な自動マージが破綻する場所です。Refinery はサブモジュール対応です。サブモジュールコミットの到達可能性でゲートし、パッチ等価性を判定し、ポインターをアトミックに更新します。このプロジェクト自体がルート + 2 サブモジュールのモノレポで、毎日この方法で収束させています。",crossHighlight:"クロスチェック",crossTitle:"単一の意見より合意を",crossDesc:"同じ読み取り専用の調査を複数のマシン × プロバイダーのレプリカにファンアウトし、一致する点と分岐する点を統合します(MAGI)。1 体のエージェントの見解より信頼できます。",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 submodule で安全",rowSubmodulesLocalCli:"サブモジュールを認識するマージ自動化なし",rowSubmodulesDesktop:"ワークツリー並列化はあるが、マージを正しく行うのは自分次第",rowSubmodulesAdhdev:"サブモジュール対応の収束:到達可能性ゲート、パッチ等価性チェック、アトミックなポインター更新 — このモノレポで毎日ドッグフーディング",rowAsync:"1 か所に、非同期で話す",rowAsyncLocalCli:"一度に 1 セッション、同期的に",rowAsyncDesktop:"各エージェントウィンドウを自分で監督する",rowAsyncAdhdev:"1 つのコーディネーターがすべてのワーカーをイベントループで駆動 — 完了/承認イベントを待つので、ポーリングも世話も不要",rowMultiMachine:"複数の物理マシン",rowMultiMachineLocalCli:"1 台のホストのプロセスのみ",rowMultiMachineDesktop:"動作する 1 台のマシンに縛られる",rowMultiMachineAdhdev:"P2P 経由のリモートデーモン — 所有するすべてのマシンにディスパッチ(SSH の配管不要)",rowParallelBranch:"分離されたブランチでの並列作業",rowParallelBranchLocalCli:"サブエージェントが 1 つの作業ツリーを共有 — 同時書き込みが衝突",rowParallelBranchDesktop:"タスクごとに 1 つの git worktree — 中核的な強み",rowParallelBranchAdhdev:"ノードごとに 1 つの git worktree — コアだけでなくマシンをまたいで並列",rowBrowser:"ブラウザやスマホから操作",rowBrowserLocalCli:"ターミナルの前にいる必要がある",rowBrowserDesktop:"ネイティブデスクトップアプリ — そのデスクの前にいる必要がある",rowBrowserAdhdev:"Web ファースト:あらゆるブラウザやスマホからセッションを制御し承認",rowNativeApp:"ネイティブデスクトップアプリ",rowNativeAppLocalCli:"ターミナルのみ",rowNativeAppDesktop:"洗練されたネイティブウィンドウ — 前に座るのが本当に心地よい",rowNativeAppAdhdev:"私たちは Web ファースト — ネイティブアプリではなくブラウザタブ",rowRestarts:"再起動やコンテキスト喪失に耐える",rowRestartsLocalCli:"状態はセッション内に存在 — 閉じれば消える",rowRestartsDesktop:"状態はアプリのプロセスに紐づく",rowRestartsAdhdev:"ミッションはディスクに永続化され、コーディネーターやデーモンの再起動後に再開 — 追記専用で改ざん検知可能な監査証跡",rowCrossCheck:"答えをクロスチェック",rowCrossCheckLocalCli:"1 体のエージェントの見解、セカンドオピニオンなし",rowCrossCheckDesktop:"並列作業、単一の判定",rowCrossCheckAdhdev:"MAGI が同じ読み取り専用の質問を独立したマシン × プロバイダーのエージェントにファンアウトし、分岐する点を可視化",footnote:"単一のマシン、単一のブランチ、一回限りのタスクなら — サブエージェント付きのローカル CLI の方が軽量でよく機能し、ネイティブデスクトップオーケストレーターの方が座り心地のよい場所です。Repo Mesh が真価を発揮するのは、作業がマシンとブランチにまたがってファンアウトし、再起動に耐える必要があり、自動で main に着地すべきときです — どこにいても操作できます。"},what:{sectionTitle:"あらゆるエージェントを自由に混在",sectionSubtitle:"設計からしてベンダーニュートラル。Mac で Claude Code、Windows の GPU マシンで Codex、レビューパスに Gemini を — 同じメッシュ内、同じポリシーの下で実行します。プラットフォームを変えずにベンダーを切り替えられます。",cliHighlight:"CLI エージェント",cliTitle:"あらゆるターミナルエージェントを Web から操作",cliDesc:"Claude Code、Codex CLI、Cursor CLI、Antigravity CLI、Hermes、Kimi、OpenCode — 適切な再開と再接続を備えた PTY アダプター経由であなたのマシンに接続し、ブラウザから操作します。プロンプトを送信し、視覚的なコンテキストを即座に提供できます(貼り付け、ドラッグ&ドロップ、または複数画像の一括アップロード、最大 5 枚 / 各 10MB まで)。Aider、Gemini CLI、Goose など他の ACP エージェントは stdio 経由で接続します。",uiHighlight:"1 つの UI",uiTitle:"同じダッシュボード、あらゆるデバイス",uiDesc:"adhf.dev でクラウドホスト — デスクにいても外出中でも、ノート PC やスマホからあらゆるエージェントを操作できます。",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:"テスト済み",tierTestedDesc:"実際のアプリ + バージョンに対して検証済み",tierCommunity:"コミュニティ",tierCommunityDesc:"組み込みおよびコミュニティサポート",groupIdes:"IDE",hintIdes:"Chrome DevTools Protocol 経由で接続。チャットの読み取り、プロンプト送信、セッション切り替え、スクリーンショットが可能です。",groupCli:"CLI エージェント",hintCli:"PTY アダプター経由で駆動し、再開と再接続に対応します。",groupExtensions:"IDE 内拡張エージェント",hintExtensions:"別の IDE 内に存在するエージェント向けの CDP webview 接続。",acpFootnote:"さらに stdio 経由の ACP エージェント(Agent Client Protocol)が {{count}}+ 種類:Codex、Claude Agent、Gemini、Goose、Cline、OpenHands など。"},pricing:{sectionTitle:"エージェントの成長に合わせたシンプルな料金",sectionSubtitle:"1 台のマシンで無料で始めましょう。2 台なら Pro、5 台なら Ultra へ。席数計算も、エンタープライズ営業への問い合わせも不要 — 下記のプランだけです。",mostPopular:"一番人気",upgradeToPro:"Pro にアップグレード",footnote:"シンプルで透明性のある料金 — 上記の価格がお支払い額です。セルフホストがお好みですか?デーモンとダッシュボードはオープンソースです。価格は USD 表示です。",plans:{free:{period:"永久",tagline:"1 台のマシンをどこからでも操作するために必要なすべて。",cta:"無料で始める",features:{machine:"1 台のマシンを 1 コマンドでペアリング",p2p:"P2P チャット、コマンド、スクリーンショット、リモート入力",providers:"すべてのプロバイダー — CLI、IDE、ACP エージェント",push:"承認・完了のプッシュ通知",share:"共有セッションリンク 1 つ"}},pro:{period:"/月",tagline:"複数のマシンでエージェントを実行。有料プランに求められる信頼性を備えています。",cta:"7 日間の Pro トライアルを始める",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:"1 日のスクリーンショット時間が無制限",webhooks:"より多くの webhook と API コール",share:"共有セッション数の増加"}}}},install:{sectionTitle:"動作するダッシュボードまで 3 ステップ",sectionSubtitle:"設定ファイルなし。配線する API キーもなし。ADHDev はエージェントの認証を管理しません — 各ツールが自身のログインを保持します。",selectOs:"OS を選択",osUnix:"macOS / Linux",osWindows:"Windows",copyInstall:"インストールコマンドをコピー: {{cmd}}",copied:"コピーしました",copy:"コピー",platformNote:"macOS と Windows は検証済みのインストール経路です。Linux は同じ Unix スクリプトで動作し、コミュニティによってテストされています。",arrow:"→",steps:{step1:{title:"デーモンをインストール",desc:"1 つの 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:"タブの切り替えはもう終わり。すべてのエージェントを 1 つのダッシュボードから操作。",subtitle:"1 つの curl コマンド、1 つのデーモン、あなたがすでに使っているすべてのエージェント。すべてをウェブから操作 — Cloud が稼働中です。",getStarted:"始める →",github:"GitHub",discord:"Discord"},footer:{docs:"ドキュメント",github:"GitHub",discord:"Discord",dashboard:"ダッシュボード",terms:"利用規約",privacy:"プライバシー",contact:"お問い合わせ",copyright:"© {{year}} RacoLab. All rights reserved."}},Hx={selectAllThatApply:"該当するものをすべて選択",other:"その他"},Bx={changeList:{binaryBadge:"bin",truncatedNote:"ファイル一覧は省略されています — 完全な出力はローカルで <code>git status</code> を実行してください。"},statusDialog:{conflicts:"コンフリクト",clean:"クリーン"}},Fx={header:{back:"戻る"}},Ox={title:"通知",subtitle:"アラート、自動承認、プロバイダー設定",sectionBrowserAlerts:"ブラウザアラート",masterToggleLabel:"通知",masterToggleDesc:"すべてのアラートのマスタートグル",browserNotificationsLabel:"ブラウザ通知",browserNotificationsDesc:"タブが非アクティブなときのデスクトップアラート",browserBackgroundInfo:"ブラウザアラートは、このダッシュボードタブがバックグラウンドで開いている間のみ発生します。",browserBackgroundInfoWithPush:"ブラウザアラートは、このダッシュボードタブがバックグラウンドで開いている間のみ発生します。タブを閉じる場合は、代わりにプッシュ通知をご利用ください。",standaloneBackgroundInfo:"ブラウザアラートは、このダッシュボードタブがバックグラウンドで開いている間のみ発生します。閉じると、スタンドアロンではホスト型プッシュ通知を配信できません。",permissionDefault:"このブラウザはまだ通知の許可を付与していません。ブラウザアラートを受け取るには許可してください。",standalonePermissionDefault:"このブラウザはまだ通知の許可を付与していません。ローカルのブラウザアラートを受け取るには許可してください。",allowNotifications:"通知を許可",permissionDenied:"ブラウザ通知はサイトまたはブラウザの設定でブロックされています。デスクトップアラートを受け取るには、そこで再度有効にしてください。",standalonePermissionUnsupported:"このブラウザではここでデスクトップ通知を表示できません。ダッシュボードを表示したままにするか、このデバイスで対応している別のブラウザをご利用ください。",permissionUnsupported:"このブラウザではここでデスクトップ通知を表示できません。対応しているデスクトップブラウザをご利用いただくか、利用可能な場合はプッシュ通知をご利用ください。",completionAlertsLabel:"完了アラート",completionAlertsDesc:"エージェントがタスクを完了したときに通知",approvalAlertsLabel:"承認アラート",approvalAlertsDesc:"エージェントが承認を必要とするときに通知",connectionAlertsLabel:"接続アラート",connectionAlertsDesc:"マシンが切断されたときにアラート",allDisabled:"すべての通知が無効です。設定するにはマスタートグルを有効にしてください。",sectionProviderAlerts:"プロバイダーアラートのルール",loading:"⏳ 読み込み中...",refresh:"↻ 更新",noOnlineMachines:"オンラインのマシンがありません。プロバイダーアラートを設定するには、マシンで ADHDev を起動してください。",loadingProviderSettings:"プロバイダー設定を読み込み中...",providerCount_one:"{{count}} 個のプロバイダー",providerCount_other:"{{count}} 個のプロバイダー",keyStatAutoApprove:"自動承認",keyStatApprovalAlert:"承認アラート",keyStatNoProgressAlert:"進捗なしアラート",bulkEnabledAll:"全 {{total}} 個のプロバイダーで有効化",bulkDisabledAll:"全 {{total}} 個のプロバイダーで無効化",bulkEnabledSome:"{{total}} 個中 {{onCount}} 個のプロバイダーで有効化",hideDetails:"▾ 詳細を隠す",showDetails:"▸ プロバイダーごとの詳細を表示 ({{count}})",soundEffectsLabel:"効果音",soundEffectsDesc:"エージェントが完了または承認を必要とするときに音を鳴らす"},Wx={language:ax,common:ox,connection:ix,toast:lx,notification:cx,event:dx,dashboard:ux,cliStop:px,approval:mx,newSession:hx,mobileInbox:fx,meshGraph:bx,repoMesh:gx,chat:xx,chatPane:vx,chatInput:yx,paneGroup:wx,terminal:kx,conversation:Sx,cliView:Cx,launch:jx,standalone:Nx,cloud:Ax,app:Ix,chatList:Tx,screenshot:Mx,remote:Dx,sessionInfo:Px,mesh:Lx,machine:Rx,settings:Ex,historyModal:_x,landing:$x,interactivePrompt:Hx,git:Bx,ide:Fx,notifications:Ox},Ux={label:"语言",select:"选择语言"},Gx={cancel:"取消"},qx={disconnected:"已断开连接",connected:"已连接",connectedToDashboard:"已连接到仪表板",connectingToMachine:"正在连接到机器...",networkOffline:"网络已离线",reconnecting:"正在重新连接",sessionExpired:"会话已过期。",logInAgain:"重新登录",connectionFailed:"连接失败 — 请刷新页面或稍后重试。",reconnectNow:"立即重新连接"},zx={label:{success:"完成",warning:"注意",info:"更新"},dismiss:"关闭"},Kx={actionNeeded:"需要操作",taskComplete:"任务完成",markRead:"标记为已读",markUnread:"标记为未读",delete:"删除"},Vx={taskCompleted:"{{label}} 代理任务已完成",taskCompletedWithDuration:"{{label}} 代理任务已完成({{duration}} 秒)",approvalNeeded:"{{label}} 需要审批",noProgress:"{{label}} 代理没有进展",noProgressWithDuration:"{{label}} 代理没有进展({{minutes}} 分钟)",noProgressTitle:"{{label}} — 无进展",noProgressBody:"代理已超过 {{duration}} 没有进展",viewRequest:"{{requester}} 想要查看你的会话",viewRequestTitle:"查看请求",viewRequestApproved:"查看请求已批准",viewRequestDeclined:"{{target}} 拒绝了你的查看请求",someoneRequester:"一位团队成员",someoneTarget:"团队成员"},Yx={header:{title:"仪表板",guide:"仪表板指南",guideOpen:"打开仪表板指南",guideShort:"指南",openGitStatus:"打开 git 状态",openMeshGraph:"打开实时 Repo Mesh 图",meshGraph:"Mesh 图",stopAcpSession:"停止 ACP 会话",stopCliProcess:"停止 CLI 进程",chatHistory:"聊天记录",remoteControl:"远程控制",generating:"生成中",activityInbox:"活动收件箱"},hidden:{title:"隐藏的标签页",dragHint:"将标签页拖到此处以将其隐藏。",resetPanels:"重置面板",restoreAll:"全部恢复",hideCurrentTab:"隐藏当前标签页",empty:"没有隐藏的标签页。"},inbox:{unread:"未读",read:"已读",empty:"没有待处理的活动。"},metaChips:{meshNode:"Mesh 节点"},versionBanner:{required:"必需",retry:"重试"},remoteDialog:{history:"历史记录"},sourceTimeline:{colWhen:"时间",colEvent:"事件",colFrom:"从",colTo:"到",colCause:"原因"}},Jx={title:"停止 {{agent}}?",gracefulDescription:"在支持的情况下,“停止”会请求提供方正常退出。“强制停止”会立即结束运行时。",forceOnlyDescription:"此提供方不支持正常停止。“强制停止”会立即结束运行时。",stop:"停止",forceStop:"强制停止"},Qx={processing:"处理中...",actionRequired:"需要操作"},Xx={title:"开始会话",close:"关闭新建会话对话框",category:"类别",detectedLocally:"本地已检测到",availableToOpen:"可打开",machine:"机器",selectMachine:"选择机器 {{name}}",workspace:"工作区",browse:"浏览…",launchTargetType:"启动目标类型",modeWorkspace:"工作区",modeWorkspaceDesc:"普通会话",modeMesh:"Mesh",modeMeshDesc:"协调器会话",homeDirectory:"主目录",customFolder:"自定义文件夹…",launchWithoutWorkspace:"在没有工作区的情况下启动。",selectWorkspaceFolder:"请选择工作区文件夹。",selectFolder:"选择文件夹",saving:"保存中…",saveWorkspace:"保存工作区",loadingMeshes:"正在加载网格…",noMeshes:"此机器上未配置任何 Repo Mesh。请先创建或同步网格,然后重新打开此选择器。",mesh:"Mesh",repoMesh:"Repo mesh",nodeCount_one:"{{count}} 个节点",nodeCount_other:"{{count}} 个节点",coordinatorWorkspace:"协调器工作区:{{path}}",chooseIde:"选择 IDE",chooseCliProvider:"选择 CLI 提供方",chooseAcpProvider:"选择 ACP 提供方",noProviders:"在所选机器上此类别没有可用项。如果二进制文件不在默认位置,请在 Providers 中设置自定义可执行路径。",startupArguments:"启动参数",optionalFlags:"可选标志...",modelAndThinking:"模型与思考(可选)",model:"模型",providerDefault:"(提供方默认)",custom:"自定义…",typeModelName:"输入模型名称",backToModelList:"← 返回模型列表",thinkingLevel:"思考级别",selectWorkspaceTitle:"选择工作区",selectWorkspaceDescription:"选择用于此新会话的文件夹。",start:"开始",starting:"启动中…",startMeshCoordinator:"启动 Mesh 协调器",startingCoordinator:"正在启动协调器…",startIde:"启动 IDE",startingIde:"正在启动 IDE…",startAcpSession:"启动 ACP 会话",startingAcpSession:"正在启动 ACP 会话…",startFresh:"全新开始",startingFresh:"正在全新开始…",resumeSavedHistory:"恢复已保存的历史",resumingSavedHistory:"正在恢复已保存的历史…",errorLoadMeshes:"无法加载 mesh",errorLoadFolder:"无法加载文件夹",errorLoadSavedSessions:"无法加载已保存的会话",errorSaveWorkspace:"无法保存工作区",workspaceSaved:"工作区已保存。机器状态刷新后即会出现在列表中。",errorManualMcpSetup:"该提供方需先完成手动 MCP 设置,才能作为 mesh 协调器运行。",errorStartMeshCoordinator:"无法启动 mesh 协调器",errorStartSession:"无法启动会话",errorResumeSession:"无法恢复会话"},Zx={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}} 的 mesh 图",openLiveMeshGraph:"打开实时 repo mesh 图",unmute:"取消静音 {{title}}",mute:"静音 {{title}}",mutedTitle:"已静音 — 通知已关闭。点按以取消静音。",muteNotifications:"静音通知",hideConversationAria:"隐藏 {{title}}",hideConversationTitle:"隐藏会话",stopSessionAria:"停止 {{title}} 会话",stopSessionTitle:"停止会话(终止该智能体)"},ev={help:{toggleAria:"Mesh 帮助",toggleTitle:"Mesh 概念帮助",regionAria:"Mesh 概念帮助",kicker:"帮助",title:"一览 mesh 概念",close:"关闭帮助",sections:{node:{term:"节点",summary:"参与 mesh 的工作区 — 一个仓库检出或一个隔离的 git worktree。",details:["基础节点与 worktree 克隆节点 — 克隆可在无冲突的情况下隔离并行工作。","同时显示健康状况(在线/离线)与 git 状态(分支 · ahead/behind · dirty)。","多个节点可以共享同一个守护进程。"]},p2p:{term:"P2P 连接",summary:"所选协调器通过 WebRTC 到达各远程节点的方式。",details:["direct — 直接的主机/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:"Refinery(refine)",summary:"将 worktree 分支安全地收敛并合并到基础分支的过程。",details:["配置驱动(.adhdev/refine.*)— 由补丁等价性预检和 no-op 保护机制守护。","原则上仅 ff-only;不进行 force-push。","若某个 submodule 提交无法从 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 个提供方且 ≥2 台机器,因此一致能真正提升可信度。","coupled — 收缩为单个 AI 或单台机器;重复的成员会重复同样的错误。","在“Panels”标签页中按机器本地管理;在 ~/.adhdev/meshes.json 中定义。"]},convergence:{term:"分支收敛状态",summary:"worktree 工作完成后,每个分支会被归类为恰好一个最终状态。",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:"daemon: {{id}}",run:"run: {{id}}",session:"session: {{id}}"},difficulty:{intro:"将每种任务难度映射到一个 brain。协调器会对任务难度进行分类;简单的工作随后在更便宜的模型上以低 effort 运行,困难的工作在更强的模型上以高 effort 运行。将字段留空以保留路由的默认值。",connectPrompt:"连接到协调器守护进程以编辑 brain 预设。",errorLoad:"加载 brain 预设失败",errorSave:"保存 brain 预设失败",provider:"提供方",model:"模型",thinking:"思考",routedDefault:"(路由默认值)",defaultOption:"(默认)",modelPlaceholder:"例如 haiku、sonnet、opus",savePresets:"保存预设",saving:"保存中…",reset:"重置",loading:"加载中…",easy:"简单",easyHint:"简单修复、重命名、文档 — 节省 token",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:"此 mesh 尚未保存任何 MAGI 交叉验证综合结果。运行 MAGI 审查(mesh_magi_review)并收集(mesh_magi_collect),综合摘要随后会显示在此处,并保存到 mesh 台账。",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:"未验证(拉取失败)",upstreamUnverified:"未验证",upstreamUnavailable:"不可用",needsFollowUp:"需要跟进",refined:"已精炼",tooltipLocalChanges:"本地更改",tooltipHasConflicts:"存在冲突",tooltipOutOfSync:"未同步",tooltipNeedsFollowUp:"需要跟进",tooltipUpstreamUnverified:"上游未验证",tooltipStartedNotReported:"开始:未报告",tooltipRefineCompleted:"精炼完成",tooltipRefinedBranch:"已精炼 {{branch}}",tooltipP2PRelayed:"P2P 链路通过 TURN 中继(较慢的路径)",tooltipP2PRtt:"P2P 往返延迟",tooltipPrefixStatus:"状态:",tooltipPrefixBranch:"分支:",tooltipPrefixNote:"备注:"},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:"提供方未知"},dialog:{kicker:"网格可观测性",showDetails:"显示网格详情",hideDetails:"隐藏网格详情",refreshedAt:"已于 {{time}} 刷新",liveMetadata:"实时守护进程元数据",metadataUnavailable:"元数据订阅不可用",refreshTitle:"刷新实时网格图谱",refresh:"刷新",refreshing:"正在刷新…",loadingStatus:"正在加载实时网格状态…",noGraph:"此协调器暂无可用的实时网格图谱。",errorNoMeshId:"此协调器未公开实时网格 ID。",errorUnexpectedPayload:"mesh_status 返回了意外的负载。"},health:{panelTitle:"网格健康面板",lastActivity:"最近活动",refineJobs:"精炼作业",failedTasks:"失败的任务",staleWork:"陈旧工作",sessions:"会话"}},tv={page:{title:"Repo Mesh",subtitle:"多工作区编排",waitingForDaemon:"正在等待守护进程连接...",observabilitySecondary:"网格可观测性"},list:{title:"Repo Mesh 列表",count_one:"{{count}} 个网格",count_other:"{{count}} 个网格",createMesh:"+ 创建网格",createTitle:"创建 Repo Mesh",createOnMachine:"在机器上创建",createOnMachineHint:"网格设置由所选守护进程存储。",noConnectedDaemon:"没有已连接的守护进程",workspace:"工作区",workspaceHint:"从所选守护进程注册的工作区中选择。",selectMachineFirst:"请先选择一台机器",noRegisteredWorkspaces:"没有已注册的工作区",name:"名称",remoteUrl:"仓库远程 URL(可选)",remoteUrlHint:"请提供远程 URL 或一个稳定的标识。",repoIdentity:"仓库标识(可选)",create:"创建",cancel:"取消",loading:"正在加载网格...",emptyTitle:"没有 Repo Mesh",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:"可见(在仪表板中显示每个 worker)",magiTitle:"MAGI 审阅面板",magiDescription:"MAGI(Multi-Agent Ground-truth Insight)运行一组 AI 智能体,彼此交叉核查工作以揭示真实情况。请选择由哪些智能体处理每种审阅类型。",advanced:"高级",coordinatorPromptTitle:"协调器提示词",coordinatorPromptDescription:"自定义协调器会话的系统提示词。按 mesh 的覆盖仅适用于此 mesh;用户级覆盖适用于此 daemon 协调的每个 mesh。",thisMesh:"此 mesh",thisMeshHint:"仅适用于 {{name}} 的协调器会话。留空则回退到用户级 / daemon 默认值。",overrideLabel:"覆盖(替换默认值)",overrideHint:"设置后将替换 daemon 的默认基础提示词。留空以保留默认值。",overridePlaceholder:"(空 — 应用 daemon 默认值)",appendLabel:"追加(添加到基础提示词之后)",appendHint:"始终添加到胜出的基础提示词之后。",appendPlaceholder:"(空 — 不追加任何内容)",availablePlaceholders:"可用占位符",saveCoordinatorPrompt:"保存协调器提示词",clear:"清除",clearTitle:"清除两个字段。点击保存以提交。",userLevel:"用户级(此 daemon)",userLevelDescription:"协调器 daemon 上的按机器提示词文件。它们适用于此 daemon 协调的每个 mesh,且不在 daemon 之间同步。上方按 mesh 的覆盖优先于这些设置。",safetyTitle:"安全性与 Git",safetyDescription:"协调器驱动任务的检查点、审批门控和 git 安全行为。",checkpointBefore:"在每个任务前自动提交检查点",checkpointAfter:"在每个任务后自动提交检查点",pushApproval:"推送审批",requireApprovalBeforePush:"推送前需要审批",doNotRequireApproval:"无需审批",destructiveGitApproval:"破坏性 git 操作审批",requireApproval:"需要审批",uncommittedChanges:"当工作区有未提交的更改时",warnAndContinue:"警告并继续",blockTask:"阻止任务",checkpointThenContinue:"创建检查点后继续",autoPublishSubmodule:"自动发布子模块提交(高级)",requireExplicitApproval:"需要明确审批",allowRefineryPublish:"允许 Refinery 非强制发布",autoFastForward:"自动 fast-forward 空闲节点",ffEnabled:"已启用(追赶在线、干净、落后的节点)",ffDisabled:"已禁用",includeRemoteNodes:"包含远程节点",includeRemoteNodesHint:"关闭 = 仅自动 fast-forward 协调器的本地工作区。",remoteNo:"否(仅本地工作区)",remoteYes:"是(委托给远程所属 daemon)",detectionMode:"检测模式",detectionModeHint:"空闲 = 在节点的空闲边缘触发。持续 = 同时定期扫描(仅限基础节点)。",idleEdgeOnly:"仅空闲边缘",continuousScan:"持续(定期扫描)",sessionCleanupLabel:"移除节点时,其会话……",sessionCleanupHint:"将转录清理与运行时/进程清理分开。",mcpMode:"MCP 模式:",mcpDescription:"· mesh MCP 服务器可直接从你的 CLI 智能体使用。"},nodeList:{title:"节点与提供方({{count}})",descriptionCloud:"此 mesh 中的工作区及其首选 AI 工具。仅为设置清单 — 实时的图/git/会话真实数据由上方的 Mesh Host 状态负责。",descriptionStandalone:"参与此 mesh 的工作区及其首选 AI 工具。",daemonCandidates:"机器 daemon 候选",daemonCandidatesHint:"选择已连接的 daemon,附加到所选的 Mesh Host 设置。",available:"{{count}} 个可用",noDaemonsAvailable:"当前没有可用的已连接机器 daemon。",allDaemonsAttached:"所有已连接的机器 daemon 均已附加。",selectedHost:"所选主机",attachMachine:"附加机器",addNode:"添加节点",attachMachineTitle:"附加机器 daemon",addNodeTitle:"添加节点",machine:"机器",selectMachine:"选择机器……",workspacePath:"工作区路径",enterCustomPath:"或输入自定义路径 →",preferredTools:"首选 AI 工具(按顺序)",preferredToolsHint:"在未指定提供方启动时使用的顺序。",add:"添加",cancel:"取消",setupInventoryWarning:"仅为设置清单 — 实时的 git/会话/分支详情将在 Mesh Host 提供直接聚合的 mesh_status 真实数据后显示在图弹窗中。",emptyTitle:"无节点",emptyDescription:"向此 mesh 添加一个工作区。",setupInventory:"设置清单",liveDetailGraphOwned:"实时的分支/git/会话详情由图负责;请使用上方实时图中的节点弹窗。",slotsLabel:"首选 AI 工具(能力槽位)",slotsHint:"每个槽位 = 提供方 + 模型 + thinking + 它处理的任务难度/能力 + 每槽位并行上限。任务将匹配到最合适的槽位(顺序 = 优先级)。若无槽位,此节点使用其旧版提供方顺序。",nodeInstruction:"节点指令(可选)",nodeInstructionHint:"在协调器系统提示词中以 📌 节点指令显示。",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:"Mesh Host daemon",descriptionSet:"拥有此 mesh 的协调器和实时真实数据(状态、队列、图、节点详情)的 daemon。在 mesh 创建时固定 — 无法在此重新分配。",descriptionUnset:"此 mesh 尚无主机。在已连接的 daemon 上启动协调器会将该 daemon 固定为 mesh 主机(1:1 绑定);此后由它拥有实时真实数据。",hostLabel:"主机:",hostNode:"主机节点:",unknown:"未知",hostOffline:"主机离线。",hostOfflineText:"固定的主机 daemon 未连接。在其重新连接之前,实时状态/队列/图将无法加载。你可以通过下方另一个已连接的 daemon 临时路由命令 — 这是路由回退,而非主机重新分配。",reconnectToCommand:"重新连接以下达命令",reconnectToCommandHint:"在主机恢复之前,通过此已连接的 daemon 路由命令。不会更改 mesh 主机。",waitForHost:"等待主机重新连接",noDaemonsToRoute:"没有可用于路由命令的已连接 daemon。请让主机(或另一个 daemon)上线。",launching:"启动中……",launchHost:"启动主机协调器",setHostBanner:"设置 mesh 主机。",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:"这是 Override 为空时协调器会话所获得的内容。"},hermesMcp:{title:"Hermes MCP 配置",description:"Hermes 不会自动导入仓库本地的 .mcp.json。请将此 YAML 添加到 Hermes 配置的 mcp_servers 下,然后启动一个全新的 Hermes 会话。",fallbackProvider:"Hermes CLI"}},sv={copyMessage:"复制消息"},nv={connectingToMachine:"正在连接到你的机器",establishingP2P:"正在建立 P2P 连接",agentNotMonitored:"代理未受监控",clickToSwitchMonitoring:"点击将监控切换到此代理",agentPanelHidden:"代理面板尚未可见",openPanelHint:"在你正在使用的应用中打开代理面板或聊天视图以开始查看消息",noMessagesYet:"尚无消息",loadingChat:"正在加载聊天...",openPanel:"打开 {{label}} 面板",switchingPanel:"正在切换...",openingPanel:"正在打开..."},rv={attachImage:"附加图片",placeholder:"向 {{panel}} 发送消息...(Shift+Enter 换行)",sendMessage:"发送消息",dropImage:"将图片拖放到此处"},av={noConversations:"尚无对话",waitingForDaemon:"正在等待你的守护进程",connectYourMachines:"连接你的机器",daemonDescription:"启动 ADHDev 守护进程以连接此仪表板。一旦上线,你便可使用任何已安装的提供方启动会话。",installDescription:"在一台机器上安装 ADHDev 并登录,它就会显示在这里。",newSession:"新建会话",newSessionDescription:"一台已连接的机器已就绪。使用任何已安装的提供方(CLI、ACP 或 IDE)开始新会话。",noTabsInGroup:"此分组中没有标签页",pressEscToCancel:"按 Esc 取消"},ov={loadOlderOutput:"加载更早的终端输出",loadingOlder:"正在加载更早的内容...",debug:"调试",copy:"复制",openControlKeys:"打开终端控制键",closeControlKeys:"关闭终端控制键"},iv={muteThis:"静音此聊天",unmuteThis:"取消静音此聊天",mutedTitle:"已静音 — 通知已关闭。点击以取消静音。",muteTitle:"为此聊天静音通知"},lv={switchToTerminal:"切换到终端视图",switchToChat:"切换到聊天视图"},cv={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:"恢复已保存的历史记录前,请检查或更改目标工作区。"},dv={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:"针对聊天文本、markdown 代码和终端输出的独立专用排版覆盖。",fontsSaved:"已为此自托管仪表板保存独立聊天字体。",notificationsSection:"通知",notificationsDescription:"针对代理活动的浏览器提示和本地声音提示。",soundEffectsLabel:"音效",soundEffectsDescription:"在代理完成或需要批准时播放声音",profileSection:"个人资料",profileDescription:"你的名字在本地聊天会话和仪表板视图中的显示方式。",displayNameLabel:"显示名称",displayNameHint:"在聊天会话和团队仪表板上显示的你的名字。",displayNamePlaceholder:"Anonymous"},onboarding:{title:"欢迎使用 ADHDev",selectedCount_one:"已选择 {{count}} 个提供商",selectedCount_other:"已选择 {{count}} 个提供商",skip:"跳过",installing:"正在安装…",done:"完成",installCount:"安装 {{count}} 个",intro:"选择你想使用的提供方。默认选中四个官方支持的 CLI 提供方;你可以从下方的选项卡安装 IDE、ACP 或扩展提供方,也可以稍后通过 Burrow → Providers → Add provider 安装。",loadingRegistry:"正在加载注册表…",loadError:"加载注册表失败:{{error}}",noProviders:"此类别下没有提供方。",installed:"✓ 已安装",installFailed:"✗ {{error}}"},about:{title:"关于",subtitle:"自托管 ADHDev 概览、内置功能,以及切换到 Cloud 后的变化",selfHostedEdition:"自托管版",headline:"保持相同的仪表盘体验,同时让运行时完全运行在本地设备上。",description:"Standalone 将浏览器、守护进程、截图和控制路径都保留在你自己的机器上。它与 Cloud 是相同的核心产品形态,只是没有远程网络和团队层。",docs:"Docs ↗",github:"GitHub ↗",tryCloud:"试用 Cloud ↗",includedSection:"Standalone 包含的功能",includedDescription:"无需云控制平面即可使用的本地优先功能集。",inventorySection:"内置清单",inventoryDescription:"在 Standalone 仪表盘中公开的捆绑编辑器和智能体功能。这些列表仅描述清单,不代表已验证的支持。",cloudExtrasSection:"仅 Cloud 提供的功能",cloudExtrasDescription:"需要托管控制平面或团队基础设施的功能。",comparisonSection:"自托管 vs Cloud",comparisonDescription:"一览产品差异。",featureHeader:"功能",selfhostHeader:"自托管",cloudHeader:"Cloud",cloudOptional:"Cloud 是可选的,并非必需",cloudOptionalDescription:"你可以在 Standalone 中保持完全本地运行,并在以后迁移到 Cloud,而无需改变使用仪表盘的方式。",compareCloud:"对比 Cloud ↗",discord:"Discord ↗"},fonts:{fontOverridesNotice:"仅 Standalone 的字体覆盖设置。这些设置不会影响云端仪表盘。聊天气泡、Markdown 正文、代码块、工具行和终端输出都使用以下偏好设置。",chat:"聊天文本",chatDescription:"助手/用户正文、Markdown 文本、思考卡片和系统备注。",code:"代码块",codeDescription:"Markdown 代码围栏、行内代码和预格式化的命令输出。",terminal:"终端",terminalDescription:"终端记录卡片,以及聊天模式下的工具/命令行。",livePreview:"实时预览",resolvedStack:"解析后的字体栈:",defaults:"默认值:",saveFontSettings:"保存字体设置",revertToSaved:"还原为已保存",resetToDefaults:"重置为默认值",saving:"正在保存…"}},uv={login:{eyebrow:"Cloud 登录",title:"登录 ADHDev",subtitle:"连接你的机器,接收审批和完成通知,让你离开办公桌时编码智能体也能持续运行。",continueWith:"使用 {{provider}} 继续",connecting:"正在连接...",devDivider:"dev",devLogin:"Dev 登录 (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}} 天前",frozenFeatureTitle:"已冻结 — 此功能已暂停,暂不可用。请参阅 docs/FROZEN_SURFACES.md"},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:"已使用 {{used}} / {{total}} 个席位",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 worktree,因此并行代理绝不会冲突。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:"从浏览器操控任意本地 CLI 代理 — Claude Code、Codex、Gemini:发送提示、批准操作并引导会话,无需触碰终端。",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:"Webhooks",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:"{{count}} TURN 分钟/天",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:"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:"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 参考 →",frozenFeatureTitle:"已冻结 — 此功能已暂停。请参阅 docs/FROZEN_SURFACES.md"},auditLogs:{title:"审计日志",subtitle:"安全事件与 API 历史",refresh:"刷新",filterPlaceholder:"按操作、资源或来源筛选...",loading:"加载中...",noLogs:"暂无日志",noMatchingLogs:"未找到匹配的日志。",logsWillAppear:"操作发生时将在此处显示。",colAction:"操作",colResource:"资源",colSource:"来源",colTime:"时间",logCount:"{{count}} 条日志",logCountFiltered:"(从 {{total}} 条中筛选)"},inviteModal:{title:"邀请团队成员",subtitle:"通过电子邮件发送邀请链接",manageSeats:"→ 在 Billing 中管理席位",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:"当您将开发环境连接到本服务时,本地 daemon 可能会传输:",s1l1:"IDE 类型和版本(例如“Cursor 0.49.1”)",s1l2:"活动 AI 代理信息(名称、状态、当前模型)",s1l3:"您与 AI 代理之间的聊天消息",s1l4:"IDE 屏幕截图(通过 P2P 传输,不存储在我们的服务器上)",s1l5:"工作区路径和打开的文件名",s1l6:"机器信息(主机名、操作系统、内存使用情况)",s1h3:"1.3 使用数据",s1p3:"出于服务改进和调试目的,我们会自动收集使用信息,包括 API 调用、功能使用模式和连接日志。",s1h4:"1.4 支付信息",s1p4:"支付处理完全由我们的 Merchant of Record,即 Paddle(Paddle.com Market Limited)处理。我们不会直接收集或存储信用卡号、银行账户详情或其他财务信息。有关其数据处理方式,请参阅",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:"用于 daemon 身份验证的按连接令牌",s3l4:"所有 API 端点上的速率限制",s3l5:"针对安全敏感操作的审计日志",s4Title:"4. 数据共享",s4p1:"我们不会将您的个人数据出售给第三方。我们可能会与以下各方共享数据:",s4l1:"作为 Merchant of Record 的支付处理",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. Cookie",s7p1:"我们仅将必要的 Cookie 用于身份验证(会话令牌)和用户偏好(主题、通知设置)。我们不使用广告或跟踪 Cookie。",s8Title:"8. 儿童隐私",s8p1:"本服务不面向 16 岁以下的用户。我们不会在知情的情况下收集 16 岁以下儿童的个人信息。",s9Title:"9. 国际数据传输",s9p1:"您的数据可能会通过 Cloudflare 的全球网络在多个位置进行处理。使用本服务即表示您同意在这些位置传输和处理您的数据。",s10Title:"10. 本政策的变更",s10p1:"我们可能会不时更新本隐私政策。如有任何重大变更,我们将通过电子邮件或本服务通知您。变更后您继续使用即表示接受更新后的政策。",s11Title:"11. 联系方式",s11p1:"有关本隐私政策或数据处理方式的问题:",s11l1Prefix:"电子邮件:",s11l2Prefix:"网站:"},terms:{title:"服务条款",lastUpdated:"最后更新:2026年4月11日",intro:"欢迎使用由 RacoLab(“我们”)运营的 ADHDev(“本服务”)。通过在以下地址访问或使用我们的本服务,",introSuffix:"即表示您同意受本服务条款(“条款”)约束。如您不同意,请勿使用本服务。",s1Title:"1. 服务说明",s1p1:"ADHDev 是一款云端开发者工具,可通过网页和移动仪表板界面对 AI 编码代理(例如 Cursor、VS Code、Antigravity、Claude Code 等)进行远程监控和控制。本服务包括本地 daemon、远程仪表板、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)处理,其在所有交易中担任 Merchant of Record。",s4Title:"4. 退款政策",s4p1:"我们为所有付费套餐提供 14 天退款保证。如您对本服务不满意,可在首次购买后 14 天内通过以下方式联系我们,申请全额退款",s4p2:"续订退款将根据具体情况逐案处理。由于 Paddle 担任 Merchant of Record,其退款政策也同样适用。",s5Title:"5. 可接受的使用",s5p1:"您同意不会:",s5l1:"将本服务用于任何非法目的或违反任何适用法律",s5l2:"试图未经授权访问其他用户的账户或数据",s5l3:"对本服务的服务器组件进行逆向工程、反编译或试图提取其源代码",s5l4:"使用本服务传输恶意软件、垃圾信息或其他有害内容",s5l5:"未经我们书面同意转售或再分发本服务",s5l6:"干扰或破坏本服务的完整性或性能",s6Title:"6. 知识产权",s6p1:"本服务及其原创内容、特性和功能均归 RacoLab 所有,并受适用的知识产权法保护。本地守护进程组件依据项目仓库中规定的开源许可证提供。",s6p2:"您通过本服务传输的所有数据和内容的所有权仍归您所有。",s7Title:"7. 数据与隐私",s7p1:"您对本服务的使用还受以下条款约束",s7PrivacyLink:"隐私政策",s7p1Suffix:"本服务为远程监控和控制目的处理 IDE 交互、聊天消息和屏幕截图。我们不会将您的数据出售给第三方。",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 运营。所有付款均由我们的销售商(Merchant of Record)处理",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:"Team",subtitle:"按席位的团队管理 — $15/席位/月,集中计费",planRequired:"需要 Team 套餐",planDesc:`Team 工作区在 Team 套餐($15/席位/月)中提供。
35
+ 管理席位、邀请团队成员,并为您的组织集中管理计费。`,upgradeBtn:"升级到 Team →",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:"移除此成员?他们将失去 Team 套餐访问权限。",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:"删除此 Team 工作区?所有成员将失去 Team 套餐权益。",leaveWorkspace:"退出工作区",leaveWorkspaceConfirm:"确定要退出此工作区吗?您的套餐可能会被降级。",defaultMemberName:"团队成员",defaultMemberNameCapitalized:"团队成员",sessionFallback:"会话",timeNow:"刚刚",yourSession:"你的会话",viewSessionTitle:"{{action}} {{sessionName}} 会话",viewingRestricted:"策略限制了查看"},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:"控制共享需要认证",unknownError:"未知错误"},apiPlayground:{title:"API Playground",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:"关闭"},announcementBanner:{eyebrow:"系统通知",visibleUntil:"显示至 {{time}}",dismiss:"关闭"},upgradeBanner:{button:"升级 →"},push:{title:"推送通知",descUnsupported:"此浏览器不支持",descDenied:"已阻止 — 请在浏览器设置中启用",descEnabled:"已启用服务器端推送",descDefault:"即使标签页关闭也能接收提醒",docs:"文档",docsLink:"推送通知文档",sent:"已发送",test:"测试",docsHintPrefix:"设置步骤、iPhone PWA 要求以及浏览器兼容性详见 ",docsHintSuffix:"。",iosHint:"在 iPhone 和 iPad 上,推送仅在已安装的 Safari PWA 中有效。普通 Safari 标签页无法接收 ADHDev 推送通知。",budget:"当前套餐推送额度:今日已使用 {{used}}/{{limit}}{{remaining}}{{resets}}。",budgetRemaining:",剩余 {{count}}",budgetResets:" • 于 {{time}} 重置",unsupportedWarning:"此浏览器不支持 Web Push。请在 iPhone/iPad 上使用 Safari PWA,或在桌面/Android 上使用 Chromium 浏览器。",deniedWarning:"通知已在浏览器或站点设置中被阻止。请在那里重新启用,然后再次开启推送通知。",registeredDevices:"已注册设备:{{count}}",noDevices:"未找到活跃的推送设备。",deviceLabel:"设备 {{number}}",thisDevice:"此设备",lastActive:"最后活跃:",removing:"正在移除...",removeHere:"在此移除",remove:"移除"},mesh:{manualMcpSetup:"此提供商需要先手动完成 MCP 设置,才能充当 Repo Mesh 协调器。",couldNotLoadMeshes:"无法加载网格",untitledMesh:"未命名网格",chooseMachineFirst:"请先选择一台机器。",launchFailed:"启动失败",coordinatorLaunchFailed:"协调器启动失败",coordinatorLaunched:"协调器已启动 ({{sessionId}})",coordinatorLaunchSent:"协调器启动命令已发送"},plans:{free:"Free",pro:"Pro",ultra:"Ultra",team:"Team",enterprise:"Enterprise"},adminAudit:{title:"全局审计",subtitle:"系统级事件跟踪",allActions:"所有操作",allSources:"所有来源",filter:"筛选",noLogs:"未找到日志",loading:"正在加载...",loadMore:"加载更多 ↓"},adminDashboard:{failedToLoad:"加载管理数据失败",title:"管理仪表板",subtitle:"服务概览与管理",accessDenied:"管理员访问被拒绝",backToDashboard:"返回仪表板",loading:"正在加载管理仪表板",loadingDesc:"正在收集服务统计和最近的审计活动。",totalUsers:"用户总数",todayCommands:"今日命令",activeApiKeys:"活跃 API 密钥",todayLogins:"今日登录",planDistribution:"套餐分布",quickActions:"快捷操作",manageUsers:"管理用户",apiKeys:"API 密钥",auditLogs:"审计日志",systemConfig:"系统配置",recentActivity:"最近活动",viewAll:"查看全部",noRecentActivity:"暂无最近活动"},adminSystem:{error:"错误:{{message}}",announcementSent:"公告已发送",announcementCleared:"公告已清除",registrationOpened:"已开放注册 — 任何人都可以注册",registrationClosed:"已关闭注册",title:"系统设置",subtitle:"公告与系统配置",loading:"正在加载系统设置",loadingDesc:"正在获取注册策略和当前公告状态。",registration:"注册",registrationOpenState:"已开放 — 任何人都可以注册",registrationClosedState:"已关闭 — 仅限允许的邮箱",registrationDesc:"关闭时,仅添加到允许列表中的邮箱才能创建新账户。现有用户不受影响。",closeRegistration:"关闭注册",openRegistration:"开放注册",announcement:"公告",current:"当前:",untilTime:"(直到 {{time}})",untilCleared:"(直到清除)",announcementPlaceholder:"输入公告消息...",severityInfo:"信息",severityWarning:"警告",severityCritical:"严重",duration1h:"1 小时",duration6h:"6 小时",duration24h:"24 小时",duration7d:"7 天",durationUntilCleared:"直到清除",send:"发送"},adminUsers:{error:"错误:{{message}}",roleUpdated:"角色已更新",planUpdated:"套餐已更新",suspensionReasonPrompt:"请输入停用原因:",userSuspended:"用户已停用",userUnsuspended:"用户已恢复",title:"用户管理",subtitle:"管理用户、角色和停用",usersTotal:"位用户",searchPlaceholder:"搜索邮箱或名称...",allRoles:"所有角色",roleUser:"用户",roleAdmin:"管理员",roleSuperAdmin:"超级管理员",allPlans:"所有套餐",search:"搜索",colUser:"用户",colRole:"角色",colPlan:"套餐",colStatus:"状态",colCreated:"创建时间",colActions:"操作",noName:"无名称",statusSuspended:"已停用",statusActive:"活跃",unsuspend:"恢复",suspend:"停用",loading:"加载中...",prev:"← 上一页",next:"下一页 →"}},pv={openMenu:"打开菜单",closeMenu:"关闭菜单"},mv={loadingOlderMessages:"正在加载较早的消息...",waitingForMessages:"正在等待消息...",agentGenerating:"智能体正在生成...",jumpToTop:"跳到顶部",jumpToOldestMessages:"跳到最早的消息",top:"↑ 顶部",latest:"↓ 最新",jumpToLatestMessages:"跳到最新消息",jumpToBottom:"跳到底部",showEarlierMessages:"↑ 显示较早的 {{count}} 条消息...",showEarlierMessagesHidden:"↑ 显示较早的 {{count}} 条消息...(隐藏了 {{total}} 条)",loadOlderMessages:"↑ 加载较早的消息",loadErrorRetry:"↻ {{error}}"},hv={zoomOut:"缩小",zoomIn:"放大",resetZoom:"重置缩放",toggleFullscreen:"切换全屏"},fv={mouse:"鼠标",touch:"触摸",connected:"已连接",ws:"WS",direct:"直连",relay:"中继",turnBlocked:"TURN 已阻止",turnUsage:"TURN {{used}}/{{budget}}m",typeAndEnter:"输入并按 Enter...",settings:"设置",zoom:"缩放:",fill:"填充",fit:"适应",directP2PTitle:"P2P 直连",turnRelayTitle:"正在使用 TURN 中继",dailyTurnTitle:"每日 TURN 中继使用量",waitingState:{turnRelayActive:"TURN 中继已启用"}},bv={title:"会话信息",loading:"加载中…",refresh:"刷新",close:"关闭",failedToLoad:"加载会话信息失败",notCoordinatorSession:"这不是 Repo Mesh 协调器会话,因此未注入协调器专用的提示词。智能体将使用其 CLI 自带的默认设置运行。",stampedToNode:"此会话绑定到了协调器不再报告的网格节点。",sectionSession:"会话",sectionLaunch:"启动",sectionMeshNode:"网格节点",sectionMeshCoordinator:"网格协调器",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:"工作树",rowLaunchReady:"启动就绪",rowGit:"Git",rowProviders:"提供程序",rowProviderPriority:"提供程序优先级",rowMeshId:"Mesh ID",rowCoordinatorCli:"协调器 CLI",rowStartedAt:"启动时间",rowPromptInjection:"提示注入",rowMcpConfig:"MCP 配置",rowRuntimeId:"运行时 ID",rowLifecycle:"生命周期",rowSurface:"界面",rowRecoveryState:"恢复状态",rowRestoredFromStorage:"从存储恢复",rowAttachedClients:"已连接客户端"},gv={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:"工作区"}},xv={launchConfirm:{workspace:"工作区",languageModel:"语言模型(可选)",autoDetect:"自动检测或默认",cliArgs:"CLI 参数(可选)",cliArgsPlaceholder:"例如 --experimental",cancel:"取消",closeAria:"关闭启动确认",launch:"启动",launching:"启动中…"},confirmExternal:{dialogAria:"确认不受信任的外部提供程序",title:"激活不受信任的外部提供程序?",description:"此清单附带了守护进程将执行的 JavaScript。请将其视为不受信任的代码 — 启用前请审查源代码。",proceedWarning:"仅当您信任所添加的源 URL 并已审查清单时才继续。",cancel:"取消",activate:"激活"},workspace:{noWorkspace:"(无工作区 — 在主目录中启动)",selectWorkspace:"📁 选择工作区…",customPath:"✏️ 自定义路径…",noWorkspacesSaved:"(未保存工作区 — 在 Overview 选项卡中添加)",selectWorkspaceBtn:"选择工作区…",enterAbsolutePath:"输入绝对路径…",browseHint:"启动前请浏览到目标文件夹。",absolutePathHint:"输入要在其中启动的绝对路径。",defaultWorkspace:"默认工作区",selectedWorkspace:"已选工作区",noWorkspaceSelected:"未选择工作区。将在主目录中启动。"},agentTab:{selectToLaunch:"选择要启动的 {{label}}",launchSettings:"启动设置",noIdesDetected:"未检测到 IDE。",scanSystem:"扫描系统",noProviders:"没有可用的 {{category}} 提供程序。",noProvidersHint:"如果二进制文件安装在默认位置之外,请在 Providers 中设置自定义可执行路径。",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:"守护进程查找提供程序清单的位置。会影响解析和重新加载。",sourceMode:"来源模式",explicitProviderDir:"显式 providerDir",providerDirPlaceholder:"留空则使用 ~/.adhdev/providers",applying:"应用中…",applyReload:"应用 + 重新加载",userRoot:"用户根目录:",upstreamRoot:"上游根目录:",providerRoots:"提供程序根目录:",loadingSettings:"正在加载提供程序设置…",noProviders:"尚未安装任何提供程序。请打开上方的“Add provider”来安装一个。",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:"连接中..."},card:{sectionIDEs:"IDE",sectionCLIs:"CLI",sectionACPAgents:"ACP 代理",emptyHeadline:"欢迎使用 ADHDev",emptyBody:"将你的第一台机器连接到仪表板。运行一次设置,然后在该机器上启动 ADHDev:",emptyDocsLink:"📚 阅读文档 →",hidden:"已隐藏",pageTitle:"Burrows",burrowCount_one:"{{count}} 个 burrow",burrowCount_other:"{{count}} 个 burrow",onlineCount_one:"{{count}} 台在线",onlineCount_other:"{{count}} 台在线",agentsActive_one:"{{count}} 个代理活跃",agentsActive_other:"{{count}} 个代理活跃",activeNow:"当前活跃",generating:"生成中",connectionFailed:"连接失败",reconnect:"重新连接",connecting:"连接中...",runtimePolling:"运行时轮询",transportRelay:"TURN 中继 — 直连失败",transportDirect:"直接连接 (STUN/host)",noAgentsRunning:"尚无运行中的代理",launchCta:"启动 →"},detail:{notFound:"未找到机器",save:"保存",cancel:"取消",loading:"⏳ 正在加载机器...",offlineHint:"该机器可能处于离线状态或尚未连接。",back:"← 返回",tabWorkspace:"工作区",tabHostedRuntimes:"托管运行时",tabProviders:"提供方",tabSystem:"系统",tabLogs:"日志",clickToSetNickname:"点击设置昵称",nicknamePlaceholder:"机器昵称...",reconnect:"重新连接",coresCount_one:"{{count}} 核",coresCount_other:"{{count}} 核",p2pState:"P2P {{state}}",p2pConnected:"已连接"},commandCenter:{currentChats:"当前聊天",recentLaunches:"最近启动",daemonUpdate:"守护进程更新"},workspaceBrowse:{currentFolder:"当前文件夹"},managedWorkspaces:{remove:"移除"}},vv={theme:{helloHelp:"你好!有什么可以帮你的?",fixBug:"请修复这个 bug",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:"🎨 自定义"},providerPriority:{available:"可用",notOnMachine:"此机器上不存在",remove:"移除",addCliLabel:"添加可用的 CLI 提供方",addProvider:"添加提供方"},coordinatorPrompts:{overrideDesc:"<strong>Override</strong> 会替换该 CLI 的守护进程内置基础提示词。",appendDesc:"<strong>Append</strong> 会在胜出的基础提示词之后追加。",overrideLabel:"Override",appendLabel:"Append"},appearance:{modeLabel:"模式",themeLabel:"主题",mobileLabel:"移动端"}},yv={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:"⌛ 正在刷新…"},wv={nav:{home:"ADHDev 首页",mesh:"Mesh",what:"功能",agents:"智能体",pricing:"定价",install:"安装",github:"GitHub",docs:"文档",getStarted:"开始使用",toggleMenu:"切换菜单",mainNavigation:"主导航"},hero:{badge:"多厂商、多机器的智能体控制平面",title:"运行十个智能体谁都会。ADHDev 让成果落地到 main。",subtitle:"从浏览器驱动任何本地编码智能体 —— Claude Code、Codex、Cursor ——然后让 Refinery <em>无人值守</em>地将完成的工作合并回 main:使用你仓库自己的门禁、补丁等价性检查、仅 fast-forward、绝不 force-push。你只需与一个协调器对话;它会在你自己的机器上异步运行并行智能体 —— 无需照看任何会话。代码始终留在你的机器上 —— P2P,端到端。",selectOs:"选择操作系统",osUnix:"macOS / Linux",osWindows:"Windows",copyInstall:"复制安装命令:{{cmd}}",copied:"已复制",copy:"复制",getStarted:"开始使用",openSource:"在 GitHub 上开源",joinDiscord:"加入 Discord",selfHost:"自行自托管",demoDesktop:"ADHDev 指挥中心跨多台机器驱动实时智能体会话",demoPush:"ADHDev 移动推送通知与一键批准"},mesh:{sectionTitle:"他们负责并行。我们负责落地。",sectionSubtitle:"启动并行智能体是简单的部分 —— 如今每个工具都能做到。难的是之后:十个分支仍需验证和合并。Refinery 无人值守地替你完成这些,让完成的工作抵达 main,而不是堆在你的审阅队列中。",refineryHighlight:"Refinery",refineryTitle:"完成的工作落地到 main —— 无人值守",refineryDesc:"启动十个并行智能体谁都会。Refinery 会根据你仓库自己的门禁(typecheck、测试、lint)验证每个工作树,核对补丁等价性,发布子模块提交,fast-forward main,并自动清理。绝不 force-push。任何含糊之处都会被退回审阅,而不是被合并。",asyncHighlight:"异步编排",asyncTitle:"你只需与一处对话。其余交给它运行。",asyncDesc:"你把工作交给一个协调器;它在事件循环上跨多台机器驱动众多工作者 —— 仅在完成、批准或状态事件到达时才响应。无需轮询,也没有一个个智能体窗口需要照看。不同于需要盯着每个智能体会话的桌面应用,这里协调器等待事件,因此你无需同步地坐在任何东西前面。",monoHighlight:"Monorepo 感知",monoTitle:"即便有 git submodule 也安全",monoDesc:"真实的生产仓库会嵌套子模块 —— 而这恰恰是幼稚的自动合并崩溃之处。Refinery 具备子模块感知能力:它以子模块提交的可达性为门禁,判断补丁等价性,并原子地更新指针。本项目本身就是一个根 + 两个子模块的 monorepo,每天都以这种方式收敛。",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 运行你仓库的门禁,核对补丁等价性,并 fast-forward main —— 无人值守,绝不 force-push",rowSubmodules:"对 git submodule 安全",rowSubmodulesLocalCli:"没有能感知它们的合并自动化",rowSubmodulesDesktop:"有工作树并行,但合并要靠你自己做对",rowSubmodulesAdhdev:"子模块感知的收敛:可达性门禁、补丁等价性检查、原子指针更新 —— 每天在本 monorepo 上自用验证",rowAsync:"与一处对话,异步",rowAsyncLocalCli:"一次一个会话,同步进行",rowAsyncDesktop:"你需要亲自监督每个智能体窗口",rowAsyncAdhdev:"一个协调器在事件循环上驱动每个工作者 —— 它等待完成/批准事件,你无需轮询或照看",rowMultiMachine:"多台物理机器",rowMultiMachineLocalCli:"仅限单台主机的进程",rowMultiMachineDesktop:"被绑定在它所运行的那台机器上",rowMultiMachineAdhdev:"通过 P2P 的远程守护进程 —— 向你拥有的每台机器分发(无需 SSH 布线)",rowParallelBranch:"隔离分支的并行工作",rowParallelBranchLocalCli:"子智能体共享一个工作树 —— 并发写入会冲突",rowParallelBranchDesktop:"每个任务一个 git worktree —— 核心优势",rowParallelBranchAdhdev:"每个节点一个 git worktree —— 跨机器并行,而不只是跨核心",rowBrowser:"从浏览器或手机驱动",rowBrowserLocalCli:"你必须守在终端前",rowBrowserDesktop:"原生桌面应用 —— 你得坐在那张桌子前",rowBrowserAdhdev:"Web 优先:从任何浏览器或手机控制会话并批准",rowNativeApp:"原生桌面应用",rowNativeAppLocalCli:"仅限终端",rowNativeAppDesktop:"精致的原生窗口 —— 坐在它前面确实更舒适",rowNativeAppAdhdev:"我们是 Web 优先 —— 一个浏览器标签页,而非原生应用",rowRestarts:"能挺过重启与上下文丢失",rowRestartsLocalCli:"状态存于会话中 —— 关闭即丢失",rowRestartsDesktop:"状态绑定于应用进程",rowRestartsAdhdev:"任务持久化到磁盘,并在协调器或守护进程重启后恢复 —— 仅追加、可防篡改的审计轨迹",rowCrossCheck:"交叉核查答案",rowCrossCheckLocalCli:"单个智能体的看法,没有第二意见",rowCrossCheckDesktop:"并行工作,单一裁定",rowCrossCheckAdhdev:"MAGI 将同一个只读问题扇出到独立的机器 × 提供方智能体,并呈现它们的分歧之处",footnote:"对于单台机器、单个分支、一次性任务 —— 带子智能体的本地 CLI 更轻量且效果很好,原生桌面编排器坐起来也更舒适。当工作跨机器和分支扇出、需要挺过重启并应自动落地到 main 时,Repo Mesh 才真正显出价值 —— 无论你身在何处都能掌控。"},what:{sectionTitle:"任意智能体,自由混用",sectionSubtitle:"设计上厂商中立。在 Mac 上运行 Claude Code,在 Windows GPU 机器上运行 Codex,用 Gemini 做审阅 —— 都在同一个网格中、同一套策略之下。切换厂商无需切换平台。",cliHighlight:"CLI 智能体",cliTitle:"从 Web 驱动任何终端智能体",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:"已测试",tierTestedDesc:"针对真实应用 + 版本验证过",tierCommunity:"社区",tierCommunityDesc:"内置且由社区支持",groupIdes:"IDE",hintIdes:"通过 Chrome DevTools Protocol 接入。可读取聊天、发送提示词、切换会话、截图。",groupCli:"CLI 代理",hintCli:"通过 PTY 适配器驱动,支持恢复与重连。",groupExtensions:"IDE 内扩展代理",hintExtensions:"为运行在其他 IDE 内的代理提供 CDP webview 接入。",acpFootnote:"外加 {{count}}+ 个通过 stdio 的 ACP 代理(Agent Client Protocol):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:"开始 7 天 Pro 试用",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:"更多 webhook 和 API 调用",share:"更多共享会话"}}}},install:{sectionTitle:"三步搭建可用的仪表盘",sectionSubtitle:"无需配置文件。无需接入 API 密钥。ADHDev 不管理代理认证 — 每个工具各自保管其登录。",selectOs:"选择操作系统",osUnix:"macOS / Linux",osWindows:"Windows",copyInstall:"复制安装命令:{{cmd}}",copied:"已复制",copy:"复制",platformNote:"macOS 和 Windows 是已验证的安装路径。Linux 运行同一套 Unix 脚本,由社区测试。",arrow:"→",steps:{step1:{title:"安装守护进程",desc:"一条 curl 命令即可安装守护进程和 adhdev CLI — 这是你用来配对机器并启动守护进程的启动器(不要与它所驱动的 CLI 代理混淆,如 Claude Code 或 Codex)。同一个二进制文件同时支持云端和独立模式。"},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. 保留所有权利。"}},kv={selectAllThatApply:"选择所有适用项",other:"其他"},Sv={changeList:{binaryBadge:"bin",truncatedNote:"文件列表已截断 — 在本地运行 <code>git status</code> 查看完整输出。"},statusDialog:{conflicts:"冲突",clean:"干净"}},Cv={header:{back:"返回"}},jv={title:"通知",subtitle:"提醒、自动审批和提供方设置",sectionBrowserAlerts:"浏览器提醒",masterToggleLabel:"通知",masterToggleDesc:"所有提醒的总开关",browserNotificationsLabel:"浏览器通知",browserNotificationsDesc:"标签页处于非活动状态时的桌面提醒",browserBackgroundInfo:"只有当此仪表盘标签页在后台保持打开时,浏览器提醒才会触发。",browserBackgroundInfoWithPush:"只有当此仪表盘标签页在后台保持打开时,浏览器提醒才会触发。如果关闭标签页,请改用推送通知。",standaloneBackgroundInfo:"只有当此仪表盘标签页在后台保持打开时,浏览器提醒才会触发。如果关闭它,独立模式将无法为你投递托管的推送通知。",permissionDefault:"此浏览器尚未授予通知权限。请允许以接收浏览器提醒。",standalonePermissionDefault:"此浏览器尚未授予通知权限。请允许以接收本地浏览器提醒。",allowNotifications:"允许通知",permissionDenied:"浏览器通知已在站点或浏览器设置中被屏蔽。请在那里重新启用以接收桌面提醒。",standalonePermissionUnsupported:"此浏览器无法在此处显示桌面通知。请让仪表盘保持可见,或在此设备上使用其他受支持的浏览器。",permissionUnsupported:"此浏览器无法在此处显示桌面通知。请使用受支持的桌面浏览器,或在可用时依靠推送通知。",completionAlertsLabel:"完成提醒",completionAlertsDesc:"代理完成任务时通知",approvalAlertsLabel:"审批提醒",approvalAlertsDesc:"代理需要审批时通知",connectionAlertsLabel:"连接提醒",connectionAlertsDesc:"机器断开连接时提醒",allDisabled:"所有通知均已禁用。启用总开关以进行配置。",sectionProviderAlerts:"提供方提醒规则",loading:"⏳ 加载中...",refresh:"↻ 刷新",noOnlineMachines:"没有在线的机器。在某台机器上启动 ADHDev 以配置提供方提醒。",loadingProviderSettings:"正在加载提供方设置...",providerCount_one:"{{count}} 个提供方",providerCount_other:"{{count}} 个提供方",keyStatAutoApprove:"自动审批",keyStatApprovalAlert:"审批提醒",keyStatNoProgressAlert:"无进展提醒",bulkEnabledAll:"已为全部 {{total}} 个提供方启用",bulkDisabledAll:"已为全部 {{total}} 个提供方禁用",bulkEnabledSome:"已为 {{total}} 个提供方中的 {{onCount}} 个启用",hideDetails:"▾ 隐藏详情",showDetails:"▸ 显示各提供方详情 ({{count}})",soundEffectsLabel:"音效",soundEffectsDesc:"代理完成或需要审批时播放声音"},Nv={language:Ux,common:Gx,connection:qx,toast:zx,notification:Kx,event:Vx,dashboard:Yx,cliStop:Jx,approval:Qx,newSession:Xx,mobileInbox:Zx,meshGraph:ev,repoMesh:tv,chat:sv,chatPane:nv,chatInput:rv,paneGroup:av,terminal:ov,conversation:iv,cliView:lv,launch:cv,standalone:dv,cloud:uv,app:pv,chatList:mv,screenshot:hv,remote:fv,sessionInfo:bv,mesh:gv,machine:xv,settings:vv,historyModal:yv,landing:wv,interactivePrompt:kv,git:Sv,ide:Cv,notifications:jv},Av={label:"Idioma",select:"Seleccionar idioma"},Iv={cancel:"Cancelar"},Tv={disconnected:"Desconectado",connected:"Conectado",connectedToDashboard:"Conectado al panel",connectingToMachine:"Conectando a la máquina...",networkOffline:"Red sin conexión",reconnecting:"Reconectando",sessionExpired:"La sesión ha expirado.",logInAgain:"Iniciar sesión de nuevo",connectionFailed:"Error de conexión — actualiza la página o vuelve a intentarlo en unos momentos.",reconnectNow:"Reconectar ahora"},Mv={label:{success:"Listo",warning:"Atención",info:"Actualización"},dismiss:"Descartar"},Dv={actionNeeded:"Se requiere acción",taskComplete:"Tarea completada",markRead:"Marcar como leído",markUnread:"Marcar como no leído",delete:"Eliminar"},Pv={taskCompleted:"La tarea del agente {{label}} se completó",taskCompletedWithDuration:"La tarea del agente {{label}} se completó ({{duration}} s)",approvalNeeded:"Se requiere aprobación de {{label}}",noProgress:"El agente {{label}} no muestra progreso",noProgressWithDuration:"El agente {{label}} no muestra progreso ({{minutes}} min)",noProgressTitle:"{{label}} — Sin progreso",noProgressBody:"El agente no ha mostrado progreso durante más de {{duration}}",viewRequest:"{{requester}} quiere ver tu sesión",viewRequestTitle:"Solicitud de visualización",viewRequestApproved:"Solicitud de visualización aprobada",viewRequestDeclined:"{{target}} rechazó tu solicitud de visualización",someoneRequester:"Un miembro del equipo",someoneTarget:"Miembro del equipo"},Lv={header:{title:"Panel",guide:"Guía del panel",guideOpen:"Abrir la guía del panel",guideShort:"Guía",openGitStatus:"Abrir estado de git",openMeshGraph:"Abrir el grafo de Repo Mesh en vivo",meshGraph:"Grafo de Mesh",stopAcpSession:"Detener sesión ACP",stopCliProcess:"Detener proceso CLI",chatHistory:"Historial de chat",remoteControl:"Control remoto",generating:"generando",activityInbox:"Bandeja de actividad"},hidden:{title:"Pestañas ocultas",dragHint:"Arrastra una pestaña aquí para ocultarla.",resetPanels:"Restablecer paneles",restoreAll:"Restaurar todo",hideCurrentTab:"Ocultar pestaña actual",empty:"No hay pestañas ocultas."},inbox:{unread:"No leído",read:"Leído",empty:"No hay actividad pendiente."},metaChips:{meshNode:"Nodo Mesh"},versionBanner:{required:"requerido",retry:"reintentar"},remoteDialog:{history:"Historial"},sourceTimeline:{colWhen:"Cuándo",colEvent:"Evento",colFrom:"Desde",colTo:"Hasta",colCause:"Causa"}},Rv={title:"¿Detener {{agent}}?",gracefulDescription:"«Detener» pide al proveedor que salga de forma limpia cuando es compatible. «Forzar detención» finaliza el runtime de inmediato.",forceOnlyDescription:"Este proveedor no admite la detención limpia. «Forzar detención» finalizará el runtime de inmediato.",stop:"Detener",forceStop:"Forzar detención"},Ev={processing:"PROCESANDO...",actionRequired:"ACCIÓN REQUERIDA"},_v={title:"Iniciar sesión",close:"Cerrar el diálogo de nueva sesión",category:"Categoría",detectedLocally:"Detectado localmente",availableToOpen:"Disponible para abrir",machine:"Máquina",selectMachine:"Seleccionar máquina {{name}}",workspace:"Espacio de trabajo",browse:"Explorar…",launchTargetType:"Tipo de destino de lanzamiento",modeWorkspace:"Espacio de trabajo",modeWorkspaceDesc:"Sesión normal",modeMesh:"Mesh",modeMeshDesc:"Sesión de coordinador",homeDirectory:"Directorio de inicio",customFolder:"Carpeta personalizada…",launchWithoutWorkspace:"Lanzar sin espacio de trabajo.",selectWorkspaceFolder:"Selecciona una carpeta de espacio de trabajo.",selectFolder:"Seleccionar carpeta",saving:"Guardando…",saveWorkspace:"Guardar espacio de trabajo",loadingMeshes:"Cargando meshes…",noMeshes:"No hay ningún Repo Mesh configurado en esta máquina. Primero crea o sincroniza un mesh y luego vuelve a abrir este selector.",mesh:"Mesh",repoMesh:"Repo mesh",nodeCount_one:"{{count}} nodo",nodeCount_other:"{{count}} nodos",coordinatorWorkspace:"Espacio de trabajo del coordinador: {{path}}",chooseIde:"Elegir IDE",chooseCliProvider:"Elegir proveedor CLI",chooseAcpProvider:"Elegir proveedor ACP",noProviders:"No hay nada utilizable para esta categoría en la máquina seleccionada. Establece una ruta de ejecutable personalizada en Providers si el binario está fuera de la ubicación predeterminada.",startupArguments:"Argumentos de inicio",optionalFlags:"Opciones adicionales...",modelAndThinking:"Modelo y razonamiento (opcional)",model:"Modelo",providerDefault:"(predeterminado del proveedor)",custom:"Personalizado…",typeModelName:"Escribe un nombre de modelo",backToModelList:"← Volver a la lista de modelos",thinkingLevel:"Nivel de razonamiento",selectWorkspaceTitle:"Seleccionar espacio de trabajo",selectWorkspaceDescription:"Elige la carpeta que se debe usar para esta nueva sesión.",start:"Iniciar",starting:"Iniciando…",startMeshCoordinator:"Iniciar coordinador de Mesh",startingCoordinator:"Iniciando coordinador…",startIde:"Iniciar IDE",startingIde:"Iniciando IDE…",startAcpSession:"Iniciar sesión ACP",startingAcpSession:"Iniciando sesión ACP…",startFresh:"Empezar de cero",startingFresh:"Empezando de cero…",resumeSavedHistory:"Reanudar historial guardado",resumingSavedHistory:"Reanudando historial guardado…",errorLoadMeshes:"No se pudieron cargar los meshes",errorLoadFolder:"No se pudo cargar la carpeta",errorLoadSavedSessions:"No se pudieron cargar las sesiones guardadas",errorSaveWorkspace:"No se pudo guardar el espacio de trabajo",workspaceSaved:"Espacio de trabajo guardado. Aparecerá en la lista cuando se actualice el estado de la máquina.",errorManualMcpSetup:"Se requiere una configuración manual de MCP antes de que este proveedor pueda actuar como coordinador del mesh.",errorStartMeshCoordinator:"No se pudo iniciar el coordinador del mesh",errorStartSession:"No se pudo iniciar la sesión",errorResumeSession:"No se pudo reanudar la sesión"},$v={machines:"Máquinas",chats:"Chats",networkOffline:"Red sin conexión",sessionExpired:"La sesión expiró",reconnecting:"Reconectando",waitingForNetwork:"Esperando la red…",pleaseLogInAgain:"Vuelve a iniciar sesión.",restoringConnection:"Restaurando la conexión con el servidor…",waitingForDaemon:"Esperando tu daemon",connectYourMachines:"Conecta tus máquinas",waitingForDaemonSubtitle:"Inicia el daemon de ADHDev para conectar este panel. Una vez que esté en línea, podrás lanzar sesiones con cualquier proveedor instalado.",connectYourMachinesSubtitle:"Instala ADHDev en una máquina, inicia sesión y aparecerá aquí.",newCount:"{{count}} nuevos",chatCount_one:"{{count}} chat",chatCount_other:"{{count}} chats",idle:"Inactivo",unreadSuffix:" · {{count}} sin leer",noActiveChats:"No hay chats activos",needsAttention:"Requiere atención",taskComplete:"Tarea completada",workingNow:"Trabajando ahora",earlier:"Anteriores",connecting:"Conectando…",connectingSubtitle:"Esperando la conexión con el servidor antes de cargar las conversaciones.",noMachinesConnected:"No hay máquinas conectadas",noMachinesSubtitle:"Cambia a la pestaña Máquinas para conectar tu primera máquina y empezar a chatear con agentes de IA.",noConversations:"Aún no hay conversaciones",allCaughtUp:"Todo al día.",hiddenTabs:"Pestañas ocultas",collapsedCount_one:"{{count}} conversación contraída",collapsedCount_other:"{{count}} conversaciones contraídas",restoreAll:"Restaurar todo",hide:"Ocultar",hideTitle:"¿Ocultar {{title}}?",hideDescription:"Esto solo contrae el chat localmente. Puedes restaurarlo desde Pestañas ocultas.",reconnectingItem:"Reconectando…",connectingItem:"Conectando…",actionNeeded:"Se requiere acción",done:"Listo",openMeshGraphFor:"Abrir el grafo de mesh de {{title}}",openLiveMeshGraph:"Abrir el grafo de repo mesh en vivo",unmute:"Reactivar el sonido de {{title}}",mute:"Silenciar {{title}}",mutedTitle:"Silenciado — notificaciones desactivadas. Toca para reactivar el sonido.",muteNotifications:"Silenciar notificaciones",hideConversationAria:"Ocultar {{title}}",hideConversationTitle:"Ocultar conversación",stopSessionAria:"Detener la sesión de {{title}}",stopSessionTitle:"Detener la sesión (termina el agente)"},Hv={help:{toggleAria:"Ayuda de mesh",toggleTitle:"Ayuda sobre conceptos de mesh",regionAria:"Ayuda sobre conceptos de mesh",kicker:"Ayuda",title:"Conceptos de mesh de un vistazo",close:"Cerrar ayuda",sections:{node:{term:"Nodo",summary:"Un espacio de trabajo que participa en el mesh: un checkout de repositorio o un git worktree aislado.",details:["Nodo base vs. nodo clon de worktree: un clon aísla el trabajo en paralelo sin conflictos.","Muestra el estado de salud (en línea/desconectado) junto con el estado de git (rama · ahead/behind · dirty).","Varios nodos pueden compartir el mismo daemon."]},p2p:{term:"Conexión P2P",summary:"Cómo el coordinador seleccionado alcanza cada nodo remoto a través de WebRTC.",details:["direct: una ruta directa de host/STUN; la menor latencia.","relay: retransmitido por TURN; funciona a través de redes restrictivas pero es más lento.","disconnected / failed: en este momento no hay un enlace P2P en vivo desde el coordinador.","La conectividad P2P se muestra como fichas de transport y RTT en cada tarjeta de nodo (y en el panel de detalles del nodo), no como una arista del grafo."]},session:{term:"Sesión",summary:"Una sesión de CLI de agente que se ejecuta en un nodo.",details:["status = idle / generating / waiting_approval.","Distingue las sesiones de coordinador (que despachan y recopilan el trabajo) de las sesiones de worker delegadas (que realizan el trabajo)."]},task:{term:"Tarea",summary:"Una única unidad de trabajo gestionada por el modelo de extracción basado en cola.",details:["Estados: pending → assigned → completed / failed / cancelled.","Los nodos inactivos reclaman de la cola automáticamente; el despacho directo apunta a una sesión específica."]},mission:{term:"Misión",summary:"Un lote de varias tareas orientado a un único objetivo, y el registro duradero de ese esfuerzo.",details:["Estados: active / paused / completed / abandoned.","El progreso se deriva de los estados de sus tareas miembro."]},refinery:{term:"Refinery (refine)",summary:"El proceso de converger y fusionar de forma segura una rama de worktree en la base.",details:["Basado en configuración (.adhdev/refine.*): protegido por una comprobación previa de equivalencia de parches y una protección no-op.","ff-only por principio; sin force-push.","Si un commit de submodule no es alcanzable desde origin, debe publicarse → se clasifica como blocked_review."]},completion:{term:"Modelo de finalización",summary:"La finalización del trabajo delegado se persiste en la cola (pending-events).",details:["El coordinador se entera de la finalización mediante sondeo periódico o eventos.","Como se persiste en la cola, las señales de finalización nunca se pierden."]},magi:{term:"MAGI",summary:"Verificación cruzada: varios agentes de IA independientes responden la misma pregunta en paralelo.",details:["La confianza proviene de la independencia: distintas IA en distintas máquinas fallan de distintas maneras.","Cuando los agentes discrepan, la propia discrepancia señala qué conviene volver a comprobar.","Se ejecuta mediante mesh_magi_review; la síntesis pondera el acuerdo frente al acoplamiento de las fuentes."]},magiPanel:{term:"Panel MAGI",summary:"Un equipo guardado y reutilizable de miembros (máquina × IA) que invocas por nombre en distintas investigaciones.",details:["Cada miembro es un proveedor (IA), opcionalmente fijado a un nodo (máquina), con un número de réplicas.","independent: abarca ≥2 proveedores Y ≥2 máquinas, por lo que el acuerdo añade confianza real.","coupled: se reduce a una sola IA o una sola máquina; los miembros repetidos repiten los mismos errores.","Se gestiona localmente por máquina desde la pestaña Panels; se define en ~/.adhdev/meshes.json."]},convergence:{term:"Estados de convergencia de rama",summary:"Tras el trabajo en worktree, cada rama se clasifica en exactamente un estado final.",details:["merged_to_main: fusionada en la base.","pushed_feature_branch_needs_merge: enviada, a la espera de fusión.","blocked_review: retenida por problemas de revisión/alcanzabilidad.","cleanup_candidate: lista para limpiar.","not_mergeable: no se puede fusionar."]}}},approvals:{title:"APROBACIONES PENDIENTES",empty:"Ninguna sesión está esperando una decisión de aprobación.",sessionFallback:"sesión {{id}}",approve:"Aprobar",reject:"Rechazar"},chat:{loading:"Cargando…",empty:"No hay mensajes."},coordinatorBadge:{daemon:"daemon: {{id}}",run:"run: {{id}}",session:"session: {{id}}"},difficulty:{intro:"Asigna cada dificultad de tarea a un brain. El coordinador clasifica la dificultad de una tarea; el trabajo fácil se ejecuta entonces en un modelo más económico con effort bajo, y el trabajo difícil en un modelo más potente con effort alto. Deja un campo en blanco para conservar el valor predeterminado del enrutamiento.",connectPrompt:"Conéctate a un daemon coordinador para editar los presets de brain.",errorLoad:"No se pudieron cargar los presets de brain",errorSave:"No se pudieron guardar los presets de brain",provider:"Proveedor",model:"Modelo",thinking:"Pensamiento",routedDefault:"(predeterminado del enrutamiento)",defaultOption:"(predeterminado)",modelPlaceholder:"p. ej. haiku, sonnet, opus",savePresets:"Guardar preajustes",saving:"Guardando…",reset:"Restablecer",loading:"Cargando…",easy:"Fácil",easyHint:"correcciones triviales, cambios de nombre, documentación — ahorra tokens",medium:"Media",mediumHint:"trabajo habitual de funciones / corrección de errores",difficult:"Difícil",difficultHint:"arquitectura, depuración complicada, razonamiento difícil",freeform:"Libre",freeformHint:"sin forma fija"},magiKind:{intro:"Elige qué agentes revisan cada tipo de tarea. Añade una fila por agente.",refresh:"Actualizar",loading:"Cargando…",connectPrompt:"Conéctate a un daemon coordinador para gestionar los vínculos kind → panel.",errorLoad:"No se pudieron cargar los paneles de kind",errorSave:"No se pudo guardar el vínculo de kind",errorRemove:"No se pudo eliminar el vínculo de kind",errorSlotProvider:"Ranura {{slot}}: se requiere un proveedor",errorSlotReplica:"Ranura {{slot}}: el número de réplicas debe ser ≥ 1",errorNoSlot:"Un vínculo de kind necesita al menos una ranura",removeConfirm:'¿Eliminar el vínculo del panel MAGI para "{{kind}}"?',kindRca:"Análisis de causa raíz",kindDesign:"Revisión de diseño / enfoque",kindClaimAudit:"Verificar afirmaciones específicas",kindFreeform:"Revisión libre",agentCount_one:"{{count}} agente",agentCount_other:"{{count}} agentes",off:"desactivado",noAgents:"Aún no hay agentes — añade uno para habilitar este tipo de revisión.",machine:"Máquina",machineTitle:'Qué máquina ejecuta este agente. Déjalo en "any" para que el coordinador enrute por etiquetas.',anyMachine:"Cualquier máquina",offlineSuffix:"{{label}} (sin conexión)",provider:"Proveedor",providerTitle:"El agente de IA que ejecuta esta ranura.",selectProvider:"Seleccionar proveedor…",model:"Modelo",modelTitle:"Anulación de modelo opcional (con el mejor esfuerzo). En blanco usa el predeterminado del proveedor.",modelDefault:"predeterminado",modelCustom:"Personalizado…",backToModelList:"← Volver a la lista de modelos",copies:"Copias",copiesTitle:"Cuántas copias paralelas de este agente ejecutar. En blanco = 1.",removeAgent:"Eliminar agente",addAgent:"+ Añadir agente",save:"Guardar",saving:"Guardando…",removeBinding:"Eliminar vínculo",removeBindingTitle:"Borrar este vínculo de kind",removeBindingDisabledTitle:"Nada que eliminar — este kind no está configurado"},synthesis:{empty:"Todavía no se ha guardado ninguna síntesis de verificación cruzada de MAGI para esta mesh. Ejecuta una revisión MAGI (mesh_magi_review) y recógela (mesh_magi_collect); el resumen sintetizado aparecerá aquí, guardado en el ledger de la mesh.",synthesized:"sintetizado",running:"en ejecución",answered:"{{answered}}/{{total}} respondidas",needsVerificationCount:"{{count}} necesitan verificación",agreedCount:"{{count}} coincidieron",staleCount:"{{count}} obsoletas",gitSkewLabel:"Desviación de Git: ",gitSkewNote_one:"{{count}} rama ({{branches}}) — la evidencia compara código diferente.",gitSkewNote_other:"{{count}} ramas ({{branches}}) — la evidencia compara código diferente.",needsVerification:"Necesita verificación",openQuestions:"Preguntas abiertas",rawReplicaAnswers:"Respuestas sin procesar de las réplicas",rawTitleLive:"Con el mejor esfuerzo: el texto sin procesar de las réplicas no se guarda — solo se puede recuperar de un coordinador en vivo con las sesiones de réplica aún accesibles.",rawTitleOffline:"Se requiere un daemon coordinador en vivo para obtener las respuestas sin procesar de las réplicas.",loading:"Cargando…",reloadRaw:"Recargar respuestas sin procesar",loadRaw:"Cargar respuestas sin procesar",rawNotice:"El texto sin procesar por réplica no se guarda (solo se guarda este resumen sintetizado). Se obtiene en vivo del coordinador y deja de estar disponible una vez que las sesiones de réplica caducan o no existe ninguna sesión en vivo.",errorLoadRaw:"No se pudieron cargar las respuestas sin procesar",rawEmpty:"No se devolvió ninguna respuesta sin procesar — las transcripciones de las réplicas no se conservan (sin procesar no se guarda), caducaron o no hay ninguna sesión en vivo accesible para este grupo.",truncated:"truncado"},panel:{selectNode:"Selecciona un nodo para ver los detalles.",submoduleBadge:"Submódulo",dirtyBadge:"Sin confirmar",outOfSyncBadge:"Desincronizado",conflictBadge:"Conflicto",orphanBadge:"Huérfano",fieldWorkspace:"Espacio de trabajo",fieldBranch:"Rama",fieldUpstream:"Upstream",fieldUpstreamState:"Estado del upstream",fieldHead:"HEAD",fieldSubmodulePath:"Ruta del submódulo",fieldSubmoduleCommit:"Commit del submódulo",fieldParentNode:"Nodo padre",fieldAhead:"Adelante",fieldBehind:"Atrás",fieldDirtyFiles:"Archivos sin confirmar",fieldActiveSessions:"Sesiones activas",fieldProviders:"Proveedores",fieldConnection:"Conexión",fieldLinkNote:"Nota de enlace",fieldError:"Error",orphanReasons:"Motivos de orfandad",attachedChats:"Chats adjuntos",providerUnknown:"proveedor desconocido",statusAwaiting:"esperando aprobación",statusGenerating:"generando",statusIdle:"inactivo",statusCoordinator:"coordinador",statusWorker:"trabajador",runtimeAgeNotReported:"tiempo de ejecución no informado",upstreamVerified:"verificado",upstreamUnverifiedFetch:"sin verificar (falló la obtención)",upstreamUnverified:"sin verificar",upstreamUnavailable:"no disponible",needsFollowUp:"necesita seguimiento",refined:"refinado",tooltipLocalChanges:"Cambios locales",tooltipHasConflicts:"Tiene conflictos",tooltipOutOfSync:"Desincronizado",tooltipNeedsFollowUp:"Necesita seguimiento",tooltipUpstreamUnverified:"Upstream sin verificar",tooltipStartedNotReported:"Iniciado: no informado",tooltipRefineCompleted:"refinamiento completado",tooltipRefinedBranch:"{{branch}} refinada",tooltipP2PRelayed:"Enlace P2P retransmitido a través de TURN (ruta más lenta)",tooltipP2PRtt:"Latencia de ida y vuelta P2P",tooltipPrefixStatus:"Estado:",tooltipPrefixBranch:"Rama:",tooltipPrefixNote:"Nota:"},obs:{tabOverview:"Resumen",tabStatus:"Estado",tabGraph:"Grafo",convergenceMergedToMain:"Fusionado en main",convergenceNeedsMerge:"Necesita fusión",convergenceBlockedReview:"Bloqueado — necesita revisión",convergenceCleanup:"Listo para limpiar",convergenceNotMergeable:"No fusionable",followUpLabel:"Seguimiento — {{status}}",selectedNode:"Nodo seleccionado",selectedEdge:"Arista seleccionada",activeSessions:"Sesiones activas",ledger:"Registro (de toda la malla)",queueTasks:"Tareas en cola",keyWarning:"Advertencia de clave",healResult:"Resultado de la reparación",healPreview:"Vista previa de la reparación",noResultCode:"No se devolvió ningún código de resultado.",health:"Estado de salud",legend:"Leyenda",checking:"Comprobando",heal:"Reparar",loadingGraph:"Cargando grafo…",bootstrapBanner:"Esperando datos en vivo — se muestra el inventario de configuración hasta que las sondas mesh_status de los pares tengan éxito.",emptyGraph:"Todavía no hay un grafo de malla en vivo disponible para este coordinador.",fieldMachine:"Máquina",fieldLocality:"Localidad",fieldWorkspace:"Espacio de trabajo",fieldHead:"HEAD",fieldDirtyAheadBehind:"Sucio/adelante/atrás",fieldSessions:"Sesiones",fieldUpstream:"Upstream",fieldSource:"Origen",fieldTransport:"Transporte",fieldMachineId:"ID de máquina",fieldDaemonId:"ID de daemon",fieldFrom:"Desde",fieldTo:"Hasta",fieldLabel:"Etiqueta",fieldCompleted:"Completado",fieldFailed:"Fallido",fieldLaunched:"Lanzado",fieldRecentFailures:"Fallos recientes",meshConnecting:"conectando a la malla...",connecting:"conectando...",providerUnknown:"proveedor desconocido"},dialog:{kicker:"Observabilidad de la malla",showDetails:"Mostrar detalles de la malla",hideDetails:"Ocultar detalles de la malla",refreshedAt:"Actualizado {{time}}",liveMetadata:"Metadatos del daemon en vivo",metadataUnavailable:"Suscripción a metadatos no disponible",refreshTitle:"Actualizar el grafo de malla en vivo",refresh:"Actualizar",refreshing:"Actualizando…",loadingStatus:"Cargando el estado de la malla en vivo…",noGraph:"Todavía no hay un grafo de malla en vivo disponible para este coordinador.",errorNoMeshId:"Este coordinador no expone un ID de malla en vivo.",errorUnexpectedPayload:"mesh_status devolvió una carga útil inesperada."},health:{panelTitle:"Panel de salud de la malla",lastActivity:"Última actividad",refineJobs:"Trabajos de refinado",failedTasks:"Tareas fallidas",staleWork:"Trabajo obsoleto",sessions:"Sesiones"}},Bv={page:{title:"Repo Mesh",subtitle:"Orquestación multiespacio de trabajo",waitingForDaemon:"Esperando la conexión del daemon...",observabilitySecondary:"Observabilidad de la malla"},list:{title:"Repo Meshes",count_one:"{{count}} malla",count_other:"{{count}} mallas",createMesh:"+ Crear malla",createTitle:"Crear Repo Mesh",createOnMachine:"Crear en la máquina",createOnMachineHint:"La configuración de la malla la almacena el daemon seleccionado.",noConnectedDaemon:"Ningún daemon conectado",workspace:"Espacio de trabajo",workspaceHint:"Elige entre los espacios de trabajo registrados por el daemon seleccionado.",selectMachineFirst:"Selecciona primero una máquina",noRegisteredWorkspaces:"No hay espacios de trabajo registrados",name:"Nombre",remoteUrl:"URL remota del repositorio (opcional)",remoteUrlHint:"Proporciona una URL remota O una identidad estable.",repoIdentity:"Identidad del repositorio (opcional)",create:"Crear",cancel:"Cancelar",loading:"Cargando mallas...",emptyTitle:"No hay Repo Meshes",emptyWithDaemons:"Crea una malla para empezar.",emptyNoDaemons:"Conecta primero un daemon de ADHDev.",createFirst:"Crear la primera malla",noRepoIdentity:"Sin identidad de repositorio",repoMeshFallback:"Repo Mesh",nodesSuffix:"nodo(s)"},detail:{back:"← Atrás",probing:"Sondeando…",refresh:"Actualizar",delete:"Eliminar",observabilityTitle:"Observabilidad",observabilityDescription:"Abre el grafo de malla en vivo, el resumen y el estado en tiempo de ejecución en el diálogo de observabilidad.",observabilityOpenTitle:"Abrir el diálogo de grafo de malla / resumen / estado",observabilityDisabledTitle:"Primero debe seleccionarse un daemon coordinador",observabilityOpen:"Abrir grafo de malla y estado",observabilityHint:"Grafo de topología, tarjetas de resumen (misiones, registro, cola, nodos, sesiones) y deriva de tiempo de ejecución por nodo.",schedulingTitle:"Programación",schedulingDescription:"Cómo se distribuye entre los nodos elegibles el trabajo en cola sin destino asignado.",distribution:"Distribución",recommended:"Recomendado",saving:"Guardando…",visibilityTitle:"Visibilidad del panel",visibilityDescription:"Si las sesiones de trabajo que genera este coordinador aparecen en la bandeja de entrada de tu panel y lanzan notificaciones.",visibilityLabel:"Sesiones de trabajo generadas por el coordinador",visibilityHint:"Ocultas = mantén la bandeja de entrada en silencio y silencia sus notificaciones; interactúas a través de la sesión del coordinador. Visibles = muestra cada sesión de trabajo generada como su propia conversación.",visibilityHidden:"Oculto (sin notificaciones, mantén la bandeja de entrada tranquila)",visibilityVisible:"Visible (muestra cada worker en el panel)",magiTitle:"Paneles de revisión MAGI",magiDescription:"MAGI (Multi-Agent Ground-truth Insight) ejecuta un panel de agentes de IA que verifican mutuamente su trabajo para revelar la verdad de fondo. Elige qué agentes gestionan cada tipo de revisión.",advanced:"avanzado",coordinatorPromptTitle:"Prompt del coordinador",coordinatorPromptDescription:"Personaliza el prompt del sistema para las sesiones del coordinador. Las anulaciones por mesh se aplican solo a este mesh; las anulaciones a nivel de usuario se aplican a cada mesh que coordina este daemon.",thisMesh:"Este mesh",thisMeshHint:"Se aplica solo a las sesiones del coordinador de {{name}}. Déjalo vacío para recurrir al valor predeterminado a nivel de usuario / daemon.",overrideLabel:"Anulación (reemplaza el valor predeterminado)",overrideHint:"Cuando se establece, reemplaza el prompt base predeterminado del daemon. Déjalo vacío para mantener el valor predeterminado.",overridePlaceholder:"(vacío — se aplica el valor predeterminado del daemon)",appendLabel:"Añadir (se agrega después de la base)",appendHint:"Siempre se agrega después del prompt base que prevalezca.",appendPlaceholder:"(vacío — no se añade nada)",availablePlaceholders:"Marcadores de posición disponibles",saveCoordinatorPrompt:"Guardar prompt del coordinador",clear:"Borrar",clearTitle:"Borra ambos campos. Haz clic en Guardar para confirmar.",userLevel:"Nivel de usuario (este daemon)",userLevelDescription:"Archivos de prompt por máquina en el daemon coordinador. Se aplican a cada mesh que coordina este daemon y no se sincronizan entre daemons. Las anulaciones por mesh de arriba prevalecen sobre estas.",safetyTitle:"Seguridad y Git",safetyDescription:"Comportamiento de puntos de control, controles de aprobación y seguridad de git para las tareas dirigidas por el coordinador.",checkpointBefore:"Confirmar automáticamente un punto de control antes de cada tarea",checkpointAfter:"Confirmar automáticamente un punto de control después de cada tarea",pushApproval:"Aprobación de push",requireApprovalBeforePush:"Requerir aprobación antes del push",doNotRequireApproval:"No requerir aprobación",destructiveGitApproval:"Aprobación de git destructivo",requireApproval:"Requerir aprobación",uncommittedChanges:"Cuando el espacio de trabajo tiene cambios sin confirmar",warnAndContinue:"Advertir y continuar",blockTask:"Bloquear la tarea",checkpointThenContinue:"Crear un punto de control y continuar",autoPublishSubmodule:"Publicar automáticamente los commits de submódulos (avanzado)",requireExplicitApproval:"Requerir aprobación explícita",allowRefineryPublish:"Permitir publicación no forzada de Refinery",autoFastForward:"Auto fast-forward de nodos inactivos",ffEnabled:"Habilitado (pone al día los nodos en línea, limpios y rezagados)",ffDisabled:"Deshabilitado",includeRemoteNodes:"Incluir nodos remotos",includeRemoteNodesHint:"Desactivado = solo se hace auto fast-forward del espacio de trabajo local del coordinador.",remoteNo:"No (solo espacio de trabajo local)",remoteYes:"Sí (delegar a los daemons remotos propietarios)",detectionMode:"Modo de detección",detectionModeHint:"Inactivo = en el borde de inactividad de un nodo. Continuo = también escanea periódicamente (solo nodos base).",idleEdgeOnly:"Solo en el borde de inactividad",continuousScan:"Continuo (escaneo periódico)",sessionCleanupLabel:"Al eliminar un nodo, sus sesiones…",sessionCleanupHint:"Separa la limpieza de transcripciones de la limpieza de runtime/procesos.",mcpMode:"Modo MCP:",mcpDescription:"· El servidor MCP del mesh se puede usar directamente desde tu agente CLI."},nodeList:{title:"Nodos y proveedores ({{count}})",descriptionCloud:"Espacios de trabajo en este mesh y sus herramientas de IA preferidas. Solo inventario de configuración — la verdad en vivo de grafo/git/sesión la posee el estado del Mesh Host de arriba.",descriptionStandalone:"Espacios de trabajo que participan en este mesh y sus herramientas de IA preferidas.",daemonCandidates:"Candidatos de daemon de máquina",daemonCandidatesHint:"Elige daemons conectados para adjuntar a la configuración del Mesh Host seleccionada.",available:"{{count}} disponible(s)",noDaemonsAvailable:"Actualmente no hay daemons de máquina conectados disponibles.",allDaemonsAttached:"Todos los daemons de máquina conectados ya están adjuntos.",selectedHost:"host seleccionado",attachMachine:"Adjuntar máquina",addNode:"Agregar nodo",attachMachineTitle:"Adjuntar daemon de máquina",addNodeTitle:"Agregar nodo",machine:"Máquina",selectMachine:"Selecciona una máquina...",workspacePath:"Ruta del espacio de trabajo",enterCustomPath:"O introduce una ruta personalizada →",preferredTools:"Herramientas de IA preferidas (en orden)",preferredToolsHint:"Orden utilizado al iniciar sin un proveedor explícito.",add:"Agregar",cancel:"Cancelar",setupInventoryWarning:"Solo inventario de configuración — el detalle en vivo de git/sesión/rama se muestra en la ventana emergente del grafo una vez que la verdad agregada directa de mesh_status está disponible desde el Mesh Host.",emptyTitle:"Sin nodos",emptyDescription:"Agrega un espacio de trabajo a este mesh.",setupInventory:"inventario de configuración",liveDetailGraphOwned:"El detalle en vivo de rama/git/sesión lo posee el grafo; usa la ventana emergente del nodo en el grafo en vivo de arriba.",slotsLabel:"Herramientas de IA preferidas (ranuras de capacidad)",slotsHint:"Cada ranura = proveedor + modelo + thinking + la dificultad/capacidad de tarea que gestiona + un límite de paralelismo por ranura. Las tareas se emparejan con la ranura más adecuada (orden = preferencia). Sin ranuras, este nodo usa su orden de proveedores heredado.",nodeInstruction:"Instrucción del nodo (opcional)",nodeInstructionHint:"Se muestra en el prompt del sistema del coordinador como 📌 Instrucción del nodo.",nodeInstructionPlaceholder:"p. ej. «Ejecuta solo pruebas de humo aquí», «Usa opus en este nodo»",saveInstruction:"Guardar instrucción",saving:"Guardando…",removeNode:"Eliminar nodo",details:"Detalles",nodeId:"ID del nodo:",launchReady:"Listo para iniciar:",launchReadyYes:"sí",launchReadyNo:"no hay herramienta preferida configurada",repoRoot:"Raíz del repositorio:",activeSessionsLabel:"Sesiones activas:",added:"Agregado:",activeQueueAssignments:"Asignaciones de cola activas",noActiveAssignment:"No hay tarea de cola asignada activa para este nodo.",activeSessions:"Sesiones activas",launchBlocked:"No se detectó ningún proveedor en este nodo — el inicio de tareas está bloqueado hasta que se seleccione o instale un proveedor. (Las ranuras de capacidad vacías por sí solas no bloquean el inicio; esto significa que no se encontró ningún proveedor.)",titleNoCount:"Nodos y proveedores",workspacesDetected:"{{count}} espacio(s) de trabajo detectado(s)",pickFromSaved:"← Elige de los espacios de trabajo guardados",ownerMachine:"Propietario: {{owner}} · Máquina: {{machine}}"},host:{coordinatorProvider:"Proveedor CLI del coordinador",coordinatorProviderHint:"Herramienta iniciada para la sesión del coordinador host.",useNodePriority:"Usar la prioridad de proveedores del nodo",title:"Daemon del Mesh Host",descriptionSet:"El daemon que posee el coordinador de este mesh y la verdad en vivo (estado, cola, grafo, detalle de nodos). Se fija cuando se crea el mesh — no se puede reasignar aquí.",descriptionUnset:"Este mesh aún no tiene host. Iniciar el coordinador en un daemon conectado fija ese daemon como host del mesh (una vinculación 1:1); a partir de entonces posee la verdad en vivo.",hostLabel:"Host:",hostNode:"Nodo host:",unknown:"Desconocido",hostOffline:"Host sin conexión.",hostOfflineText:"El daemon host fijado no está conectado. El estado/cola/grafo en vivo no se cargará hasta que se reconecte. Puedes enrutar temporalmente los comandos a través de otro daemon conectado abajo — esto es un enrutamiento de reserva, no una reasignación del host.",reconnectToCommand:"Reconectar para comandar",reconnectToCommandHint:"Enruta los comandos a través de este daemon conectado hasta que el host regrese. No cambia el host del mesh.",waitForHost:"Esperar a que el host se reconecte",noDaemonsToRoute:"No hay daemons conectados disponibles para enrutar los comandos. Pon en línea el host (u otro daemon).",launching:"Iniciando...",launchHost:"Iniciar el coordinador host",setHostBanner:"Establece el host del mesh.",setHostBannerText:"El host es el daemon que posee el coordinador y la verdad en vivo de esta malla. Inicia el coordinador del host abajo para establecerlo — el host queda fijado una vez establecido.",hostDaemon:"Daemon host",hostDaemonHint:"Elige el daemon que alojará esta malla. Iniciar el coordinador en él lo fija como host.",resolvingHost:"Resolviendo el host… (o elige un daemon para alojar)",launchHostSetsHost:"Iniciar coordinador del host (establece el host)",noDaemonsToHost:"No hay daemons conectados. Pon un daemon en línea para alojar esta malla.",online:"en línea",offline:"sin conexión",noCommandTarget:"No hay ningún destino de comando disponible — pon en línea el host o un daemon.",pickHostFirst:"Elige primero un daemon host (o espera a que se resuelva la fijación del host).",attachNodeFirst:"Primero adjunta un espacio de trabajo de este daemon como nodo."},slotEditor:{empty:"No hay ranuras de capacidad configuradas — no pasa nada. Este nodo sigue ejecutando tareas según su orden de prioridad de proveedores (abajo). Las ranuras son un ajuste opcional: añade una para dirigir dificultades o capacidades de tareas específicas a una herramienta concreta.",moveUp:"Subir",moveDown:"Bajar",removeSlot:"Quitar ranura",provider:"Proveedor",select:"(seleccionar)",model:"Modelo",providerDefault:"(predeterminado del proveedor)",custom:"Personalizado…",modelPlaceholder:"modelo",backToModelList:"← Volver a la lista de modelos",thinking:"Razonamiento",thinkingDefault:"(predeterminado)",difficulty:"Dificultad (en blanco = todas)",capabilityTags:"Etiquetas de capacidad (separadas por comas)",maxParallel:"Máximo en paralelo (por ranura)",maxParallelPlaceholder:"sin límite",addSlot:"Añadir ranura",saving:"Guardando…",saveSlots:"Guardar ranuras"},tagEditor:{noSpaces:"Las etiquetas no pueden contener espacios.",reservedPrefix:"Ese prefijo se deriva automáticamente — elige otra etiqueta.",alreadyAdded:"Ya añadida.",routingTags:"Etiquetas de enrutamiento",autoDerivedTitle:"Derivada automáticamente — no se puede editar",customTagTitle:"Etiqueta personalizada",remove:"Quitar {{tag}}",addPlaceholder:"añade una etiqueta personalizada (p. ej. test-runner)",add:"Añadir",saving:"Guardando…",saveTags:"Guardar etiquetas",empty:"No hay etiquetas de enrutamiento — las tareas pueden ejecutarse aquí sin coincidir con ninguna capacidad específica. Las etiquetas son opcionales."},missions:{errorFetch:"Error al obtener los objetivos completos de las misiones",title:"Misiones",description:"Misiones actuales e históricas reportadas por el coordinador. Expande un objetivo para obtener su texto completo bajo demanda.",empty:"No hay misiones {{status}}.",taskCount_one:"{{count}} tarea",taskCount_other:"{{count}} tareas",goalUnavailable:" … (objetivo completo no disponible)",showLess:"Mostrar menos",loading:"Cargando…",showFullGoal:"Mostrar objetivo completo",showMore:"Mostrar {{count}} más"},queue:{title:"Cola",description:"Inspecciona el trabajo de la cola activa por separado de los registros históricos de tareas completadas, fallidas y canceladas.",statActive:"Activas",statPending:"Pendientes",statAssigned:"Asignadas",statStale:"Obsoletas",statHistorical:"Históricas",statCompleted:"Completadas",statFailed:"Fallidas",loading:"Cargando...",refresh:"Actualizar cola",refreshHint:"Actualiza la cola para ver los recuentos de tareas del host y las asignaciones recientes.",empty:"La cola está vacía.",staleBadge:"obsoleta",staleTitle:"Asignación obsoleta",waitingOnTitle:"Esperando a: {{tasks}}",waitsOn_one:"espera {{count}} tarea",waitsOn_other:"espera {{count}} tareas",blocked:"bloqueada",durationTitle:"Despacho → tiempo real hasta el estado terminal",retry_one:" · {{count}} reintento",retry_other:" · {{count}} reintentos",node:"nodo {{id}}",session:"sesión {{id}}"},promptPreview:{connectPrompt:"Conecta un daemon para previsualizar el valor predeterminado.",errorRender:"Error al renderizar el prompt predeterminado",hide:"Ocultar el prompt predeterminado",view:"Ver el prompt predeterminado",rendering:"Renderizando…",retry:"Reintentar",info:"Esto es lo que recibe una sesión de coordinador cuando Override está vacío."},hermesMcp:{title:"Configuración de Hermes MCP",description:"Hermes no importa automáticamente el .mcp.json local del repositorio. Añade este YAML bajo mcp_servers en la configuración de Hermes y luego inicia una nueva sesión de Hermes.",fallbackProvider:"Hermes CLI"}},Fv={copyMessage:"Copiar mensaje"},Ov={connectingToMachine:"Conectando con tu máquina",establishingP2P:"Estableciendo conexión P2P",agentNotMonitored:"Agente no monitorizado",clickToSwitchMonitoring:"Haz clic para cambiar la monitorización a este agente",agentPanelHidden:"El panel del agente aún no está visible",openPanelHint:"Abre el panel del agente o la vista de chat en la app que estés usando para empezar a ver los mensajes",noMessagesYet:"Aún no hay mensajes",loadingChat:"Cargando chat...",openPanel:"Abrir panel de {{label}}",switchingPanel:"Cambiando...",openingPanel:"Abriendo..."},Wv={attachImage:"Adjuntar imagen",placeholder:"Enviar mensaje a {{panel}}... (Shift+Enter para salto de línea)",sendMessage:"Enviar mensaje",dropImage:"Suelta la imagen aquí"},Uv={noConversations:"Aún no hay conversaciones",waitingForDaemon:"Esperando a tu daemon",connectYourMachines:"Conecta tus máquinas",daemonDescription:"Inicia el daemon de ADHDev para conectar este panel. Una vez en línea, podrás lanzar sesiones con cualquier proveedor instalado.",installDescription:"Instala ADHDev en una máquina, inicia sesión y aparecerá aquí.",newSession:"Nueva sesión",newSessionDescription:"Hay una máquina conectada lista. Inicia una nueva sesión con cualquier proveedor instalado — CLI, ACP o IDE.",noTabsInGroup:"No hay pestañas en este grupo",pressEscToCancel:"Pulsa Esc para cancelar"},Gv={loadOlderOutput:"Cargar salida anterior del terminal",loadingOlder:"Cargando anteriores...",debug:"Depurar",copy:"Copiar",openControlKeys:"Abrir teclas de control del terminal",closeControlKeys:"Cerrar teclas de control del terminal"},qv={muteThis:"Silenciar este chat",unmuteThis:"Reactivar el sonido de este chat",mutedTitle:"Silenciado: notificaciones desactivadas. Haz clic para reactivar el sonido.",muteTitle:"Silenciar las notificaciones de este chat"},zv={switchToTerminal:"Cambiar a la vista de Terminal",switchToChat:"Cambiar a la vista de Chat"},Kv={resumeSavedHistory:"Reanudar el historial guardado",startFresh:"Empezar de cero",resumingSavedHistory:"Reanudando el historial guardado…",startingFresh:"Empezando de cero…",startIde:"Iniciar IDE",startingIde:"Iniciando IDE…",startAcpSession:"Iniciar sesión ACP",startingAcpSession:"Iniciando sesión ACP…",recoverHostedRuntime:"Recuperar el entorno de ejecución alojado",hostedRuntimeRecoveryDescription:"Recuperación alternativa para entornos de ejecución alojados tras interrupciones. Para una continuidad normal, abre el historial guardado en su lugar.",openSavedHistory:"Abrir el historial guardado",savedHistoryTitle:"Historial guardado",savedHistoryHelper:"Usa el historial guardado cuando quieras dar continuidad a la conversación con el mismo proveedor.",savedHistoryEmpty:"Aún no se ha encontrado ningún historial guardado.",refreshSavedHistory:"Actualizar el historial guardado",refreshingSavedHistory:"Actualizando el historial guardado…",startFreshWith:"¿Empezar de cero con {{label}}?",restart:"¿Reiniciar {{label}}?",startFreshReview:"Revisa el proveedor y la carpeta de destino antes de empezar de cero.",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 cero",confirmRestart:"Reiniciar",confirmStartingFresh:"Empezando de cero…",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."},Vv={nav:{dashboard:"Panel",settings:"Configuración",docs:"Documentación",about:"Acerca de"},layout:{expandSidebar:"Expandir barra lateral",collapseSidebar:"Contraer barra lateral",collapse:"Contraer"},auth:{loading:"Cargando el panel independiente…",loadError:"No se pudo cargar el estado de autenticación independiente: {{error}}",signInTitle:"Inicio de sesión independiente",passwordProtected:"Este panel autoalojado está protegido por una contraseña local.",tokenProtected:"Este servidor independiente está protegido por un token. Ábrelo con la URL con token o establece una contraseña desde una sesión ya autenticada.",passwordPlaceholder:"Introduce la contraseña independiente",unlock:"Desbloquear panel",signingIn:"Iniciando sesión…",noPasswordEnabled:"El inicio de sesión con contraseña no está habilitado en este servidor."},machine:{loading:"⏳ Cargando la máquina...",awaitingInput:"Esperando tu entrada ↑"},settings:{title:"Configuración",subtitle:"Configuración del daemon local, apariencia y preferencias en el dispositivo",infoNotice:"La configuración independiente permanece en esta máquina. El navegador solo se comunica con tu daemon local a través de localhost o de tu endpoint LAN autoalojado.",publicHostWarning:"Este servidor independiente está actualmente vinculado a 0.0.0.0 sin autenticación. Cualquier persona en tu LAN puede abrir el panel hasta que establezcas una contraseña o un token.",daemonSection:"Daemon",daemonDescription:"Estado de la conexión y endpoints locales del entorno de ejecución autoalojado.",versionLabel:"Versión",statusLabel:"Estado",statusRunning:"● En ejecución",statusNotConnected:"○ No conectado",currentBindLabel:"Vinculación actual",defaultBindLabel:"Vinculación predeterminada",authLabel:"Autenticación",authPassword:"Contraseña habilitada",authToken:"Token habilitado",authNone:"Sin autenticación configurada",networkSection:"Acceso a la red",networkDescription:"Elige el host de vinculación predeterminado para futuros arranques independientes. El --host de la CLI sigue anulando esto en ejecuciones puntuales.",networkHint:"Usa solo localhost si este panel debe permanecer en la máquina actual. Usa todas las interfaces si sueles acceder a él desde teléfonos, tabletas u otros dispositivos de tu LAN. Si expones esa máquina de forma más amplia, establece una contraseña o un token.",localhostLabel:"Solo localhost",localhostHint:"Vincular a 127.0.0.1. Mejor cuando solo esta máquina debe abrir el panel.",allInterfacesLabel:"Todas las interfaces",allInterfacesHint:"Vincular a 0.0.0.0. Ideal para acceso por LAN, proxies inversos u otros puntos de entrada externos.",saveNetworkMode:"Guardar modo de red predeterminado",saving:"Guardando…",networkRestartHint:"Se aplica en el próximo reinicio independiente. La ejecución actual permanece vinculada a {{host}}.",networkSavedAll:"Modo de red independiente predeterminado establecido en todas las interfaces (0.0.0.0). Reinicia el modo independiente para aplicarlo.",networkSavedLocal:"Modo de red independiente predeterminado establecido en solo localhost. Reinicia el modo independiente para aplicarlo.",securitySection:"Seguridad del panel",securityDescription:"Protección con contraseña exclusiva para autoalojamiento, para los navegadores que usan este panel independiente.",passwordSet:"Actualmente se requiere una contraseña local para el acceso desde el navegador. Las sesiones existentes se rotan cuando la cambias.",passwordNotSet:"Aún no se ha establecido ninguna contraseña independiente. Si sueles ejecutar con --host, se recomienda encarecidamente establecer una.",currentPasswordPlaceholder:"Contraseña actual",currentPasswordFirstTimePlaceholder:"Contraseña actual (no necesaria para la primera configuración)",newPasswordPlaceholder:"Nueva contraseña",newPasswordFirstTimePlaceholder:"Nueva contraseña independiente",confirmPasswordPlaceholder:"Confirmar nueva contraseña",updatePassword:"Actualizar contraseña",enablePassword:"Habilitar contraseña",disablePassword:"Deshabilitar contraseña",passwordUpdated:"Contraseña independiente actualizada.",passwordEnabled:"Contraseña independiente habilitada.",passwordDisabled:"Contraseña independiente deshabilitada.",passwordTooShort:"La contraseña debe tener al menos 4 caracteres.",passwordMismatch:"La nueva contraseña y la confirmación no coinciden.",detectedIdesSection:"IDE detectados",detectedIdesDescription:"Editores descubiertos por el daemon local en esta máquina.",noIdesDetected:"No se detectaron IDE. Inicia un IDE para verlo aquí.",machineSection:"Máquina",machineDescription:"El burrow local expuesto por tu daemon independiente.",daemonNotConnected:"Daemon no conectado. Ejecuta 'adhdev-standalone' para iniciar.",appearanceSection:"Apariencia",appearanceDescription:"Unifica el resto del panel con un único lugar para el modo, el tema y las anulaciones de fuente exclusivas del modo independiente.",themeDescription:"Elige un preajuste o crea una paleta personalizada de superficie, acento y chat para la interfaz independiente.",mobileDescription:"Elige si los teléfonos abren el panel primero como una app de chat o con el diseño completo del espacio de trabajo.",fontsLabel:"Fuentes",fontsDescription:"Anulaciones tipográficas exclusivas del modo independiente para el texto del chat, el código markdown y la salida del terminal.",fontsSaved:"Fuentes de chat independientes guardadas para este panel autoalojado.",notificationsSection:"Notificaciones",notificationsDescription:"Avisos del navegador y señales sonoras locales para la actividad del agente.",soundEffectsLabel:"Efectos de sonido",soundEffectsDescription:"Reproducir un sonido cuando el agente termina o necesita aprobación",profileSection:"Perfil",profileDescription:"Cómo aparece tu nombre en los hilos de chat locales y en las vistas del panel.",displayNameLabel:"Nombre visible",displayNameHint:"Tu nombre mostrado en los hilos de chat y en el panel del equipo.",displayNamePlaceholder:"Anonymous"},onboarding:{title:"Te damos la bienvenida a ADHDev",selectedCount_one:"{{count}} proveedor seleccionado",selectedCount_other:"{{count}} proveedores seleccionados",skip:"Omitir",installing:"Instalando…",done:"Listo",installCount:"Instalar {{count}}",intro:"Elige los proveedores que quieras usar. De forma predeterminada se seleccionan los cuatro proveedores CLI con soporte oficial; puedes instalar proveedores de IDE, ACP o extensiones desde las pestañas de abajo, o más tarde desde Burrow → Providers → Add provider.",loadingRegistry:"Cargando registro…",loadError:"Error al cargar el registro: {{error}}",noProviders:"No hay proveedores en esta categoría.",installed:"✓ instalado",installFailed:"✗ {{error}}"},about:{title:"Acerca de",subtitle:"Resumen de ADHDev autoalojado, funciones integradas y qué cambia en Cloud",selfHostedEdition:"Edición autoalojada",headline:"Mantén la misma experiencia del panel, con el runtime totalmente en el dispositivo.",description:"Standalone mantiene el navegador, el daemon, las capturas de pantalla y la ruta de control en tu propia máquina. Es la misma forma de producto central que Cloud, solo que sin las capas de red remota ni de equipo.",docs:"Docs ↗",github:"GitHub ↗",tryCloud:"Probar Cloud ↗",includedSection:"Incluido en standalone",includedDescription:"El conjunto de funciones local-first disponible sin el plano de control en la nube.",inventorySection:"Inventario integrado",inventoryDescription:"Editores agrupados y superficies de agentes expuestos en el panel de standalone. Estas listas describen el inventario, no un soporte verificado.",cloudExtrasSection:"Extras exclusivos de Cloud",cloudExtrasDescription:"Capacidades que requieren el plano de control alojado o la infraestructura de equipo.",comparisonSection:"Autoalojado vs Cloud",comparisonDescription:"La división del producto de un vistazo.",featureHeader:"Función",selfhostHeader:"Autoalojado",cloudHeader:"Cloud",cloudOptional:"Cloud es opcional, no obligatorio",cloudOptionalDescription:"Puedes permanecer totalmente local en standalone y pasar a Cloud más tarde sin cambiar tu forma de usar el panel.",compareCloud:"Comparar Cloud ↗",discord:"Discord ↗"},fonts:{fontOverridesNotice:"Anulaciones de fuente solo para standalone. No afectan al panel en la nube. Las burbujas de chat, el texto de markdown, los bloques de código, las filas de herramientas y la salida del terminal usan todas las preferencias de abajo.",chat:"Texto del chat",chatDescription:"Texto del asistente/usuario, texto en markdown, tarjetas de pensamiento y notas del sistema.",code:"Bloques de código",codeDescription:"Bloques de código de markdown, código en línea y salida de comandos preformateada.",terminal:"Terminal",terminalDescription:"Tarjetas de transcripción del terminal y filas de herramientas/comandos en el modo chat.",livePreview:"Vista previa en vivo",resolvedStack:"Pila resuelta:",defaults:"Valores predeterminados:",saveFontSettings:"Guardar configuración de fuentes",revertToSaved:"Revertir a lo guardado",resetToDefaults:"Restablecer valores predeterminados",saving:"Guardando…"}},Yv={login:{eyebrow:"Inicio de sesión en Cloud",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 del escritorio.",continueWith:"Continuar con {{provider}}",connecting:"Conectando...",devDivider:"dev",devLogin:"Inicio de sesión Dev (test_jwt_token)",providerNote:"GitHub y Google se usan únicamente para la 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 ",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 visible",displayNameDesc:"Tu nombre mostrado en el panel y en los espacios de trabajo 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:"Habilitado",disabled:"Deshabilitado",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 de API y tokens de conexión",deleteItemWebhooks:"Webhooks e historial de entregas",deleteItemPush:"Suscripciones a 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:", luego inicia ",runSetupSuffix:" en una máquina para registrarla aquí.",removeMachineConfirm:"¿Quitar esta máquina? Necesitará ejecutar `adhdev setup` de nuevo para volver a conectarse.",failedToDeleteMachine:"Error al eliminar la máquina",failedToUpdate:"Error al actualizar",rename:"Cambiar nombre",online:"En línea",connecting:"Conectando",lastSeen:"Visto por última vez {{time}}",removeMachine:"Quitar máquina",never:"Nunca",justNow:"Justo ahora",minutesAgo:"hace {{minutes}} min",hoursAgo:"hace {{hours}} h",daysAgo:"hace {{days}} d",frozenFeatureTitle:"Congelado — esta función está en pausa y no está disponible. Consulta docs/FROZEN_SURFACES.md"},billing:{title:"Facturación",subtitle:"Gestiona tu suscripción y tu plan",currentPlan:"Plan actual:",statusTrial:"Prueba",statusActive:"Activo",statusPastDue:"Vencido",statusCanceled:"Cancelado",nextBilling:"Próxima facturación: {{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 un 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:"Puestos del equipo",seatsUsed:"{{used}} / {{total}} puestos usados",pricePerMonth:"${{price}}/mes",cannotReduceSeats:"No se puede reducir por debajo de {{count}} puestos (actualmente en uso). Elimina miembros primero.",removeSeat:"− Quitar puesto",addSeat:"+ Añadir puesto",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:"Acerca de",subtitle:"Resumen de la nube, superficies compatibles y capacidades por nivel de plan",cloudEdition:"Edición en la nube",heroTitle:"Controla tus agentes CLI locales desde cualquier lugar — web o móvil.",heroDesc:"ADHDev Cloud muestra en tu navegador los agentes que se ejecutan en tus máquinas: envía prompts, aprueba acciones, orquesta el trabajo entre máquinas y recibe notificaciones en tu teléfono — el código fluye por P2P directamente a tu daemon, nunca a través del servidor.",openDashboard:"Abrir panel",viewMachines:"Ver máquinas",docs:"Documentación ↗",whyTitle:"Por qué ADHDev Cloud",whyDesc:"Capacidades principales disponibles cuando tus máquinas están conectadas mediante el plano de control en la nube.",howTitle:"Cómo funciona",howDesc:"El camino de incorporación en la nube, desde la instalación hasta el control remoto.",repoMeshTitle:"Repo Mesh",repoMeshDesc:"Orquesta agentes entre máquinas — solo en la nube.",meshCard1Title:"Un coordinador, muchos agentes",meshCard1Desc:"Encola tareas contra una misión y deja que los nodos inactivos reclamen trabajo desde una cola local-first basada en extracción. Distribuye entre máquinas y proveedores — Claude Code en una, Codex en otra — y luego converge los resultados desde una única sesión de coordinador.",meshCard2Title:"El mismo repositorio, muchas máquinas a la vez",meshCard2Desc:"Cada nodo es un checkout o un git worktree aislado, de modo que los agentes paralelos nunca colisionan. El Refinery converge cada rama — validar, fusionar, hacer push, limpiar — con un manejo seguro de submódulos. Se ejecuta sobre un canal P2P directo de daemon a daemon; el servidor solo señaliza y autoriza a pares de la misma cuenta.",worksWith:"Compatible con",worksWithDesc:"Agentes CLI, IDE y extensiones de IA compatibles.",groupCli:"Agentes CLI",groupIdes:"IDE",groupExtensions:"Agentes de IA",pricingTitle:"Precios",pricingDesc:"Planes de nube actuales y capacidad de máquinas por nivel.",planPopular:"Popular",planPerMonth:"/mes",readyTitle:"Listo para conectar una máquina",readyDesc:"Entra en tu panel, inspecciona tus máquinas conectadas o continúa en la documentación si aún estás con la configuración.",dashboard:"Panel",machines:"Máquinas",discord:"Discord ↗",github:"GitHub ↗",features:{webControlTitle:"Control web de agentes CLI locales",webControlDesc:"Controla cualquier agente CLI local — Claude Code, Codex, Gemini — desde tu navegador: envía prompts, aprueba acciones y dirige sesiones sin tocar la terminal.",chatRelayTitle:"Relé de chat de agentes",chatRelayDesc:"Lee y responde conversaciones de agentes desde cualquier lugar, incluidas las superficies móviles.",liveViewTitle:"Vista de sesión en vivo",liveViewDesc:"Observa la actividad del agente en tiempo real; en las sesiones de IDE, visualiza y controla la pantalla por P2P sin cambiar de ventana.",mobileTitle:"Listo para móvil",mobileDesc:"Recibe aprobaciones y consulta el progreso mientras estás lejos de tu máquina de desarrollo.",secureTitle:"Seguro por defecto",secureDesc:"El chat, los comandos y las capturas fluyen directamente entre tu navegador y tu daemon a través de WebRTC — la nube solo gestiona los metadatos de autenticación y señalización. Tu código nunca pasa por el servidor."},steps:{step1Title:"Instalación en una línea",step1Desc:"Ejecuta un solo comando en cualquier máquina que quieras controlar. Instala el daemon de ADHDev y la CLI de adhdev.",step2Title:"Iniciar sesión",step2Desc:"Inicia sesión con GitHub o Google y el daemon se empareja con tu cuenta — sin ningún token que copiar.",step3Title:"Controla tus agentes desde cualquier lugar",step3Desc:"La máquina aparece en tu panel al instante. Inicia y controla Claude Code, Codex, Gemini y otros agentes CLI desde la web — también las sesiones de IDE."},plans:{freeName:"Free",proName:"Pro",ultraName:"Ultra",freePer:"/mes",proPer:"/mes",ultraPer:"/mes",freeFeature1:"1 máquina",freeFeature2:"Relé de chat en tiempo real",freeFeature3:"Control web de tus agentes locales",freeFeature4:"Soporte de la comunidad",proFeature1:"2 máquinas",proFeature2:"Agentes de IA ilimitados",proFeature3:"Vista remota P2P",proFeature4:"Prueba gratuita de 7 días",ultraFeature1:"5 máquinas — tarifa plana, no por puesto",ultraFeature2:"Todo lo de Pro",ultraFeature3:"Mayor concurrencia y límites de uso",ultraFeature4:"Minutos de captura diarios ilimitados"}},layout:{navDashboard:"Panel",navBurrows:"Burrows",navNotifications:"Notificaciones",navMesh:"Mesh",navMarketplace:"Marketplace",navTeam:"Equipo",navApi:"API",navWebhooks:"Webhooks",navAccount:"Cuenta",navSettings:"Ajustes",navDocs:"Documentación",navAbout:"Acerca de",adminSection:"Administración",adminOverview:"Resumen",adminUsers:"Usuarios",adminAuditLogs:"Registros de auditoría",adminSystem:"Sistema",adminEntry:"Administración",footerPlanTitle:"Plan actual: {{plan}} — gestionar o mejorar",expandSidebar:"Expandir barra lateral",collapseSidebar:"Contraer barra lateral",collapse:"Contraer",logoutConfirm:"¿Seguro que quieres cerrar sesión?",logout:"Cerrar sesión",machineLimitBanner:"Has alcanzado el límite de {{count}} máquina{{plural}} del plan Free. Mejora para añadir más.",upgradeArrow:"Mejorar →"},settings:{title:"Ajustes",subtitle:"Apariencia y preferencias",quickLinksTitle:"Enlaces rápidos",quickLinksDesc:"Abre las páginas más útiles desde la bandeja de entrada móvil.",linkNotificationsTitle:"Notificaciones",linkNotificationsSubtitle:"Push, alertas del navegador y ajustes de entrega",linkAccountTitle:"Cuenta",linkAccountSubtitle:"Perfil, facturación, sesiones y eliminar cuenta",linkAboutTitle:"Acerca de",linkAboutSubtitle:"Resumen de la nube, superficies compatibles y planes",linkDocsTitle:"Documentación",linkDocsSubtitle:"Abrir la documentación del producto en una pestaña nueva",appearanceTitle:"Apariencia"},planCard:{unlimited:"Ilimitado",machineSingular:"{{count}} máquina",machinePlural:"{{count}} máquinas",sharedSessionSingular:"{{count}} sesión compartida",sharedSessionPlural:"{{count}} sesiones compartidas",teamMemberSingular:"{{count}} miembro del equipo",teamMemberPlural:"{{count}} miembros del equipo",turnPerDay:"{{count}} min de TURN/día",recommended:"Recomendado",currentPlan:"Plan actual",contactUs:"Contáctanos",freeForever:"Gratis para siempre",startTrial:"Iniciar prueba gratuita de 7 días",upgradeTo:"Mejorar a {{name}}",noChargeCancel:"Sin cargo durante 7 días. Cancela cuando quieras.",periodSeatMo:"puesto/mes",periodMo:"mes",yearlyNote:"${{yearly}}/año — Ahorra ${{saved}}",pricingCustom:"Personalizado"},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 ocurran.",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:"Fallido",deleteConfirm:"¿Eliminar este webhook?",testFailed:"La prueba falló",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://your-service.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:"Desactivado automáticamente",autoDisabledTitle:"Desactivado automáticamente tras 10 fallos consecutivos",failuresWarning:"⚠ {{count}} fallos",failuresTitle:"{{count}} fallos consecutivos — se desactivará automáticamente 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:"Desactivado automáticamente tras 10 fallos consecutivos"},apiKeys:{title:"Claves de API",keyCount:"{{count}} claves",playground:"Playground",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:"Congelada",revokeConfirm:"¿Revocar esta clave de 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 de API",enterKeyToTest:"Introduce una clave de API para probar.",open:"Abrir",createKeyTitle:"Crear clave de API",labelName:"Nombre",namePlaceholder:"p. ej. Production Bot",permissions:"Permisos ({{count}})",createBtn:"Crear",cancel:"Cancelar",loading:"Cargando...",noKeys:"Sin claves de API",noKeysDesc:"Crea una clave para integrar con servicios externos.",createFirstKey:"Crear primera clave",usedDate:"Usada el {{date}}",neverUsed:"Nunca usada",revoke:"Revocar",usageLabel:"Uso:",apiReference:"Referencia de API →",frozenFeatureTitle:"Congelado — esta función está en pausa. Consulta docs/FROZEN_SURFACES.md"},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 ocurran.",colAction:"Acción",colResource:"Recurso",colSource:"Origen",colTime:"Hora",logCount:"{{count}} registros",logCountFiltered:" (filtrado de {{total}})"},inviteModal:{title:"Invitar a un miembro del equipo",subtitle:"Envía un enlace de invitación por correo electrónico",manageSeats:"→ Gestionar asientos en Billing",emailLabel:"Dirección de correo electrónico",emailPlaceholder:"colleague@company.com",roleLabel:"Rol",roleViewer:"Espectador",roleMember:"Miembro",roleAdmin:"Administrador",roleViewerDesc:"Puede ver paneles e historial de chat",roleMemberDesc:"Puede controlar agentes y enviar comandos",roleAdminDesc:"Puede gestionar miembros y configuración",cancel:"Cancelar",sending:"Enviando...",sendInvite:"Enviar invitación",inviteSent:"¡Invitación enviada!",shareWith:"Comparte este enlace con",copied:"¡Copiado!",copy:"Copiar",done:"Listo"},shareModal:{title:"Compartir sesión",chatLabel:"Chat",chatDesc:"Solo conversación con IA",remoteLabel:"Remoto",remoteDesc:"Captura de pantalla + escritorio",permissionLabel:"Nivel de permiso",authRequired:"Se requiere cuenta",expiresAfter:"Caduca después de",maxViewers:"Máximo de espectadores",hide:"Ocultar",activeShares:"Recursos compartidos activos",creating:"Creando...",createChatLink:"Crear enlace de chat",createRemoteLink:"Crear enlace remoto",expires:"caduca",revoke:"Revocar",shareLinkCreated:"¡Enlace de uso compartido creado!",viewerMustLogin:"El espectador debe haber iniciado sesión para usar este enlace",copy:"Copiar",copied:"¡Copiado!",expiresAt:"Caduca:",done:"Listo",failedToCreate:"Error al crear el enlace de uso compartido",expiry1h:"1 hora",expiry6h:"6 horas",expiry24h:"24 horas",expiry7d:"7 días",chatView:{label:"Solo ver",desc:"Leer la conversación con IA en tiempo real"},chatControl:{label:"Control",desc:"Leer + enviar mensajes + aprobar/rechazar acciones"},remoteView:{label:"Solo ver",desc:"Ver capturas de pantalla y chat en tiempo real"},remoteControl:{label:"Control",desc:"Capturas de pantalla + enviar mensajes + aprobar/rechazar"},remoteFull:{label:"Acceso completo",desc:"Control remoto completo, incluida la entrada de escritorio"}},onboarding:{title:"Conecta tu primera máquina",subtitle:"Instala ADHDev en una máquina e inicia sesión — se empareja sola y aparece aquí. Luego controla cada agente de esa máquina desde este panel.",platformMac:"🍎🐧 macOS / Linux",platformWindows:"🪟 Windows",copyTitle:"Haz clic para copiar",copiedLabel:"✓ Copiado",copyLabel:"📋 Copiar",listeningLabel:"Esperando tu daemon — mantén esta página abierta, aparecerá automáticamente.",connectingLabel:"Conectando con ADHDev…",step1Title:"Instala el daemon",step1Desc:"Ejecuta el comando de arriba en cualquier máquina que quieras controlar. Instala el daemon más el CLI de adhdev.",step2Title:"Inicia sesión — la máquina se empareja sola",step2Desc:"El daemon se vincula a esta cuenta automáticamente. No hay ningún token que copiar; aparece aquí en cuanto se conecta.",step3Title:"Inicia tu primera sesión",step3Desc:"Una vez que una máquina esté en línea, inicia Claude Code, Codex, Cursor y otros agentes directamente desde el panel.",readDocs:"📚 Lee la documentación →"},legal:{navHome:"Inicio",navDashboard:"Panel",footerHome:"Inicio",footerTerms:"Términos",footerPrivacy:"Privacidad",footerRefund:"Política de reembolsos",footerCopyright:"© 2026 RacoLab. All rights reserved."},authCallback:{authFailed:"Error de autenticación",backToLogin:"Volver al inicio de sesión",completing:"Completando la autenticación...",noTokenError:"No se recibió ningún token de acceso"},cliAuth:{title:"Autenticación de ADHDev CLI",verifying:"Verificando...",authorizeAs:"¿Autorizar la CLI como {{name}}?",noCodeError:"No se proporcionó ningún código de autenticación.",approve:"✓ Aprobar",signInFirst:"Inicia sesión primero para autorizar la CLI.",signIn:"Iniciar sesión →",failed:"Error",successMessage:"¡Autenticación de la CLI completada!",returnToTerminal:"Puedes volver a la terminal."},privacy:{title:"Política de privacidad",lastUpdated:"Última actualización: 23 de marzo de 2026",intro:"Esta Política de privacidad describe cómo RacoLab («nosotros», «nos», «nuestro») recopila, usa y protege tu información cuando utilizas el servicio ADHDev («Servicio») en",s1Title:"1. Información que recopilamos",s1h1:"1.1 Información de la cuenta",s1p1:"Cuando creas una cuenta, recopilamos la información proporcionada por tu proveedor de autenticación (GitHub o Google), incluidos tu nombre, dirección de correo electrónico e imagen de perfil.",s1h2:"1.2 Datos de IDE y agentes",s1p2:"Cuando conectas tu entorno de desarrollo al Servicio, el daemon local puede transmitir:",s1l1:"Tipo y versión del IDE (p. ej., «Cursor 0.49.1»)",s1l2:"Información del agente de IA activo (nombre, estado, modelo actual)",s1l3:"Mensajes de chat entre tú y los agentes de IA",s1l4:"Capturas de pantalla del IDE (transmitidas por P2P, no almacenadas en nuestros servidores)",s1l5:"Rutas del área de trabajo y nombres de archivos abiertos",s1l6:"Información de la máquina (nombre de host, SO, uso de memoria)",s1h3:"1.3 Datos de uso",s1p3:"Recopilamos automáticamente información de uso, incluidas las llamadas a la API, los patrones de uso de funciones y los registros de conexión, con fines de mejora del servicio y depuración.",s1h4:"1.4 Información de pago",s1p4:"El procesamiento de pagos lo gestiona íntegramente nuestro Merchant of Record, Paddle (Paddle.com Market Limited). No recopilamos ni almacenamos directamente números de tarjetas de crédito, datos de cuentas bancarias ni otra información financiera. Consulta",s1p4PaddleLink:"la Política de privacidad de Paddle",s1p4Suffix:"para conocer sus prácticas de tratamiento de datos.",s2Title:"2. Cómo usamos tu información",s2p1:"Usamos la información recopilada para:",s2l1:"Proporcionar y mantener el Servicio",s2l2:"Autenticar tu identidad y gestionar tu cuenta",s2l3:"Enrutar comandos y datos entre tu panel y las máquinas conectadas",s2l4:"Enviar notificaciones (de navegador y push) sobre cambios de estado de los agentes",s2l5:"Procesar la facturación y la gestión de suscripciones (a través de Paddle)",s2l6:"Detectar y prevenir abusos o accesos no autorizados",s2l7:"Mejorar el Servicio y desarrollar nuevas funciones",s2l8:"Responder a las solicitudes de soporte",s3Title:"3. Almacenamiento y seguridad de los datos",s3h1:"3.1 Infraestructura",s3p1:"Nuestro Servicio se ejecuta en la red global de Cloudflare mediante Cloudflare Workers, Durable Objects y D1 Database. Los datos se almacenan en la infraestructura de Cloudflare y están sujetos a",s3p1CloudflareLink:"la Política de privacidad de Cloudflare",s3h2:"3.2 Datos P2P",s3p2:"Las capturas de pantalla del IDE y los datos de terminal en tiempo real se transmiten directamente entre tu navegador y tu máquina mediante conexiones punto a punto de WebRTC. Estos datos no pasan por nuestros servidores ni se almacenan en ellos.",s3h3:"3.3 Medidas de seguridad",s3p3:"Implementamos las siguientes medidas de seguridad:",s3l1:"Autenticación basada en JWT con tokens de acceso de corta duración y rotación de tokens de actualización",s3l2:"Conexiones WebSocket cifradas (WSS/TLS)",s3l3:"Tokens por conexión para la autenticación del daemon",s3l4:"Limitación de velocidad en todos los endpoints de la API",s3l5:"Registro de auditoría para operaciones sensibles a la seguridad",s4Title:"4. Compartición de datos",s4p1:"No vendemos tus datos personales a terceros. Podemos compartir datos con:",s4l1:"Procesamiento de pagos como Merchant of Record",s4l2:"Proveedor de infraestructura (alojamiento, CDN, base de datos)",s4l3Label:"Proveedores de autenticación",s4l3:"GitHub/Google para el inicio de sesión con OAuth",s4p2:"Podemos divulgar datos si así lo exige la ley, un proceso legal, o para proteger nuestros derechos y la seguridad de nuestros usuarios.",s5Title:"5. Conservación de datos",s5p1:"Conservamos los datos de tu cuenta mientras esta esté activa. Los mensajes de chat y los datos de actividad de los agentes se conservan hasta 90 días para el funcionamiento del servicio.",s5p2:"Tras la eliminación de la cuenta, borraremos tus datos personales en un plazo de 30 días. Algunos datos de uso anonimizados podrán conservarse con fines analíticos.",s6Title:"6. Tus derechos",s6p1:"Tienes derecho a:",s6l1Label:"Acceso",s6l1:"Solicitar una copia de tus datos personales",s6l2Label:"Rectificación",s6l2:"Actualizar o corregir tu información personal",s6l3Label:"Eliminación",s6l3:"Solicitar la eliminación de tu cuenta y los datos asociados",s6l4Label:"Exportación",s6l4:"Descargar tus datos en un formato portable",s6l5Label:"Oposición",s6l5:"Oponerte a ciertas actividades de tratamiento de datos",s6p2:"Para ejercer estos derechos, contáctanos en",s7Title:"7. Cookies",s7p1:"Usamos cookies esenciales únicamente para la autenticación (tokens de sesión) y las preferencias del usuario (tema, configuración de notificaciones). No usamos cookies de publicidad ni de seguimiento.",s8Title:"8. Privacidad de los menores",s8p1:"El Servicio no está destinado a usuarios menores de 16 años. No recopilamos conscientemente información personal de menores de 16 años.",s9Title:"9. Transferencias internacionales de datos",s9p1:"Tus datos pueden procesarse en distintas ubicaciones a través de la red global de Cloudflare. Al usar el Servicio, consientes la transferencia y el tratamiento de tus datos en dichas ubicaciones.",s10Title:"10. Cambios en esta política",s10p1:"Podemos actualizar esta Política de privacidad de vez en cuando. Te notificaremos cualquier cambio importante por correo electrónico o a través del Servicio. El uso continuado tras los cambios constituye la aceptación de la política actualizada.",s11Title:"11. Contacto",s11p1:"Para preguntas sobre esta Política de privacidad o el tratamiento de datos:",s11l1Prefix:"Correo electrónico:",s11l2Prefix:"Sitio web:"},terms:{title:"Términos del servicio",lastUpdated:"Última actualización: 11 de abril de 2026",intro:"Te damos la bienvenida a ADHDev («Servicio»), operado por RacoLab («nosotros», «nos», «nuestro»). Al acceder o usar nuestro Servicio en",introSuffix:"aceptas quedar vinculado por estos Términos del servicio («Términos»). Si no estás de acuerdo, no uses el Servicio.",s1Title:"1. Descripción del servicio",s1p1:"ADHDev es una herramienta para desarrolladores en la nube que permite la supervisión y el control remotos de agentes de codificación de IA (como Cursor, VS Code, Antigravity, Claude Code, entre otros) a través de paneles web y móviles. El Servicio incluye un daemon local, paneles remotos, acceso a la REST API y notificaciones de navegador y push.",s2Title:"2. Registro de cuenta",s2p1:"Debes crear una cuenta para usar el Servicio. Eres responsable de mantener la confidencialidad de las credenciales de tu cuenta. Aceptas proporcionar información precisa y completa durante el registro y mantener actualizada la información de tu cuenta.",s2p2:"Debes tener al menos 16 años para usar el Servicio. Al crear una cuenta, declaras que cumples este requisito de edad.",s3Title:"3. Planes de suscripción y facturación",s3p1:"El Servicio ofrece los siguientes planes:",s3l1:"Funciones limitadas, 1 máquina conectada",s3l2:"2 máquinas conectadas, agentes ilimitados, vista remota P2P, prueba gratuita de 7 días",s3l3:"5 máquinas conectadas, todo lo de Pro más mayor concurrencia y límites de uso (precio único, no por asiento)",s3p2:"Las suscripciones de pago se facturan por adelantado de forma mensual o anual. Todos los pagos son procesados por nuestro socio de pagos, Paddle (Paddle.com Market Limited), que actúa como Merchant of Record en todas las transacciones.",s4Title:"4. Política de reembolsos",s4p1:"Ofrecemos una garantía de devolución del dinero de 14 días para todos los planes de pago. Si no estás satisfecho con el Servicio, puedes solicitar un reembolso completo dentro de los 14 días posteriores a tu compra inicial contactándonos en",s4p2:"Los reembolsos de las renovaciones se gestionan caso por caso. También se aplican las políticas de reembolso de Paddle, ya que actúa como Merchant of Record.",s5Title:"5. Uso aceptable",s5p1:"Aceptas no:",s5l1:"Usar el Servicio con fines ilícitos o en violación de las leyes aplicables",s5l2:"Intentar obtener acceso no autorizado a las cuentas o los datos de otros usuarios",s5l3:"Aplicar ingeniería inversa, descompilar o intentar extraer el código fuente de los componentes de servidor del Servicio",s5l4:"Usar el Servicio para transmitir malware, spam u otro contenido dañino",s5l5:"Revender o redistribuir el Servicio sin nuestro consentimiento por escrito",s5l6:"Interferir o alterar la integridad o el rendimiento del Servicio",s6Title:"6. Propiedad intelectual",s6p1:"El Servicio, incluidos su contenido original, características y funcionalidad, es propiedad de RacoLab y está protegido por las leyes de propiedad intelectual aplicables. El componente del daemon local está disponible bajo una licencia de código abierto según se especifica en el repositorio del proyecto.",s6p2:"Usted conserva la propiedad de todos los datos y el contenido que transmite a través del Servicio.",s7Title:"7. Datos y privacidad",s7p1:"Su uso del Servicio también se rige por nuestra",s7PrivacyLink:"Política de Privacidad",s7p1Suffix:"El Servicio procesa las interacciones con el IDE, los mensajes de chat y las capturas de pantalla con el fin de supervisar y controlar de forma remota. No vendemos sus datos a terceros.",s8Title:"8. Disponibilidad del servicio",s8p1:"Nos esforzamos por mantener una alta disponibilidad, pero no garantizamos un acceso ininterrumpido. El Servicio puede no estar disponible temporalmente debido a mantenimiento, actualizaciones o circunstancias fuera de nuestro control. No somos responsables de las pérdidas derivadas de interrupciones del servicio.",s9Title:"9. Limitación de responsabilidad",s9p1:"EN LA MÁXIMA MEDIDA PERMITIDA POR LA LEY, RacoLab NO SERÁ RESPONSABLE DE NINGÚN DAÑO INDIRECTO, INCIDENTAL, ESPECIAL, CONSECUENTE O PUNITIVO, NI DE NINGUNA PÉRDIDA DE BENEFICIOS O INGRESOS, YA SEA INCURRIDO DIRECTA O INDIRECTAMENTE, QUE SURJA DE SU USO DEL SERVICIO.",s9p2:"Nuestra responsabilidad total por cualquier reclamación derivada del Servicio no excederá el importe que usted nos haya pagado en los 12 meses anteriores a la reclamación.",s10Title:"10. Terminación",s10p1:"Podemos suspender o cancelar su acceso al Servicio en cualquier momento por infracciones de estos Términos o por cualquier otro motivo, a nuestra entera discreción. Puede cancelar su cuenta en cualquier momento desde la página de Configuración. Tras la cancelación, sus datos se eliminarán en un plazo de 30 días.",s11Title:"11. Cambios en los Términos",s11p1:"Nos reservamos el derecho de modificar estos Términos en cualquier momento. Le notificaremos los cambios importantes por correo electrónico o a través del Servicio. Su uso continuado tras los cambios constituye la aceptación de los Términos modificados.",s12Title:"12. Ley aplicable",s12p1:"Estos Términos se regirán e interpretarán de conformidad con las leyes de la República de Corea, sin tener en cuenta las disposiciones sobre conflicto de leyes.",s13Title:"13. Contacto",s13p1:"Si tiene alguna pregunta sobre estos Términos, contáctenos:",s13l1Prefix:"Correo electrónico:",s13l2Prefix:"Sitio web:"},refund:{title:"Política de reembolsos",lastUpdated:"Última actualización: 24 de marzo de 2026",intro:"ADHDev es operado por RacoLab. Todos los pagos son procesados por nuestro Comerciante Registrado (Merchant of Record),",introSuffix:"que gestiona la facturación, las facturas y los reembolsos en nuestro nombre.",s1Title:"1. Garantía de reembolso de 14 días",s1p1:"Ofrecemos una garantía de reembolso de 14 días en todos los planes de pago (Pro). Si no está satisfecho con el Servicio por cualquier motivo, puede solicitar un reembolso completo dentro de los 14 días posteriores a la compra inicial de su suscripción.",s1p2:"Para solicitar un reembolso, contáctenos en",s1p2Suffix:"con el correo electrónico de su cuenta y los detalles del pedido. Procesaremos su solicitud en un plazo de 3 días hábiles.",s2Title:"2. Reembolsos de renovaciones",s2p1:"Los reembolsos por renovaciones de suscripción (mensuales o anuales) se gestionan caso por caso. Si se le cobró una renovación que no tenía intención de realizar, contáctenos dentro de los 7 días posteriores al cargo en",s3Title:"3. Casos no reembolsables",s3p1:"No se emitirán reembolsos por:",s3l1:"Solicitudes realizadas después del período de garantía de 14 días para compras iniciales",s3l2Prefix:"Cuentas suspendidas o canceladas debido a infracciones de nuestros",s3l2Link:"Términos de Servicio",s3l3:"Meses parciales de servicio ya utilizados fuera del plazo de reembolso",s4Title:"4. Cómo se procesan los reembolsos",s4p1:"Los reembolsos aprobados se procesan a través de Paddle y se devuelven al método de pago original. Según su banco o emisor de la tarjeta, los reembolsos pueden tardar de 5 a 10 días hábiles en aparecer. También se aplican los propios",s4p1RefundLink:"términos de reembolso",s4p1Suffix:"de Paddle.",s5Title:"5. Cancelación",s5p1Prefix:"Puede cancelar su suscripción en cualquier momento desde la página de",s5p1BillingLink:"Facturación",s5p1Suffix:"en su panel. La cancelación detiene los cargos futuros. Conserva el acceso a las funciones de su plan hasta el final del período de facturación actual. La cancelación por sí sola no genera un reembolso.",s6Title:"6. Contacto",s6p1:"Para solicitudes de reembolso o preguntas sobre facturación:",s6l1Prefix:"Correo electrónico:",s6l2Prefix:"Sitio web:"},teamWorkspace:{title:"Team",subtitle:"Gestión de equipos por asientos — $15/asiento/mes, facturación centralizada",planRequired:"Se requiere el plan Team",planDesc:`Los espacios de trabajo Team están disponibles en el plan Team ($15/asiento/mes).
36
+ Gestione asientos, invite a miembros del equipo y administre de forma centralizada la facturación de su organización.`,upgradeBtn:"Actualizar a Team →",seatsTitle:"Asientos del equipo",seatsUsedOf:"{{used}} / {{total}} asientos usados",seatsAvailable:"{{count}} disponibles",seatsFullMsg:"Todos los asientos están en uso. Agregue más asientos en",seatsBillingLink:"Facturación",seatsBillingLinkSuffix:"para invitar a más miembros.",newWorkspace:"Nuevo espacio de trabajo",workspaceNamePlaceholder:"Nombre del espacio de trabajo...",createBtn:"Crear",cancelBtn:"Cancelar",noWorkspaceYet:"Aún no hay espacio de trabajo de equipo",noWorkspaceDesc:"Cree un espacio de trabajo para empezar a gestionar su equipo y compartir asientos.",createWorkspace:"Crear espacio de trabajo",membersTab:"Miembros ({{count}})",sessionsTab:"Sesiones",settingsTab:"Configuración",membersTitle:"Miembros ({{count}})",inviteBtn:"+ Invitar",pendingInvites:"Invitaciones pendientes ({{count}})",pendingBadge:"Pendiente",removeBtn:"Eliminar",removeMemberConfirm:"¿Eliminar a este miembro? Perderá el acceso al plan Team.",removeSuccess:"Miembro eliminado",invitationSent:"¡Invitación enviada!",joinedSuccess:"¡Se unió correctamente al espacio de trabajo del equipo!",waitingApproval:"Esperando a que {{name}} apruebe su solicitud de visualización...",viewRequestSent:"Solicitud de visualización enviada a {{name}}. Esperando aprobación...",viewDeclined:"{{name}} rechazó la solicitud de visualización",sessionRestricted:"La visualización de sesiones está restringida por la política de la organización (admin_only)",sessionTitle:"Sesiones del equipo",noMembersOnline:"No hay miembros del equipo en línea",selfBadge:"Tú",machineNoSessions:"Máquina en línea, sin sesiones activas",offline:"Desconectado",statusGenerating:"Generando...",statusApprovalNeeded:"Se requiere aprobación",statusStarting:"Iniciando...",statusStopped:"Detenido",statusError:"Error",statusDisconnected:"Desconectado",statusHidden:"Oculto",statusUnmonitored:"Sin supervisar",statusIdle:"Inactivo",viewBtn:"Ver →",requestBtn:"Solicitar →",policyOpen:"Abierto",policyRequest:"Solicitud",policyAdminOnly:"Solo administradores",settingsTitle:"Configuración del espacio de trabajo",sessionVisibilityTitle:"Visibilidad de sesiones",sessionVisibilityDesc:"Controle quién puede ver las sesiones de agentes de IA de los miembros del equipo",visibilityOpen:"Abierto",visibilityOpenDesc:"Todos los miembros pueden ver cualquier sesión libremente",visibilityRequest:"Basado en solicitudes",visibilityRequestDesc:"Los miembros deben solicitar acceso. Los administradores siempre pueden ver.",visibilityAdminOnly:"Solo administradores",visibilityAdminOnlyDesc:"Solo los administradores y el propietario pueden ver las sesiones.",dangerZone:"Zona de peligro",dangerZoneDesc:"Acciones irreversibles",deleteWorkspace:"Eliminar espacio de trabajo",deleteWorkspaceConfirm:"¿Eliminar este espacio de trabajo Team? Todos los miembros perderán los beneficios del plan Team.",leaveWorkspace:"Salir del espacio de trabajo",leaveWorkspaceConfirm:"¿Está seguro de que desea salir de este espacio de trabajo? Su plan podría degradarse.",defaultMemberName:"miembro del equipo",defaultMemberNameCapitalized:"Miembro del equipo",sessionFallback:"Sesión",timeNow:"ahora",yourSession:"Tu sesión",viewSessionTitle:"{{action}} la sesión {{sessionName}}",viewingRestricted:"Visualización restringida por la política"},sessionShare:{loading:"Cargando sesión...",sessionNotFound:"Sesión no encontrada",noLongerAvailable:"Esta sesión ya no está disponible",homeBtn:"← Inicio de ADHDev",sharedSession:"Sesión compartida",host:"Anfitrión",mode:"Modo",permission:"Permiso",auth:"Autenticación",authRequired:"Se requiere una cuenta",viewers:"Espectadores",joinChat:"Unirse al chat",joinSession:"Unirse a la sesión",expires:"Vence: {{date}}",chatLabel:"Chat",remoteLabel:"Remoto",waitingMessages:"Esperando mensajes...",connecting:"Conectando... ({{state}})",sendMessageAs:"Enviar mensaje como {{name}}...",sendAs:"Enviar como {{name}}...",ownerChat:"Chat de {{name}}",ownerSession:"Sesión de {{name}}",agentName:"Agente de {{name}}",fullControlBadge:"Control total activo",failedToJoin:"No se pudo unir a la sesión",sessionRevoked:"El anfitrión ha revocado la sesión",sessionExpired:"La sesión ha caducado",authRequired2:"Se requiere autenticación para compartir con control",unknownError:"Error desconocido"},apiPlayground:{title:"API Playground",history:"Historial ({{count}})",apiRelayWarning:"El relé de la API del daemon es opcional. Las rutas de proxy REST de comandos/chat permanecen deshabilitadas a menos que ese daemon las habilite explícitamente con `adhdev daemon:api enable`.",authBearer:"Authorization: Bearer {{key}}",copyAsCurl:"cURL",copied:"Copiado",targetDaemon:"Daemon de destino",quickActions:"Acciones rápidas",requestBody:"Cuerpo de la solicitud (JSON)",recentRequests:"Solicitudes recientes",clearHistory:"Borrar",noDaemonsWarning:"No hay daemons conectados. Inicia un daemon primero o reemplaza {daemonId} manualmente.",send:"▶ Enviar",sending:"⏳",close:"Cerrar"},announcementBanner:{eyebrow:"Aviso del sistema",visibleUntil:"Visible hasta {{time}}",dismiss:"Descartar"},upgradeBanner:{button:"Mejorar →"},push:{title:"Notificaciones push",descUnsupported:"No compatible con este navegador",descDenied:"Bloqueado — actívalo en la configuración del navegador",descEnabled:"Push del lado del servidor habilitado",descDefault:"Recibe alertas incluso con la pestaña cerrada",docs:"Documentación",docsLink:"Documentación de notificaciones push",sent:"Enviado",test:"Probar",docsHintPrefix:"Los pasos de configuración, los requisitos de la PWA de iPhone y la compatibilidad con navegadores están documentados en ",docsHintSuffix:".",iosHint:"En iPhone y iPad, las notificaciones push solo funcionan desde la PWA de Safari instalada. Una pestaña normal de Safari no puede recibir notificaciones push de ADHDev.",budget:"Presupuesto de push del plan actual: {{used}}/{{limit}} usados hoy{{remaining}}{{resets}}.",budgetRemaining:", {{count}} restantes",budgetResets:" • Se restablece a las {{time}}",unsupportedWarning:"Este navegador no admite Web Push aquí. Usa la PWA de Safari en iPhone/iPad o un navegador Chromium en escritorio/Android.",deniedWarning:"Las notificaciones están bloqueadas en la configuración del navegador o del sitio. Vuelve a habilitarlas allí y luego activa de nuevo las notificaciones push.",registeredDevices:"Dispositivos registrados: {{count}}",noDevices:"No se encontraron dispositivos push activos.",deviceLabel:"Dispositivo {{number}}",thisDevice:"Este dispositivo",lastActive:"Última actividad:",removing:"Eliminando...",removeHere:"Eliminar aquí",remove:"Eliminar"},mesh:{manualMcpSetup:"Este proveedor requiere una configuración manual de MCP antes de poder actuar como coordinador de Repo Mesh.",couldNotLoadMeshes:"No se pudieron cargar las meshes",untitledMesh:"Mesh sin título",chooseMachineFirst:"Elige una máquina primero.",launchFailed:"Error al iniciar",coordinatorLaunchFailed:"Error al iniciar el coordinador",coordinatorLaunched:"Coordinador iniciado ({{sessionId}})",coordinatorLaunchSent:"Comando de inicio del coordinador enviado"},plans:{free:"Free",pro:"Pro",ultra:"Ultra",team:"Team",enterprise:"Enterprise"},adminAudit:{title:"Auditoría global",subtitle:"Seguimiento de eventos en todo el sistema",allActions:"Todas las acciones",allSources:"Todas las fuentes",filter:"Filtrar",noLogs:"No se encontraron registros",loading:"Cargando...",loadMore:"Cargar más ↓"},adminDashboard:{failedToLoad:"Error al cargar los datos de administración",title:"Panel de administración",subtitle:"Resumen y gestión del servicio",accessDenied:"Acceso de administrador denegado",backToDashboard:"Volver al panel",loading:"Cargando el panel de administración",loadingDesc:"Recopilando estadísticas del servicio y la actividad de auditoría reciente.",totalUsers:"Usuarios totales",todayCommands:"Comandos de hoy",activeApiKeys:"Claves de API activas",todayLogins:"Inicios de sesión de hoy",planDistribution:"Distribución de planes",quickActions:"Acciones rápidas",manageUsers:"Gestionar usuarios",apiKeys:"Claves de API",auditLogs:"Registros de auditoría",systemConfig:"Configuración del sistema",recentActivity:"Actividad reciente",viewAll:"Ver todo",noRecentActivity:"Sin actividad reciente"},adminSystem:{error:"Error: {{message}}",announcementSent:"Anuncio enviado",announcementCleared:"Anuncio borrado",registrationOpened:"Registro abierto — cualquiera puede registrarse",registrationClosed:"Registro cerrado",title:"Configuración del sistema",subtitle:"Anuncios y configuración del sistema",loading:"Cargando la configuración del sistema",loadingDesc:"Obteniendo la política de registro y el estado actual del anuncio.",registration:"Registro",registrationOpenState:"Abierto — cualquiera puede registrarse",registrationClosedState:"Cerrado — solo correos permitidos",registrationDesc:"Cuando está cerrado, solo los correos añadidos a la lista de permitidos pueden crear una cuenta nueva. Los usuarios existentes nunca se ven afectados.",closeRegistration:"Cerrar registro",openRegistration:"Abrir registro",announcement:"Anuncio",current:"Actual:",untilTime:"(hasta {{time}})",untilCleared:"(hasta que se borre)",announcementPlaceholder:"Introduce el mensaje del anuncio...",severityInfo:"Información",severityWarning:"Advertencia",severityCritical:"Crítico",duration1h:"1 hora",duration6h:"6 horas",duration24h:"24 horas",duration7d:"7 días",durationUntilCleared:"Hasta que se borre",send:"Enviar"},adminUsers:{error:"Error: {{message}}",roleUpdated:"Rol actualizado",planUpdated:"Plan actualizado",suspensionReasonPrompt:"Introduce el motivo de la suspensión:",userSuspended:"Usuario suspendido",userUnsuspended:"Suspensión del usuario retirada",title:"Gestión de usuarios",subtitle:"Gestiona usuarios, roles y suspensiones",usersTotal:"usuarios en total",searchPlaceholder:"Buscar correo o nombre...",allRoles:"Todos los roles",roleUser:"Usuario",roleAdmin:"Administrador",roleSuperAdmin:"Superadministrador",allPlans:"Todos los planes",search:"Buscar",colUser:"Usuario",colRole:"Rol",colPlan:"Plan",colStatus:"Estado",colCreated:"Creado",colActions:"Acciones",noName:"Sin nombre",statusSuspended:"Suspendido",statusActive:"Activo",unsuspend:"Reactivar",suspend:"Suspender",loading:"Cargando...",prev:"← Anterior",next:"Siguiente →"}},Jv={openMenu:"Abrir menú",closeMenu:"Cerrar menú"},Qv={loadingOlderMessages:"Cargando mensajes anteriores...",waitingForMessages:"Esperando mensajes...",agentGenerating:"El agente está generando...",jumpToTop:"Ir al principio",jumpToOldestMessages:"Ir a los mensajes más antiguos",top:"↑ Principio",latest:"↓ Más reciente",jumpToLatestMessages:"Ir a los mensajes más recientes",jumpToBottom:"Ir al final",showEarlierMessages:"↑ Mostrar {{count}} mensajes anteriores...",showEarlierMessagesHidden:"↑ Mostrar {{count}} mensajes anteriores... ({{total}} ocultos)",loadOlderMessages:"↑ Cargar mensajes anteriores",loadErrorRetry:"↻ {{error}}"},Xv={zoomOut:"Alejar",zoomIn:"Acercar",resetZoom:"Restablecer zoom",toggleFullscreen:"Alternar pantalla completa"},Zv={mouse:"Ratón",touch:"Táctil",connected:"Conectado",ws:"WS",direct:"Directo",relay:"Relé",turnBlocked:"TURN bloqueado",turnUsage:"TURN {{used}}/{{budget}}m",typeAndEnter:"Escribe y pulsa Enter...",settings:"AJUSTES",zoom:"ZOOM:",fill:"RELLENAR",fit:"AJUSTAR",directP2PTitle:"Conexión P2P directa",turnRelayTitle:"Relé TURN en uso",dailyTurnTitle:"Uso diario del relé TURN",waitingState:{turnRelayActive:"Relé TURN activo"}},ey={title:"Información de la sesión",loading:"Cargando…",refresh:"Actualizar",close:"Cerrar",failedToLoad:"Error al cargar la información de la sesión",notCoordinatorSession:"Esta no es una sesión de coordinador de Repo Mesh, por lo que no se inyectó ningún prompt específico del coordinador. El agente se ejecuta con los valores predeterminados que trae su CLI.",stampedToNode:"Esta sesión está asociada a un nodo de malla que el coordinador ya no reporta.",sectionSession:"Sesión",sectionLaunch:"Lanzamiento",sectionMeshNode:"Nodo de malla",sectionMeshCoordinator:"Coordinador de malla",sectionRuntime:"Entorno de ejecución",rowSessionId:"ID de sesión",rowProvider:"Proveedor",rowTransport:"Transporte",rowWorkspace:"Espacio de trabajo",rowSpawnedAt:"Generado a las",rowProviderSessionId:"ID de sesión del proveedor",rowMachine:"Máquina",rowConnection:"Conexión",rowWorkspaceGit:"git del espacio de trabajo",rowCommand:"Comando",rowWorkingDirectory:"Directorio de trabajo",rowArgs:"Argumentos",rowExtraArgs:"Argumentos adicionales",rowExtraEnv:"Variables de entorno adicionales",rowNodeId:"ID de nodo",rowRepoRoot:"Raíz del repositorio",rowDaemonId:"ID de daemon",rowRole:"Rol",rowMachineStatus:"Estado de la máquina",rowHealth:"Estado de salud",rowWorktree:"Worktree",rowLaunchReady:"Listo para iniciar",rowGit:"Git",rowProviders:"Proveedores",rowProviderPriority:"Prioridad de proveedores",rowMeshId:"Mesh ID",rowCoordinatorCli:"CLI del coordinador",rowStartedAt:"Iniciado a las",rowPromptInjection:"Inyección de prompt",rowMcpConfig:"Configuración de MCP",rowRuntimeId:"ID de runtime",rowLifecycle:"Ciclo de vida",rowSurface:"Superficie",rowRecoveryState:"Estado de recuperación",rowRestoredFromStorage:"Restaurado desde el almacenamiento",rowAttachedClients:"Clientes conectados"},ty={status:{schedulingNotReported:"Este daemon (build más antiguo) no reporta el runtime de planificación. Actualiza el daemon coordinador para mostrar la distribución, los límites de paralelismo y la carga por nodo.",schedulingTitle:"Planificación",distributionTitle:"La distribución solo determina cómo se reparte el trabajo sin destino entre los nodos elegibles. La carga por nodo, la prioridad y los límites de proveedores aparecen a continuación.",protocolTitle:"Versiones de protocolo y proveedores",nodesRuntime:"Nodos — runtime",noNodesReporting:"Todavía no hay nodos que reporten el runtime."},overview:{missionCard:"Misiones",ledgerCard:"Registro",queueCard:"Cola",nodesCard:"Nodos",sessionsCard:"Sesiones activas",refineCard:"Trabajos de Refine",recentActivity:"Actividad reciente",recentTasks:"Tareas recientes",showFewer:"Mostrar menos",showMore:"+{{count}} más",noActiveMissions:"No hay misiones activas. El coordinador crea una misión para el trabajo de varias tareas.",missionDataUnavailable:"Datos de misión no disponibles desde este daemon — actualiza el daemon para ver las misiones.",completedHistory:"Historial de completadas / abandonadas",noQueueActivity:"No hay actividad en la cola.",noNodes:"Todavía no hay nodos en este mesh.",noActiveSessions:"No hay sesiones activas.",noRefineJobs:"No hay trabajos de Refine.",closeDetail:"Cerrar detalle",loadingGoal:"Cargando…",showFullGoal:"Mostrar objetivo completo",statCompleted:"Completadas",statAssigned:"Asignadas",statPending:"Pendientes",statFailed:"Fallidas",statBlocked:"Bloqueadas",statCancelled:"Canceladas",statWallClock:"Tiempo real",statTotalRuntime:"Tiempo total de ejecución",statRetries:"Reintentos",statDispatched:"Despachadas",statStalled:"Estancadas",statSessions:"Sesiones",statCheckpoints:"Puntos de control",statActive:"Activas",recentFailures:"{{count}} fallos recientes",activeCount:"{{count}} activas",failedCount:"{{count}} fallidas",detailKickerMission:"Misión",detailKickerLedger:"Entrada del registro",detailKickerQueue:"Tarea en cola",detailKickerSession:"Sesión",detailLabelMissionId:"ID de misión",detailLabelCreated:"Creada",detailLabelUpdated:"Actualizada",detailLabelLastActivity:"Última actividad de tarea",detailLabelIncompleteEvidence:"Evidencia incompleta",incompleteTaskCount_one:"{{count}} tarea",incompleteTaskCount_other:"{{count}} tareas",detailLabelEntryId:"ID de entrada",detailLabelWhen:"Cuándo",detailLabelNode:"Nodo",detailLabelSession:"Sesión",detailLabelProvider:"Proveedor",detailLabelPayload:"Payload",detailLabelTaskId:"ID de tarea",detailLabelAutoLaunch:"Inicio automático",detailLabelCancelReason:"Motivo de cancelación",detailLabelRequeueReason:"Motivo de reencolado",detailLabelRequeued:"reencolada {{count}}",detailLabelSessionId:"ID de sesión",detailLabelBranch:"Rama",detailLabelRole:"Rol",detailLabelStarted:"Iniciada",detailLabelWorkspace:"Espacio de trabajo"}},sy={launchConfirm:{workspace:"Espacio de trabajo",languageModel:"Modelo de lenguaje (opcional)",autoDetect:"Detección automática o predeterminado",cliArgs:"Argumentos de CLI (opcional)",cliArgsPlaceholder:"p. ej. --experimental",cancel:"Cancelar",closeAria:"Cerrar confirmación de inicio",launch:"Iniciar",launching:"Iniciando…"},confirmExternal:{dialogAria:"Confirmar proveedor externo no confiable",title:"¿Activar proveedor externo no confiable?",description:"Este manifiesto incluye JavaScript que el daemon ejecutará. Trátalo como código no confiable — revisa la fuente antes de habilitarlo.",proceedWarning:"Continúa solo si confías en la URL de origen que añadiste y has revisado el manifiesto.",cancel:"Cancelar",activate:"Activar"},workspace:{noWorkspace:"(sin espacio de trabajo — iniciar en home)",selectWorkspace:"📁 Seleccionar espacio de trabajo…",customPath:"✏️ Ruta personalizada…",noWorkspacesSaved:"(no hay espacios de trabajo guardados — añade en la pestaña Overview)",selectWorkspaceBtn:"Seleccionar espacio de trabajo…",enterAbsolutePath:"Introduce una ruta absoluta…",browseHint:"Navega a una carpeta antes de iniciar allí.",absolutePathHint:"Introduce una ruta absoluta para iniciar allí.",defaultWorkspace:"Espacio de trabajo predeterminado",selectedWorkspace:"Espacio de trabajo seleccionado",noWorkspaceSelected:"No hay espacio de trabajo seleccionado. Esto se inicia en el directorio home."},agentTab:{selectToLaunch:"Selecciona {{label}} para iniciar",launchSettings:"Configuración de inicio",noIdesDetected:"No se detectaron IDE.",scanSystem:"Escanear sistema",noProviders:"No hay proveedores de {{category}} disponibles.",noProvidersHint:"Configura una ruta de ejecutable personalizada en Providers si el binario está instalado fuera de la ubicación predeterminada.",targetModel:"Modelo objetivo",leaveEmptyDefault:"Dejar vacío para usar el valor predeterminado",startupArguments:"Argumentos de inicio",optionalFlags:"Flags opcionales...",openSession:"Abrir sesión",starting:"Iniciando...",configure:"Configurar",select:"Seleccionar",launching:"⏳ Lanzando...",launchBtn:"▶ Lanzar",running:"En ejecución ({{count}})",noRunning:"No hay {{plural}} en ejecución",launchingProcess:"Lanzando proceso...",waitingProcess:"Esperando a que se registren el proceso y la sesión...",startingBadge:"iniciando",chatView:"Vista de chat",terminalView:"Vista de terminal",localTerminal:"Terminal local:",copied:"Copiado",copy:"Copiar",openRemoteControl:"Abrir control remoto",restart:"Reiniciar",viewChat:"Ver chat",openInDashboard:"Abrir la vista actual en el panel",stop:"Detener",extensions:"Extensiones",browseFolderTitle:"Seleccionar espacio de trabajo",browseFolderDesc:"Elige una carpeta en un cuadro de diálogo estilo explorador habitual y úsala como destino de lanzamiento.",browseFolderConfirm:"Usar esta carpeta",detailMode:"Modo",detailProvider:"Proveedor",detailResume:"Reanudar",detailArguments:"Argumentos",detailModel:"Modelo",categoryIde:"IDE",categoryCliPlural:"CLIs",categoryAcp:"Agente ACP",categoryAcpPlural:"Agentes ACP"},providers:{filter:"Filtrar",sourceConfigTitle:"Configuración de origen de proveedores",sourceConfigDesc:"Dónde busca el daemon los manifiestos de proveedores. Afecta a la resolución y las recargas.",sourceMode:"Modo de origen",explicitProviderDir:"providerDir explícito",providerDirPlaceholder:"Dejar en blanco para usar ~/.adhdev/providers",applying:"Aplicando…",applyReload:"Aplicar + Recargar",userRoot:"Raíz de usuario:",upstreamRoot:"Raíz upstream:",providerRoots:"Raíces de proveedores:",loadingSettings:"Cargando configuración de proveedores…",noProviders:'Aún no hay proveedores instalados. Abre "Add provider" arriba para instalar uno.',noFilteredProviders:"No hay proveedores de {{filter}} instalados.",refresh:"↻ Actualizar",sources:"🌐 Orígenes",create:"✨ Crear",advanced:"⚙ Avanzado"},providerRow:{statusDetected:"Detectado",statusNotDetected:"No detectado",statusEnabledUnchecked:"Habilitado (sin comprobar)",statusDisabled:"Deshabilitado",labelType:"Tipo:",labelVersion:"Versión:",labelBinary:"Binario:",labelStatus:"Estado:",labelDetails:"Detalles:",labelSource:"Origen:",labelTrust:"Confianza:",labelLinks:"Enlaces:",labelDetection:"Detección:",labelVerification:"Verificación:",saving:"guardando…",disable:"Deshabilitar",enable:"Habilitar",detect:"Detectar",resetCommand:"Restablecer comando"},providerFix:{aiAgent:"Agente de IA",scriptsToFix:"Scripts a corregir",all:"Todos",none:"Ninguno",additionalInstructions:"Instrucciones adicionales",optional:"(opcional)",agentOutput:"Salida del agente",running:"● En ejecución...",agentGenerating:"El agente está generando...",validateHint:"Ejecuta `adhdev provider verify` para validar",cancel:"Cancelar",startFix:"🚀 Iniciar corrección",cancelRunning:"⬛ Cancelar",back:"← Atrás",close:"Cerrar",footerHint:"El agente de IA implementará los scripts del proveedor",scriptsSelected_one:"{{count}} script seleccionado",scriptsSelected_other:"{{count}} scripts seleccionados",titlePrefix:"Corrección automática: {{name}}",descCodex:"OpenAI o3/gpt-5.4",descClaude:"Anthropic Claude",descGemini:"Google Gemini"},providerClone:{title:"✨ Crear proveedor de usuario",subtitle:"Clona un proveedor IDE upstream para personalizarlo",baseProvider:"Proveedor base",providerTypeId:"Tipo de proveedor (ID)",typeIdPlaceholder:"my-cursor, custom-windsurf...",typeIdHint:"Solo minúsculas, alfanuméricos y guiones. Se creará en",displayName:"Nombre para mostrar",displayNamePlaceholder:"My Custom IDE",cancel:"Cancelar",creating:"⏳ Creando...",createProvider:"✨ Crear proveedor",createdTitle:"¡Proveedor creado!",createdDesc:"{{type}} se ha creado en",createdRunHint:"Ejecuta adhdev provider fix {{type}} o usa la corrección automática para implementar los scripts.",close:"Cerrar"},connectedMachines:{noMachines:"No hay máquinas conectadas",defaultDescription:"Instala ADHDev en una máquina e inicia sesión para conectarla aquí.",startingUpgrade:"Iniciando actualización...",machineDisconnected:"La máquina se desconectó.",tokenRevoked:"Token revocado. Reinicia ADHDev en esa máquina para volver a conectar.",failedToDisconnect:"Error al desconectar",failedToRevokeToken:"Error al revocar el token",connectionLostUpgrade:"Conexión perdida durante la actualización",disconnect:"Desconectar",remove:"Eliminar",disconnectTitle:"🔌 Desconectar máquina",removeTitle:"⚠️ Eliminar máquina",cancel:"Cancelar",noIdesConnected:"No hay IDE conectados",upgrading:"Actualizando...",updated:"✓ Actualizado",updateNow:"↑ Actualizar ahora",updateTo:"↑ Actualizar a v{{version}}",cdpConnected:"CDP conectado",cdpConnecting:"Conectando CDP...",connecting:"conectando..."},card:{sectionIDEs:"IDE",sectionCLIs:"CLI",sectionACPAgents:"Agentes ACP",emptyHeadline:"Te damos la bienvenida a ADHDev",emptyBody:"Conecta tu primera máquina al panel. Ejecuta la configuración una vez y luego inicia ADHDev en esa máquina:",emptyDocsLink:"📚 Leer la documentación →",hidden:"Oculto",pageTitle:"Burrows",burrowCount_one:"{{count}} burrow",burrowCount_other:"{{count}} burrows",onlineCount_one:"{{count}} en línea",onlineCount_other:"{{count}} en línea",agentsActive_one:"{{count}} agente activo",agentsActive_other:"{{count}} agentes activos",activeNow:"Activo ahora",generating:"generando",connectionFailed:"Error de conexión",reconnect:"Reconectar",connecting:"Conectando...",runtimePolling:"Sondeo de runtime",transportRelay:"Relé TURN — falló la conexión directa",transportDirect:"Conexión directa (STUN/host)",noAgentsRunning:"Aún no hay agentes en ejecución",launchCta:"Iniciar →"},detail:{notFound:"Máquina no encontrada",save:"Guardar",cancel:"Cancelar",loading:"⏳ Cargando máquina...",offlineHint:"Es posible que la máquina esté desconectada o aún no se haya conectado.",back:"← Volver",tabWorkspace:"Espacio de trabajo",tabHostedRuntimes:"Runtimes alojados",tabProviders:"Proveedores",tabSystem:"Sistema",tabLogs:"Registros",clickToSetNickname:"Haz clic para establecer un alias",nicknamePlaceholder:"Alias de la máquina...",reconnect:"Reconectar",coresCount_one:"{{count}} núcleo",coresCount_other:"{{count}} núcleos",p2pState:"P2P {{state}}",p2pConnected:"conectado"},commandCenter:{currentChats:"Chats actuales",recentLaunches:"Inicios recientes",daemonUpdate:"Actualización del daemon"},workspaceBrowse:{currentFolder:"Carpeta actual"},managedWorkspaces:{remove:"Eliminar"}},ny={theme:{helloHelp:"¡Hola! ¿En qué puedo ayudarte?",fixBug:"Corrige el error, por favor",onIt:"¡Enseguida! ✨",customEditorTitle:"🎨 Editor de tema personalizado",darkMode:"🌙 Modo oscuro",lightMode:"☀️ Modo claro",sectionAppBackground:"Fondo de la aplicación",sectionAppText:"Texto de la aplicación",sectionBordersAccent:"Bordes y acento",sectionChatBubbles:"Burbujas de chat",sectionChatLayout:"Diseño del chat",colorBackground:"Fondo",colorSurface:"Superficie",colorCard:"Tarjeta",colorPrimary:"Primario",colorSecondary:"Secundario",colorMuted:"Atenuado",colorBorderSubtle:"Borde sutil",colorBorderDefault:"Borde predeterminado",colorAccent:"Acento",colorUserBubble:"Burbuja del usuario",colorUserText:"Texto del usuario",colorAgentBubble:"Burbuja del agente",colorAgentText:"Texto del agente",colorChatBg:"Fondo del chat",colorSendButton:"Botón de enviar",colorInputBorder:"Borde del campo de entrada",labelBubbleRadius:"Radio de la burbuja",resetToDefaults:"Restablecer valores predeterminados",customLabel:"🎨 Personalizado"},providerPriority:{available:"disponible",notOnMachine:"no está en esta máquina",remove:"Eliminar",addCliLabel:"Añadir proveedor CLI disponible",addProvider:"Añadir proveedor"},coordinatorPrompts:{overrideDesc:"<strong>Override</strong> reemplaza el prompt base integrado del daemon para esa CLI.",appendDesc:"<strong>Append</strong> se apila después de la base que prevalezca.",overrideLabel:"Override",appendLabel:"Append"},appearance:{modeLabel:"Modo",themeLabel:"Tema",mobileLabel:"Móvil"}},ry={chatHistory:"Historial de chat",startNewChat:"+ Iniciar nueva sesión de chat",creating:"⌛ Creando...",searchPlaceholder:"Buscar por título o vista previa",filterWorkspace:"Filtrar por espacio de trabajo",filterModel:"Filtrar por modelo",sortRecent:"Más recientes",sortOldest:"Más antiguos primero",sortMessages:"Más mensajes",resumeReadyOnly:"Solo listos para reanudar",untitledSession:"Sesión sin título",noSavedPreview:"Aún no hay vista previa guardada",workspaceUnknown:"Espacio de trabajo desconocido",selectedWorkspaceSuffix:" · espacio de trabajo seleccionado",msgCount:"{{count}} mensajes",statusActive:"ACTIVA",statusMissingWorkspace:"FALTA EL ESPACIO DE TRABAJO",statusResumeSelectedWorkspace:"REANUDAR EN EL ESPACIO DE TRABAJO 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:"Inicio de ADHDev",mesh:"Mesh",what:"Qué es",agents:"Agentes",pricing:"Precios",install:"Instalar",github:"GitHub",docs:"Documentación",getStarted:"Comenzar",toggleMenu:"Alternar menú",mainNavigation:"Navegación principal"},hero:{badge:"El plano de control de agentes multiproveedor y multimáquina",title:"Cualquiera puede ejecutar diez agentes. ADHDev hace que el trabajo aterrice en main.",subtitle:"Controla cualquier agente de codificación local —Claude Code, Codex, Cursor— desde tu navegador y luego deja que Refinery fusione el trabajo terminado de vuelta a main de forma <em>desatendida</em>: las propias comprobaciones de tu repositorio, verificaciones de equivalencia de parches, solo fast-forward, sin force-push. Hablas con un único coordinador; este ejecuta agentes en paralelo por tus propias máquinas de forma asíncrona, sin sesiones que vigilar. El código permanece en tu máquina —P2P, de extremo a extremo.",selectOs:"Seleccionar SO",osUnix:"macOS / Linux",osWindows:"Windows",copyInstall:"Copiar comando de instalación: {{cmd}}",copied:"Copiado",copy:"Copiar",getStarted:"Comenzar",openSource:"Código abierto en GitHub",joinDiscord:"Unirse a Discord",selfHost:"Aloja tú mismo",demoDesktop:"Centro de mando de ADHDev controlando sesiones de agentes en vivo en varias máquinas",demoPush:"Notificación push móvil de ADHDev y aprobación con un toque"},mesh:{sectionTitle:"Ellos paralelizan. Nosotros aterrizamos.",sectionSubtitle:"Lanzar agentes en paralelo es la parte fácil: ahora lo hace cualquier herramienta. Lo difícil es lo que viene después: diez ramas que todavía hay que verificar y fusionar. Refinery lo hace por ti, de forma desatendida, para que el trabajo terminado llegue a main en lugar de a tu cola de revisión.",refineryHighlight:"Refinery",refineryTitle:"El trabajo terminado aterriza en main, de forma desatendida",refineryDesc:"Cualquiera puede lanzar diez agentes en paralelo. Refinery valida cada worktree contra las propias comprobaciones de tu repositorio (typecheck, tests, lint), verifica la equivalencia de parches, publica los commits de submódulos, hace fast-forward de main y limpia, todo automáticamente. Nunca force-push. Cualquier cosa ambigua se devuelve para revisión en lugar de fusionarse.",asyncHighlight:"Orquestación asíncrona",asyncTitle:"Hablas con un solo lugar. Él ejecuta el resto.",asyncDesc:"Le das trabajo a un solo coordinador; este dirige a muchos trabajadores en muchas máquinas sobre un bucle de eventos, reaccionando solo cuando llega un evento de finalización, aprobación o estado. Sin sondeo, sin una ventana por agente que vigilar. A diferencia de una aplicación de escritorio donde observas cada sesión de agente, aquí el coordinador espera eventos, así que no tienes que estar sentado de forma síncrona frente a nada.",monoHighlight:"Con soporte para monorepo",monoTitle:"Seguro incluso con submódulos de git",monoDesc:"Los repositorios de producción reales anidan submódulos, y ahí es justo donde falla la fusión automática ingenua. Refinery reconoce los submódulos: condiciona la fusión a la accesibilidad de los commits de submódulos, juzga la equivalencia de parches y actualiza el puntero de forma atómica. Este proyecto es en sí mismo un monorepo con una raíz y dos submódulos, convergido de esta manera cada día.",crossHighlight:"Verificación cruzada",crossTitle:"Consenso por encima de una sola opinión",crossDesc:"Distribuye la misma investigación de solo lectura a varias réplicas de máquina × proveedor y sintetiza dónde coinciden y dónde divergen (MAGI). Más fiable que la opinión de un solo agente.",tryMesh:"Probar Repo Mesh →",seePlans:"Ver planes",availableOn:"Disponible en Pro y superiores. Contrólalo desde la página de <strong>Repo Mesh</strong> una vez conectado.",readGuide:"Leer la guía"},compare:{sectionTitle:"Los agentes en paralelo están por todas partes ahora. ¿Dónde aterriza realmente el trabajo?",sectionSubtitle:"Una pregunta justa. Las CLI locales lanzan subagentes; los orquestadores de escritorio distribuyen el trabajo por worktrees con una elegante interfaz nativa. Ambos se detienen en la rama. Aquí está la línea honesta —incluido dónde cada uno de ellos nos supera— sin rodeos.",colLocalCli:"CLI local + subagentes",colDesktop:"Orquestador de escritorio",colAdhdev:"ADHDev Repo Mesh",rowLandsMain:"Aterriza el trabajo terminado en main",rowLandsMainLocalCli:"Ejecutas las comprobaciones y fusionas a mano",rowLandsMainDesktop:"Paraleliza el trabajo y luego te entrega las ramas para revisar",rowLandsMainAdhdev:"Refinery ejecuta las comprobaciones de tu repositorio, verifica la equivalencia de parches y hace fast-forward de main, de forma desatendida y sin force-push",rowSubmodules:"Seguro con submódulos de git",rowSubmodulesLocalCli:"Sin automatización de fusión que los reconozca",rowSubmodulesDesktop:"Paralelismo por worktree, pero la fusión corre por tu cuenta",rowSubmodulesAdhdev:"Convergencia con reconocimiento de submódulos: filtro de accesibilidad, comprobación de equivalencia de parches, actualización atómica del puntero —probado a diario en este monorepo",rowAsync:"Habla con un solo lugar, de forma asíncrona",rowAsyncLocalCli:"Una sesión a la vez, de forma síncrona",rowAsyncDesktop:"Tú mismo supervisas cada ventana de agente",rowAsyncAdhdev:"Un coordinador dirige a cada trabajador sobre un bucle de eventos: espera eventos de finalización/aprobación, tú no sondeas ni vigilas",rowMultiMachine:"Varias máquinas físicas",rowMultiMachineLocalCli:"Solo los procesos de un host",rowMultiMachineDesktop:"Atado a la única máquina en la que se ejecuta",rowMultiMachineAdhdev:"Daemons remotos por P2P: despacha a cada máquina que poseas (sin infraestructura SSH)",rowParallelBranch:"Trabajo en paralelo en ramas aisladas",rowParallelBranchLocalCli:"Los subagentes comparten un mismo árbol de trabajo: las escrituras concurrentes chocan",rowParallelBranchDesktop:"Un git worktree por tarea: una fortaleza central",rowParallelBranchAdhdev:"Un git worktree por nodo: en paralelo entre máquinas, no solo entre núcleos",rowBrowser:"Contrólalo desde un navegador o teléfono",rowBrowserLocalCli:"Tienes que estar en la terminal",rowBrowserDesktop:"Aplicación de escritorio nativa: estás en ese escritorio",rowBrowserAdhdev:"Prioridad web: controla sesiones y aprueba desde cualquier navegador o teléfono",rowNativeApp:"Aplicación de escritorio nativa",rowNativeAppLocalCli:"Solo terminal",rowNativeAppDesktop:"Ventana nativa pulida: genuinamente más agradable para trabajar frente a ella",rowNativeAppAdhdev:"Somos de prioridad web: una pestaña del navegador, no una aplicación nativa",rowRestarts:"Sobrevive a reinicios y pérdida de contexto",rowRestartsLocalCli:"El estado vive en una sesión: ciérrala y desaparece",rowRestartsDesktop:"El estado está ligado al proceso de la aplicación",rowRestartsAdhdev:"Las misiones persisten en disco y se reanudan tras el reinicio de un coordinador o daemon: registro de auditoría de solo anexión y a prueba de manipulaciones",rowCrossCheck:"Verifica la respuesta de forma cruzada",rowCrossCheckLocalCli:"La opinión de un solo agente, sin una segunda opinión",rowCrossCheckDesktop:"Trabajo en paralelo, un único veredicto",rowCrossCheckAdhdev:"MAGI distribuye la misma pregunta de solo lectura a agentes independientes de máquina × proveedor y muestra dónde divergen",footnote:"Para una sola máquina, una sola rama, una tarea puntual, una CLI local con subagentes es más ligera y funciona de maravilla, y un orquestador de escritorio nativo es un lugar más agradable para trabajar. Repo Mesh se gana su lugar cuando el trabajo se distribuye entre máquinas y ramas, necesita sobrevivir a reinicios y debe aterrizar en main automáticamente, controlado desde donde estés."},what:{sectionTitle:"Cualquier agente, mezclado libremente",sectionSubtitle:"Neutral respecto al proveedor por diseño. Ejecuta Claude Code en el Mac, Codex en la máquina GPU con Windows, Gemini para las pasadas de revisión, en el mismo mesh y bajo las mismas políticas. Cambia de proveedor sin cambiar de plataforma.",cliHighlight:"Agentes CLI",cliTitle:"Controla cualquier agente de terminal desde la web",cliDesc:"Claude Code, Codex CLI, Cursor CLI, Antigravity CLI, Hermes, Kimi y OpenCode: conectados en tu máquina mediante un adaptador PTY con reanudación y reconexión adecuadas, controlados desde tu navegador. Envía prompts y aporta contexto visual al instante (pega, arrastra y suelta, o sube varias imágenes a la vez, hasta 5 imágenes / 10MB cada una). Aider, Gemini CLI, Goose y otros agentes ACP se conectan por stdio.",uiHighlight:"Una sola UI",uiTitle:"El mismo panel, cualquier dispositivo",uiDesc:"Alojado en la nube en adhf.dev: controla cada agente desde una laptop o un teléfono, ya sea en tu escritorio o lejos de él.",ideHighlight:"Agentes IDE",ideTitle:"Además: conéctate a editores en ejecución",ideDesc:"Cursor, VS Code, VSCodium, Windsurf, Antigravity, Kiro, PearAI, Trae. Lee el chat en vivo, envía prompts, cambia de sesión, captura pantallas.",p2pHighlight:"Tuyo, de extremo a extremo",p2pTitle:"Prioridad P2P: tus datos siguen siendo tuyos",p2pDesc:"El chat, los comandos y las capturas de pantalla fluyen directamente entre tu navegador y tu daemon a través de WebRTC. La nube ve los metadatos de autenticación y señalización, nada más: tu código nunca pasa por el servidor."},oss:{sectionTitle:"Código abierto y autoalojable",sectionSubtitle:"El daemon y el panel son AGPL-3.0 y están disponibles en GitHub. Ejecútalos tú mismo en cualquier máquina o servidor, sin necesidad de cuenta.",github:"GitHub",selfHostDocs:"Documentación de autoalojamiento"},agents:{sectionTitle:"Agentes compatibles",sectionSubtitle:"{{ides}} integraciones de IDE incorporadas, {{clis}} agentes CLI incorporados, {{extensions}} agentes de extensión residentes en el IDE y {{acp}}+ agentes ACP (stdio MCP). Los scripts de proveedor están en <code>adhdev-providers/</code>: añade los tuyos en <code>~/.adhdev/providers/</code>.",tierTested:"Probado",tierTestedDesc:"validado contra una app + versión real",tierCommunity:"Comunidad",tierCommunityDesc:"incorporado y con soporte de la comunidad",groupIdes:"IDE",hintIdes:"Conectado mediante Chrome DevTools Protocol. Lee el chat, envía prompts, cambia de sesión y captura pantallas.",groupCli:"Agentes CLI",hintCli:"Controlados a través de un adaptador PTY con reanudación y reconexión.",groupExtensions:"Agentes de extensión dentro del IDE",hintExtensions:"Conexión de webview por CDP para agentes que viven dentro de otro IDE.",acpFootnote:"Además de {{count}}+ agentes ACP por stdio (Agent Client Protocol): Codex, Claude Agent, Gemini, Goose, Cline, OpenHands y más."},pricing:{sectionTitle:"Precios sencillos a medida que crecen tus agentes",sectionSubtitle:"Empieza gratis con una máquina. Pasa a Pro para dos, o a Ultra para cinco. Sin cálculos por puesto, sin llamadas de ventas empresariales: solo los planes de abajo.",mostPopular:"Más popular",upgradeToPro:"Actualizar a Pro",footnote:"Precios sencillos y transparentes: los precios de arriba son lo que pagarás. ¿Prefieres autoalojarlo? El daemon y el panel son de código abierto. Precios en USD.",plans:{free:{period:"para siempre",tagline:"Todo lo que necesitas para controlar una máquina desde cualquier lugar.",cta:"Empezar gratis",features:{machine:"Una máquina, emparejada con un solo comando",p2p:"Chat, comandos, capturas y entrada remota por P2P",providers:"Todos los proveedores: agentes CLI, IDE y ACP",push:"Notificaciones push para aprobaciones y finalizaciones",share:"Un enlace de sesión compartida"}},pro:{period:"/mes",tagline:"Ejecuta agentes en un par de máquinas, con la fiabilidad que necesitan los planes de pago.",cta:"Empezar prueba Pro de 7 días",features:{machines:"2 máquinas: ejecuta agentes en ambas",p2p:"Más sesiones P2P simultáneas",push:"Notificaciones push ilimitadas",turn:"Relay TURN para redes restrictivas",mesh:"Repo Mesh: orquesta agentes entre máquinas",share:"Más sesiones compartidas"}},ultra:{period:"/mes",tagline:"Todo lo de Pro, a mayor escala: más máquinas y límites más altos para el trabajo paralelo intensivo.",cta:"Pasar a Ultra",features:{machines:"5 máquinas: precio único, no por puesto",everything:"Todo lo de Pro",p2p:"El mayor número de sesiones P2P simultáneas",screenshots:"Minutos diarios de captura de pantalla ilimitados",webhooks:"Más webhooks y llamadas a la API",share:"Más sesiones compartidas"}}}},install:{sectionTitle:"Tres pasos hasta un panel funcional",sectionSubtitle:"Sin archivos de configuración. Sin claves de API que conectar. ADHDev no gestiona la autenticación de los agentes: cada herramienta conserva su propio inicio de sesión.",selectOs:"Seleccionar SO",osUnix:"macOS / Linux",osWindows:"Windows",copyInstall:"Copiar comando de instalación: {{cmd}}",copied:"Copiado",copy:"Copiar",platformNote:"macOS y Windows son las rutas de instalación validadas. Linux ejecuta el mismo script de Unix y cuenta con pruebas de la comunidad.",arrow:"→",steps:{step1:{title:"Instala el daemon",desc:"Un solo comando curl instala el daemon y el CLI adhdev: el lanzador que ejecutas para emparejar máquinas e iniciar el daemon (no confundir con los agentes CLI que controla, como Claude Code o Codex). El mismo binario impulsa la nube y el modo autónomo."},step2:{title:"Vincula una máquina",desc:"Inicia sesión una vez con GitHub o Google y el daemon se empareja solo: no hay ningún token que copiar."},step3:{title:"Controla tus agentes",desc:"Lanza Claude Code, Codex CLI, Cursor CLI, Antigravity CLI, Hermes, Kimi y otros agentes desde el panel. Lee el chat, envía prompts, aporta contexto visual (pega, arrastra y suelta, o sube varias imágenes a la vez), aprueba acciones y cambia de sesión."}}},cta:{headline:"Deja de hacer malabares con las pestañas. Controla cada agente desde un único panel.",subtitle:"Un comando curl, un daemon, cada agente que ya usas. Contrólalos todos desde la web: Cloud ya está disponible.",getStarted:"Empezar →",github:"GitHub",discord:"Discord"},footer:{docs:"Documentación",github:"GitHub",discord:"Discord",dashboard:"Panel",terms:"Términos",privacy:"Privacidad",contact:"Contacto",copyright:"© {{year}} RacoLab. Todos los derechos reservados."}},oy={selectAllThatApply:"Selecciona todas las que correspondan",other:"Otro"},iy={changeList:{binaryBadge:"bin",truncatedNote:"Lista de archivos truncada: ejecuta <code>git status</code> localmente para ver la salida completa."},statusDialog:{conflicts:"conflictos",clean:"limpio"}},ly={header:{back:"Atrás"}},cy={title:"Notificaciones",subtitle:"Alertas, aprobación automática y ajustes de proveedor",sectionBrowserAlerts:"Alertas del navegador",masterToggleLabel:"Notificaciones",masterToggleDesc:"Interruptor general para todas las alertas",browserNotificationsLabel:"Notificaciones del navegador",browserNotificationsDesc:"Alertas de escritorio cuando la pestaña está inactiva",browserBackgroundInfo:"Las alertas del navegador solo se activan mientras esta pestaña del panel permanece abierta en segundo plano.",browserBackgroundInfoWithPush:"Las alertas del navegador solo se activan mientras esta pestaña del panel permanece abierta en segundo plano. Si cierras la pestaña, usa las notificaciones push en su lugar.",standaloneBackgroundInfo:"Las alertas del navegador solo se activan mientras esta pestaña del panel permanece abierta en segundo plano. Si la cierras, el modo autónomo no puede entregarte notificaciones push alojadas.",permissionDefault:"Este navegador aún no ha concedido permiso de notificaciones. Permítelo para recibir alertas del navegador.",standalonePermissionDefault:"Este navegador aún no ha concedido permiso de notificaciones. Permítelo para recibir alertas locales del navegador.",allowNotifications:"Permitir notificaciones",permissionDenied:"Las notificaciones del navegador están bloqueadas en los ajustes del sitio o del navegador. Vuelve a habilitarlas allí para recibir alertas de escritorio.",standalonePermissionUnsupported:"Este navegador no puede mostrar notificaciones de escritorio aquí. Mantén el panel visible o usa otro navegador compatible en este dispositivo.",permissionUnsupported:"Este navegador no puede mostrar notificaciones de escritorio aquí. Usa un navegador de escritorio compatible o recurre a las notificaciones push donde estén disponibles.",completionAlertsLabel:"Alertas de finalización",completionAlertsDesc:"Notificar cuando el agente termina una tarea",approvalAlertsLabel:"Alertas de aprobación",approvalAlertsDesc:"Notificar cuando el agente necesita aprobación",connectionAlertsLabel:"Alertas de conexión",connectionAlertsDesc:"Alertar cuando una máquina se desconecta",allDisabled:"Todas las notificaciones están desactivadas. Activa el interruptor general para configurarlas.",sectionProviderAlerts:"Reglas de alerta de proveedor",loading:"⏳ Cargando...",refresh:"↻ Actualizar",noOnlineMachines:"No hay máquinas en línea. Inicia ADHDev en una máquina para configurar las alertas de proveedor.",loadingProviderSettings:"Cargando ajustes de proveedor...",providerCount_one:"{{count}} proveedor",providerCount_other:"{{count}} proveedores",keyStatAutoApprove:"Aprobación automática",keyStatApprovalAlert:"Alerta de aprobación",keyStatNoProgressAlert:"Alerta de sin progreso",bulkEnabledAll:"Activado para los {{total}} proveedores",bulkDisabledAll:"Desactivado para los {{total}} proveedores",bulkEnabledSome:"Activado para {{onCount}} de {{total}} proveedores",hideDetails:"▾ Ocultar detalles",showDetails:"▸ Mostrar detalles por proveedor ({{count}})",soundEffectsLabel:"Efectos de sonido",soundEffectsDesc:"Reproducir un sonido cuando el agente completa o necesita aprobación"},dy={language:Av,common:Iv,connection:Tv,toast:Mv,notification:Dv,event:Pv,dashboard:Lv,cliStop:Rv,approval:Ev,newSession:_v,mobileInbox:$v,meshGraph:Hv,repoMesh:Bv,chat:Fv,chatPane:Ov,chatInput:Wv,paneGroup:Uv,terminal:Gv,conversation:qv,cliView:zv,launch:Kv,standalone:Vv,cloud:Yv,app:Jv,chatList:Qv,screenshot:Xv,remote:Zv,sessionInfo:ey,mesh:ty,machine:sy,settings:ny,historyModal:ry,landing:ay,interactivePrompt:oy,git:iy,ide:ly,notifications:cy},Ko="lang",Ul="common",uy={en:{common:yg},ko:{common:rx},ja:{common:Wx},"zh-CN":{common:Nv},es:{common:dy}};function py(){try{const e=localStorage.getItem(Ko);if(un(e))return e}catch{}return null}function fu(){const e=py();return e||(typeof navigator<"u"?_b(navigator.language):Qn)}function Vo(e){typeof document>"u"||document.documentElement.setAttribute("lang",e)}let Gl=!1;function my(){if(Gl)return wt;Gl=!0;const e=fu();return wt.use(jh).init({resources:uy,lng:e,fallbackLng:Qn,supportedLngs:hu,ns:[Ul],defaultNS:Ul,interpolation:{escapeValue:!1},returnEmptyString:!1}),Vo(e),wt}var hy=new Set(["generating","streaming","loading","loading_reference","thinking","active"]);function fy(e){var t;return(((t=e==null?void 0:e.buttons)==null?void 0:t.length)??0)>0}function Zt(e,t){if(fy(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":hy.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 Yo(e){return Zt(e)==="generating"}function ql(e,t){return Zt(e,t)==="waiting_approval"}function ft(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Pe(...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 Ya(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function by(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 Ei(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 gy(e,t){if(!Array.isArray(e))return;const n=e.map(r=>{const a=ft(r),o=Pe(a.path),i=Pe(a.commit),c=Pe(a.repoPath,a.repo_root)??by(t,o);if(!o||!i)return null;const d={path:o,commit:i,dirty:_t(a.dirty)??!1,outOfSync:_t(a.outOfSync,a.out_of_sync)??!1,lastCheckedAt:zt(a.lastCheckedAt,a.last_checked_at)??Date.now()};c&&(d.repoPath=c);const p=Pe(a.error);return p&&(d.error=p),d}).filter(r=>r!==null);return n.length>0?n:void 0}function xy(e){return _t(e.isGitRepo)!==void 0||!!Pe(e.branch,e.upstream,e.upstreamStatus,e.upstream_status,e.headCommit)||!!Pe(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 Wr(e,t,n){const r=_t(e.isGitRepo);if(!Object.keys(e).length||!xy(e))return;const a=r??!0,o=Array.isArray(e.conflictFiles)?e.conflictFiles.filter(S=>typeof S=="string"):[],i=zt(e.conflicts)??o.length,c=_t(e.hasConflicts)??i>0,d=Pe(e.repoRoot,e.repo_root,t.repoRoot,t.repo_root,e.workspace,t.workspace)||void 0,p=gy(e.submodules,d),u=Pe(e.upstreamStatus,e.upstream_status),m=zt(e.upstreamFetchedAt,e.upstream_fetched_at),f=Pe(e.upstreamFetchError,e.upstream_fetch_error),g=Pe(e.error),C=zt(e.staged)??0,h=zt(e.modified)??0,x=zt(e.untracked)??0,y=zt(e.deleted)??0,b=zt(e.renamed)??0;return{workspace:Pe(e.workspace,t.workspace)||"",repoRoot:d??null,isGitRepo:a,branch:Pe(e.branch)??null,headCommit:Pe(e.headCommit)??null,headMessage:Pe(e.headMessage)??null,upstream:Pe(e.upstream)??null,upstreamStatus:u??"unchecked",...m!==void 0?{upstreamFetchedAt:m}:{},...f?{upstreamFetchError:f}:{},ahead:zt(e.ahead)??0,behind:zt(e.behind)??0,staged:C,modified:h,untracked:x,deleted:y,renamed:b,dirty:_t(e.dirty,e.isDirty,e.is_dirty)??(C+h+x+y+b>0||c),hasConflicts:c,conflictFiles:o,stashCount:zt(e.stashCount,e.stash_count)??0,lastCheckedAt:(n==null?void 0:n.lastCheckedAt)??zt(e.lastCheckedAt,e.last_checked_at)??Date.now(),...p?{submodules:p}:{},...g?{error:g}:{}}}function vy(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+=Ei(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 yy(e,t){const n=ft(e.lastGit??e.last_git),r=ft(n.result),a=ft(n.status),o=ft(r.status),i=ft(e.lastProbe??e.last_probe),c=ft(i.git),d=ft(c.result),p=ft(c.status),u=ft(d.status),m=t==null?void 0:t.lastCheckedAt;let f=null;for(const g of[a,o,p,u]){const C=Wr(g,e,{lastCheckedAt:m??Date.now()});if(!C)continue;const h=vy(C);(!f||h>f.score)&&(f={git:C,score:h})}return f==null?void 0:f.git}function wy(e){const t=[Pe(e.workspace),Pe(e.providerType,e.provider),Pe(e.role),Pe(e.state,e.status),Pe(e.title),Pe(e.createdAt,e.created_at),Pe(e.startedAt,e.started_at)].filter(n=>!!n);if(t.length!==0)return`synthetic:${t.join("|")}`}function Jo(e){const t=ft(e),n=Pe(t.sessionId,t.session_id,t.id)??wy(t);return n?{sessionId:n,...Pe(t.providerType,t.provider)?{providerType:Pe(t.providerType,t.provider)}:{},...Pe(t.state,t.status)?{state:Pe(t.state,t.status)}:{},...Pe(t.chatStatus,t.chat_status)?{chatStatus:Pe(t.chatStatus,t.chat_status)}:{},...Pe(t.lifecycle)?{lifecycle:Pe(t.lifecycle)}:{},...Pe(t.surfaceKind,t.surface_kind)?{surfaceKind:Pe(t.surfaceKind,t.surface_kind)}:{},...Pe(t.recoveryState,t.recovery_state)?{recoveryState:Pe(t.recoveryState,t.recovery_state)}:{},...Pe(t.workspace)?{workspace:Pe(t.workspace)}:{},...Pe(t.title)?{title:Pe(t.title)}:{},...Pe(t.role)?{role:Pe(t.role)}:{},..._t(t.isSelfCoordinator,t.is_self_coordinator)!==void 0?{isSelfCoordinator:_t(t.isSelfCoordinator,t.is_self_coordinator)}:{},...Pe(t.statusNote,t.status_note)?{statusNote:Pe(t.statusNote,t.status_note)}:{},...Pe(t.createdAt,t.created_at)?{createdAt:Pe(t.createdAt,t.created_at)}:{},...Pe(t.startedAt,t.started_at)?{startedAt:Pe(t.startedAt,t.started_at)}:{},...Pe(t.lastActivityAt,t.last_activity_at)?{lastActivityAt:Pe(t.lastActivityAt,t.last_activity_at)}:{},..._t(t.isCached,t.is_cached)!==void 0?{isCached:_t(t.isCached,t.is_cached)}:{}}:null}function ky(e){const t=e&&typeof e=="object"?e:{};return Pe(t.id,t.nodeId,t.node_id)}function Sy(e,t){if(!t)return!1;const n=t.trim();return n?ky(e)===n:!1}var Cy=["daemon_","standalone_"];function zl(e){const t=Pe(e);if(t){for(const n of Cy)if(t.startsWith(n))return t.slice(n.length).trim()||void 0;return t}}function Os(e,t){const n=zl(e),r=zl(t);return!n||!r?!1:n===r}var jy=["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),a=Et(n);r&&e.push(r),a&&e.push(a)}function pn(e){const t=[],n=new Set;for(const r of e)!r||n.has(r)||(n.add(r),t.push(r));return t}function bu(e){return Et(e.providerSessionId)||Et(e.sessionId)||Et(e.tabKey)||Et(e.routeId)}function Na(e){return pn([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),pn(t)}function Ny(e){const t=[];return Et(e.providerSessionId)?(As(t,"provider",e.providerSessionId),pn(t)):Et(e.sessionId)?(As(t,"session",e.sessionId),pn(t)):Et(e.tabKey)?(As(t,"tab",e.tabKey),pn(t)):Et(e.routeId)?(As(t,"route",e.routeId),pn(t)):[]}function gu(e){return ws("provider",e.providerSessionId)||ws("session",e.sessionId)||ws("tab",e.tabKey)||ws("route",e.routeId)||"unknown:"}function Aa(e){return Na(e)[0]}function Ia(e){const t=Et(e.sessionId),n=Aa(e);if(n&&!(t&&n===t))return n}function Ay(e){const t=Et(e.providerSessionId),n=Et(e.sessionId),r=Et(e.tabKey),a=Et(e.routeId),o=[ws("provider",t),ws("session",n),ws("tab",r),ws("route",a)].filter(d=>typeof d=="string"),i=Xn({providerSessionId:t,sessionId:n,tabKey:r,routeId:a}),c=gu({providerSessionId:t,sessionId:n,tabKey:r,routeId:a});return{providerSessionId:t,sessionId:n,tabKey:r,routeId:a,canonicalKey:c,targetKey:c,targetValue:bu({providerSessionId:t,sessionId:n,tabKey:r,routeId:a}),historySessionId:Aa({providerSessionId:t,sessionId:n}),runtimeSessionId:n,allKeys:o,lookupKeys:i}}function Qo(e,t){const n=Ay(e);return Ny(t).some(r=>n.lookupKeys.includes(r))}function xu(e){const t=String(e.daemonId||"").trim(),n=String(e.id||"").trim();return t&&n.startsWith(`${t}:`)?n.slice(t.length+1):n}function Xo(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 Iy(e,t){const n=String(e.daemonId||"").trim(),r=String(e.id||"").trim(),a=xu(e);if(a&&t.has(a))return`mesh:${a}`;const o=String(e.ownerDaemonId||"").trim()||n;return o?a?`${o}:${a}`:o:r}function Ja(e,t){return t||e||"unknown"}function Ty(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 My(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 a=Math.floor(n/24),o=n%24;return`${a}d ${o}h`}function Qa(e){return e<1024*1024*1024?`${(e/(1024*1024)).toFixed(0)} MB`:`${(e/(1024*1024*1024)).toFixed(1)} GB`}function vu(e,t){const n=typeof t=="string"?t.trim():"";if(n)return n;const r=typeof e=="string"?e.trim():"";if(!r)return"";const a=r.replace(/[\\/]+$/,""),o=a.split(/[\\/]/).filter(Boolean);return o[o.length-1]||a}function Dy(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 Py(e){const t=e.trim().toLowerCase();return t.startsWith("mach_")||t.startsWith("standalone_mach_")||t.startsWith("daemon_mach_")}function Ly(e){return Dy(e.trim().replace(/\.local$/i,""))}function Ry(e){const t=e.machineNickname??e.nickname;return typeof t!="string"?null:t.trim()||null}function yu(e,t={}){var a,o;const n=[e.hostname,(a=e.machine)==null?void 0:a.hostname,(o=e.system)==null?void 0:o.hostname].find(i=>typeof i=="string"&&i.trim().length>0&&!Py(i));if(n&&n!=="Unknown")return Ly(n);const r=t.fallbackId||e.id;return r?`Machine-${r.substring(0,8)}`:t.fallbackLabel||"Machine"}function ts(e,t={}){return Ry(e)||yu(e,t)}function wu(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 ku(e,t,n={}){const r=String(t).trim();if(!e||!Array.isArray(e.items)||!r)return"";const a=e.items.find(o=>String((o==null?void 0:o.id)||"").trim()===r);return a?String(n.preferShortValue?a.shortValue||a.value||"":a.value||a.shortValue||"").trim():""}function Js(e,t){return wu(e).join(" · ")}function ir(e){return e.transport==="pty"}function mn(e){return e.transport==="acp"}function Ey(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 Kl(e,t,n){const r=(e||"").trim().toLowerCase();if(!r)return!0;const a=(t||"").trim().toLowerCase(),o=(n||"").trim().toLowerCase(),i=$t(n||"").trim().toLowerCase();return r===a||r===o||r===i}function _y(e,t=[],n=[]){var d,p,u,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 a=t.find(f=>ql(f.status,{activeModal:f.activeModal})||Yo(f.status));if(a)return Zt(a.status,{activeModal:a.activeModal});const o=n.find(f=>ql(f.status,{activeModal:f.activeModal})||Yo(f.status));if(o)return Zt(o.status,{activeModal:o.activeModal});if(r&&r!=="idle")return r;const i=Zt((d=t[0])==null?void 0:d.status,{activeModal:(p=t[0])==null?void 0:p.activeModal});if(i!=="idle")return i;const c=Zt((u=n[0])==null?void 0:u.status,{activeModal:(m=n[0])==null?void 0:m.activeModal});return c!=="idle"?c:"idle"}function $y(e){return Zt(e==null?void 0:e.status,{activeModal:e==null?void 0:e.activeModal})}function Hy(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 a=(r.name||r.id||"").toLowerCase().replace(/\s+/g,"-"),o=t.get(a),i=Zt(r.status);if(!o){t.set(a,{...r,status:i});continue}const c=n.indexOf(o.status||"idle"),d=n.indexOf(i||"idle");d>=0&&(c<0||d<c)&&t.set(a,{...r,status:i})}return Array.from(t.values())}function By(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 Fy(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&&By(t.receivedAt)||0}function Oy(e){return(e.recentLaunches||[]).reduce((n,r)=>Math.max(n,r.lastLaunchedAt||0),0)}function Zo(e){return Math.max(Oy(e),Fy(e.activeChat))}function Wy(e,t,n,r,a,o){const i=t-e;if(i!==0)return i;const c=n.localeCompare(r);return c!==0?c:a.localeCompare(o)}function _i(e,t){return Wy(Zo(e),Zo(t),ts(e,{fallbackId:e.id}),ts(t,{fallbackId:t.id}),e.id,t.id)}const Su="adhdev_notification_prefs",Vl={globalEnabled:!0,disconnectAlert:!0,browserNotifications:!0,completionAlert:!0,approvalAlert:!0};function Uy(){try{const e=localStorage.getItem(Su);if(e){const t=JSON.parse(e);return{...Vl,...t}}}catch{}return{...Vl}}function Gy(e){try{localStorage.setItem(Su,JSON.stringify(e))}catch{}}let ys=Uy(),Ur=[];function qy(){Ur.forEach(e=>e())}function zy(e){ys={...ys,...e},Gy(ys),qy()}function Ky(){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=>{zy(n)},[]);return[{...ys},t]}function Zn(e){if(!ys.globalEnabled)return!1;switch(e){case"disconnect":return ys.disconnectAlert;case"completion":return ys.completionAlert;case"approval":return ys.approvalAlert;case"browser":return ys.browserNotifications;default:return!0}}const Vy={enabled:!0,onApproval:!0,onComplete:!0,onError:!0,throttleMs:5e3};async function Cu(){return"Notification"in window?Notification.permission==="granted"?"granted":Notification.permission==="denied"?"denied":Notification.requestPermission():"denied"}function ju(){return"Notification"in window&&Notification.permission==="granted"}let Es=null;function Yy(e){return e!==!1}async function Jy(){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 ei(e,t,n){if(ju())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 Qy(e,t={}){const n={...Vy,...t},r=l.useRef(new Map),a=l.useRef(0),[o,i]=l.useState(null);l.useEffect(()=>{let d=!1;return Jy().then(p=>{d||i(p)}),()=>{d=!0}},[]);const c=l.useCallback((d,p,u)=>{const m=Date.now();m-a.current<n.throttleMs||(a.current=m,ei(d,p,u))},[n.throttleMs]);l.useEffect(()=>{var d;if(!(!n.enabled||!ju())&&Zn("browser")&&!Yy(o)){if(document.hasFocus()){for(const p of e)r.current.set(p.id,Zt(p.status,{activeModal:p.activeModal}));return}for(const p of e){const u=r.current.get(p.id),m=Zt(p.status,{activeModal:p.activeModal}),f=p.name||p.id;if(p.muted){r.current.set(p.id,m);continue}if(n.onApproval&&Zn("approval")&&m==="waiting_approval"&&u!=="waiting_approval"){const g=((d=p.activeModal)==null?void 0:d.message)||"Action requires your approval";c(`🔔 ${f} — Approval needed`,g.slice(0,120),`approval-${p.id}`)}n.onComplete&&Zn("completion")&&Yo(u)&&m==="idle"&&c(`✅ ${f} — Task complete`,"Agent has finished generating",`complete-${p.id}`),n.onError&&m==="error"&&u!=="error"&&c(`⚠️ ${f} — Error`,"Agent encountered an error",`error-${p.id}`),r.current.set(p.id,m)}}},[e,n.enabled,n.onApproval,n.onComplete,n.onError,o,c])}const Xy=/^(run|approve|accept|yes|allow|always)/,Zy=/^(run|approve|accept|yes|allow|always|proceed|save)/,ew=/^(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 tw(e){const t=$i(e).toLowerCase();return Xy.test(t)?"primary":ew.test(t)?"danger":"default"}function sw(e){return Zy.test($i(e).toLowerCase())?"approve":"reject"}function nw(e){return e.map((t,n)=>({label:$i(t),variant:tw(t),action:sw(t),button:t,buttonIndex:n}))}function rw(e,t,n){return t?`⚡ ${e}: ${t.replace(/[\n\r]+/g," ").slice(0,80)}`:n}function aw(e,t,n,r){return[{label:"Approve",variant:"primary",onClick:()=>{n(e,t,"approve").catch(a=>r==null?void 0:r("approve",a))}},{label:"Decline",variant:"danger",onClick:()=>{n(e,t,"reject").catch(a=>r==null?void 0:r("reject",a))}}]}class ow{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 a=(r==null?void 0:r.id)||Date.now();this.emitToast({id:a,message:t,type:n,timestamp:a,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[a,o]of this.dedupMap)n-o>this.DEDUP_CLEANUP_AGE_MS&&this.dedupMap.delete(a);return!1}resolveOwningDaemon(t){if(t.daemonId){const a=this.ides.find(o=>o.id===t.daemonId&&o.type==="adhdev-daemon");if(a)return a}const n=t.targetSessionId&&this.findOwningSession(t.targetSessionId)||void 0;if(n){const a=n.daemonId;if(a){const o=this.ides.find(i=>i.id===a&&i.type==="adhdev-daemon");if(o)return o}}const r=this.ides.filter(a=>a.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(a=>(a==null?void 0:a.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 o=(Array.isArray(r.childSessions)?r.childSessions:[]).find(i=>(i==null?void 0:i.id)===n);if(o)return!!o.muted}return!1}handleRawEvent(t,n){var h;const r=this.resolveConversationKey(t),a=Number.isFinite(t.timestamp)?Number(t.timestamp):Date.now(),o=r||t.daemonId||"",i=t.requestId||t.targetName||t.requesterName||t.modalMessage||String(a),c=`${o}:${t.event}:${i}`;if(this.isDuplicate(c))return;for(const x of this.statusEventCallbacks)x(t);const d=this.isConversationEventMuted(t),p=t.targetSessionId?this.findOwningSession(t.targetSessionId):null,u=(p==null?void 0:p.type)||"";let m=$t(u);const f=this.resolveOwningDaemon(t);if(f){const x=ts(f,{fallbackId:f.id});x&&(m=!u||u==="adhdev-daemon"?x:`${x}/${m}`)}let g="",C="info";if(t.event==="agent:generating_completed"){if(g=t.duration?`✅ ${wt.t("event.taskCompletedWithDuration",{label:m,duration:t.duration})}`:`✅ ${wt.t("event.taskCompleted",{label:m})}`,C="success",!d)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(g=`⚡ ${wt.t("event.approvalNeeded",{label:m})}`,C="warning",d)g="";else if((h=t.modalButtons)!=null&&h.length&&this.resolveActionFn){const x=this.resolveActionRouteTarget(t);if(!x)return;const y=this.resolveActionFn,b=nw(t.modalButtons).map(w=>({label:w.label,variant:w.variant,onClick:()=>{y(x,"resolve_action",{action:w.action,button:w.button,buttonIndex:w.buttonIndex,...t.targetSessionId&&{targetSessionId:t.targetSessionId}})}})),S=rw(m,t.modalMessage,g),k=Date.now();this.emitToast({id:k,message:S,type:C,timestamp:k,targetKey:r||x,actions:b,duration:15e3}),g=""}}else if(t.event==="monitor:no_progress"||t.event==="monitor:long_generating"){const x=t.elapsedSec?Math.round(t.elapsedSec/60):0;g=x?`⚠️ ${wt.t("event.noProgressWithDuration",{label:m,minutes:x})}`:`⚠️ ${wt.t("event.noProgress",{label:m})}`,C="warning",!d&&Zn("browser")&&!document.hasFocus()&&ei(`⚠️ ${wt.t("event.noProgressTitle",{label:m})}`,wt.t("event.noProgressBody",{duration:x?`${x}m`:""}),`no-progress-${t.targetSessionId||t.daemonId||"daemon"}`)}else if(t.event==="team:view_request"){const x=t.requesterName||wt.t("event.someoneRequester"),y=t.requestId,b=t.orgId;if(g=`👁️ ${wt.t("event.viewRequest",{requester:x})}`,C="warning",y&&b&&this.viewRequestRespondFn){const S=Date.now(),k=aw(b,y,this.viewRequestRespondFn,(w,v)=>console.error(`[EventManager] ${w} view request failed:`,v));this.emitToast({id:S,message:g,type:C,timestamp:S,actions:k,duration:3e4}),g=""}Zn("browser")&&!document.hasFocus()&&ei(`👁️ ${wt.t("event.viewRequestTitle")}`,wt.t("event.viewRequest",{requester:x}),`view-request-${y}`)}else if(t.event==="team:view_request_approved")g=`✅ ${wt.t("event.viewRequestApproved")}`,C="success";else if(t.event==="team:view_request_rejected"){const x=t.targetName||wt.t("event.someoneTarget");g=`❌ ${wt.t("event.viewRequestDeclined",{target:x})}`,C="warning"}}if(g&&!d){const x=Date.now();this.emitToast({id:x,message:g,type:C,timestamp:x,targetKey:r||t.daemonId,duration:5e3})}}}const mt=new ow,Yl=new Map;function na(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function hn(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Ta(e){return na(e)?na(e.result)?e.result:e:null}function iw(e){const t=Ta(e);return!t||!na(t.controlResult)||!Array.isArray(t.controlResult.options)?null:t.controlResult}function Sr(e){const t=Ta(e);return!t||!na(t.controlResult)||typeof t.controlResult.ok!="boolean"?null:t.controlResult}function En(e){const t=Ta(e);if(!(!t||typeof t.error!="string"||!t.error.trim()))return t.error}function Cr(e){const t=Ta(e);return!!t&&t.success===!1}function lw(e){var t,n;for(const r of e||[]){if(r.type==="toast"&&((t=r.toast)!=null&&t.message)){const a=r.toast.level==="warning"?"warning":r.toast.level==="success"?"success":"info";mt.showToast(r.toast.message,a);continue}if(r.type==="notification"&&((n=r.notification)!=null&&n.body)){const a=r.notification.level==="warning"?"warning":r.notification.level==="success"?"success":"info";mt.showToast(r.notification.body,a)}}}function cw(e,t){return e&&hn(e.currentValue)?e.currentValue:t}function dw(e,t){const n=Object.keys(e).filter(a=>t[a]!==void 0);if(n.length===0)return e;const r={...e};for(const a of n)delete r[a];return r}function uw(e,t){return hn(t)?hn(e)?typeof e=="string"&&e.trim()==="":!0:!1}function pw(e,t){var o,i;if((t.now??Date.now())<t.localOverrideUntil){const c=t.localValues[e];if(hn(c))return c}const r=(o=t.controlValues)==null?void 0:o[e];if(hn(r))return r;const a=(i=t.defaultValues)==null?void 0:i[e];return hn(a)?a:void 0}function Gr(e,t){return e.options||t[e.id]||[]}const mw={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 hw(e,t,n){var r;return((r=mw[t])==null?void 0:r.has(n.id))===!0}function fw(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 bw(e,t){const n=e.visibleWhenState;if(!n||n.length===0)return!0;const r=fw(t);return r?r.some(a=>n.includes(a)):!0}function Hi(e,t){return(e||[]).filter(n=>n.placement==="bar"&&n.hidden!==!0&&!hw(t.hostIdeType,t.providerType,n)&&bw(n,t.currentStatus)).sort((n,r)=>(n.order??50)-(r.order??50))}function Xa(e,t){return{value:t}}function gw(e,t,n){var a;return n?((a=Gr(e,t).find(o=>o.value===n))==null?void 0:a.label)||n:""}const xw={cline:"#22d3ee","roo-code":"#a78bfa",cursor:"#60a5fa","claude-code-vscode":"#ea580c",codex:"#10b981",antigravity:"#f97316",windsurf:"#34d399"};function vw({routeId:e,sessionId:t,hostIdeType:n,providerType:r,displayLabel:a,controls:o,controlValues:i,currentStatus:c,coordinatorHint:d}){const{sendCommand:p}=vt(),u=`${e}:${t||r}`,m=xw[r]||"#94a3b8",[f,g]=l.useState({}),C=l.useRef({}),h=l.useRef(i);C.current=f,h.current=i;const x=l.useRef(0),y={};for(const R of o||[])R.defaultValue!==void 0&&(y[R.id]=R.defaultValue);const b={...y,...i||{},...Date.now()<x.current?f:{}};l.useEffect(()=>{i&&Date.now()>x.current&&g(R=>dw(R,i))},[i]);const[S,k]=l.useState(Yl.get(u)||{}),[w,v]=l.useState(null),[N,j]=l.useState(null),A=l.useCallback(async(R,T={})=>{const H={...T,...t&&{targetSessionId:t},...d??{}};return await p(e,R,H)},[e,t,p,d]),I=l.useCallback(async(R,T={})=>{const H=t?{targetSessionId:t}:{agentType:r,...n?{ideType:n}:{}};return await A("invoke_provider_script",{...H,scriptName:R,...T})},[A,r,n,t]),D=l.useCallback((R,T,H)=>{const M=cw(H,T);g(W=>({...W,[R.id]:M})),lw(H==null?void 0:H.effects)},[]),L=l.useCallback((R,T)=>{g(H=>{const M={...H};return T===void 0?delete M[R.id]:M[R.id]=T,M}),x.current=0},[]);if(!o||o.length===0)return null;const P=Hi(o,{hostIdeType:n,providerType:r,currentStatus:c});if(P.length===0)return null;const _=async R=>{if(w===R.id){v(null);return}if(Gr(R,S).length>0){v(R.id);return}if(R.dynamic&&R.listScript){j(R.id);try{const H=await I(R.listScript,{}),M=iw(H);if(!M){const re=En(H);re&&mt.showToast(re,"warning");return}const W=M.options;k(re=>{const V={...re,[R.id]:W};return Yl.set(u,V),V});const J=pw(R.id,{localOverrideUntil:x.current,localValues:C.current,controlValues:h.current,defaultValues:y});if(uw(J,M.currentValue)){const re=M.currentValue;g(V=>({...V,[R.id]:re}))}v(R.id)}catch(H){const M=H instanceof Error?H.message:`Could not load ${R.label}`;mt.showToast(M,"warning")}finally{j(null)}}},q=async(R,T)=>{v(null);const H=(i==null?void 0:i[R.id])??y[R.id];g(M=>({...M,[R.id]:T})),x.current=Date.now()+5e3;try{if(!R.setScript)return;const M=await I(R.setScript,Xa(R,T)),W=Sr(M);if(W&&!W.ok||Cr(M))throw new Error((W==null?void 0:W.error)||En(M)||`Could not update ${R.label}`);D(R,T,W)}catch(M){L(R,H);const W=M instanceof Error?M.message:`Could not update ${R.label}`;mt.showToast(W,"warning")}},B=async R=>{const T=Gr(R,S).map(V=>V.value);if(T.length===0)return;const H=String(b[R.id]||""),W=(T.indexOf(H)+1)%T.length,J=T[W];if(typeof J!="string")return;const re=(i==null?void 0:i[R.id])??y[R.id];g(V=>({...V,[R.id]:J})),x.current=Date.now()+5e3;try{if(!R.setScript)return;const V=await I(R.setScript,Xa(R,J)),X=Sr(V);if(X&&!X.ok||Cr(V))throw new Error((X==null?void 0:X.error)||En(V)||`Could not update ${R.label}`);D(R,J,X)}catch(V){L(R,re);const X=V instanceof Error?V.message:`Could not update ${R.label}`;mt.showToast(X,"warning")}},E=async R=>{const H=!b[R.id],M=(i==null?void 0:i[R.id])??y[R.id];g(W=>({...W,[R.id]:H})),x.current=Date.now()+5e3;try{if(!R.setScript)return;const W=await I(R.setScript,Xa(R,H)),J=Sr(W);if(J&&!J.ok||Cr(W))throw new Error((J==null?void 0:J.error)||En(W)||`Could not update ${R.label}`);D(R,H,J)}catch(W){L(R,M);const J=W instanceof Error?W.message:`Could not update ${R.label}`;mt.showToast(J,"warning")}},K=async R=>{if(!R.invokeScript)return;if(R.confirmMessage){const H=[R.confirmTitle,R.confirmMessage,R.confirmLabel].filter(W=>typeof W=="string"&&W.trim().length>0);if(!window.confirm(H.join(`
37
+
38
+ `)))return}const T=(i==null?void 0:i[R.id])??y[R.id];try{const H=await I(R.invokeScript),M=Sr(H);if(M&&!M.ok||Cr(H))throw new Error((M==null?void 0:M.error)||En(H)||`Could not run ${R.label}`);M&&D(R,T??!0,M)}catch(H){L(R,T);const M=H instanceof Error?H.message:`Could not run ${R.label}`;mt.showToast(M,"warning")}};return s.jsx("div",{className:"border-t border-border-subtle bg-[var(--surface-primary)] px-3 py-2 font-[var(--font)]",children:s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:"inline-flex h-7 items-center rounded-full border px-3 text-[11px] font-semibold tracking-[0.02em]",style:{borderColor:`${m}33`,background:`${m}12`,color:m},children:a}),P.map(R=>{const T=String(b[R.id]||""),H=gw(R,S,T),M=w===R.id,W=N===R.id,J=Gr(R,S),re="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(R.type){case"select":return s.jsxs("div",{className:"relative max-w-full",children:[s.jsxs("button",{type:"button",className:`${re} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:M?`${m}55`:"var(--border-default)",background:M?`${m}10`:"var(--surface-tertiary)",color:T?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void _(R),title:R.label,children:[R.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:W?"Loading…":H||R.label}),s.jsx("span",{className:"text-[9px] opacity-55",children:"▼"})]}),M&&J.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"fixed inset-0 z-[var(--z-dropdown)]",onClick:()=>v(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:R.label}),J.map(V=>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:V.value===T?`${m}14`:"transparent",color:V.value===T?"var(--text-primary)":"var(--text-secondary)",borderLeft:V.value===T?`2px solid ${m}`:"2px solid transparent"},title:V.description||V.label,onMouseEnter:X=>{X.currentTarget.style.background=`${m}10`},onMouseLeave:X=>{X.currentTarget.style.background=V.value===T?`${m}14`:"transparent"},onClick:()=>void q(R,V.value),children:[s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:V.label}),V.value===T&&s.jsx("span",{className:"shrink-0 text-[11px] font-semibold",style:{color:m},children:"✓"})]},V.value))]})]})]},R.id);case"cycle":return s.jsxs("button",{type:"button",className:`${re} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:T?"var(--text-primary)":"var(--text-muted)"},onClick:()=>void B(R),title:`Click to cycle: ${J.map(V=>V.label).join(" → ")}`,children:[R.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:H||R.label}),s.jsx("span",{className:"text-[10px] opacity-55",children:"⟳"})]},R.id);case"toggle":return s.jsxs("button",{type:"button",className:`${re} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:T?`${m}44`:"var(--border-default)",background:T?`${m}14`:"var(--surface-tertiary)",color:T?m:"var(--text-muted)"},onClick:()=>void E(R),"aria-pressed":!!T,children:[R.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),R.label]},R.id);case"action":return s.jsxs("button",{type:"button",className:`${re} hover:bg-[var(--surface-tertiary-hover)]`,style:{borderColor:"var(--border-default)",background:"var(--surface-tertiary)",color:"var(--text-primary)"},onClick:()=>void K(R),children:[R.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:R.resultDisplay==="inline"&&T?`${R.label}: ${T}`:R.label})]},R.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:T?"var(--text-primary)":"var(--text-muted)"},children:[R.icon&&s.jsx("span",{className:"text-[11px] opacity-70",children:R.icon}),s.jsx("span",{className:"min-w-0 overflow-hidden text-ellipsis",children:T?`${R.label}: ${T}`:R.label})]},R.id);default:return null}})]})})}function yw({isActive:e=!0,isCliTerminal:t=!1,routeId:n,sessionId:r,hostIdeType:a,providerType:o,displayLabel:i,controls:c,controlValues:d,currentStatus:p,coordinatorHint:u}){const{isVisible:m}=Ri(),f=Hi(c,{hostIdeType:a,providerType:o,currentStatus:p});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(vw,{routeId:n,sessionId:r,hostIdeType:a,providerType:o,displayLabel:i,controls:f,controlValues:d,currentStatus:p,coordinatorHint:u})})}const _n=5,Nu=10*1024*1024;function ww({hasDraft:e,isBusy:t=!1}){return!e||t}function kw(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 Sw(e){if(e.size>Nu)return null;const t=await kw(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 Cw(e){return e?e.mediaTypes.includes("image")&&e.multipart:!1}const Au=l.memo(function({contextKey:t,panelLabel:n,isSending:r,isBusy:a=!1,statusMessage:o=null,inlineStatusMessage:i=null,onSend:c,onForceSend:d,canForceSend:p=!1,isActive:u=!0,showControlsToggle:m=!1,animateVisibility:f=!0,onControlsToggle:g,messageInput:C}){const{t:h}=Ne("common"),x=l.useRef(null),y=l.useRef(null),[b,S]=l.useState(""),[k,w]=l.useState([]),[v,N]=l.useState(null),[j,A]=l.useState(!1),I=l.useRef(!1),{isVisible:D,toggleVisibility:L}=Ri(),P=Cw(C),_=!!b.trim()||k.length>0;l.useEffect(()=>{S(""),w([]),N(null)},[t]),l.useEffect(()=>{var M;u&&((M=x.current)==null||M.focus({preventScroll:!0}))},[t,u]),l.useEffect(()=>{const M=x.current;M&&(M.style.height="auto",M.style.height=`${Math.min(M.scrollHeight,160)}px`)},[b]);const q=l.useCallback(async M=>{N(null);const W=Array.from(M).filter(ne=>ne.type.startsWith("image/"));if(W.length===0)return;const J=_n-k.length;if(J<=0){N(`Max ${_n} images`);return}const re=W.slice(0,J);if(re.filter(ne=>ne.size>Nu).length>0){N("Image too large (max 10 MB)");return}const de=(await Promise.all(re.map(Sw))).filter(ne=>ne!==null);w(ne=>[...ne,...de])},[k.length]),B=l.useCallback(M=>{w(W=>W.filter((J,re)=>re!==M))},[]),E=l.useCallback(async()=>{const M=b.trim();if(!M&&k.length===0||a||I.current)return;I.current=!0;const W=k.length>0?[...k]:void 0;try{await c(M,W)!==!1&&(S(""),w([]),N(null))}finally{I.current=!1}},[b,k,a,c]),K=l.useCallback(async()=>{if(!p||!d)return;const M=b.trim();if(!M&&k.length===0||I.current)return;I.current=!0;const W=k.length>0?[...k]:void 0;try{await d(M,W)!==!1&&(S(""),w([]),N(null))}finally{I.current=!1}},[k,p,b,d]),R=l.useCallback(M=>{P&&(M.preventDefault(),A(!0))},[P]),T=l.useCallback(()=>A(!1),[]),H=l.useCallback(M=>{P&&(M.preventDefault(),A(!1),M.dataTransfer.files.length>0&&q(M.dataTransfer.files))},[P,q]);return s.jsxs("div",{className:["dashboard-input-area bg-[var(--surface-primary)] shrink-0 overflow-hidden",f?"transition-all duration-200 ease-out":"",j?"ring-1 ring-inset ring-[var(--accent-primary)]":""].filter(Boolean).join(" "),style:{borderTop:u?"1px solid var(--border-subtle)":"1px solid transparent",maxHeight:u?200:0,opacity:u?1:0,transform:u?"translateY(0)":"translateY(10px)",padding:u?"10px 12px":"0 12px",pointerEvents:u?"auto":"none"},"aria-hidden":!u,onDragOver:R,onDragLeave:T,onDrop:H,children:[k.length>0&&s.jsx("div",{className:"flex gap-2 flex-wrap mb-2",children:k.map((M,W)=>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:M.previewUrl,alt:M.name,className:"w-full h-full object-cover"}),s.jsx("button",{type:"button",onClick:()=>B(W),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 ${M.name}`,children:"✕"})]},W))}),s.jsxs("div",{className:"flex gap-2 items-center",title:u?`Send message to ${n}`:void 0,children:[m&&s.jsx("button",{type:"button",onClick:()=>{L(),g==null||g()},"aria-label":D?"Hide controls":"Show controls","aria-pressed":D,title:D?"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:y,type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:M=>{M.target.files&&q(M.target.files),M.target.value=""}}),s.jsx("button",{type:"button",onClick:()=>{var M;return(M=y.current)==null?void 0:M.click()},disabled:k.length>=_n,title:k.length>=_n?`Max ${_n} images`:h("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":h("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:x,rows:1,placeholder:o||(P&&k.length>0?"Add a message (optional)...":h("chatInput.placeholder",{panel:n})),value:b,onChange:M=>S(M.target.value),onPaste:M=>{if(P&&M.clipboardData.files.length>0&&Array.from(M.clipboardData.files).some(ie=>ie.type.startsWith("image/"))){M.preventDefault(),q(M.clipboardData.files);return}const W=M.clipboardData.getData("text/plain"),J=Vh(W);if(J===W)return;M.preventDefault();const re=x.current,V=(re==null?void 0:re.selectionStart)??b.length,X=(re==null?void 0:re.selectionEnd)??b.length,de=b.slice(0,V)+J+b.slice(X);S(de);const ne=V+J.length;requestAnimationFrame(()=>{re==null||re.setSelectionRange(ne,ne)})},onKeyDown:M=>{M.key==="Enter"&&(M.nativeEvent.isComposing||M.shiftKey||(M.preventDefault(),E()))},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:()=>{E()},disabled:ww({hasDraft:_,isBusy:a}),className:`w-10 h-10 rounded-full flex items-center justify-center border-none shrink-0 transition-all duration-300 ${_&&!a?"cursor-pointer":"bg-bg-secondary cursor-default"}`,style:_&&!a?{background:"var(--chat-send-bg, var(--accent-primary))"}:void 0,"aria-label":h("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:_?"text-white":"text-text-muted",children:s.jsx("path",{d:"M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"})})}),p&&s.jsx("button",{type:"button",onClick:()=>{K()},disabled:!_,className:`h-10 px-3 rounded-full text-[11px] font-medium border border-border-subtle shrink-0 transition-colors ${_?"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"})]}),(v||P&&j)&&s.jsx("div",{className:`pt-1.5 px-1 text-[11px] ${v?"text-red-400":"text-[var(--accent-primary)]"}`,children:v||h("chatInput.dropImage")}),i&&!v&&s.jsx("div",{className:"pt-2 px-1 text-[11px] text-text-muted opacity-80",children:i})]})}),jw=l.createContext(null);function Bi(){return l.useContext(jw)}function Nw(e){return yy(e,{lastCheckedAt:Date.now()})}function Aw(e){const t=Array.isArray(e==null?void 0:e.submodules)?e.submodules:[];let n=!1,r=!1;for(const a of t)a!=null&&a.outOfSync&&(r=!0),a!=null&&a.dirty&&(n=!0);return{dirty:n,outOfSync:r}}function Iw(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 ra(e){if(!e||e.isGitRepo===!1||!e.branch)return"degraded";const t=Aw(e);return t.outOfSync?"degraded":t.dirty||Iw(e)?"dirty":"online"}function Tw(e,t){const n=t?ra(t):void 0;return!e||e==="unknown"?n:e}function Mw(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 o=t.map(Jo).filter(i=>i!==null);if(o.length>0)return o}const n=ft(e.activeSession??e.active_session),r={...n,sessionId:Pe(n.sessionId,n.id,n.session_id,e.activeSessionId,e.active_session_id,e.sessionId,e.session_id)},a=Jo(r);return a?[a]:void 0}function Dw(e){const t=ft(e.connection);return Object.keys(t).length>0?t:void 0}function Pw(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 Jl(e){var r,a,o,i,c,d;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+=Ei(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),(a=e.branchConvergence)!=null&&a.status&&(t+=12),(((o=e.connection)==null?void 0:o.state)==="connected"||((i=e.connection)==null?void 0:i.state)==="self")&&(t+=8),((c=e.connection)==null?void 0:c.transport)==="direct"&&(t+=4),((d=e.connection)==null?void 0:d.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 Lw(e,t){var C,h,x,y;const n=Jl(e),a=Jl(t)>n?t:e,o=a===t?e:t,i=a.git??o.git,c=(((C=a.providers)==null?void 0:C.length)??0)>0?a.providers:o.providers,d=(((h=a.activeSessions)==null?void 0:h.length)??0)>0?a.activeSessions:o.activeSessions,p=(((x=a.activeSessionDetails)==null?void 0:x.length)??0)>0?a.activeSessionDetails:o.activeSessionDetails,u=(((y=a.providerPriority)==null?void 0:y.length)??0)>0?a.providerPriority:o.providerPriority,m=a.connection??o.connection,f={...o,...a,machineLabel:a.machineLabel||o.machineLabel,workspace:a.workspace||o.workspace,...a.repoRoot||o.repoRoot?{repoRoot:a.repoRoot||o.repoRoot}:{},...a.daemonId||o.daemonId?{daemonId:a.daemonId||o.daemonId}:{},...a.machineId||o.machineId?{machineId:a.machineId||o.machineId}:{},...a.machineStatus||o.machineStatus?{machineStatus:a.machineStatus||o.machineStatus}:{},health:i&&(!a.health||a.health==="unknown")?ra(i):a.health,providers:c??[],activeSessions:d??[],...p&&p.length>0?{activeSessionDetails:p}:{},...u&&u.length>0?{providerPriority:u}:{},...m?{connection:m}:{},...i?{git:i}:{}},g=ft(a.branchConvergence);return Object.keys(g).length>0?Object.assign(f,{branchConvergence:g}):delete f.branchConvergence,i&&(delete f.gitProbePending,delete f.error),f}function Iu(e){const t=ft(e),n=Pe(t.nodeId,t.id);if(!n)return null;const r=ft(t.cachedStatus),a=Nw(t),o=a?void 0:Wr(ft(t.git),t)??Wr(t,t),i=a??o,c=i?void 0:Wr(ft(r.git),t),d=i??c,p=Pe(t.machineStatus,t.machine_status,r.machineStatus,r.machine_status),u=Pe(t.health),m=a?ra(d):Tw(u,i)||(d?ra(d):void 0)||Pe(r.health)||p||Pe(t.status)||"unknown",g=(a?void 0:Pe(t.error))??(i?void 0:Pe(r.error)),C=Mw(t),h=Ya(t.activeSessions),x=(C==null?void 0:C.map(j=>j.sessionId))??[],y=Ya(t.providerPriority),b=_t(t.gitProbePending,t.git_probe_pending),S=i?void 0:b,k=Dw(t),w=ft(t.branchConvergence??t.branch_convergence),v=k==null?void 0:k.state,N=a&&(!(k!=null&&k.reported)||v==="unknown")?Pw(k):k;return{nodeId:n,machineLabel:Pe(t.machineLabel,t.machine_label,t.hostname,t.daemonId,t.daemon_id,t.machineId,t.machine_id,n)||n,workspace:Pe(t.workspace,d==null?void 0:d.workspace)||"",...Pe(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)?{repoRoot:Pe(t.repoRoot,t.repo_root,d==null?void 0:d.repoRoot)}:{},...Pe(t.daemonId,t.daemon_id)?{daemonId:Pe(t.daemonId,t.daemon_id)}:{},...Pe(t.machineId,t.machine_id)?{machineId:Pe(t.machineId,t.machine_id)}:{},...p?{machineStatus:p}:{},..._t(t.isLocalWorktree,t.is_local_worktree)!==void 0?{isLocalWorktree:_t(t.isLocalWorktree,t.is_local_worktree)}:{},...Pe(t.worktreeBranch,t.worktree_branch)?{worktreeBranch:Pe(t.worktreeBranch,t.worktree_branch)}:{},...Pe(t.clonedFromNodeId,t.cloned_from_node_id)?{clonedFromNodeId:Pe(t.clonedFromNodeId,t.cloned_from_node_id)}:{},health:m,...d?{git:d}:{},...S!==void 0?{gitProbePending:S}:{},providers:Ya(t.providers),activeSessions:h.length>0?h:x,...C&&C.length>0?{activeSessionDetails:C}:{},...y.length>0?{providerPriority:y}:{},..._t(t.launchReady)!==void 0?{launchReady:_t(t.launchReady)}:a?{launchReady:!0}:{},...Pe(t.lastSeenAt,t.last_seen_at,r.lastSeenAt,r.last_seen_at)?{lastSeenAt:Pe(t.lastSeenAt,t.last_seen_at,r.lastSeenAt,r.last_seen_at)}:{},...Pe(t.updatedAt,t.updated_at,r.updatedAt,r.updated_at)?{updatedAt:Pe(t.updatedAt,t.updated_at,r.updatedAt,r.updated_at)}:{},...N?{connection:N}:{},...Object.keys(w).length>0?{branchConvergence:w}:{},...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}:{},...Pe(t.daemonBuildVersion,t.daemon_build_version)?{daemonBuildVersion:Pe(t.daemonBuildVersion,t.daemon_build_version)}:{},...g?{error:g}:{}}}function Ql(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(Jo).filter(a=>a!==null);return r.length===0?t:t.map(a=>{const o=r.filter(c=>{const d=ft(n.find(f=>{const g=ft(f);return Pe(g.sessionId,g.session_id,g.id)===c.sessionId})),p=Pe(d.nodeId,d.node_id),u=Pe(d.daemonId,d.daemon_id),m=Pe(d.workspace);return p&&p===a.nodeId?!0:Os(u,a.daemonId)?!m||!a.workspace||m===a.workspace:!!(m&&a.workspace&&m===a.workspace)});if(o.length===0)return a;const i=Ql([...a.activeSessionDetails??[],...o]);return{...a,activeSessionDetails:i,activeSessions:Ql([...a.activeSessionDetails??[],...o,...(a.activeSessions??[]).map(c=>({sessionId:c}))]).map(c=>c.sessionId)}})}function Rw(e){const t=ft(e);return Array.isArray(t.sessions)||Array.isArray(t.active_session_details)||Pe(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 Mu(e){const t=new Map,n=[];for(const r of e){const a=Rw(r)?Iu(r)??r:r;if(!(a!=null&&a.nodeId))continue;const o=t.get(a.nodeId);if(!o){t.set(a.nodeId,a),n.push(a);continue}const i=Lw(o,a);t.set(a.nodeId,i);const c=n.findIndex(d=>d.nodeId===a.nodeId);c>=0&&(n[c]=i)}return n}function Du(e){const t=e??{},n=Mu(t.nodes??[]);return{...t,nodes:Tu(t,n)}}function Ew(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 _w(e){const t=Pe(e.meshId,e.mesh_id,e.id),n=e.nodes,r=Array.isArray(n)?n.map(d=>Iu(d)).filter(d=>d!==null):null;if(!t||!r)return null;const a=Tu(e,Mu(r)),o=Pe(e.meshName,e.mesh_name,e.name),i=Pe(e.repoIdentity,e.repo_identity),c=Pe(e.refreshedAt,e.refreshed_at,e.updatedAt,e.updated_at);return!o||!i||!c?null:{...e,meshId:t,meshName:o,repoIdentity:i,refreshedAt:c,nodes:a}}function $w(e){var o;let t=0;const n=ft(e.sourceOfTruth),r=ft(n.directPeerTruth);Pe(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+=Ei(c.upstreamStatus),typeof c.ahead=="number"&&(t+=1),typeof c.behind=="number"&&(t+=1),typeof c.lastCheckedAt=="number"&&(t+=2),t+=(((o=c.submodules)==null?void 0:o.length)??0)*2}return t}function Hw(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 Bw=20;function Xl(e){let t=null;for(const n of e){const r=_w(ft(n));if(!r)continue;const a=$w(r),o=Hw(r);if(!t){t={status:r,score:a,refreshedAt:o};continue}(Math.abs(a-t.score)<=Bw?o>t.refreshedAt||o===t.refreshedAt&&a>t.score:a>t.score)&&(t={status:r,score:a,refreshedAt:o})}return(t==null?void 0:t.status)??null}function Oi(e){const n=!!(e&&typeof e=="object"&&"result"in e)?e==null?void 0:e.result:e,r=Xl([n==null?void 0:n.status,n]);return r||Xl([e==null?void 0:e.status,e])}function Fw(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 a of["meshNodeFor","meshCoordinatorFor"]){const o=n[a];if(typeof o=="string"&&o.trim())return o.trim()}return null}function Ow(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 Ww(e,t){var a;if(!t)return null;const n=Oi(e),r=(a=n==null?void 0:n.nodes)==null?void 0:a.find(o=>Sy(o,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 Uw={sm:"max-w-md",md:"max-w-lg",lg:"max-w-3xl"};function Pu({open:e,onClose:t,size:n="md",title:r,footer:a,children:o,showClose:i=!0,closeOnBackdrop:c=!0,closeOnEsc:d=!0,ariaLabel:p,className:u,contentClassName:m}){l.useEffect(()=>{if(!e||!d)return;const h=x=>{x.key==="Escape"&&t()};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[e,d,t]);const f=l.useCallback(h=>{c&&h.target===h.currentTarget&&t()},[c,t]);if(!e)return null;const g=r!=null||i,C=s.jsx("div",{className:Ft("fixed inset-0 flex items-center justify-center bg-black/60 p-4",u),style:{zIndex:"var(--z-modal-backdrop)"},onClick:f,children:s.jsxs("div",{role:"dialog","aria-modal":"true","aria-label":r==null?p:void 0,className:Ft("relative flex max-h-[calc(100dvh-2rem)] w-full flex-col overflow-hidden","rounded-xl border border-border-default bg-surface-primary shadow-2xl",Uw[n],m),style:{zIndex:"var(--z-modal)"},onClick:h=>h.stopPropagation(),children:[g&&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:o}),a!=null&&s.jsx("div",{className:"flex shrink-0 items-center justify-end gap-2 border-t border-border-default px-5 py-4",children:a})]})});return typeof document>"u"?C:fn.createPortal(C,document.body)}function Zl(e){if(!e||!Number.isFinite(e))return"—";try{return`${new Date(e).toLocaleString()} (${e})`}catch{return String(e)}}function ec(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 a=Math.floor(r/60);return a<24?`${a}h ago`:`${Math.floor(a/24)}d ago`}function Gw({sessionId:e,daemonId:t,conv:n,onClose:r}){var v,N;const{t:a}=Ne("common"),{sendCommand:o}=vt(),i=Bi(),[c,d]=l.useState(!0),[p,u]=l.useState(null),[m,f]=l.useState(null),[g,C]=l.useState(null),[h,x]=l.useState(null),y=l.useMemo(()=>Fw(n),[n]),b=l.useMemo(()=>Ow(n),[n]),S=l.useCallback(async()=>{d(!0),f(null);try{const j=await o(t,"get_session_info",{targetSessionId:e}),A=j&&typeof j=="object"?j:{},I=A.result&&typeof A.result=="object"?A.result:A;I!=null&&I.success?u(I):(f((I==null?void 0:I.error)||a("sessionInfo.failedToLoad")),u(null))}catch(j){f((j==null?void 0:j.message)||String(j)),u(null)}finally{d(!1)}},[o,t,e]);l.useEffect(()=>{S()},[S]);const k=l.useCallback(async()=>{if(C(null),x(null),!(!y||!b||!(i!=null&&i.loadMeshStatus)))try{const j=await i.loadMeshStatus(t,y,{refresh:!1}),A=Ww(j,b);if(!A){x(a("sessionInfo.stampedToNode"));return}C(A)}catch(j){x((j==null?void 0:j.message)||"Failed to load mesh node info")}},[i,t,y,b]);l.useEffect(()=>{k()},[k]);const w=s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",onClick:()=>void S(),className:"px-3 py-1 text-sm rounded border border-border-default hover:bg-surface-secondary",children:a("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:a("sessionInfo.close")})]});return s.jsx(Pu,{open:!0,onClose:r,title:a("sessionInfo.title"),size:"lg",footer:w,children:s.jsxs("div",{className:"text-sm space-y-4",children:[c&&s.jsx("div",{className:"text-text-secondary",children:a("sessionInfo.loading")}),m&&s.jsx("div",{className:"text-red-500",children:m}),(p==null?void 0:p.session)&&s.jsxs(an,{title:a("sessionInfo.sectionSession"),children:[s.jsx(nt,{k:a("sessionInfo.rowSessionId"),v:s.jsx(Mt,{children:p.session.sessionId})}),s.jsx(nt,{k:a("sessionInfo.rowProvider"),v:`${p.session.providerName||p.session.providerType} (${p.session.providerType})`}),p.session.transport&&s.jsx(nt,{k:a("sessionInfo.rowTransport"),v:p.session.transport}),p.session.workspace&&s.jsx(nt,{k:a("sessionInfo.rowWorkspace"),v:s.jsx(Mt,{children:p.session.workspace})}),s.jsx(nt,{k:a("sessionInfo.rowSpawnedAt"),v:s.jsxs(s.Fragment,{children:[Zl(p.session.spawnedAtMs),p.session.spawnedAtMs?s.jsx("span",{className:"text-text-secondary ml-2",children:ec(p.session.spawnedAtMs)}):null]})}),p.session.providerSessionId&&s.jsx(nt,{k:a("sessionInfo.rowProviderSessionId"),v:s.jsx(Mt,{children:p.session.providerSessionId})}),!p.session.workspace&&(n==null?void 0:n.workspacePath)&&s.jsx(nt,{k:a("sessionInfo.rowWorkspace"),v:s.jsx(Mt,{children:n.workspacePath})}),(n==null?void 0:n.machineName)&&s.jsx(nt,{k:a("sessionInfo.rowMachine"),v:n.machineName}),(n==null?void 0:n.connectionState)&&s.jsx(nt,{k:a("sessionInfo.rowConnection"),v:n.connectionState}),(n==null?void 0:n.git)&&s.jsx(nt,{k:a("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"]})})]}),((v=p==null?void 0:p.session)==null?void 0:v.launch)&&s.jsxs(an,{title:a("sessionInfo.sectionLaunch"),children:[p.session.launch.command&&s.jsx(nt,{k:a("sessionInfo.rowCommand"),v:s.jsx(Mt,{children:p.session.launch.command})}),p.session.launch.cwd&&s.jsx(nt,{k:a("sessionInfo.rowWorkingDirectory"),v:s.jsx(Mt,{children:p.session.launch.cwd})}),Array.isArray(p.session.launch.args)&&p.session.launch.args.length>0&&s.jsx(nt,{k:a("sessionInfo.rowArgs"),v:s.jsx(Mt,{children:p.session.launch.args.join(" ")})}),Array.isArray(p.session.launch.extraArgs)&&p.session.launch.extraArgs.length>0&&s.jsx(nt,{k:a("sessionInfo.rowExtraArgs"),v:s.jsx(Mt,{children:p.session.launch.extraArgs.join(" ")})}),Array.isArray(p.session.launch.extraEnvKeys)&&p.session.launch.extraEnvKeys.length>0&&s.jsx(nt,{k:a("sessionInfo.rowExtraEnv"),v:s.jsx(Mt,{children:p.session.launch.extraEnvKeys.join(", ")})})]}),g&&s.jsxs(an,{title:a("sessionInfo.sectionMeshNode"),children:[g.nodeId&&s.jsx(nt,{k:a("sessionInfo.rowNodeId"),v:s.jsx(Mt,{children:g.nodeId})}),g.workspace&&s.jsx(nt,{k:a("sessionInfo.rowWorkspace"),v:s.jsx(Mt,{children:g.workspace})}),g.repoRoot&&g.repoRoot!==g.workspace&&s.jsx(nt,{k:a("sessionInfo.rowRepoRoot"),v:s.jsx(Mt,{children:g.repoRoot})}),g.daemonId&&s.jsx(nt,{k:a("sessionInfo.rowDaemonId"),v:s.jsx(Mt,{children:g.daemonId})}),g.role&&s.jsx(nt,{k:a("sessionInfo.rowRole"),v:g.role}),g.machineStatus&&s.jsx(nt,{k:a("sessionInfo.rowMachineStatus"),v:g.machineStatus}),g.health&&s.jsx(nt,{k:a("sessionInfo.rowHealth"),v:g.health}),g.isLocalWorktree&&s.jsx(nt,{k:a("sessionInfo.rowWorktree"),v:g.worktreeBranch?s.jsx(Mt,{children:g.worktreeBranch}):"yes"}),typeof g.launchReady=="boolean"&&s.jsx(nt,{k:a("sessionInfo.rowLaunchReady"),v:g.launchReady?"yes":"no"}),g.git&&s.jsx(nt,{k:a("sessionInfo.rowGit"),v:s.jsxs("span",{children:[g.git.branch||"(detached)",g.git.headCommit?` @ ${String(g.git.headCommit).slice(0,10)}`:"",g.git.ahead?` ↑${g.git.ahead}`:"",g.git.behind?` ↓${g.git.behind}`:"",g.git.dirty?" · dirty":" · clean",g.git.upstream?` · ${g.git.upstream}`:""]})}),g.connection&&s.jsx(nt,{k:"Connection",v:s.jsxs("span",{children:[g.connection.transport||"—",g.connection.state?` · ${g.connection.state}`:"",typeof g.connection.rttMs=="number"?` · ${g.connection.rttMs}ms RTT`:""]})}),Array.isArray(g.providers)&&g.providers.length>0&&s.jsx(nt,{k:a("sessionInfo.rowProviders"),v:s.jsx(Mt,{children:g.providers.join(", ")})}),Array.isArray(g.providerPriority)&&g.providerPriority.length>0&&s.jsx(nt,{k:a("sessionInfo.rowProviderPriority"),v:s.jsx(Mt,{children:g.providerPriority.join(" › ")})})]}),!g&&h&&(y||b)&&s.jsx(an,{title:a("sessionInfo.sectionMeshNode"),children:s.jsx("div",{className:"text-text-secondary italic",children:h})}),(p==null?void 0:p.coordinator)&&s.jsxs(an,{title:a("sessionInfo.sectionMeshCoordinator"),children:[s.jsx(nt,{k:a("sessionInfo.rowMeshId"),v:s.jsx(Mt,{children:p.coordinator.meshId})}),p.coordinator.cliType&&s.jsx(nt,{k:a("sessionInfo.rowCoordinatorCli"),v:p.coordinator.cliType}),s.jsx(nt,{k:a("sessionInfo.rowStartedAt"),v:s.jsxs(s.Fragment,{children:[Zl(p.coordinator.startedAt),p.coordinator.startedAt?s.jsx("span",{className:"text-text-secondary ml-2",children:ec(p.coordinator.startedAt)}):null]})}),p.coordinator.injection&&s.jsx(nt,{k:a("sessionInfo.rowPromptInjection"),v:`${p.coordinator.injection.mode}${p.coordinator.injection.target?` → ${p.coordinator.injection.target}`:""}`}),p.coordinator.mcpConfigPath&&s.jsx(nt,{k:a("sessionInfo.rowMcpConfig"),v:s.jsx(Mt,{children:p.coordinator.mcpConfigPath})}),p.coordinator.extraSystemPrompt&&s.jsx(ti,{title:"Per-launch extra prompt",body:p.coordinator.extraSystemPrompt,defaultOpen:!0}),p.coordinator.systemPrompt&&s.jsx(ti,{title:"Final system prompt (click to expand)",body:p.coordinator.systemPrompt})]}),((N=p==null?void 0:p.session)==null?void 0:N.runtimeMetadata)!=null&&s.jsx(qw,{meta:p.session.runtimeMetadata}),p&&!p.coordinator&&s.jsx("div",{className:"text-text-secondary italic",children:a("sessionInfo.notCoordinatorSession")})]})})}function an({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 qw({meta:e}){const{t}=Ne("common");if(!e||typeof e!="object")return null;const n=e,r=p=>typeof p=="string"&&p.trim()?p:null,a=r(n.runtimeId),o=r(n.lifecycle),i=r(n.surfaceKind),c=r(n.recoveryState),d=Array.isArray(n.attachedClients)?n.attachedClients.length:null;return s.jsxs(an,{title:t("sessionInfo.sectionRuntime"),children:[a&&s.jsx(nt,{k:t("sessionInfo.rowRuntimeId"),v:s.jsx(Mt,{children:a})}),o&&s.jsx(nt,{k:t("sessionInfo.rowLifecycle"),v:o}),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"}),d!=null&&s.jsx(nt,{k:t("sessionInfo.rowAttachedClients"),v:String(d)}),s.jsx(ti,{title:"Raw runtime metadata (click to expand)",body:zw(e)})]})}function zw(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function ti({title:e,body:t,defaultOpen:n=!1}){const[r,a]=l.useState(n);return s.jsxs("div",{className:"mt-2",children:[s.jsxs("button",{type:"button",onClick:()=>a(o=>!o),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 Kw({sessionId:e,daemonId:t,conv:n}){const[r,a]=l.useState(!1);return!e||!t?null:s.jsxs(s.Fragment,{children:[s.jsx("button",{type:"button",onClick:()=>a(!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(Gw,{sessionId:e,daemonId:t,conv:n,onClose:()=>a(!1)})]})}const Vw=8e3;function Yw({sessionId:e,daemonId:t,muted:n,sendDaemonCommand:r}){const{t:a}=Ne("common"),[o,i]=l.useState(null),c=l.useRef(null);if(l.useEffect(()=>{o!==null&&n===o&&i(null)},[n,o]),l.useEffect(()=>()=>{c.current&&clearTimeout(c.current)},[]),!e||!t)return null;const d=o!==null?o:n,p=()=>{const u=!d;i(u),c.current&&clearTimeout(c.current),c.current=setTimeout(()=>i(null),Vw),r(t,"set_conversation_prefs",{sessionId:e,muted:u}).catch(m=>{console.warn("[conversation-prefs] toggle mute failed",m),i(null)})};return s.jsx("button",{type:"button",onClick:p,"aria-label":a(d?"conversation.unmuteThis":"conversation.muteThis"),"aria-pressed":d,title:a(d?"conversation.mutedTitle":"conversation.muteTitle"),className:`inline-flex items-center justify-center w-6 h-6 rounded-full leading-none transition-colors ${d?"bg-amber-500 text-white hover:bg-amber-600":"text-text-secondary hover:text-text-primary hover:bg-surface-secondary"}`,style:{pointerEvents:"auto"},children:d?s.jsx(Zd,{size:13}):s.jsx(Nn,{size:13})})}function Lu(e){const t=Number((e==null?void 0:e.receivedAt)||(e==null?void 0:e.timestamp)||0);return Number.isFinite(t)?t:0}function Ru(e,t){return t!=null&&t.hasLiveSnapshot?t.liveMessages||[]:Array.isArray(e.messages)?e.messages:[]}function Jw(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 Za(e){return Jw(e)?String(e.role||"").toLowerCase():""}const Qw=4;function Xw(e,t){if(e.length===0)return[];for(let o=t.length-1;o>=0;o-=1)if(Za(t[o])==="assistant")return[];const n=t.some(o=>Za(o)==="user"),r=[];let a=!1;for(let o=e.length-1;o>=0&&r.length<Qw;o-=1){const i=e[o],c=Za(i);if(c){if(!a&&c==="assistant"){r.unshift(i),a=!0;continue}if(a&&c==="user"){n||r.unshift(i);break}}}return r}function Zw(e){return e.map((t,n)=>({message:t,index:n,ts:Lu(t)})).sort((t,n)=>t.ts-n.ts||t.index-n.index).map(t=>t.message)}function e0(e){const{historyMessages:t,liveMessages:n,visibleLiveCount:r}=e,a=Math.max(0,n.length-r),o=a>0?n.slice(0,a):[],i=a>0?n.slice(-r):n,c=Xw(o,i),d=c.length>0?[...c,...i]:i,p=t.length===0?d:[...t,...d];return Zw(p)}const ct=e=>e.transport==="pty",In=(e,t)=>ct(e)&&e.mode||"chat",Eu=(e,t)=>ct(e)&&In(e)==="terminal",lt=e=>e.transport==="acp",t0=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 Ma(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 _u(e){return e.machineName||""}function en(e){return Ps(e)}function bs(e){return e.agentType||""}function aa(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 s0(e,t){const n=Ru(e,t);return[...n].reverse().find(r=>!(r!=null&&r._localId))||n[n.length-1]}function Hu(e,t){const n=s0(e,t),r=gn(n==null?void 0:n.content),a=gn(e.lastMessagePreview);return a&&e.lastMessageRole==="assistant"&&(n==null?void 0:n.role)==="user"?a:r||a||""}function n0(e,t=t0){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 r0(e){return n0(Hu(e)||e.displaySecondary||"")}function Bu(e){return[e.displaySecondary,_u(e)].filter(Boolean)}function vn(e){return e.agentName||$t(bs(e))}function a0(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(aa(e)||bs(e))}function Fu(e){return Ms(e)?e.sessionId:e.nativeSessionId}function tc(e){return Ms(e)?"native":e.tabKey}function o0(e){return e.sessionId}function i0(e,t){if(t)return Ms(e)||!t.childSessions?t:t.childSessions.find(n=>n.id===e.sessionId||n.providerType===e.agentType)||t}function l0(e,t){const n=bs(e),r=Ms(e),a=ct(e)||lt(e),o=r?a?vn(e)||(t==null?void 0:t.cliName)||$t(aa(e)||n):t!=null&&t.type?$t(t.type):$t(aa(e)||n):vn(e);return{isNativeConversation:r,isCli:ct(e),isAcp:lt(e),isCliTerminal:Eu(e),providerType:n,displayLabel:o,targetEntry:i0(e,t)}}function Ws(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 on(e,t){e(n=>[...n,{id:Date.now(),message:t,type:"warning",timestamp:Date.now()}])}function Ui(e){return e&&Array.isArray(e.modalButtons)&&e.modalButtons.length>0?"Resolve the pending approval prompt before sending another message.":null}function sc(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 Ou(){return"select_session"}function c0(){return"open_panel"}function d0({hasMessage:e,blockedMessage:t}){return e?!!t:!0}function nc(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 Gi(e){return e instanceof Error?e.message:String(e||"")}function rc(e){const t=Gi(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function ac(e,t){const n=Gi(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 a=Ws(n);if(!t||t.length===0)return{message:e,...r.force?{force:!0}:{},...a};const o=t.map(i=>({type:"image",mimeType:i.mimeType,data:i.data,alt:i.name}));return e&&o.push({type:"text",text:e}),{message:e,input:{parts:o,textFallback:e},...r.force?{force:!0}:{},...a}}function Da({sendDaemonCommand:e,activeConv:t,setActionLogs:n,isStandalone:r}){const[a,o]=l.useState(!1),[i,c]=l.useState(!1),[d,p]=l.useState(null),u=l.useRef(!1),m=l.useRef(null);l.useEffect(()=>{p(null)},[t==null?void 0:t.tabKey]);const f=l.useCallback(async(y,b)=>{if(!t||u.current)return!1;const S=y.trim(),k=Ui(t);if(d0({hasMessage:!!S,blockedMessage:k,sendInFlight:u.current}))return k&&p(k),!1;const w=Date.now(),v={tabKey:t.tabKey,message:S,timestamp:w};if(nc(m.current,v))return p(null),!0;u.current=!0,c(!0),p(null),m.current=v;try{const N=Us(t);if(!N)return m.current=jr(m.current,v),p("Unable to send message right now."),!1;const j=await e(N,"send_chat",oc(S,b,t)),A=er(j);if(A!=null&&A.deduplicated)return p(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 p(null),!0}catch(N){const j=Gi(N);return j.toLowerCase().includes("provider sendmessage did not confirm send")?console.warn("Send not confirmed by provider script:",j):console.warn("Send blocked/failed",N),m.current=jr(m.current,v),p(sc(N)),!1}finally{u.current=!1,c(!1)}},[t,e]),g=l.useCallback(async(y,b)=>{if(!t||u.current)return!1;const S=y.trim();if(!S&&(!b||b.length===0))return!1;const k=Date.now(),w={tabKey:t.tabKey,message:`force:${S}`,timestamp:k};if(nc(m.current,w))return p(null),!0;u.current=!0,c(!0),p(null),m.current=w;try{const v=Us(t);if(!v)return m.current=jr(m.current,w),p("Unable to send message right now."),!1;const N=await e(v,"send_chat",oc(S,b,t,{force:!0})),j=er(N);if((j==null?void 0:j.success)===!1||(j==null?void 0:j.sent)===!1)throw new Error((j==null?void 0:j.error)||"Send failed");return p(null),!0}catch(v){return console.warn("Force send blocked/failed",v),m.current=jr(m.current,w),p(sc(v)),!1}finally{u.current=!1,c(!1)}},[t,e]),C=l.useCallback(async()=>{if(t)try{if(!t.hostIdeType)return;await e(t.routeId,"launch_ide",{ideType:t.hostIdeType,enableCdp:!0})}catch(y){console.error("Relaunch failed",y)}},[t,e]),h=l.useCallback(async y=>{if(t)try{const S=(t.modalButtons||[]).indexOf(y),k=y.replace(/[⌥⏎⇧⌫⌘⌃]/g,"").trim().toLowerCase(),w=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(k),v=Us(t);if(!v)return;const N=await e(v,"resolve_action",{button:y,action:w?"approve":"reject",...S>=0&&{buttonIndex:S},...Ws(t),...Ma(t)}),j=er(N);j.success||n(A=>[...A,{routeId:t.tabKey,text:ac(y,j==null?void 0:j.error),timestamp:Date.now()}])}catch(b){rc(b)||console.error("[ModalButton] Error:",b),n(S=>[...S,{routeId:t.tabKey,text:rc(b)?ac(y,b):`❌ **${y}** error`,timestamp:Date.now()}])}},[t,e,n]),x=l.useCallback(async()=>{if(!(!t||a)){o(!0);try{await e(t.routeId,c0(),{...t.sessionId&&{targetSessionId:t.sessionId}})}catch(y){console.error("Focus agent failed",y)}finally{o(!1)}}},[t,a,e]);return{isSendingChat:i,sendFeedbackMessage:d,isFocusingAgent:a,handleSendChat:f,handleForceSendChat:g,handleRelaunch:C,handleModalButton:h,handleFocusAgent:x}}const u0=10,p0=8e3,m0=/(?:token|secret|password|passwd|authorization|cookie|api[_-]?key|access[_-]?key|refresh[_-]?token|client[_-]?secret|private[_-]?key)/i;function h0(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 si(e,t="",n=0){if(e==null||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="string"){if(m0.test(t)&&e.trim())return"[REDACTED:secret-field]";const r=h0(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(a=>si(a,t,n+1));return e.length>20?[{truncatedBefore:e.length-20},...r]:r}return Object.fromEntries(Object.entries(e).slice(0,80).map(([r,a])=>[r,si(a,r,n+1)]))}function $n(e,t){return Array.isArray(e)?e.slice(-t):[]}function f0(e,t=Date.now()){const n=e&&t-e.firstAt<=p0,r=n?e.count+1:1;return r>=u0?{state:{count:0,firstAt:t},shouldCollect:!0}:{state:{count:r,firstAt:n?e.firstAt:t},shouldCollect:!1}}function Wu(e){var r,a;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:((a=e.chatTailState.historyMessages)==null?void 0:a.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(o=>o.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 si(n)}function Uu(e,t={}){const n=e&&typeof e=="object"?e:{},r=t.locatorCopyStatus??(t.locatorCopied===!1?"failed":"copied"),a=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, ${a}.`:`Chat debug signal sent; ${a}.`}async function Gu(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 qu(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 eo(e,t){return`${e}:${t}`}function b0(e,t){try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function g0(){if(typeof window>"u")return!1;try{return window.localStorage.getItem("adhdev_mobile_debug")==="1"}catch{return!1}}function sn(e,t){g0()&&console.debug(`[subscription-manager] ${e}`,t)}class x0{constructor(){st(this,"active",new Map);st(this,"retryTimers",new Map)}subscribe(t,n,r,a,o){var u,m;const i=eo(r.topic,r.key),c=this.active.get(i);let d=!0;if(c)c.handlers.add(a),(!b0(c.request,r)||c.daemonId!==n)&&(c.daemonId=n,c.request=r,d=((u=t.sendData)==null?void 0:u.call(t,n,r))??!1,!d&&(o!=null&&o.retryIntervalMs)?this.scheduleRetry(i,t,o.retryIntervalMs):d&&this.clearRetry(i),sn("subscribe_update",{daemonId:n,topic:r.topic,key:r.key,accepted:d})),c.lastUpdate&&a(c.lastUpdate);else{const f={daemonId:n,request:r,handlers:new Set([a])};this.active.set(i,f),sn("subscribe",{daemonId:n,topic:r.topic,key:r.key}),d=((m=t.sendData)==null?void 0:m.call(t,n,r))??!1,!d&&(o!=null&&o.retryIntervalMs)&&this.scheduleRetry(i,t,o.retryIntervalMs)}const p=()=>{var C;this.clearRetry(i);const f=this.active.get(i);if(!f||(f.handlers.delete(a),f.handlers.size>0))return;this.active.delete(i);const g={type:"unsubscribe",topic:r.topic,key:r.key};sn("unsubscribe",{daemonId:n,topic:r.topic,key:r.key}),(C=t.sendData)==null||C.call(t,n,g)};return p.initialSendAccepted=d,p}publish(t){const n=eo(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(a=>{a(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 a=eo(t,n),o=this.active.get(a);o&&(o.request={...o.request,params:{...o.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 a;const r=Array.from(this.active.values()).filter(o=>o.daemonId===t);sn("resubscribe_daemon",{daemonId:t,count:r.length,subscriptions:r.map(o=>({topic:o.request.topic,key:o.request.key}))});for(const o of r)(a=n.sendData)==null||a.call(n,o.daemonId,o.request)}scheduleRetry(t,n,r){if(this.retryTimers.has(t))return;const a=setTimeout(()=>{var c;this.retryTimers.delete(t);const o=this.active.get(t);if(!o)return;const i=((c=n.sendData)==null?void 0:c.call(n,o.daemonId,o.request))??!1;sn("subscribe_retry",{id:t,accepted:i,topic:o.request.topic,key:o.request.key}),i||this.scheduleRetry(t,n,r)},r);this.retryTimers.set(t,a)}clearRetry(t){const n=this.retryTimers.get(t);n!==void 0&&(clearTimeout(n),this.retryTimers.delete(t))}}const ls=new x0;function v0(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 o of r.childSessions||[]){if(!(o!=null&&o.id))continue;const i=n.get(o.id)||{};n.set(o.id,{...i,...o})}}return n}function y0(e){const t=[],n=new Map;for(const r of e)if(r.parentId){const a=n.get(r.parentId)||[];a.push(r),n.set(r.parentId,a)}else t.push(r);return{topLevel:t,childrenByParent:n}}function to(e,t){return t&&(t.startsWith(`${e}:`)?t:`${e}:${t}`)}function w0(){if(typeof window>"u")return!1;try{return!!(window.__ADHDEV_CONVERSATION_DEBUG__||window.localStorage.getItem("adhdev_conversation_debug")==="1")}catch{return!1}}function k0(e){w0()&&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 oa(e,t){const n=[],{daemonId:r,existingDaemon:a,existingEntries:o,timestamp:i}=t,c=i||e.timestamp||Date.now(),d=e.sessions||[],{topLevel:p,childrenByParent:u}=y0(d),m=v0(o,r),f=e.machine?{...(a==null?void 0:a.machine)||{},...e.machine}:a==null?void 0:a.machine,g=p.filter(x=>x.kind==="workspace"&&x.transport==="cdp-page"),C=p.filter(x=>x.kind==="agent"&&x.transport==="pty"),h=p.filter(x=>x.kind==="agent"&&x.transport==="acp");n.push({...a||{},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:g.some(x=>!!x.cdpConnected)});for(const x of g){const y=m.get(x.id),b=zn(x,y),S=(u.get(x.id)||[]).map(k=>zn(k,m.get(k.id)));n.push({id:`${r}:ide:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(y==null?void 0:y.providerSessionId),parentSessionId:b.parentId,sessionKind:b.kind,transport:b.transport,sessionCapabilities:b.capabilities,type:b.providerType,status:b.cdpConnected?"online":"detected",daemonId:r,instanceId:to(r,x.id),workspace:b.workspace,terminals:0,childSessions:S,agents:S.map(k=>({id:k.id,name:k.providerName||k.providerType,type:k.providerType,status:k.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 x of C){const y=m.get(x.id),b=zn(x,y);n.push({id:`${r}:cli:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(y==null?void 0:y.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:to(r,x.id),cliName:b.providerName||b.providerType,mode:b.mode||(y==null?void 0:y.mode)||"terminal",workspace:b.workspace||"",...x.ownerDaemonId&&{ownerDaemonId:x.ownerDaemonId},...x.ownerMachineName&&{ownerMachineName:x.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 x of h){const y=m.get(x.id),b=zn(x,y);n.push({id:`${r}:acp:${x.id}`,sessionId:x.id,providerSessionId:x.providerSessionId??(y==null?void 0:y.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:to(r,x.id),cliName:b.providerName||b.providerType,mode:"chat",workspace:b.workspace||"",...x.ownerDaemonId&&{ownerDaemonId:x.ownerDaemonId},...x.ownerMachineName&&{ownerMachineName:x.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 k0(n),n}const S0=15e3,C0=15e3,j0=6e4,ic=12,N0=8e3,A0=4e3;function I0(e){const{force:t,hasSubscription:n,loadedAt:r,now:a,minFreshMs:o}=e;return t||r<=0?!0:n?!1:a-r>=o}const so=new Map,no=new Map,Nr=new Set;function T0(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 a=r.status;if(a&&typeof a=="object")return a}return t}function Tn(){const{sendCommand:e,sendData:t}=vt(),{injectEntries:n,getIdes:r}=ar();return l.useCallback(async(a,o)=>{if(!a)return;const i=(o==null?void 0:o.minFreshMs)??j0;if(!I0({force:o==null?void 0:o.force,hasSubscription:Nr.has(a),loadedAt:no.get(a)||0,now:Date.now(),minFreshMs:i}))return;const c=so.get(a);if(c)return c;const d=(async()=>{t&&!Nr.has(a)&&(ls.subscribe({sendData:t},a,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${a}`,params:{includeSessions:!0}},h=>{const x=r(),y=x.find(S=>S.id===a),b=oa(h.status,{daemonId:a,existingDaemon:y,existingEntries:x,timestamp:h.timestamp});b.length>0&&n(b),no.set(a,Date.now())}).initialSendAccepted?Nr.add(a):Nr.delete(a));const p=await e(a,"get_status_metadata"),u=T0(p);if(!u)return;const m=r(),f=m.find(C=>C.id===a),g=oa(u,{daemonId:a,existingDaemon:f,existingEntries:m,timestamp:u.timestamp||Date.now()});g.length>0&&n(g,{authoritativeDaemonIds:[a]}),no.set(a,Date.now())})().finally(()=>{so.delete(a)});return so.set(a,d),d},[r,n,e,t])}const M0=60,D0=50;function zu(e={}){return e.isCliLike?D0:M0}function P0(e={}){return zu(e)}const fr=60,L0=1e3,R0=750,lc=500,Pa=12e4,Ku=new Set(["generating","waiting_approval","starting","streaming","working"]),lr=new Map;let Vu=0;const ni=new Set;function E0(){Vu+=1;for(const e of ni)e()}function _0(e){return ni.add(e),()=>{ni.delete(e)}}function cc(){return Vu}function br(e,t,n){return`${e}::${t}::${n||t}`}function ia(e=fr){return{liveMessages:[],hasLiveSnapshot:!1,cursor:$0([],e),historyMessages:[],historyOffset:0,hasMoreHistory:!0,historyError:null}}function $0(e,t=fr){return{tailLimit:t}}function dc(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 la(e){if(typeof e=="string")return e;if(e==null)return"";if(Array.isArray(e))return e.map(la).join(`
48
+ `);if(typeof e=="object"){const t=e;return la(t.text??t.content??t.value??"")}return String(e)}function qi(e){return la(e.content).replace(/[─━═│┃┄┅┈┉┌┐└┘├┤┬┴┼╭╮╰╯╴╶╷╵\s]+/g,"").length===0}function H0(e){return e.length===0||e.every(qi)}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:"",a=typeof(n==null?void 0:n.kind)=="string"?n.kind:"";if(!(r==="system"||a==="system")&&!(a==="tool"||a==="thought"||a==="terminal"||a==="activity")&&!qi(e[t]))return r}return""}function pc(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:"",a=typeof(n==null?void 0:n.kind)=="string"?n.kind:"";if(r==="system"||a==="system"||a==="tool"||a==="thought"||a==="terminal"||a==="activity"||qi(e[t]))continue;if(r!=="assistant")return"";const o=e[t];return`${String(o.bubbleId??o.providerUnitKey??o.id??"")}#${la(o.content).length}`}return""}function Yu(e,t){if(uc(t)!=="assistant")return!1;const n=Array.isArray(e.liveMessages)?e.liveMessages:[];return uc(n)!=="assistant"}function B0(e){return!!e&&typeof e=="object"&&e.selected==="native-history"}function F0(e,t,n){return B0(n)?Yu(e,t):!1}function Ju(e){const t=typeof e=="string"?e.toLowerCase():"";return t==="generating"||t==="no_progress"||t==="long_generating"||t==="streaming"||t==="working"||t==="starting"}function Qu(e){const t=typeof e=="string"?e.trim().toLowerCase():"";return Ku.has(t)}function Xu(e,t){return Math.max(Math.max(0,t),Array.isArray(e.liveMessages)?e.liveMessages.length:0)}function O0(e,t,n,r,a,o){const i=Qu(r)||Ju(r),c=o&&e.hasLiveSnapshot;if(!i&&!c)return!1;const d=i?Xu(e,t):Array.isArray(e.liveMessages)?e.liveMessages.length:0;if(d<=0)return!1;if(H0(n))return!0;if(c&&!i&&Yu(e,n))return!1;if(a&&typeof a=="object"){const p=a.selected,u=a.fallbackReason;if(p==="native-history"||typeof u=="string"&&u!==""&&!u.startsWith("native_history_"))return!1}return n.length<d}function W0(e,t,n,r){if(n.length!==0||Xu(e,t)<=0||e.hasLiveSnapshot&&e.liveMessages.length===0||!r||typeof r!="object")return!1;const o=r.selected,i=r.fallbackReason,c=r.nativeSource;return o==="native-history"?!1:c==="native-unavailable"?!0:typeof i=="string"&&i.startsWith("native_history_")}function U0(e,t,n,r,a,o){return O0(e,t,n,r,a,o)?"defer-busy-shrink":W0(e,t,n,a)?"skip-transient-empty":"apply"}function G0(e){if(Array.isArray(e.messages))return e.messages;const t=e.messagesTail;return Array.isArray(t)?t:[]}function mc(e,t){const n=e[t];return typeof n=="string"?n:""}class q0{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=ia(Math.max(0,t.tailLimit??fr))}updateOptions(t){const n=this.sendData,r=this.daemonId,a=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 o=Math.max(0,t.tailLimit);o!==this.snapshot.cursor.tailLimit&&(this.snapshot={...this.snapshot,cursor:{tailLimit:o}},this.transportSubscription&&(this.disconnect(),this.connect()))}this.retainCount>0&&(n!==this.sendData||r!==this.daemonId||a!==this.sessionId)&&(this.disconnect(),this.connect())}getSnapshot(){return this.snapshot}clearLiveSnapshot(){this.snapshot={...ia(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,a=r?this.snapshot.liveMessages.length:Math.max(this.snapshot.liveMessages.length,this.fallbackRecentCount),o=await t({offset:this.snapshot.historyOffset,excludeRecentCount:a}),i=Array.isArray(o.messages)?o.messages:[],c=!r&&i.length===0&&o.hasMore!==!0&&this.fallbackRecentCount>0,d=[...i,...this.snapshot.historyMessages],p=d.length>lc?d.slice(d.length-lc):d;this.snapshot={...this.snapshot,historyMessages:p,historyOffset:this.snapshot.historyOffset+i.length,hasMoreHistory:c?!0:o.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<R0)return Promise.resolve();this.lastAuthoritativeRefreshAt=r;const a=(async()=>{try{const o=await t();o&&this.handleUpdate(o)}catch{}})().finally(()=>{this.authoritativeRefreshPromise=null});return this.authoritativeRefreshPromise=a,a}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:L0}))}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=mc(t,"sessionId");if(n&&n!==this.sessionId)return;const r=mc(t,"historySessionId");if(r&&this.historySessionId&&r!==this.historySessionId)return;const a=G0(t),o=t.messageSource,i=this.now(),c=this.lastActiveStatusAt>0&&i-this.lastActiveStatusAt<=Pa;(Qu(t.status)||Ju(t.status))&&(this.lastActiveStatusAt=i);const d=F0(this.snapshot,a,o);if(!d&&U0(this.snapshot,this.fallbackRecentCount,a,t.status,o,c)!=="apply")return;const p={tailLimit:this.snapshot.cursor.tailLimit};!d&&dc(this.snapshot.liveMessages)===dc(a)&&pc(this.snapshot.liveMessages)===pc(a)&&this.snapshot.cursor.tailLimit===p.tailLimit||(this.snapshot={...this.snapshot,liveMessages:a,hasLiveSnapshot:!0,cursor:p,messageSource:o},this.emit())}}function Zu(e){const t=br(e.daemonId,e.sessionId,e.historySessionId),n=lr.get(t);if(n)return n.updateOptions(e),n;const r=new q0(e);return lr.set(t,r),E0(),r}function z0(e,t,n){if(!e||!t)return;const r=`${e}::${t}::`,a=br(e,t,n);for(const[o,i]of lr.entries())(o===a||o.startsWith(r))&&i.clearLiveSnapshot()}function ep(e){const t=en(e),n=e.sessionId||"";if(!t||!n)return;const r=Ia(e),a=br(t,n,r||n),o=lr.get(a);if(!o)return;const i=o.getSnapshot();return i.hasLiveSnapshot?i:void 0}function K0(e,t){return{...e,loadHistoryPage:t}}function V0(e,t){return e.subscriptionKey.localeCompare(t.subscriptionKey)||e.daemonId.localeCompare(t.daemonId)||e.sessionId.localeCompare(t.sessionId)||(e.historySessionId||"").localeCompare(t.historySessionId||"")}function Y0(e,t={}){const n=String(e.status||"").trim().toLowerCase();if(Ku.has(n)||(e.modalMessage||"").trim()||Array.isArray(e.modalButtons)&&e.modalButtons.length>0)return!0;const r=t.now??Date.now(),a=Math.max(0,Number(t.recentActivityMs??Pa)),o=Math.max(Number(e.lastUpdated||0),Number(e.lastMessageAt||0));return o>0?r-o<=a:Array.isArray(e.messages)&&e.messages.length>0}function J0(e=Pa){return Math.max(1e3,Math.min(3e4,Math.max(0,Number(e||0))))}function Q0(e,t={}){const n=new Set,r=[];for(const a of e){if(!Y0(a,t))continue;const o=en(a),i=a.sessionId||"";if(!o||!i)continue;const c=Ia(a),d=br(o,i,c||i);n.has(d)||(n.add(d),r.push({daemonId:o,sessionId:i,historySessionId:c,subscriptionKey:`daemon:${o}:session:${i}`}))}return r.sort(V0),{descriptors:r,signature:r.map(a=>`${a.subscriptionKey}|${a.historySessionId}`).join("||")}}function X0(e,t){const{sendData:n,sendCommand:r,isConnected:a}=vt(),o=(t==null?void 0:t.enabled)!==!1,i=en(e),c=e.sessionId||"",d=Ia(e),p=`daemon:${i}:session:${c}`,u=Math.max(0,(t==null?void 0:t.tailLimit)??fr),m=e.messages.length,f=l.useMemo(()=>!o||!i||!c?null:Zu({daemonId:i,sessionId:c,historySessionId:d,subscriptionKey:p,sendData:n,tailLimit:u,fallbackRecentCount:m}),[i,o,d,n,c,p,u]);l.useEffect(()=>{f==null||f.updateOptions({fallbackRecentCount:m})},[f,m]);const[g,C]=l.useState(()=>(f==null?void 0:f.getSnapshot())||ia(u));l.useEffect(()=>{if(!f){C(ia(u));return}f.retain(),C(f.getSnapshot());const y=f.subscribe(b=>{C(b)});return()=>{y(),f.release()}},[f,u]);const h=l.useCallback(async()=>{!f||!i||!c||await f.loadHistoryPage(async({offset:y,excludeRecentCount:b})=>{const S=e.agentType,k=await r(i,"chat_history",{agentType:S,offset:y,limit:30,targetSessionId:c,historySessionId:d,excludeRecentCount:b}),w=k&&typeof k=="object"&&"result"in k?k.result||{}:k||{};return{messages:Array.isArray(w.messages)?w.messages:[],hasMore:w.hasMore===!0}})},[e.agentType,f,i,d,r,c]),x=l.useCallback((y=!1)=>!f||!i||!c?Promise.resolve():f.refreshAuthoritativeTail(async()=>{const b=await r(i,"read_chat",{agentType:e.agentType,targetSessionId:c,historySessionId:d,...u>0?{tailLimit:u}:{}}),S=b&&typeof b=="object"&&"result"in b?b.result:b;if(!S||typeof S!="object"||S.success===!1)return null;const k=Array.isArray(S.messages)?S.messages:Array.isArray(S.messagesTail)?S.messagesTail:[];return{topic:"session.chat_tail",key:p,sessionId:c,historySessionId:d,seq:0,timestamp:0,messages:k,status:typeof S.status=="string"?S.status:"idle",...S.messageSource&&typeof S.messageSource=="object"?{messageSource:S.messageSource}:{}}},{force:y}),[e.agentType,f,i,d,r,c,p,u]);return l.useEffect(()=>{if(!f||!o||!i||!c)return;x(!0);const y=()=>{typeof document<"u"&&document.visibilityState==="visible"&&x()};typeof document<"u"&&document.addEventListener("visibilitychange",y);let b=a?a(i):!0;const S=setInterval(()=>{if(!a)return;const k=a(i);k&&!b&&x(),b=k},2e3);return()=>{typeof document<"u"&&document.removeEventListener("visibilitychange",y),clearInterval(S)}},[f,i,o,c,d]),l.useMemo(()=>K0(g,h),[h,g])}function Z0(e,t){const{sendData:n}=vt(),r=(t==null?void 0:t.enabled)!==!1,a=Math.max(0,(t==null?void 0:t.tailLimit)??fr),o=Math.max(0,Number((t==null?void 0:t.recentActivityMs)??Pa)),i=J0(o),[c,d]=l.useState(0);l.useEffect(()=>{if(!r||e.length===0)return;const u=setInterval(()=>{d(m=>m+1)},i);return()=>{clearInterval(u)}},[e.length,r,i]);const p=l.useMemo(()=>Q0(e,{recentActivityMs:o}),[e,o,c]);l.useEffect(()=>{if(!r||!n||p.descriptors.length===0)return;const u=p.descriptors.map(m=>Zu({...m,sendData:n,tailLimit:a}));return u.forEach(m=>{m.retain()}),()=>{u.forEach(m=>m.release())}},[p.signature,r,n,a])}function ek(e){const[t,n]=l.useState(0),r=l.useMemo(()=>{const i=[];for(const c of e){const d=en(c),p=c.sessionId||"";if(!d||!p)continue;const u=Ia(c);i.push(br(d,p,u||p))}return i},[e]),a=r.join("|"),o=l.useSyncExternalStore(_0,cc,cc);return l.useEffect(()=>{if(r.length===0)return;const i=[];for(const c of r){const d=lr.get(c);if(!d)continue;let p=!1;i.push(d.subscribe(()=>{if(!p){p=!0;return}n(u=>u+1)}))}return()=>{for(const c of i)c()}},[a,o]),t}function tk(e,t){return Array.isArray(e.sessionCapabilities)&&e.sessionCapabilities.includes(t)}function sk(e){return tk(e,"open_panel")?e.status==="panel_hidden"||e.status==="not_monitored":!1}const qr=new Map,ri=new Set;function hc(e,t){!e||qr.get(e)===t||(t?qr.set(e,!0):qr.delete(e),ri.forEach(r=>r(e,t)))}function nk(e){return e?qr.get(e)===!0:!1}function rk(e){return ri.add(e),()=>{ri.delete(e)}}function ak(e,t,n=`${t}s`){return`${e} ${e===1?t:n}`}function ok(e){return e.replace(/[^a-zA-Z0-9._:-]+/g,"-").slice(0,80)||"latest"}function ik(e){return typeof e.workspacePath=="string"&&e.workspacePath.trim().length>0&&!!e.git&&e.git.isGitRepo===!0}function tp(e){return e.status==="generating"||e.status==="streaming"||e.status==="working"||e.inboxBucket==="working"}function sp(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 lk(e){return tp(e)?!1:e.inboxBucket==="task_complete"&&sp(e).length>0}function fc(e){return e.branch||"detached HEAD"}function ck(e){if(e.error)return`${fc(e)} · Git error: ${e.error}`;const t=[fc(e)];return e.changedFiles>0?t.push(ak(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 dk(e,t){return`Git workspace · ${e==="working"?"work started":"work completed"} · ${ck(t)}`}function uk(e,t){return e.lastUpdated||e.lastMessageAt||t.lastCheckedAt||0}function pk(e,t={}){if(t.enabled===!1)return[];if(!ik(e))return[];const n=tp(e)?"working":lk(e)?"complete":null;if(!n)return[];const r=n==="complete"?sp(e):"";return[{id:n==="complete"?`git-system:${e.sessionId||e.tabKey}:complete:${ok(r)}`:`git-system:${e.sessionId||e.tabKey}:working`,role:"system",kind:"system",content:dk(n,e.git),timestamp:uk(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 mk=60;function hk(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 ai({activeConv:e,ideEntry:t,handleSendChat:n,handleForceSendChat:r,isSendingChat:a=!1,sendFeedbackMessage:o=null,handleFocusAgent:i,isFocusingAgent:c,actionLogs:d,userName:p,scrollToBottomRequestNonce:u,isInputActive:m=!0,isVisible:f=!0}){var me,G,U,Z,Y,fe,Te,ce;const{t:g}=Ne("common"),C=l.useRef(new Map),h=l.useRef(void 0),x=Tn(),{sendCommand:y}=vt(),{isVisible:b}=Ri();hr("ChatPane",{tabKey:e.tabKey,messageCount:e.messages.length,actionLogCount:d.length,isSendingChat:a});const S=Rt.useMemo(()=>An(e),[e.status,e.connectionState]);Rt.useEffect(()=>{const $=e.sessionId;if($)return hc($,S.isGenerating),()=>{hc($,!1)}},[e.sessionId,S.isGenerating]);const k=l.useMemo(()=>l0(e,t),[e,t]),w=l.useMemo(()=>{var $;return Hi(($=k.targetEntry)==null?void 0:$.providerControls,{hostIdeType:e.hostIdeType,providerType:k.providerType})},[e.hostIdeType,k.providerType,(me=k.targetEntry)==null?void 0:me.providerControls]),v=zu({isCliLike:k.isCli||k.isAcp}),N=P0({isCliLike:k.isCli||k.isAcp}),j=X0(e,{enabled:f&&!!e.sessionId,tailLimit:N}),[A,I]=l.useState(v),[D,L]=l.useState(()=>Ll()),P=e.tabKey,_=j.historyMessages,q=j.hasMoreHistory,B=j.historyError,E=Ru(e,j),K=nu(E).length;l.useEffect(()=>{I(v)},[v,P]);const R=Math.max(0,E.length-A),T=Wi(e),H=en(e),M=sk(e),W=Ui(e),J=hk(e),re=o||W,V=re||J,X=!!W,[de,ne]=l.useState(!1);l.useEffect(()=>{const $=k.targetEntry;H&&(!$||$.providerControls===void 0||$.controlValues===void 0)&&x(H,{minFreshMs:3e4}).catch(()=>{})},[H,k.isAcp,(G=k.targetEntry)==null?void 0:G.providerControls,(U=k.targetEntry)==null?void 0:U.controlValues,x]);const O=l.useCallback(async()=>{if(!de){if(E.length>A){I($=>Math.min(E.length,$+mk));return}ne(!0);try{await j.loadHistoryPage()}finally{ne(!1)}}},[j,de,E.length,A]),{allMessages:ie,receivedAtMap:z}=l.useMemo(()=>{const $=e0({historyMessages:_,liveMessages:E,visibleLiveCount:A}),pe=pk(e),le=pe.length>0?[...$,...pe]:$,F={};return le.forEach((be,je)=>{const Se=`${e.tabKey}:${ta(be)}`;let He=Lu(be)||C.current.get(Se)||0;He||(He=Date.now(),C.current.set(Se,He)),F[ta(be)]=He}),{allMessages:le,receivedAtMap:F}},[e.tabKey,e.sessionId,e.status,e.inboxBucket,e.completionMarker,e.lastMessageHash,e.lastMessageAt,e.lastUpdated,e.workspacePath,e.git,R,_,E,A]),ae=l.useMemo(()=>d.filter($=>$.routeId===e.tabKey).sort(($,pe)=>$.timestamp-pe.timestamp),[d,e.tabKey]),Ce=l.useCallback(async()=>{var je,Se;if(!H)return;const $=Wu({activeConv:e,visibleMessages:ie,actionLogs:d,controls:(je=k.targetEntry)==null?void 0:je.providerControls,controlValues:(Se=k.targetEntry)==null?void 0:Se.controlValues,visibleBarControlCount:w.length,chatTailState:{liveMessages:j.liveMessages,hasLiveSnapshot:j.hasLiveSnapshot,hasMoreHistory:q,historyError:B,historyMessages:_},ui:{controlsVisible:b,visibleLiveCount:A,activityVisible:D,activityCount:K,hiddenLiveCount:R,isInputActive:m,isVisible:f}}),pe=await y(H,"get_chat_debug_bundle",{agentType:k.providerType||e.agentType,targetSessionId:e.sessionId,delivery:"daemon_file",frontendSnapshot:$}),le=er(pe),F=qu(le),be=await Gu(F);be==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present debug bundle locator"),mt.showToast(Uu(le,{locatorCopyStatus:be}),be==="failed"?"warning":"success")},[e,d,K,ie,b,j.hasLiveSnapshot,j.liveMessages,k.providerType,(Z=k.targetEntry)==null?void 0:Z.controlValues,(Y=k.targetEntry)==null?void 0:Y.providerControls,H,q,R,_,m,f,B,y,D,w.length,A]);l.useEffect(()=>{const $=pe=>{pe.key===tu&&L(Ll())};return window.addEventListener("storage",$),()=>window.removeEventListener("storage",$)},[]);const ye=l.useCallback(()=>{const $=f0(h.current);h.current=$.state,$.shouldCollect&&Ce().catch(pe=>{console.warn("[chat-debug-bundle] failed to collect debug bundle",pe),mt.showToast("Chat debug signal failed. Check the browser console or P2P connection.","warning")})},[Ce]),ke=l.useMemo(()=>{if(E.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:[g("chatPane.connectingToMachine"),s.jsx("span",{className:"connecting-dots"})]}),s.jsx("div",{className:"text-[11px] opacity-35",children:g("chatPane.establishingP2P")})]})]});if((S.isGenerating||e.status==="streaming")&&ne(!1),e.status==="not_monitored"&&M)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(or,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:g("chatPane.agentNotMonitored")}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?`⌛ ${g("chatPane.switchingPanel")}`:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(xn,{size:14})," ",g("chatPane.openPanel",{label:T})]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:g("chatPane.clickToSwitchMonitoring")})]});if(e.status==="panel_hidden"&&M)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(Jd,{size:28})}),s.jsx("div",{className:"text-[13px] opacity-50",children:g("chatPane.agentPanelHidden")}),s.jsx("button",{onClick:i,disabled:c,className:"btn btn-primary",children:c?`⌛ ${g("chatPane.openingPanel")}`:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(xn,{size:14})," ",g("chatPane.openPanel",{label:T})]})}),s.jsx("div",{className:"text-[11px] opacity-35 max-w-[280px]",children:g("chatPane.openPanelHint")})]});if(e.status==="idle"&&!de)return!q&&_.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:g("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:g("chatPane.loadingChat")})]})}},[e.connectionState,e.status,M,i,q,_.length,c,de,E.length,T,S.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(Yw,{sessionId:e.sessionId,daemonId:e.daemonId,muted:!!((fe=k.targetEntry)!=null&&fe.muted),sendDaemonCommand:y}),s.jsx(Kw,{sessionId:e.sessionId,daemonId:e.daemonId,conv:e})]})}),s.jsx(bb,{messages:ie,actionLogs:ae,agentName:vn(e)||T||"Agent",userName:p,isCliMode:k.isCli||k.isAcp,isWorking:S.isGenerating,contextKey:e.tabKey,receivedAtMap:z,lastMessageHash:e.lastMessageHash,showActivityMessages:D,onLoadMore:O,isLoadingMore:de,hasMoreHistory:q,hiddenLiveCount:R,loadError:B??void 0,emptyState:ke,scrollToBottomRequestNonce:u,isVisible:f}),s.jsx(yw,{routeId:e.routeId,sessionId:e.sessionId,hostIdeType:e.hostIdeType,providerType:k.providerType,displayLabel:k.displayLabel,controls:(Te=k.targetEntry)==null?void 0:Te.providerControls,controlValues:(ce=k.targetEntry)==null?void 0:ce.controlValues,currentStatus:e.status,coordinatorHint:Ma(e),isActive:m,isCliTerminal:k.isCliTerminal}),!k.isCliTerminal&&s.jsx(Au,{contextKey:e.tabKey,panelLabel:T,isSending:a,isBusy:X,statusMessage:V,inlineStatusMessage:re,onSend:n,onForceSend:r,canForceSend:!!r&&S.isGenerating&&!X,isActive:m,showControlsToggle:w.length>0,onControlsToggle:ye,messageInput:e.messageInput})]})}let np=gs;function rp(){return np()}class fk{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(a=>a(...n))}}let ap=new fk;class bk{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 bk;function gk(e){e.dashboardWS&&(ap=e.dashboardWS),e.connectionManager&&(kt=e.connectionManager),e.useDaemonsHook&&(np=e.useDaemonsHook)}const xk=.5,vk=1.25,ns="\x1B",bc={ArrowUp:"A",ArrowDown:"B",ArrowLeft:"D",ArrowRight:"C"};function yk(e){return 1+(e.shift?1:0)+(e.alt?2:0)+(e.ctrl?4:0)}function gc(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 wk(e,t){if(t in bc){const r=bc[t],a=yk(e);return a===1?`${ns}[${r}`:`${ns}[1;${a}${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=gc(" ",e);return e.alt?`${ns}${r}`:r}}const n=gc(t,e);return e.alt?`${ns}${n}`:n}function xt(e){return Wi(e)}function yn(e){return Bu(e).join(" · ")}function op(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 kk(e){var a,o,i;const t=[],n=typeof((a=e.settings)==null?void 0:a.meshNodeFor)=="string"&&e.settings.meshNodeFor.trim().length>0,r=!!((o=e.coordinator)!=null&&o.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 Sk(e){var i,c,d;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():"",a=typeof((d=e.settings)==null?void 0:d.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor.trim():"",o=r||a;if(n&&t.push(`Mesh node: ${n}`),o&&t.push(`Coordinator: ${o}`),e.meshQueueStats){const{pending:p,assigned:u,completed:m,failed:f}=e.meshQueueStats;t.push(`Queue: ${p} pending, ${u} assigned, ${m} completed, ${f} failed`)}return t.join(" · ")}function ip(e,t){const n=Hu(e,t);return n||(e.title?e.title:yn(e)||"No messages yet")}function lp(e,t){const{isReconnecting:n,isConnecting:r}=An(e);return n?"Reconnecting…":r?"Connecting…":t!=null&&t.requiresAction?"Action needed":null}function Ck(e,t){const n=["Chat",...Bu(e)];return t!=null&&t.timestampLabel&&n.push(t.timestampLabel),n.filter(Boolean).join(" · ")}function Gs(e){return lp(e)||yn(e)}function jk(e,t){return`${xt(e)} · ${ip(e,t)}`}function Nk(e){const t=aa(e),n=t?$t(t):vn(e);return`${xt(e)} — ${n||"Agent"}`}function Ak(e){return vn(e)||"CLI"}function cp(e){return $u(e)}function dp(e){return e?`Remote · ${xt(e)||e.workspaceName||"Session"}`:"Remote"}const xc=[{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:""}})}],Ik=[{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 Tk(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 zi({cond:e,path:t,sections:n,onChange:r,onRemove:a,onPreview:o,preview:i}){const c=Tk(e),d=i[t],p=u=>{const m=xc.find(f=>f.kind===u);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:u=>p(u.target.value),className:"bg-bg-secondary text-text-primary text-[10px] font-mono rounded border border-border-default px-1 py-0.5",children:xc.map(u=>s.jsx("option",{value:u.kind,children:u.label},u.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:()=>o(t,e),children:"test"}),d&&d!=="loading"&&s.jsx("span",{className:`text-[10px] font-mono px-1.5 py-0.5 rounded ${d.result?"text-status-online bg-status-online/20":"text-text-secondary bg-bg-glass"}`,children:d.result?"match ✓":"no match"}),d==="loading"&&s.jsx("span",{className:"text-[10px] text-text-muted",children:"testing…"}),a&&s.jsx("button",{type:"button",className:"ml-auto text-text-muted hover:text-status-error text-xs px-1",onClick:a,children:"×"})]}),c==="regex"&&s.jsxs("div",{className:"flex items-center gap-1",children:[s.jsxs("select",{value:e.section??"",onChange:u=>r({...e,section:u.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(u=>s.jsx("option",{value:u,children:u},u))]}),s.jsx("input",{value:e.matches??"",onChange:u=>r({...e,matches:u.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(Is,{label:"elapsed_ms",value:e.elapsed_ms,onChange:u=>r({elapsed_ms:u})}),c==="stable"&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Is,{label:"stable_ms",value:e.stable_ms,onChange:u=>r({...e,stable_ms:u})}),s.jsx(Is,{label:"cursor_above",value:e.cursor_above??0,onChange:u=>r({...e,cursor_above:u||void 0})})]}),c==="changed"&&s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Is,{label:"cursor_above",value:e.cursor_above,onChange:u=>r({...e,cursor_above:u})}),s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-text-secondary",children:[s.jsx("input",{type:"checkbox",checked:!!e.changed,onChange:u=>r({...e,changed:u.target.checked}),className:"accent-[var(--accent-primary)]"}),"changed"]})]}),(c==="all"||c==="any")&&s.jsx(Mk,{kind:c,cond:e,path:t,sections:n,onChange:r,onPreview:o,preview:i}),c==="not"&&s.jsx("div",{className:"pl-2 border-l border-border-default",children:s.jsx(zi,{cond:e.not,path:`${t}.not`,sections:n,onChange:u=>r({not:u}),onPreview:o,preview:i})})]})}function Mk({kind:e,cond:t,path:n,sections:r,onChange:a,onPreview:o,preview:i}){const c=(e==="all"?t.all:t.any)??[],d=p=>a(e==="all"?{all:p}:{any:p});return s.jsxs("div",{className:"pl-2 border-l border-border-default space-y-1",children:[c.map((p,u)=>s.jsx(zi,{cond:p,path:`${n}.${e}[${u}]`,sections:r,onChange:m=>d(c.map((f,g)=>g===u?m:f)),onRemove:()=>d(c.filter((m,f)=>f!==u)),onPreview:o,preview:i},u)),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:()=>d([...c,{section:r[0],matches:""}]),children:"+ condition"}),Ik.map(p=>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:()=>d([...c,JSON.parse(JSON.stringify(p.cond))]),title:"insert verified pattern",children:["+ ",p.label]},p.label))]})]})}function Is({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 Dk({sections:e,otherSectionIds:t,onChange:n,onTest:r,testResult:a}){const o=Object.keys(e),i=a&&a!=="loading"&&!("error"in a)?Object.fromEntries(a.sections.map(m=>[m.id,m])):{},c=(m,f)=>{if(!f||f===m||e[f])return;const g={};for(const[C,h]of Object.entries(e))g[C===m?f:C]=h;n(g)},d=(m,f)=>n({...e,[m]:f}),p=m=>{const f={...e};delete f[m],n(f)},u=()=>{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:a==="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:u,children:"+ section"})]}),a&&a!=="loading"&&"error"in a&&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:a.error}),s.jsx("div",{className:"space-y-1.5",children:o.map(m=>{var h;const f=e[m],g=f.anchor!=null?"anchor":"positional",C=x=>{x==="anchor"?d(m,{anchor:f.anchor??"^",anchor_last:f.anchor_last,until:f.until}):d(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:x=>c(m,x.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 ${g==="positional"?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>C("positional"),children:"positional"}),s.jsx("button",{type:"button",className:`px-1.5 py-0.5 ${g==="anchor"?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>C("anchor"),children:"anchor"})]}),s.jsx("button",{type:"button",className:"ml-auto text-text-muted hover:text-status-error text-sm px-1",onClick:()=>p(m),children:"×"})]}),g==="positional"?s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx(Is,{label:"from_top",value:typeof f.from_top=="number"?f.from_top:0,onChange:x=>d(m,{...f,from_top:x,from_bottom:void 0})}),s.jsx(Is,{label:"from_bottom",value:typeof f.from_bottom=="number"?f.from_bottom:0,onChange:x=>d(m,{...f,from_bottom:x||void 0})}),s.jsx(vc,{def:f,otherIds:t(m),onChange:x=>d(m,x)})]}):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:x=>d(m,{...f,anchor:x.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:x=>d(m,{...f,anchor_last:x.target.checked||void 0}),className:"accent-[var(--accent-primary)]"}),"last"]})]}),s.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:s.jsx(vc,{def:f,otherIds:t(m),onChange:x=>d(m,x)})}),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:((h=f.anchor_context)==null?void 0:h.next)??"",onChange:x=>d(m,{...f,anchor_context:{...f.anchor_context,next:x.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 vc({def:e,otherIds:t,onChange:n}){const r=e.until??"",a=r.startsWith("^");return s.jsxs("label",{className:"flex items-center gap-1 text-[10px] text-text-secondary",children:["until",s.jsxs("select",{value:a?"__regex__":r,onChange:o=>{const i=o.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(o=>s.jsx("option",{value:o,children:o},o)),s.jsx("option",{value:"__regex__",children:"regex…"})]}),a&&s.jsx("input",{value:r,onChange:o=>n({...e,until:o.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 Pk({model:e,onChange:t,onPreview:n,preview:r,onTestSections:a,sectionPreview:o}){const i=e.states.map(m=>m.id),c=Object.keys(e.sections??{}),d=l.useCallback(m=>t({...e,...m}),[e,t]),p=(m,f)=>d({states:e.states.map((g,C)=>C===m?{...g,...f}:g)}),u=(m,f)=>d({transitions:e.transitions.map((g,C)=>C===m?{...g,...f}:g)});return s.jsxs("div",{className:"space-y-3",children:[s.jsx(Dk,{sections:e.sections??{},otherSectionIds:m=>c.filter(f=>f!==m),onChange:m=>d({sections:m}),onTest:()=>a(e.sections??{}),testResult:o}),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:()=>d({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:g=>p(f,{id:g.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:g=>p(f,{label:g.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:()=>d({states:e.states.filter((g,C)=>C!==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:()=>d({states:e.states.map((g,C)=>({...g,initial:C===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:g=>p(f,{modal:g.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:g=>p(f,{status:g.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:()=>d({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(Lk,{value:m.from,states:i,onChange:g=>u(f,{from:g})}),s.jsx("span",{className:"text-[10px] text-text-muted",children:"→"}),s.jsx("select",{value:m.to,onChange:g=>u(f,{to:g.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(g=>s.jsx("option",{value:g,children:g},g))}),s.jsx("span",{className:"text-[10px] text-text-muted ml-1",children:"label"}),s.jsx("input",{value:m.label??"",onChange:g=>u(f,{label:g.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:()=>d({transitions:e.transitions.filter((g,C)=>C!==f)}),children:"×"})]}),s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(Is,{label:"min_hold_ms",value:m.min_hold_ms??0,onChange:g=>u(f,{min_hold_ms:g||void 0})}),s.jsx(Is,{label:"priority",value:m.priority??0,onChange:g=>u(f,{priority:g||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:()=>u(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:()=>u(f,{when:void 0}),children:"remove guard"})]}),m.when&&s.jsx(zi,{cond:m.when,path:`t${f}`,sections:c,onChange:g=>u(f,{when:g}),onPreview:n,preview:r})]})]},f))})]})]})}function Lk({value:e,states:t,onChange:n}){const r=new Set(Array.isArray(e)?e:e==="*"?t:[e]),a=e==="*",o=i=>{const c=new Set(r);c.has(i)?c.delete(i):c.add(i);const d=t.filter(p=>c.has(p));n(d.length===1?d[0]:d)};return s.jsx("div",{className:"flex items-center gap-0.5 flex-wrap",children:t.map(i=>s.jsx("button",{type:"button",onClick:()=>o(i),className:`font-mono text-[10px] px-1 py-0.5 rounded border ${a||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 Hn(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 Rk={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"},Ek={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 ro(e){return Ek[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 Ir(){return s.jsx("div",{className:"border-t border-white/8 my-2"})}function up({node:e,depth:t=0}){var a;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)"]}),(a=e.children)==null?void 0:a.map((o,i)=>s.jsx(up,{node:o,depth:t+1},i))]})}function _k({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(a=>!a),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(up,{node:e.cond})})]})}function $k({activeConv:e,onClose:t}){var ae,Ce,ye,ke,me;const{sendCommand:n}=vt(),[r,a]=l.useState(!0),[o,i]=l.useState(null),[c,d]=l.useState(null),[p,u]=l.useState(!1),[m,f]=l.useState(new Set(["footer"])),[g,C]=l.useState("Snapshot"),[h,x]=l.useState(!1),[y,b]=l.useState(null),[S,k]=l.useState(!1),[w,v]=l.useState(""),[N,j]=l.useState(!1),[A,I]=l.useState("idle"),[D,L]=l.useState(null),[P,_]=l.useState([]),[q,B]=l.useState({}),[E,K]=l.useState(null),[R,T]=l.useState(!1),H=e.daemonId||((ae=e.routeId)==null?void 0:ae.split(":")[0])||e.routeId||"",M=e.sessionId||"",W=l.useCallback(async()=>{a(!0),d(null);try{const G=await n(H,"get_spec_debug",{targetSessionId:M}),U=G&&typeof G=="object"?G:{},Z=U.result&&typeof U.result=="object"?U.result:U;Z!=null&&Z.success?i(Z):(d((Z==null?void 0:Z.error)||"Failed to load spec debug"),i(null))}catch(G){d((G==null?void 0:G.message)||String(G)),i(null)}finally{a(!1)}},[n,H,M]);l.useEffect(()=>{W()},[W]),l.useEffect(()=>{if(!R)return;const G=setInterval(()=>{W()},1e3);return()=>clearInterval(G)},[R,W]),l.useEffect(()=>{const G=U=>{U.key==="Escape"&&!h&&t()};return window.addEventListener("keydown",G),()=>window.removeEventListener("keydown",G)},[t,h]);const J=l.useCallback(async G=>{try{const U=await n(H,"validate_spec",{content:JSON.stringify(G)}),Z=U&&typeof U=="object"?U:{},Y=Z.result&&typeof Z.result=="object"?Z.result:Z;_(Y!=null&&Y.valid?[]:(Y==null?void 0:Y.errors)??["validation failed"])}catch(U){_([(U==null?void 0:U.message)||String(U)])}},[n,H]),re=l.useCallback(async()=>{L(null),I("idle"),B({});try{const G=await n(H,"get_spec_source",{targetSessionId:M}),U=G&&typeof G=="object"?G:{},Z=U.result&&typeof U.result=="object"?U.result:U;if(!(Z!=null&&Z.success)||typeof Z.content!="string"){L((Z==null?void 0:Z.error)||"Failed to load spec source");return}v(Z.content);let Y=null;try{Y=JSON.parse(Z.content)}catch{}Y&&Y.$schema==="adhdev:cli/spec@4"?(b(Y),k(!1),J(Y)):(b(null),k(!0)),j(!1),x(!0)}catch(G){L((G==null?void 0:G.message)||String(G))}},[n,H,M,J]),V=l.useCallback(G=>{b(G),v(JSON.stringify(G,null,2)),j(!0),I("idle"),J(G)},[J]),X=l.useCallback(async(G,U)=>{B(Z=>({...Z,[G]:"loading"}));try{const Z=await n(H,"eval_condition_preview",{targetSessionId:M,condition:U}),Y=Z&&typeof Z=="object"?Z:{},fe=Y.result&&typeof Y.result=="object"?Y.result:Y;!(fe!=null&&fe.success)||!fe.result?B(Te=>({...Te,[G]:{result:!1,detail:fe==null?void 0:fe.error}})):B(Te=>({...Te,[G]:{result:fe.result.result,detail:fe.result.detail}}))}catch(Z){B(Y=>({...Y,[G]:{result:!1,detail:Z==null?void 0:Z.message}}))}},[n,H,M]),de=l.useCallback(async G=>{K("loading");try{const U=await n(H,"resolve_section_preview",{targetSessionId:M,sections:G}),Z=U&&typeof U=="object"?U:{},Y=Z.result&&typeof Z.result=="object"?Z.result:Z;!(Y!=null&&Y.success)||!Array.isArray(Y.sections)?K({error:(Y==null?void 0:Y.error)||"resolve failed"}):K({sections:Y.sections,screenLineCount:Y.screenLineCount??0})}catch(U){K({error:(U==null?void 0:U.message)||String(U)})}},[n,H,M]),ne=l.useCallback(async()=>{var Z,Y;const G=(Z=o==null?void 0:o.snapshot)==null?void 0:Z.specPath;if(!G){L("No spec path on this session");return}if(!S&&P.length>0){L("Fix validation errors before saving");return}const U=!S&&y?JSON.stringify(y,null,2):w;I("saving"),L(null);try{const fe=await n(H,"write_spec_source",{specPath:G,content:U}),Te=fe&&typeof fe=="object"?fe:{},ce=Te.result&&typeof Te.result=="object"?Te.result:Te;if(!(ce!=null&&ce.success)){I("error"),L(((Y=ce==null?void 0:ce.validationErrors)==null?void 0:Y.join(`
49
+ `))||(ce==null?void 0:ce.error)||"Save failed");return}I("saved"),j(!1),setTimeout(()=>{W()},400),setTimeout(()=>I("idle"),1500)}catch(fe){I("error"),L((fe==null?void 0:fe.message)||String(fe))}},[n,H,(Ce=o==null?void 0:o.snapshot)==null?void 0:Ce.specPath,w,y,S,P,W]),O=o==null?void 0:o.snapshot,ie=async()=>{var ce,$,pe;let G=o;G||(await W(),G=o);const U=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: ${(U==null?void 0:U.spec_id)??""} (${(U==null?void 0:U.specPath)??""})`),Z.push(`Provider: ${(U==null?void 0:U.name)??""} (${(U==null?void 0:U.cliType)??""})`),Z.push(`Working dir: ${(U==null?void 0:U.workingDir)??""}`),Z.push(`Spawned: ${U!=null&&U.spawnedAtMs?new Date(U.spawnedAtMs).toISOString():""}`),Z.push(""),Z.push("## Current State"),Z.push(`State: ${((ce=U==null?void 0:U.current_state)==null?void 0:ce.id)??"none"} (${(($=U==null?void 0:U.current_state)==null?void 0:$.label)??""})`),Z.push(`Status: ${(U==null?void 0:U.status)??""}`),Z.push(`Idle hold pending: ${(U==null?void 0:U.idleHoldPending)??!1}`),Z.push(`Exited: ${(U==null?void 0:U.exited)??!1}`),Z.push(`Last busy: ${U!=null&&U.lastBusyAt?Hn(U.lastBusyAt):""}`),Z.push(`Cursor: ${(U==null?void 0:U.cursorPosition)!=null?`(${U.cursorPosition.row},${U.cursorPosition.col})`:"n/a"}`),(pe=U==null?void 0:U.completionIdleDebounce)!=null&&pe.active){const le=U.completionIdleDebounce;Z.push(`completion_idle_after: age=${le.ageMs}ms hold=${le.holdMs}ms force=${le.forceAfterMs}ms remaining=${Math.max(0,le.holdMs-le.ageMs)}ms`)}if(Z.push(""),Z.push("## Modal"),U!=null&&U.current_modal){const le=U.current_modal.buttons.map(F=>F.label).join(" / ");Z.push(`${U.current_modal.title??""} [${le}]`)}else Z.push("none");Z.push(""),Z.push("## State History (last 20)");const Y=U!=null&&U.stateHistory?[...U.stateHistory].reverse().slice(0,20):[];for(const le of Y){const F=le.reason!=null?typeof le.reason=="string"?le.reason:JSON.stringify(le.reason):"",be=le.debounceKind!=null?typeof le.debounceKind=="string"?le.debounceKind:JSON.stringify(le.debounceKind):"",je=le.matchedStateId!=null?String(le.matchedStateId):"",Se=(le.matchedRules??[]).map(He=>typeof He=="string"?He:JSON.stringify(He)).join(", ");Z.push(`- ${le.stateId} @ ${new Date(le.at).toISOString()} held ${le.durationMs}ms | reason: ${F} | debounce: ${be} | eval→${je} | rules: ${Se}`)}if(Z.push(""),Z.push("## Sections"),U!=null&&U.sections)for(const[le,F]of Object.entries(U.sections)){const be=F.split(`
50
+ `).slice(0,3).join(`
51
+ `);Z.push(`${le}: ${be}`)}Z.push(""),Z.push("## Last Assistant Message");const Te=[...(U==null?void 0:U.messages)??(U==null?void 0:U.committedMessages)??[]].reverse().find(le=>le.role==="assistant");Z.push(Te?Te.content.slice(0,400):""),Z.push(""),Z.push("## Screen (first 50 lines)"),Z.push(U!=null&&U.screen?U.screen.split(`
52
+ `).slice(0,50).join(`
53
+ `):"");try{await navigator.clipboard.writeText(Z.join(`
54
+ `)),C("Copied!"),setTimeout(()=>C("Snapshot"),1500)}catch(le){console.error("[SpecDebugPanel] clipboard write failed",le)}},z=G=>{f(U=>{const Z=new Set(U);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"}),O&&s.jsx("span",{className:"text-[11px] text-text-secondary font-mono bg-surface-secondary px-1.5 py-0.5 rounded truncate",children:O.spec_id})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[(O==null?void 0:O.specPath)&&s.jsx("button",{type:"button",className:`text-[11px] transition-colors px-2 py-1 rounded border ${h?"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:()=>{h?x(!1):re()},disabled:r,children:h?"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:()=>{ie()},disabled:r,children:g}),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:()=>{W()},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:"×"})]})]}),h&&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 ${S?"text-text-secondary hover:bg-bg-glass-hover":"bg-accent-primary/20 text-accent-primary"}`,onClick:()=>{if(S)try{const G=JSON.parse(w);b(G),J(G)}catch{return}k(!1)},disabled:!y&&S,children:"Form"}),s.jsx("button",{type:"button",className:`px-2 py-0.5 ${S?"bg-accent-primary/20 text-accent-primary":"text-text-secondary hover:bg-bg-glass-hover"}`,onClick:()=>{y&&v(JSON.stringify(y,null,2)),k(!0)},children:"JSON"})]}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate flex-1",title:O==null?void 0:O.specPath,children:((O==null?void 0:O.specPath)??"").split("/").slice(-3).join("/")}),N&&s.jsx("span",{className:"text-status-warning text-[10px]",children:"unsaved"}),!S&&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"||!S&&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:()=>{ne()},disabled:A==="saving"||!S&&P.length>0,children:A==="saving"?"Saving…":A==="saved"?"Saved ✓ (reloading)":"Save & Apply"})]}),D&&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:D}),!S&&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,U)=>s.jsx("div",{className:"font-mono",children:G},U))}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:S||!y?s.jsx("textarea",{value:w,onChange:G=>{v(G.target.value),j(!0),I("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(Pk,{model:y,onChange:V,onPreview:X,preview:q,onTestSections:de,sectionPreview:E})}),s.jsx("div",{className:"text-[10px] text-text-muted shrink-0",children:S?"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.'})]}),!h&&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&&!o&&s.jsx("div",{className:"text-text-muted text-center py-6",children:"Loading…"}),o&&!o.isSpecProvider&&s.jsxs("div",{className:"text-text-muted text-center py-6",children:["Not a spec-driven provider (",o.providerType||"unknown",")."]}),O&&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:[O.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:[O.name," ",s.jsxs("span",{className:"text-text-muted",children:["(",O.cliType,")"]})]})]}),O.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:O.workingDir,children:O.workingDir})]}),O.spawnedAtMs?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"Spawned"}),s.jsx("span",{className:"text-text-secondary",children:Hn(O.spawnedAtMs)})]}):null,O.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:O.providerSessionId,children:O.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 ${O.current_state?ro(O.current_state.id):"text-text-muted"}`,children:O.current_state?O.current_state.id:"none"}),((ye=O.current_state)==null?void 0:ye.label)&&O.current_state.label!==O.current_state.id&&s.jsx("span",{className:"text-text-secondary text-[11px]",children:O.current_state.label}),O.status&&O.status!==((ke=O.current_state)==null?void 0:ke.id)&&s.jsxs("span",{className:"text-text-muted text-[11px]",children:["engine: ",s.jsx("span",{className:`font-mono ${ro(O.status)} px-1 py-0.5 rounded text-[10px]`,children:O.status})]}),O.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"}),O.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"}),O.cursorPosition!=null&&s.jsxs("span",{className:"text-text-muted text-[11px] font-mono",children:["cursor: ",s.jsxs("span",{className:"text-text-secondary",children:[O.cursorPosition.row,",",O.cursorPosition.col]})]}),O.lastBusyAt>0&&s.jsxs("span",{className:"text-text-muted text-[11px] ml-auto",children:["last busy: ",s.jsx("span",{className:"text-text-secondary",children:Hn(O.lastBusyAt)})]})]}),((me=O.completionIdleDebounce)==null?void 0:me.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:[O.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:[O.completionIdleDebounce.holdMs,"ms"]})]}),s.jsxs("span",{className:"text-text-secondary",children:["force: ",s.jsxs("span",{className:"text-text-secondary",children:[O.completionIdleDebounce.forceAfterMs,"ms"]})]}),s.jsx("span",{className:"text-text-muted ml-auto",children:O.completionIdleDebounce.ageMs<O.completionIdleDebounce.holdMs?s.jsxs("span",{className:"text-status-warning",children:["hold remaining: ",O.completionIdleDebounce.holdMs-O.completionIdleDebounce.ageMs,"ms"]}):O.completionIdleDebounce.ageMs<O.completionIdleDebounce.forceAfterMs?s.jsxs("span",{className:"text-orange-300",children:["force in: ",O.completionIdleDebounce.forceAfterMs-O.completionIdleDebounce.ageMs,"ms"]}):s.jsx("span",{className:"text-status-error",children:"overdue"})})]}),O.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:O.current_modal.title||""}),O.current_modal.buttons.length>0&&s.jsxs("span",{className:"text-text-secondary ml-2",children:["[",O.current_modal.buttons.map(G=>G.label).join(" / "),"]"]})]}),O.fsm&&s.jsxs(s.Fragment,{children:[s.jsx(Ir,{}),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:O.fsm.currentState})," (held ",yc(O.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:R,onChange:G=>T(G.target.checked),className:"accent-[var(--accent-primary)]"}),"live"]})]}),s.jsxs("div",{className:"space-y-1",children:[O.fsm.transitions.length===0&&s.jsx("div",{className:"text-text-muted text-[11px] italic px-1",children:"no outgoing transitions (terminal state)"}),O.fsm.transitions.map((G,U)=>s.jsx(_k,{t:G},U))]})]})]}),s.jsx(Ir,{}),O.sections&&Object.keys(O.sections).length>0&&s.jsxs("div",{children:[s.jsx(Ar,{children:"Sections"}),s.jsx("div",{className:"space-y-1",children:Object.entries(O.sections).map(([G,U])=>{var Te;const Z=m.has(G),Y=U.split(`
55
+ `),fe=((Te=Y[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:()=>z(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:fe}),s.jsxs("span",{className:"ml-auto text-text-muted text-[10px] shrink-0",children:[Y.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:U||"(empty)"})]},G)})})]}),s.jsx(Ir,{}),O.stateHistory&&O.stateHistory.length>0&&s.jsxs("div",{children:[s.jsxs(Ar,{children:["State History (",O.stateHistory.length,")"]}),s.jsx("div",{className:"space-y-px",children:[...O.stateHistory].reverse().slice(0,20).map((G,U)=>s.jsxs("div",{className:"rounded px-2 py-1 hover:bg-bg-glass-hover transition-colors",children:[s.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[s.jsx("span",{className:`font-mono text-[11px] font-semibold px-1.5 py-0.5 rounded shrink-0 ${ro(G.stateId)}`,children:G.stateId}),s.jsx("span",{className:"text-text-secondary text-[11px] shrink-0 tabular-nums",children:Hn(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 ${Rk[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,Y)=>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)},Y)),G.matchedRules.length>3&&s.jsxs("span",{className:"text-[10px] text-text-muted",children:["+",G.matchedRules.length-3," more"]})]})]},U))})]}),s.jsx(Ir,{}),(()=>{const G=O.messages??O.committedMessages??[];if(G.length===0)return null;const U=G.filter(fe=>fe.role==="user").length,Z=G.filter(fe=>fe.role==="assistant").length,Y=[...G].reverse().find(fe=>fe.role==="assistant");return s.jsxs("div",{children:[s.jsxs(Ar,{children:["Transcript (",G.length," — ",U,"u / ",Z,"a)"]}),Y&&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 ",Y.receivedAt?Hn(Y.receivedAt):""]}),s.jsxs("div",{className:"text-text-secondary font-mono whitespace-pre-wrap line-clamp-4 break-all",children:[Y.content.slice(0,400),Y.content.length>400?"…":""]})]})]})})(),O.specPath&&s.jsx("div",{className:"text-[10px] text-text-muted font-mono truncate border-t border-border-default pt-2 mt-1",title:O.specPath,children:O.specPath}),s.jsxs("div",{children:[s.jsxs("button",{type:"button",className:"text-[11px] text-text-secondary hover:text-text-primary transition-colors flex items-center gap-1.5",onClick:()=>u(G=>!G),children:[s.jsx("span",{className:"text-text-muted",children:p?"▾":"▸"}),s.jsxs("span",{children:["Raw screen (",O.screen?O.screen.split(`
56
+ `).length:0," lines)"]})]}),p&&s.jsx("pre",{className:"mt-1.5 px-3 py-2 font-mono text-[11px] text-text-secondary whitespace-pre bg-bg-secondary rounded-md border border-border-default max-h-64 overflow-auto",children:O.screen||"(empty)"})]})]})]})]})})}function Hk({activeConv:e,clearToken:t=0,terminalRef:n,handleSendChat:r,isSendingChat:a=!1,sendFeedbackMessage:o=null,isVisible:i=!0,isInputActive:c=!0}){var et;const{t:d}=Ne("common");gs();const{sendPtyInput:p}=vt(),[u,m]=l.useState(!1),f=l.useRef(!1);f.current=u;const[g,C]=l.useState("Runtime terminal unavailable"),[h,x]=l.useState(!1),[y,b]=l.useState(null),[S,k]=l.useState(!1),[w,v]=l.useState(!1),[N,j]=l.useState(1),[A,I]=l.useState(!1),[D,L]=l.useState(!1),[P,_]=l.useState(!1),[q,B]=l.useState(!1),[E,K]=l.useState(!1),[R,T]=l.useState({width:0,height:0}),[H,M]=l.useState({width:0,height:0}),[W,J]=l.useState({scrollTop:0,scrollHeight:0,clientHeight:0,atTop:!1,canScroll:!1}),[re,V]=l.useState(null),X=l.useRef(null),de=l.useRef(null),ne=l.useRef(!1),O=l.useRef(!1),ie=l.useRef(i),z=l.useRef(0),ae=l.useRef(!1),Ce=l.useRef(""),ye=l.useRef(null),ke=l.useRef(!1),me=l.useRef(!1),G=l.useRef(null),U=l.useRef(null),Z=l.useRef(null),Y=32*1024,fe=()=>{var te,ge,we,ze;return((ge=(te=X.current)==null?void 0:te.ownerDocument)==null?void 0:ge.defaultView)||((ze=(we=de.current)==null?void 0:we.ownerDocument)==null?void 0:ze.defaultView)||window},Te=te=>{const ge=fe();return{ownerWindow:ge,frameId:ge.requestAnimationFrame(te)}},ce=()=>{const te=G.current;if(te){try{te.ownerWindow.cancelAnimationFrame(te.frameId)}catch{}G.current=null}},$=()=>{const te=U.current;if(te){try{te.ownerWindow.clearTimeout(te.timeoutId)}catch{}U.current=null}},pe=()=>{const te=Z.current;if(te){try{te.ownerWindow.clearTimeout(te.timeoutId)}catch{}Z.current=null}},le=()=>{i&&G.current===null&&(G.current=Te(()=>{Q()}))},F=e.tabKey,be=e.sessionId||"",je=e.daemonId||((et=e.routeId)==null?void 0:et.split(":")[0])||e.routeId||"",Se=Ui(e),He=u?o||Se:g,Xe=xk,dt=vk,it=.05,he=()=>{const te=H.width,ge=H.height;if(!Number.isFinite(R.width)||R.width<=0||!Number.isFinite(R.height)||R.height<=0||!Number.isFinite(te)||te<=0||!Number.isFinite(ge)||ge<=0)return 1;const we=R.width/te,ze=R.height/ge;return Number(Math.min(dt,Math.max(Xe,Math.min(we,ze))).toFixed(2))},$e=he(),Be=ne.current&&N>$e,Me=Number.isFinite(H.width)&&H.width>0?Math.max(R.width,Math.round(H.width*N)):R.width,ve=Number.isFinite(H.height)&&H.height>0?Math.max(R.height,Math.round(H.height*N)):R.height,We=()=>{Te(()=>{const te=de.current;te&&(te.scrollLeft=0,te.scrollTop=te.scrollHeight-te.clientHeight)})},ut=()=>{var te,ge;z.current=0,ae.current=!1,Ce.current="",ye.current=null,ke.current=!1,me.current=!1,ne.current||(O.current=!1,j(1)),G.current!==null&&ce(),m(!1),C("Runtime terminal unavailable"),pe(),$(),b(null),V(null),I(!1),x(!1),k(!1),v(!1),(ge=(te=n.current)==null?void 0:te.reset)==null||ge.call(te)},ot=()=>{var te,ge;z.current=0,ae.current=!1,Ce.current="",ye.current=null,ke.current=!1,me.current=!1,G.current!==null&&ce(),m(!0),C(""),pe(),$(),b(null),V(null),I(!1),x(!1),k(!1),v(!1),(ge=(te=n.current)==null?void 0:te.reset)==null||ge.call(te)},pt=()=>{me.current&&(me.current=!1,Te(()=>{var te,ge;(ge=(te=n.current)==null?void 0:te.scrollToTop)==null||ge.call(te)}))},Q=()=>{if(G.current=null,!i)return;const te=Ce.current;if(!te)return;const ge=te.slice(0,Y);Ce.current=te.slice(ge.length);const we=n.current;if(!we){Ce.current=ge+Ce.current,le();return}we.write(ge,()=>{if(Ce.current.length>0){le();return}pt()})},ee=te=>{te&&(Ce.current+=te,le())},oe=(te,ge=0,we,ze,Oe={})=>{var Ke,Ye,It,Ot;const tt=!!Oe.force;!tt&&ge>0&&z.current>=ge||!tt&&ge===0&&ae.current||(z.current=ge,ge>0&&k(!0),m(!0),C(""),typeof we=="number"&&typeof ze=="number"&&we>0&&ze>0&&((Ye=(Ke=n.current)==null?void 0:Ke.resize)==null||Ye.call(Ke,we,ze)),Ce.current="",(Ot=(It=n.current)==null?void 0:It.reset)==null||Ot.call(It),te?ee(te):pt())};l.useEffect(()=>{ut()},[be]),l.useEffect(()=>{var ge;if(!be)return;const te=((ge=kt.onRuntimeEvent)==null?void 0:ge.call(kt,be,we=>{if(!(!we||we.sessionId!==be)){if(we.type==="runtime_snapshot"){if(!i){ye.current={text:we.text||"",seq:we.seq||0,cols:we.cols,rows:we.rows,force:!!we.force};return}oe(we.text||"",we.seq||0,we.cols,we.rows,{force:!!we.force});return}if(we.type==="session_output"){ae.current=!0,typeof we.seq=="number"&&(z.current=Math.max(z.current,we.seq),we.seq>0&&k(!0)),f.current||m(!0),f.current||C(""),typeof we.data=="string"&&ee(we.data);return}if(we.type==="session_cleared"){if(!i){ke.current=!0,Ce.current="",ye.current=null;return}ot();return}if(we.type==="session_io_error"){const ze=typeof we.error=="string"&&we.error?we.error:typeof we.reason=="string"&&we.reason?we.reason:"unknown error";m(!1),C(`Runtime input failed: ${ze}`);return}}},je))||(()=>{});return()=>{te()}},[je,be,n,i]);const ue=async(te={})=>{var ge;if(!je||!be)return{success:!1,error:"daemonId and sessionId are required"};te.preserveStatus||C(te.loadingMessage||"Loading runtime terminal...");try{const we=await((ge=kt.requestRuntimeSnapshot)==null?void 0:ge.call(kt,je,be,{sinceSeq:te.sinceSeq,force:te.force}));return we&&we.success===!1?(te.preserveStatus||(m(!1),C(`Runtime terminal unavailable: ${we.error}`)),we):we||{success:!0}}catch(we){const ze=(we==null?void 0:we.message)||String(we);return te.preserveStatus||(m(!1),C(`Runtime terminal unavailable: ${ze}`)),{success:!1,error:ze}}},xe=async te=>{var tt,Ke;const ge=((tt=X.current)==null?void 0:tt.ownerDocument)||document,we=ge.defaultView||window,ze=(Ke=we.navigator)==null?void 0:Ke.clipboard;if(ze!=null&&ze.writeText&&we.isSecureContext)try{return await ze.writeText(te),!0}catch{}let Oe=null;try{return Oe=ge.createElement("textarea"),Oe.value=te,Oe.setAttribute("readonly","true"),Oe.style.position="fixed",Oe.style.left="-9999px",Oe.style.top="0",ge.body.appendChild(Oe),Oe.focus(),Oe.select(),ge.execCommand("copy")}catch{return!1}finally{Oe==null||Oe.remove()}},Ie=te=>{$(),V(te);const ge=fe();U.current={ownerWindow:ge,timeoutId:ge.setTimeout(()=>{U.current=null,V(we=>we===te?null:we)},2200)}},Le=te=>{pe(),b(te);const ge=fe();Z.current={ownerWindow:ge,timeoutId:ge.setTimeout(()=>{Z.current=null,b(we=>we===te?null:we)},2200)}},Ae=async()=>{var Oe,tt,Ke,Ye;const te=((tt=(Oe=n.current)==null?void 0:Oe.getSelection)==null?void 0:tt.call(Oe))||"",ge=((Ye=(Ke=n.current)==null?void 0:Ke.getVisibleText)==null?void 0:Ye.call(Ke))||"",we=te.trimEnd()||ge.trimEnd();if(!we){Ie("Nothing to copy");return}if(!await xe(we)){Ie("Copy failed");return}Ie(te.trimEnd()?"Copied selection":"Copied visible terminal")},Fe=te=>{if(!u||!i)return;((p==null?void 0:p(je,be,te))??!1)||Ie("Terminal input failed")},qe=te=>{Fe(wk({ctrl:D,alt:P,shift:q},te)),L(!1),_(!1),B(!1)},Ze=async()=>{if(h)return;x(!0),b("Loading older terminal output..."),me.current=!0;const te=await ue({sinceSeq:0,force:!0,loadingMessage:"Loading older terminal output...",preserveStatus:u});if(x(!1),(te==null?void 0:te.success)===!1){me.current=!1,b(`Older terminal output unavailable: ${te.error}`);return}v(!0),Le("Older terminal output loaded"),Te(()=>{var ge;(ge=n.current)==null||ge.bumpResize()})};l.useEffect(()=>{var ge,we;if(!be)return;je&&((ge=kt.getState)==null?void 0:ge.call(kt,je))==="connected"&&ue();const te=(we=kt.onStateChange)==null?void 0:we.call(kt,(ze,Oe)=>{ze!==je||Oe!=="connected"||ue()});return()=>{te==null||te()}},[je,be,n]),l.useEffect(()=>{t&&ut()},[t,F,n]),l.useEffect(()=>{var ze,Oe;const te=X.current,ge=(Oe=(ze=te==null?void 0:te.ownerDocument)==null?void 0:ze.defaultView)==null?void 0:Oe.ResizeObserver;if(!te||!ge)return;const we=new ge(tt=>{const Ke=tt[0];if(!Ke)return;const{width:Ye,height:It}=Ke.contentRect;T(Ot=>{const ss=Math.round(Ye),De=Math.round(It);return Ot.width===ss&&Ot.height===De?Ot:{width:ss,height:De}})});return we.observe(te),()=>we.disconnect()},[]),l.useEffect(()=>{if(ne.current)return;const te=he();!Number.isFinite(te)||te<=0||j(ge=>O.current?te<ge-it?te:ge:(O.current=!0,te))},[H.height,H.width,R.height,R.width]),l.useEffect(()=>{Be&&We()},[Be,ve,Me]),l.useEffect(()=>{var we;const te=ie.current;if(ie.current=i,!i)return;te||v(!1),ke.current&&(ke.current=!1,ot());const ge=ye.current;ge&&(ye.current=null,oe(ge.text,ge.seq,ge.cols,ge.rows,{force:!!ge.force})),je&&be&&((we=kt.getState)==null?void 0:we.call(kt,je))==="connected"&&ue(),Ce.current&&G.current===null&&le(),Te(()=>{var ze;(ze=n.current)==null||ze.bumpResize()})},[je,i,be]),l.useEffect(()=>()=>{G.current!==null&&ce(),$(),pe()},[]),l.useEffect(()=>{const te=ze=>{var tt;const Oe=ze.detail;Oe!=null&&Oe.sessionId&&Oe.sessionId!==be||u&&((tt=n.current)==null||tt.bumpResize())},ge=fe(),we=ge===window?[window]:[window,ge];for(const ze of we)ze.addEventListener("adhdev:fit-cli-terminal",te);return()=>{for(const ze of we)ze.removeEventListener("adhdev:fit-cli-terminal",te)}},[u,be,n]);const Ue=u&&S&&!w&&(W.atTop||!W.canScroll)||h||!!y;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:!be||h,title:"Replay raw session scrollback so the terminal viewport can scroll farther up",children:d(h?"terminal.loadingOlder":"terminal.loadOlderOutput")}),y&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:y})]}),s.jsxs("div",{className:"absolute right-3 top-3 z-10 flex items-center gap-1.5",children:[re&&s.jsx("span",{className:"rounded-full border border-white/10 bg-black/35 px-2 py-1 text-[10px] text-white/70 backdrop-blur-sm",children:re}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>K(te=>!te),title:"Spec debug — inspect current state, sections, and transition history",children:d("terminal.debug")}),s.jsx("button",{type:"button",className:"h-8 rounded-full border border-white/10 bg-black/35 px-3 text-[11px] font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55 disabled:cursor-not-allowed disabled:opacity-60",onClick:()=>{Ae()},disabled:!u,title:"Copy selected terminal text, or the visible terminal viewport if nothing is selected",children:d("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:()=>I(te=>!te),disabled:!u,"aria-label":d(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":d("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:()=>I(!1),"aria-label":d("terminal.closeControlKeys"),children:"×"})]}),s.jsx("div",{className:"mb-2 grid grid-cols-3 gap-1.5",children:[["Ctrl",D,L],["Alt",P,_],["Shift",q,B]].map(([te,ge,we])=>s.jsx("button",{type:"button","aria-pressed":ge,className:`h-9 rounded-lg border text-[12px] font-semibold transition-colors ${ge?"border-sky-400/50 bg-sky-400/25 text-white":"border-white/10 bg-white/[0.06] hover:bg-white/[0.12]"}`,onClick:()=>we(ze=>!ze),children:te},te))}),s.jsx("div",{className:"my-2 h-px bg-white/10"}),s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>qe("Escape"),children:"Esc"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>qe("Tab"),children:"Tab"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>qe("Enter"),children:"Enter"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>qe("ArrowUp"),"aria-label":"Arrow up",children:"↑"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>qe("ArrowLeft"),"aria-label":"Arrow left",children:"←"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>qe("ArrowDown"),"aria-label":"Arrow down",children:"↓"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[15px] font-semibold hover:bg-white/[0.12]",onClick:()=>qe("ArrowRight"),"aria-label":"Arrow right",children:"→"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>Fe(""),title:"Send SIGINT (Ctrl-C)",children:"Ctrl-C"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>qe("Space"),children:"Space"}),s.jsx("button",{type:"button",className:"h-9 rounded-lg border border-white/10 bg-white/[0.06] text-[12px] font-semibold hover:bg-white/[0.12]",onClick:()=>qe("Backspace"),children:"Bksp"})]})]})]}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{ne.current=!0,j(te=>{const ge=Math.max($e,Number((te-.1).toFixed(2)));return ge>$e&&We(),ge})},title:"Shrink terminal viewport",children:"-"}),s.jsx("button",{type:"button",className:"h-8 w-8 rounded-full border border-white/10 bg-black/35 text-sm font-semibold text-white/85 backdrop-blur-sm transition-colors hover:bg-black/55",onClick:()=>{ne.current=!0,j(te=>{const ge=Math.min(dt,Number((te+.1).toFixed(2)));return ge>$e&&We(),ge})},title:"Increase terminal viewport",children:"+"})]}),s.jsx("div",{ref:de,className:Be?"w-full h-full overflow-auto rounded-lg overscroll-contain":"w-full h-full overflow-hidden rounded-lg overscroll-contain",children:s.jsx("div",{style:{width:Me>0?`${Me}px`:"100%",height:ve>0?`${ve}px`:"100%",minWidth:"100%",minHeight:"100%",position:"relative"},children:s.jsx("div",{style:{width:H.width>0?`${H.width}px`:"100%",height:H.height>0?`${H.height}px`:"100%",position:"absolute",left:0,bottom:0,zoom:N},children:s.jsx(iu,{ref:n,readOnly:!u||!i,sizingMode:"measured",onViewportMetrics:M,onScrollMetrics:J,onInput:te=>{!u||(p==null||p(je,be,te))}})})})}),!u&&s.jsx("div",{className:"absolute inset-x-2 top-2 rounded-md border border-red-500/30 bg-red-500/10 px-3 py-2 text-[11px] text-red-300 pointer-events-none",children:g})]}),s.jsx(Au,{contextKey:e.tabKey,panelLabel:xt(e),isSending:a,isBusy:!!Se,statusMessage:He,inlineStatusMessage:He,onSend:async te=>Se?!1:r(te),isActive:c&&i,showControlsToggle:!1,animateVisibility:!1}),E&&s.jsx($k,{activeConv:e,onClose:()=>K(!1)})]})}const Bk=5e3,Fk=12e3;function Ok(e){return e==="disconnected"||e==="reconnecting"}function Wk({wsStatus:e,showReconnected:t,loginUrl:n,onReconnect:r,reconnectDelayMs:a=Bk,reconnectActionDelayMs:o=Fk}){const{t:i}=Ne(),c=Ok(e),[d,p]=l.useState(()=>!c||a<=0),[u,m]=l.useState(()=>!c||o<=0),f=l.useRef(!1);l.useEffect(()=>{if(!c){p(!1);return}if(f.current=!1,a<=0){f.current=!0,p(!0);return}p(!1);const v=setTimeout(()=>{f.current=!0,p(!0)},a);return()=>clearTimeout(v)},[a,c]),l.useEffect(()=>{if(!c){m(!1);return}if(o<=0){m(!0);return}m(!1);const v=setTimeout(()=>{m(!0)},o);return()=>clearTimeout(v)},[o,c]);const g=c?d:e==="offline"||e==="auth_failed",C=!!(r&&e!=="auth_failed"&&(!c||u)),h=l.useMemo(()=>!t||e!=="connected"?!1:a<=0||f.current,[a,t,e]),x=e==="auth_failed"?"red":e==="offline"?"orange":"accent",y={red:"linear-gradient(90deg, rgba(239,68,68,0.12), rgba(239,68,68,0.04))",orange:"linear-gradient(90deg, rgba(255,107,53,0.12), rgba(255,107,53,0.04))",accent:"linear-gradient(90deg, color-mix(in srgb, var(--accent-primary) 18%, transparent), color-mix(in srgb, var(--accent-primary) 6%, transparent))"},b={red:"1px solid rgba(239,68,68,0.2)",orange:"1px solid rgba(255,107,53,0.2)",accent:"1px solid color-mix(in srgb, var(--accent-primary) 28%, transparent)"},S={red:"#ef4444",orange:"#ff6b35",accent:"var(--accent-primary-light)"},k="fixed left-1/2 top-4 z-[var(--z-toast)] flex items-center justify-center pointer-events-none",w={top:"calc(env(safe-area-inset-top, 0px) + 16px)",transform:"translateX(-50%)"};return s.jsxs(s.Fragment,{children:[g&&s.jsx("div",{className:k,style:w,children:s.jsxs("div",{className:"pointer-events-auto max-w-[min(720px,calc(100vw-24px))] rounded-2xl border px-3 py-2.5 sm:px-4 sm:py-3 text-[13px] font-semibold flex flex-wrap items-center gap-x-2.5 gap-y-2 justify-center shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:y[x],border:b[x],color:S[x]},children:[s.jsx("img",{src:"/otter-logo.png",alt:"",className:"w-5 h-5 shrink-0",style:{opacity:e==="auth_failed"?.6:1,animation:e==="auth_failed"?void 0:"pulse 2s ease-in-out infinite",filter:e==="auth_failed"?"grayscale(1)":void 0}}),s.jsxs("span",{className:"min-w-0 text-center whitespace-nowrap",children:[e==="offline"&&i("connection.networkOffline"),e==="disconnected"&&i("connection.reconnecting"),e==="reconnecting"&&i("connection.reconnecting"),e==="auth_failed"&&(n?s.jsxs(s.Fragment,{children:[i("connection.sessionExpired")," ",s.jsx("a",{href:n,className:"text-inherit underline",children:i("connection.logInAgain")})]}):i("connection.connectionFailed"))]}),C&&s.jsx("button",{type:"button",className:"basis-full sm:basis-auto mx-auto sm:mx-0 sm:ml-1 shrink-0 px-2.5 py-1 rounded-md border border-current/30 text-[12px] font-semibold hover:bg-white/5 disabled:opacity-50 disabled:cursor-not-allowed",onClick:()=>r==null?void 0:r(),disabled:e==="offline",children:i("connection.reconnectNow")})]})}),h&&s.jsx("div",{className:k,style:w,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 pp({mode:e,onChange:t,compact:n=!1}){const{t:r}=Ne("common"),a=n?14:15;return s.jsx("button",{type:"button",onClick:()=>t(e==="chat"?"terminal":"chat"),className:"btn btn-sm btn-secondary",title:r(e==="chat"?"cliView.switchToTerminal":"cliView.switchToChat"),children:e==="chat"?s.jsx(Mi,{size:a}):s.jsx(Zs,{size:a})})}const Hs="New session",Uk="A connected machine is ready. Start a new session with any installed provider — CLI, ACP, or IDE.";function Gk(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 qk(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 zk(e){switch(e){case"conflict":return"border-status-error/40 bg-status-error/10 text-status-error";case"error":return"border-yellow-500/25 bg-yellow-500/[0.08] text-yellow-500";case"dirty":return"border-orange-500/25 bg-orange-500/[0.08] text-orange-400";case"quiet":default:return"border-status-online/40 bg-status-online/10 text-status-online"}}function ca({git:e,className:t="",compact:n=!1}){const r=Gk(e),a=qk(e);if(!r||!a)return null;const o=[e!=null&&e.branch?`Branch: ${e.branch}`:null,e!=null&&e.changedFiles?`Changed files: ${e.changedFiles}`:null,e!=null&&e.ahead?`Ahead: ${e.ahead}`:null,e!=null&&e.behind?`Behind: ${e.behind}`:null,e!=null&&e.hasConflicts?"Conflicts detected":null,e!=null&&e.error?`Git error: ${e.error}`:null].filter(Boolean);return s.jsxs("span",{className:`inline-flex min-w-0 max-w-[12rem] items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-semibold leading-none ${zk(a)} ${t}`.trim(),title:o.join(" · ")||r,"data-git-tone":a,children:[s.jsx("span",{"aria-hidden":"true",children:"⑂"}),s.jsx("span",{className:"truncate",children:r})]})}function Kk({wsStatus:e,isConnected:t,daemonCount:n,p2pStates:r={}}){if(e!=="connected")return{tone:"disconnected",titleKey:"connection.disconnected",subtitleKey:null};const a=Object.values(r),o=a.filter(c=>c==="connected").length,i=a.filter(c=>c==="connecting"||c==="new"||c==="checking").length;return n>0&&i>0&&o===0?{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:"connection.connectingToMachine"}:t?{tone:"connected",titleKey:"connection.connected",subtitleKey:null}:{tone:"limited",titleKey:"connection.connectedToDashboard",subtitleKey:null}}function wc({value:e}){return e?s.jsx("span",{className:"dashboard-header-shortcut-pill",children:e}):null}function kc({notification:e,shortcutIndex:t,onOpen:n,onMarkRead:r,onMarkUnread:a,onDelete:o}){const{t:i}=Ne(),c=Ca(e.updatedAt),d=!e.readAt;return s.jsxs("div",{className:`dashboard-header-inbox-item ${d?"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:[d?s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),r()},children:i("notification.markRead")}):s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),a()},children:i("notification.markUnread")}),s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:p=>{p.stopPropagation(),o()},children:i("notification.delete")})]})]})}function Vk({activeConv:e,wsStatus:t,isConnected:n,conversations:r,onOpenHistory:a,onOpenRemote:o,onStopCli:i,activeCliViewMode:c,onSetCliViewMode:d,onHideConversation:p,hiddenConversations:u=[],onShowConversation:m,onShowAllHidden:f,onResetPanelsToMain:g,inboxOpen:C,onInboxOpenChange:h,hiddenOpen:x,onHiddenOpenChange:y,onOpenNewSession:b,onOpenDashboardGuide:S,guideNudgeVisible:k=!1,actionShortcuts:w,notifications:v,notificationUnreadCount:N,onOpenNotification:j,onMarkNotificationRead:A,onMarkNotificationUnread:I,onDeleteNotification:D,onOpenGitDialog:L,onOpenMeshGraph:P}){var Z;const{t:_}=Ne(),{ides:q,p2pStates:B={}}=gs(),E=!!e&&ct(e)&&!lt(e),K=!!e&&lt(e),R=!!(e!=null&&e.daemonId)&&!!((Z=e==null?void 0:e.coordinator)!=null&&Z.meshId),T=c||(e?Eu(e)?"terminal":"chat":null),[H,M]=l.useState(!1),[W,J]=l.useState(!1),re=l.useRef(null),V=l.useRef(null),X=l.useRef(null),de=q.filter(Y=>Y.type==="adhdev-daemon"),ne=Kk({wsStatus:t,isConnected:n,daemonCount:de.length,p2pStates:B}),O=_(ne.titleKey),ie=ne.subtitleKey?_(ne.subtitleKey):null,z=ne.tone==="connected"?"#22c55e":ne.tone==="limited"?"#eab308":"#ef4444",ae=ne.tone==="connected"?"0 0 4px #22c55e80":ne.tone==="limited"?"0 0 4px #eab30880":"0 0 4px #ef444480",Ce=l.useMemo(()=>v.filter(Y=>!Y.readAt),[v]),ye=l.useMemo(()=>v.filter(Y=>!!Y.readAt),[v]),ke=l.useMemo(()=>Ce.slice(0,9),[Ce]),me=N;l.useEffect(()=>{if(!C)return;const Y=fe=>{var Te;(Te=V.current)!=null&&Te.contains(fe.target)||h(!1)};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[C,h]),l.useEffect(()=>{if(!x)return;const Y=fe=>{var Te;(Te=X.current)!=null&&Te.contains(fe.target)||y(!1)};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[x,y]),l.useEffect(()=>{if(!x&&!C)return;const Y=fe=>{if(!fe.altKey)return;const Te=fe.code.match(/^Digit([1-9])$/);if(!Te)return;const ce=Number(Te[1])-1,$=x?u[ce]:void 0,pe=C?ke[ce]:void 0;if(!(!$&&!pe)){if(fe.preventDefault(),fe.stopPropagation(),$){m==null||m($),y(!1);return}pe&&(j(pe),h(!1))}};return window.addEventListener("keydown",Y,!0),()=>window.removeEventListener("keydown",Y,!0)},[u,x,C,ke,y,h,j,m]),l.useEffect(()=>{const Y=u.length;if(re.current===null){re.current=Y;return}Y>re.current&&J(!0),re.current=Y},[u.length]);const G=()=>J(!1),U=Y=>{if(!Y)return;const fe=r.find(Te=>Te.tabKey===Y);fe&&(p==null||p(fe))};return s.jsxs("div",{className:"dashboard-header",children:[s.jsx("div",{className:"flex items-center gap-3",children:s.jsx("div",{className:"header-title-block",children:s.jsxs("div",{className:"header-title-row",children:[s.jsxs("h1",{className:"header-title m-0 flex items-center gap-1.5",children:[s.jsx(Zs,{size:18}),s.jsx("span",{className:"header-title-desktop",children:_("dashboard.header.title")}),s.jsx("span",{className:"header-title-mobile",children:e?xt(e):_("dashboard.header.title")}),s.jsx("span",{title:O,"aria-label":O,className:"header-title-status-dot",style:{background:z,boxShadow:ae}}),s.jsx("span",{className:"header-count-mobile text-[10px] font-semibold opacity-60 ml-2 tracking-wide",children:s.jsx("span",{className:"inline-block w-[6px] h-[6px] rounded-full align-middle",style:{background:z,boxShadow:ae}})})]}),s.jsxs("div",{className:"header-subtitle flex items-center",children:[ie&&s.jsxs("span",{className:"header-subtitle-status mr-2",children:["· ",ie]}),b&&s.jsx("button",{type:"button",onClick:b,className:"btn btn-secondary btn-sm ml-2",title:`${Hs}${w!=null&&w.openNewSession?` (${w.openNewSession})`:""}`,"aria-label":Hs,children:s.jsx(Di,{size:14})})]})]})})}),s.jsxs("div",{className:"flex gap-2 items-center",children:[S&&s.jsxs("button",{type:"button",onClick:S,className:"btn btn-secondary btn-sm hidden md:inline-flex items-center gap-1.5 dashboard-header-guide-button",title:_("dashboard.header.guide"),"aria-label":_("dashboard.header.guideOpen"),children:[s.jsx("span",{className:"font-semibold leading-none",children:"?"}),k&&s.jsx("span",{children:_("dashboard.header.guideShort")})]}),e&&(E||K||!lt(e))&&s.jsxs("div",{className:"dashboard-header-actions-group",children:[s.jsx("span",{className:"dashboard-header-action-target",title:yn(e)||xt(e),children:xt(e)}),L&&e.git&&e.daemonId&&e.workspacePath?s.jsx("button",{type:"button",className:"appearance-none bg-transparent border-0 p-0 cursor-pointer",title:_("dashboard.header.openGitStatus"),onClick:()=>L(e.daemonId,e.workspacePath),children:s.jsx(ca,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"})}):s.jsx(ca,{git:e.git,compact:!0,className:"max-w-[8rem] shrink-0"}),R&&P&&s.jsxs("button",{type:"button",onClick:()=>P(e),className:"btn btn-secondary btn-sm dashboard-header-mesh-button",title:_("dashboard.header.openMeshGraph"),children:[s.jsx(es,{size:14}),s.jsx("span",{className:"hidden lg:inline",children:_("dashboard.header.meshGraph")})]}),(E||K)&&i&&s.jsxs(s.Fragment,{children:[E&&d&&T&&s.jsx(pp,{mode:T,onChange:d,compact:!0}),s.jsx("button",{onClick:()=>i(e),className:"btn btn-secondary btn-sm",title:_(K?"dashboard.header.stopAcpSession":"dashboard.header.stopCliProcess"),style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(At,{size:14})})]}),!lt(e)&&s.jsx("button",{onClick:()=>a(e),className:"btn btn-secondary btn-sm",title:_("dashboard.header.chatHistory"),children:s.jsx(Ii,{size:14})}),!E&&!lt(e)&&s.jsx("button",{onClick:o,className:"btn btn-secondary btn-sm",title:_("dashboard.header.remoteControl"),children:s.jsx(us,{size:14})})]}),s.jsxs("div",{className:"dashboard-header-inbox",ref:V,children:[s.jsxs("div",{className:`dashboard-header-hidden${H?" is-drop-target":""}${W?" hidden-spawn-flash":""}`,onAnimationEnd:G,ref:X,onDragEnter:Y=>{Y.dataTransfer.types.includes("text/tab-key")&&(Y.preventDefault(),M(!0))},onDragOver:Y=>{Y.dataTransfer.types.includes("text/tab-key")&&(Y.preventDefault(),Y.dataTransfer.dropEffect="move",M(!0))},onDragLeave:Y=>{Y.currentTarget.contains(Y.relatedTarget)||M(!1)},onDrop:Y=>{const fe=Y.dataTransfer.getData("text/tab-key");Y.preventDefault(),M(!1),U(fe)},children:[s.jsxs("button",{type:"button",onClick:()=>y(!x),className:"btn btn-secondary btn-sm dashboard-header-hidden-button",title:`${_("dashboard.hidden.title")}${w!=null&&w.toggleHiddenTabs?` (${w.toggleHiddenTabs})`:""}. ${_("dashboard.hidden.dragHint")}`,children:[s.jsx(Ti,{size:16}),u.length>0&&s.jsx("span",{className:`dashboard-header-hidden-badge${W?" hidden-badge-pop":""}`,children:u.length})]}),x&&s.jsxs("div",{className:"dashboard-header-hidden-popover",children:[s.jsxs("div",{className:"dashboard-header-hidden-topbar",children:[s.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title mb-0",children:_("dashboard.hidden.title")}),s.jsx(wc,{value:w==null?void 0:w.toggleHiddenTabs})]}),s.jsxs("div",{className:"dashboard-header-hidden-actions",children:[g&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-secondary",onClick:g,children:_("dashboard.hidden.resetPanels")}),u.length>0&&f&&s.jsx("button",{type:"button",className:"dashboard-header-hidden-restore-all",onClick:()=>{f(),y(!1)},children:_("dashboard.hidden.restoreAll")})]})]}),e&&p&&s.jsxs("button",{type:"button",className:"dashboard-header-hidden-current",onClick:()=>p(e),children:[s.jsxs("span",{className:"dashboard-header-hidden-current-leading",children:[s.jsx("span",{className:"dashboard-header-hidden-current-label",children:_("dashboard.hidden.hideCurrentTab")}),s.jsx(wc,{value:w==null?void 0:w.hideCurrentTab})]}),s.jsx("span",{className:"dashboard-header-hidden-current-title",children:xt(e)})]}),u.length>0?s.jsx("div",{className:"dashboard-header-hidden-list",children:u.map(Y=>s.jsxs("button",{type:"button",className:"dashboard-header-inbox-item",onClick:()=>{m==null||m(Y),y(!1)},children:[s.jsxs("span",{className:"dashboard-header-inbox-item-title",children:[Y.status==="generating"&&s.jsx("span",{className:"tab-spinner dashboard-header-inbox-item-spinner","aria-label":_("dashboard.header.generating")}),xt(Y)]}),s.jsxs("span",{className:"dashboard-header-inbox-item-meta",children:[u.indexOf(Y)<9?s.jsxs("span",{className:"dashboard-header-item-shortcut",children:["⌥",u.indexOf(Y)+1]}):null,yn(Y)]})]},Y.tabKey))}):s.jsx("div",{className:"dashboard-header-inbox-empty",children:_("dashboard.hidden.empty")})]})]}),s.jsxs("button",{type:"button",onClick:()=>h(!C),className:"btn btn-secondary btn-sm dashboard-header-inbox-button",title:_("dashboard.header.activityInbox"),children:[s.jsx(Nn,{size:16}),me>0&&s.jsx("span",{className:"dashboard-header-inbox-badge",children:me})]}),C&&s.jsxs("div",{className:"dashboard-header-inbox-popover",children:[Ce.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:_("dashboard.inbox.unread")}),Ce.map(Y=>s.jsx(kc,{notification:Y,shortcutIndex:ke.indexOf(Y)>=0?ke.indexOf(Y)+1:void 0,onOpen:()=>j(Y),onMarkRead:()=>A(Y.id),onMarkUnread:()=>I(Y.id),onDelete:()=>D(Y.id)},Y.id))]}),ye.length>0&&s.jsxs("div",{className:"dashboard-header-inbox-section",children:[s.jsx("div",{className:"dashboard-header-inbox-section-title",children:_("dashboard.inbox.read")}),ye.map(Y=>s.jsx(kc,{notification:Y,onOpen:()=>j(Y),onMarkRead:()=>A(Y.id),onMarkUnread:()=>I(Y.id),onDelete:()=>D(Y.id)},Y.id))]}),v.length===0&&s.jsx("div",{className:"dashboard-header-inbox-empty",children:_("dashboard.inbox.empty")})]})]})]})]})}function Bt(e={}){return{textQuery:e.textQuery||"",workspaceQuery:e.workspaceQuery||"",modelQuery:e.modelQuery||"",resumableOnly:!!e.resumableOnly,sortMode:e.sortMode||"recent"}}function Yk(e,t){return String(e||"")!==String(t||"")}function Jk(e,t={}){const n=String(t.textQuery||"").trim().toLowerCase(),r=String(t.workspaceQuery||"").trim().toLowerCase(),a=String(t.modelQuery||"").trim().toLowerCase(),o=!!t.resumableOnly;return!n&&!r&&!a&&!o?e:e.filter(i=>!(o&&!i.canResume||n&&![i.title,i.preview].map(d=>String(d||"").toLowerCase()).join(`
57
+ `).includes(n)||r&&!String(i.workspace||"").toLowerCase().includes(r)||a&&!wu(i.summaryMetadata).map(d=>d.toLowerCase()).join(`
58
+ `).includes(a)))}function Qk(e,t="recent"){const n=e.slice();return n.sort((r,a)=>{if(t==="oldest")return(Number(r.lastMessageAt)||0)-(Number(a.lastMessageAt)||0);if(t==="messages"){const o=(Number(a.messageCount)||0)-(Number(r.messageCount)||0);if(o!==0)return o}return(Number(a.lastMessageAt)||0)-(Number(r.lastMessageAt)||0)}),n}function mp(e,t={}){return Qk(Jk(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 hp(e,t){return typeof e=="function"?e(t??!1?"launch.resumingSavedHistory":"launch.startingFresh"):e?"Resuming saved history…":"Starting fresh…"}function Xk(e){return e?e("launch.startFresh"):"Start fresh"}function Zk(e){return e?e("launch.hostedRuntimeRecoveryDescription"):"Fallback recovery for hosted runtimes after interruptions. For normal continuity, open saved history instead."}function eS(e){return e?e("launch.openSavedHistory"):"Open saved history"}function tS(e){return e?e("launch.savedHistoryTitle"):"Saved History"}function Ki(e){return e?e("launch.savedHistoryHelper"):"Use saved history when you want continuity in the same provider conversation."}function sS(e){return e?e("launch.savedHistoryEmpty"):"No saved history found yet."}function nS(e){return e?e("launch.refreshSavedHistory"):"Refresh saved history"}function rS(e){return e?e("launch.refreshingSavedHistory"):"Refreshing saved history…"}function da(e,t,n){if(typeof e=="function"){const o=t,i=n;return o==="start-fresh"?e("launch.startFreshWith",{label:i}):e("launch.restart",{label:i})}const r=e,a=t;return r==="start-fresh"?`Start fresh with ${a}?`:`Restart ${a}?`}function ua(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 pa(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartFresh":"launch.confirmRestart"):e==="start-fresh"?"Start fresh":"Restart"}function ma(e,t){return typeof e=="function"?e(t==="start-fresh"?"launch.confirmStartingFresh":"launch.confirmRestarting"):e==="start-fresh"?"Starting fresh…":"Restarting…"}function fp(e,t){return typeof e=="function"?e("launch.resumeWith",{label:t}):`Resume saved history with ${e}?`}function bp(e){return e?e("launch.resumeReview"):"Review or change the target workspace before resuming saved history."}function aS(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 gp({activeConv:e,ides:t,isCreatingChat:n,isRefreshingHistory:r,savedSessions:a=[],isSavedSessionsLoading:o=!1,isResumingSavedSessionId:i=null,savedHistoryFilters:c,missingWorkspaceResumePath:d,onSavedHistoryFiltersChange:p,onClose:u,onNewChat:m,onSwitchSession:f,onRefreshHistory:g,onResumeSavedSession:C}){var L;const{t:h}=Ne("common"),x=t.find(P=>P.id===e.routeId),y=(x==null?void 0:x.chats)||[],b=(L=x==null?void 0:x.activeChat)==null?void 0:L.id,S=ct(e)&&!lt(e),[k,w]=l.useState(()=>Bt()),v=c||k,N=String(d||"").trim(),j=P=>{if(p){p(P);return}w(P)},A=l.useMemo(()=>a.map(P=>{const _=String(P.workspace||"").trim();return P.canResume||_||!N?P:{...P,workspace:N,canResume:!0,workspaceFallbackSource:"selected-workspace"}}),[N,a]),I=l.useMemo(()=>mp(A,{textQuery:v.textQuery,workspaceQuery:v.workspaceQuery,modelQuery:v.modelQuery,resumableOnly:v.resumableOnly,sortMode:v.sortMode}),[A,v.modelQuery,v.resumableOnly,v.sortMode,v.textQuery,v.workspaceQuery]),D=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:u,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{className:"card fade-in relative w-full sm:w-[90%] max-w-[500px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[80vh] flex flex-col p-0 overflow-hidden shadow-[0_20px_40px_rgba(0,0,0,0.4)] rounded-[24px] sm:rounded-[20px]",children:[s.jsxs("div",{className:"px-4 py-4 sm:px-6 sm:py-5 border-b border-border-subtle flex justify-between items-center bg-[var(--surface-primary)] shrink-0",children:[s.jsxs("div",{children:[s.jsx("h3",{className:"m-0 text-lg font-extrabold",children:S?tS(h):h("historyModal.chatHistory")}),s.jsx("div",{className:"text-xs text-text-muted mt-0.5",children:Nk(e)}),S&&s.jsx("div",{className:"text-[11px] text-text-muted mt-1",children:Ki(h)})]}),s.jsx("button",{onClick:u,className:"btn btn-secondary btn-sm rounded-md px-1.5 py-1.5 border-transparent bg-transparent hover:bg-bg-secondary",children:s.jsx(At,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto p-3 bg-bg-primary",children:[!S&&s.jsx("button",{onClick:m,disabled:n,className:"w-full p-3.5 rounded-xl mb-3 bg-indigo-500/10 border border-dashed border-accent text-accent font-bold text-sm cursor-pointer",children:h(n?"historyModal.creating":"historyModal.startNewChat")}),S?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-[var(--surface-secondary)] p-3 mb-3",children:[s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-2",children:[s.jsx("input",{type:"text",value:v.textQuery,onChange:P=>j({...v,textQuery:P.target.value}),placeholder:h("historyModal.searchPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:v.workspaceQuery,onChange:P=>j({...v,workspaceQuery:P.target.value}),placeholder:h("historyModal.filterWorkspace"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("input",{type:"text",value:v.modelQuery,onChange:P=>j({...v,modelQuery:P.target.value}),placeholder:h("historyModal.filterModel"),className:"w-full rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsxs("select",{value:v.sortMode,onChange:P=>j({...v,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:h("historyModal.sortRecent")}),s.jsx("option",{value:"oldest",children:h("historyModal.sortOldest")}),s.jsx("option",{value:"messages",children:h("historyModal.sortMessages")})]})]}),s.jsxs("label",{className:"mt-2 flex items-center gap-2 text-[11px] text-text-muted",children:[s.jsx("input",{type:"checkbox",checked:v.resumableOnly,onChange:P=>j({...v,resumableOnly:P.target.checked})}),h("historyModal.resumeReadyOnly")]})]}),I.map(P=>{const _=e.providerSessionId===P.providerSessionId,q=_||!P.canResume||!!i,B=P.workspaceFallbackSource==="selected-workspace";return s.jsxs("button",{type:"button",onClick:()=>{q||!C||C(P)},disabled:q,className:`w-full text-left p-4 rounded-xl mb-2 border transition-all ${_?"bg-[var(--bg-glass-hover)] border-accent":"bg-[var(--surface-secondary)] border-border-subtle"} ${q?"opacity-70 cursor-default":"cursor-pointer hover:border-[var(--accent-primary-light)]"}`,children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:`font-bold text-sm mb-1 truncate ${_?"text-[var(--accent-primary-light)]":"text-text-primary"}`,children:P.title||h("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:aS(P.lastMessageAt)})]}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted line-clamp-2",children:P.preview||h("historyModal.noSavedPreview")}),s.jsxs("div",{className:"mt-3 flex items-center justify-between gap-3 text-[11px] text-text-muted",children:[s.jsxs("div",{className:"truncate",children:[P.workspace||h("historyModal.workspaceUnknown"),B?h("historyModal.selectedWorkspaceSuffix"):"",Js(P.summaryMetadata)?` · ${Js(P.summaryMetadata)}`:"",P.messageCount>0?` · ${h("historyModal.msgCount",{count:P.messageCount})}`:""]}),s.jsx("div",{className:"shrink-0",children:_?h("historyModal.statusActive"):P.canResume?B?h("historyModal.statusResumeSelectedWorkspace"):i===P.providerSessionId?h("historyModal.statusResuming"):h("historyModal.statusResume"):h("historyModal.statusMissingWorkspace")})]})]},P.id)})]}):y.map(P=>s.jsxs("div",{onClick:()=>{f(e.routeId,P.id),u()},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||h("historyModal.untitledSession")}),s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-mono",children:[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:h("historyModal.statusActive")})]})]},P.id)),(S&&!o&&I.length===0||!S&&y.length===0)&&s.jsxs("div",{className:"py-10 px-5 text-center text-text-muted",children:[s.jsx("div",{className:"text-3xl mb-3 opacity-60",children:s.jsx(Of,{size:32})}),s.jsx("div",{className:"text-[13px]",children:S?a.length>0?h("historyModal.noMatchingHistory"):sS(h):h("historyModal.noRecentChats")})]}),S&&o&&s.jsx("div",{className:"py-10 px-5 text-center text-text-muted",children:s.jsx("div",{className:"text-[13px]",children:rS(h)})})]}),s.jsx("div",{className:"px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 bg-[var(--surface-tertiary)] border-t border-border-subtle text-right shrink-0",children:s.jsx("button",{onClick:g,disabled:r||o,className:"btn btn-secondary btn-sm rounded-[10px]",children:r||o?h("historyModal.refreshing"):s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Sa,{size:13})," ",S?nS(h):h("historyModal.refreshHistory")]})})})]})]});return typeof document>"u"?D:fn.createPortal(D,document.body)}const Sc={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 xp({toasts:e,onDismiss:t,onClickToast:n}){const{t:r}=Ne();return s.jsx("div",{className:"fixed right-4 z-[var(--z-toast)] flex flex-col gap-2 pointer-events-none",style:{top:"calc(env(safe-area-inset-top, 0px) + 16px)"},children:e.map(a=>{const o=Sc[a.type]||Sc.info;return s.jsxs("div",{className:"fade-in pointer-events-auto cursor-pointer animate-[toast-in_0.3s_ease-out] max-w-[380px] relative group overflow-hidden rounded-[16px] border shadow-[0_18px_40px_rgba(2,6,23,0.24)] backdrop-blur-xl",style:{background:"color-mix(in srgb, var(--surface-primary) 94%, var(--bg-secondary) 6%)",borderColor:"color-mix(in srgb, var(--border-default) 88%, transparent)",color:"var(--text-primary)"},onClick:()=>{var i;(i=a.actions)!=null&&i.length||n&&n(a)},children:[s.jsx("div",{className:"absolute inset-y-0 left-0 w-[3px]",style:{background:`linear-gradient(180deg, ${o.accent}, color-mix(in srgb, ${o.accent} 55%, transparent))`}}),s.jsx("button",{className:"absolute top-2 right-2 w-7 h-7 rounded-full flex items-center justify-center text-text-muted hover:text-text-primary hover:bg-bg-glass transition-colors leading-none cursor-pointer",onClick:i=>{i.stopPropagation(),t(a.id)},"aria-label":r("toast.dismiss"),children:s.jsx(At,{size:14})}),s.jsxs("div",{className:"px-4 py-3.5 pl-5",children:[s.jsx("div",{className:"flex items-center gap-2 pr-8",children:s.jsx("span",{className:"inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-[0.08em]",style:{background:o.chipBg,color:o.chipText,border:`1px solid color-mix(in srgb, ${o.accent} 22%, transparent)`},children:r(o.labelKey)})}),s.jsx("div",{className:"mt-2 text-[13px] font-semibold leading-[1.45] text-text-primary",children:a.message}),a.actions&&a.actions.length>0&&s.jsx("div",{className:"flex gap-2 mt-3",children:a.actions.map((i,c)=>s.jsx("button",{className:`text-xs px-3 py-1.5 rounded-lg font-bold border transition-colors cursor-pointer ${i.variant==="primary"||i.variant==="danger",""}`,style:i.variant==="primary"?{background:"color-mix(in srgb, var(--accent-primary) 12%, var(--surface-primary))",color:"var(--text-primary)",borderColor:"color-mix(in srgb, var(--accent-primary) 26%, transparent)"}:i.variant==="danger"?{background:"color-mix(in srgb, var(--status-error) 10%, var(--surface-primary))",color:"var(--status-error)",borderColor:"color-mix(in srgb, var(--status-error) 22%, transparent)"}:{background:"var(--surface-secondary)",color:"var(--text-secondary)",borderColor:"var(--border-subtle)"},onClick:d=>{d.stopPropagation(),i.onClick(),t(a.id)},children:i.label},c))})]})]},a.id)})})}const oS=e=>e.transport==="pty"||e.transport==="acp"||e.transport==="cdp-page"?!0:e.daemonId!==e.id;function iS(e){const t=e.workspace||"";if(!t)return"";const n=t.split(/[/\\]/).filter(Boolean);return n.length>0?n[n.length-1]:t}function lS(e,t){return vp(e)||t}function vp(e){var a,o,i;const t=(o=(a=e.summaryMetadata)==null?void 0:a.items)==null?void 0:o.find(c=>(c==null?void 0:c.id)==="model"),n=((t==null?void 0:t.value)||(t==null?void 0:t.shortValue)||"").trim();if(n)return n;const r=(i=e.controlValues)==null?void 0:i.model;return typeof r=="string"&&r.trim()?r.trim():""}function cS(e){return vp(e)||void 0}function dS(e){return e.sessionId||e.instanceId||e.agentType}function yp(e=[]){const t={};for(const n of e)n.type==="adhdev-daemon"&&(t[n.id]=ts(n,{fallbackId:n.id}));return t}function wp(e,t={}){var r;const n=e.daemonId||((r=e.id)==null?void 0:r.split(":")[0])||e.id;return{machineName:Ty(e,t.machineNames),connectionState:t.connectionStates?t.connectionStates[n]||t.defaultConnectionState||"new":t.defaultConnectionState}}function Vi(e,t={}){return uS(e,wp(e,t))}function uS(e,t={}){var f,g,C,h,x,y,b,S,k;const n=[],r=t.machineName,a=t.connectionState,o=iS(e),i=e.workspace||"",c=Ey(e.type,{agentName:e.cliName}),d=ct(e)||lt(e)?c:$t(e.type),p=lS(e,d),u=Array.isArray(e.childSessions)?e.childSessions.map(w=>{var v,N,j;return{sessionId:w.id,instanceId:w.id,providerSessionId:w.providerSessionId,activeChatId:(v=w.activeChat)==null?void 0:v.id,transport:w.transport,sessionCapabilities:w.capabilities,agentType:w.providerType,agentName:w.providerName||$t(w.providerType),model:cS(w),status:w.status,title:w.title,lastMessagePreview:w.lastMessagePreview,lastMessageRole:w.lastMessageRole,lastMessageAt:w.lastMessageAt,lastMessageHash:w.lastMessageHash,messages:((N=w.activeChat)==null?void 0:N.messages)||[],activeModal:((j=w.activeChat)==null?void 0:j.activeModal)||void 0,unread:w.unread,lastSeenAt:w.lastSeenAt,lastUpdated:w.lastUpdated,inboxBucket:w.inboxBucket,completionMarker:w.completionMarker,surfaceHidden:w.surfaceHidden,muted:w.muted,git:w.git,settings:w.settings,coordinator:w.coordinator,messageInput:w.messageInput}}):[],m=oS(e);if(m){const w=e.sessionId||e.instanceId,v=(f=e.settings)==null?void 0:f.meshCoordinatorFor,N=((g=e.settings)==null?void 0:g.meshNodeFor)||!((C=e.settings)!=null&&C.meshCoordinatorFor)&&((h=e.settings)==null?void 0:h.launchedByCoordinator),j=v?" (Coordinator)":N?" (Mesh Node)":"",A=c+j,I=(x=e.activeChat)==null?void 0:x.activeModal,D=I&&Array.isArray(I.buttons)&&I.buttons.length>0,L=_y(e.activeChat,[{status:e.status,activeModal:(y=e.activeChat)==null?void 0:y.activeModal}],e.agents||[]),P=e.activeChat||{title:"",messages:[]};let _=P.title&&String(P.title).trim()?String(P.title).trim():"";const q=(b=e.activeChat)==null?void 0:b.id,B=e.chats;if(q&&Array.isArray(B)&&B.length>0){const J=B.find(re=>re.id===q||re.id&&String(re.id)===String(q));J!=null&&J.title&&String(J.title).trim()&&(_=String(J.title).trim())}const E=(ct(e)||lt(e),e.type),K=(ct(e)||lt(e))&&Kl(_,A,E)?"":_,R=P.messages||[],T=typeof q=="string"?q.trim():"",H=(ct(e)||lt(e))&&T===String(e.type||"").trim(),M=T&&!H?T:e.providerSessionId,W=e.coordinator||(typeof((S=e.settings)==null?void 0:S.meshCoordinatorFor)=="string"&&e.settings.meshCoordinatorFor?{meshId:e.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:w,providerSessionId:e.providerSessionId,historySessionId:M,nativeSessionId:w,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:ct(e)&&e.mode||"chat",agentName:A,agentType:E,status:L,title:K,messages:R,resume:e.resume,hostIdeType:!ct(e)&&!lt(e)?e.type:void 0,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||K||(ct(e)?e.mode==="chat"?A:`Terminal${j}`:A),displaySecondary:p,cdpConnected:e.cdpConnected,lastMessagePreview:e.lastMessagePreview,lastMessageRole:e.lastMessageRole,lastMessageAt:e.lastMessageAt,lastMessageHash:e.lastMessageHash,lastUpdated:e.lastUpdated,inboxBucket:e.inboxBucket,completionMarker:e.completionMarker,modalButtons:D?I.buttons:void 0,modalMessage:D?I.message:void 0,streamSource:"native",tabKey:Ja(w,e.id),machineName:r,connectionState:a,settings:e.settings,coordinator:W,messageInput:e.messageInput})}if(m&&(ct(e)||lt(e)))return n;for(const w of u){const v=w.activeModal&&Array.isArray(w.activeModal.buttons)&&w.activeModal.buttons.length>0,N=$y(w),j=dS(w),A=`${e.id}:${j}`,I=w.title&&String(w.title).trim()||"",D=Kl(I,w.agentName,w.agentType)?"":I,L=w.messages||[];if(!(w.transport==="cdp-webview"||!!w.sessionId||!!w.providerSessionId||L.length>0||v||!!D||!["idle","panel_hidden","disconnected","not_monitored"].includes(N)))continue;const _=w.coordinator||(typeof((k=w.settings)==null?void 0:k.meshCoordinatorFor)=="string"&&w.settings.meshCoordinatorFor?{meshId:w.settings.meshCoordinatorFor,role:"coordinator"}:void 0);n.push({routeId:e.id,sessionId:w.sessionId||w.instanceId,providerSessionId:w.providerSessionId,historySessionId:w.activeChatId||w.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:w.transport||"cdp-webview",daemonId:e.daemonId||void 0,sessionCapabilities:w.sessionCapabilities,mode:"chat",agentName:w.agentName,agentType:w.agentType,status:N,title:D,messages:L,hostIdeType:e.type,workspaceName:o,workspacePath:i,git:w.git||e.git,displayPrimary:o||D||w.agentName||d,displaySecondary:w.model&&w.model.trim()?w.model.trim():`${d} · ${w.agentName}`,cdpConnected:e.cdpConnected,lastMessagePreview:w.lastMessagePreview,lastMessageRole:w.lastMessageRole,lastMessageAt:w.lastMessageAt,lastMessageHash:w.lastMessageHash,lastUpdated:w.lastUpdated||e.lastUpdated,inboxBucket:w.inboxBucket,completionMarker:w.completionMarker,modalButtons:v?w.activeModal.buttons:void 0,modalMessage:v?w.activeModal.message:void 0,streamSource:"agent-stream",tabKey:Ja(w.sessionId||w.instanceId,A),machineName:r,connectionState:a,settings:w.settings,coordinator:_,messageInput:w.messageInput})}return n.length===0&&n.push({routeId:e.id,sessionId:e.sessionId||e.instanceId,providerSessionId:e.providerSessionId,nativeSessionId:e.sessionId||e.instanceId,transport:e.transport,daemonId:e.daemonId||void 0,sessionCapabilities:e.sessionCapabilities,mode:"chat",agentName:c,agentType:"ide-native",status:"idle",title:"",messages:[],hostIdeType:e.type,workspaceName:o,workspacePath:i,git:e.git,displayPrimary:o||d,displaySecondary:p,cdpConnected:e.cdpConnected,lastUpdated:e.lastUpdated,streamSource:"native",tabKey:Ja(e.sessionId||e.instanceId,e.id),connectionState:a,settings:e.settings,messageInput:e.messageInput}),n}function kp(e){return String(e.type||e.id||"").trim()}function ha(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&!!t.trim()).map(t=>t.trim()):[]}function pS(e,t){const n=(t||"").trim();if(!n)return[];const r=(e||[]).find(a=>a.type===n);return ha(r==null?void 0:r.modelOptions)}function mS(e,t){const n=(t||"").trim();if(!n)return[];const r=(e||[]).find(a=>a.type===n);return ha(r==null?void 0:r.thinkingLevelOptions)}function Sp(e){const t=new Map;for(const n of e||[])n!=null&&n.type&&t.set(n.type,{models:ha(n.modelOptions),thinking:ha(n.thinkingLevelOptions)});return t}function hS(e){var t;return e.category!=="cli"||!kp(e)||e.enabled===!1?!1:e.machineStatus?e.machineStatus==="detected":((t=e.lastDetection)==null?void 0:t.ok)===!0||e.installed===!0||!!e.detectedPath}function wn(e){var r;const t=new Set,n=[];for(const a of e||[]){if(!hS(a))continue;const o=kp(a);if(!o||t.has(o))continue;t.add(o);const i=String(a.displayName||a.name||o),c=a.detectedPath||((r=a.lastDetection)==null?void 0:r.path)||null;n.push({type:o,label:i,icon:a.icon,statusLabel:c?`Detected at ${c}`:"Detected on this machine",detectedPath:c,...Array.isArray(a.modelOptions)&&a.modelOptions.length?{modelOptions:a.modelOptions}:{},...Array.isArray(a.thinkingLevelOptions)&&a.thinkingLevelOptions.length?{thinkingLevelOptions:a.thinkingLevelOptions}:{}})}return n}function kn(e){const t=Array.isArray(e)?e:typeof e=="string"?e.split(/[\s,]+/):[],n=new Set,r=[];for(const a of t){const o=typeof a=="string"?a.trim():"";!o||n.has(o)||(n.add(o),r.push(o))}return r}function cr(e){return e.map(t=>t.type)}function fS(e,t){const n=kn(e),r=t.trim();return!r||n.includes(r)?n:[...n,r]}function bS(e,t){return kn(e).filter(n=>n!==t)}function Cc(e,t,n){const r=kn(e),a=r.indexOf(t);if(a<0)return r;const o=r.filter(c=>c!==t);if(n==="top")return[t,...o];if(n==="bottom")return[...o,t];const i=n==="up"?Math.max(0,a-1):Math.min(o.length,a+1);return o.splice(i,0,t),o}function jc({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 gS({value:e,availableProviders:t,onChange:n,disabled:r=!1,saveButton:a}){const{t:o}=Ne("common"),[i,c]=l.useState(""),d=l.useMemo(()=>new Map(t.map(g=>[g.type,g])),[t]),p=l.useMemo(()=>kn(e),[e]),u=p.filter(g=>!d.has(g)).length,m=t.filter(g=>!p.includes(g.type)),f=()=>{i&&(n(fS(p,i)),c(""))};return s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/60 p-3",children:[s.jsx("div",{className:"flex flex-col gap-2",children:p.length===0?s.jsx("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:"No provider priority configured. Launches without an explicit CLI provider will fail closed."}):p.map((g,C)=>{const h=d.get(g),x=!!h;return s.jsxs("div",{className:`flex flex-col gap-2 rounded-md border border-border-subtle px-3 py-2 sm:flex-row sm:items-center sm:justify-between ${x?"bg-bg-primary":"bg-bg-primary/40"}`,children:[s.jsxs("div",{className:"min-w-0",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsxs("span",{className:"text-[10px] font-semibold text-text-muted",children:["#",C+1]}),(h==null?void 0:h.icon)&&s.jsx("span",{"aria-hidden":"true",children:h.icon}),s.jsx("span",{className:`font-mono text-[12px] ${x?"text-text-primary":"text-text-muted"}`,children:g}),x?s.jsx("span",{className:"rounded border border-green-500/20 bg-green-500/10 px-1.5 py-px text-[9px] font-semibold text-green-400",children:o("settings.providerPriority.available")}):s.jsx("span",{className:"rounded border border-amber-500/25 bg-amber-500/10 px-1.5 py-px text-[9px] font-semibold text-amber-400",children:o("settings.providerPriority.notOnMachine")})]}),s.jsx("div",{className:"mt-1 text-[10px] text-text-muted",children:h?`${h.label} · ${h.statusLabel}`:"Kept in order; skipped at launch until detected here."})]}),s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex h-8 w-8 items-center justify-center p-0","aria-label":"Move up",disabled:r||C===0,title:"Move up",onClick:()=>n(Cc(p,g,"up")),children:s.jsx(jc,{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||C===p.length-1,title:"Move down",onClick:()=>n(Cc(p,g,"down")),children:s.jsx(jc,{direction:"down"})}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm text-red-400",disabled:r,onClick:()=>n(bS(p,g)),children:o("settings.providerPriority.remove")})]})]},g)})}),s.jsxs("div",{className:"mt-3 flex flex-col gap-2 sm:flex-row sm:items-end",children:[s.jsxs("label",{className:"flex-1 text-[11px] text-text-secondary",children:[s.jsx("span",{className:"mb-1 block font-medium text-text-primary",children:o("settings.providerPriority.addCliLabel")}),s.jsxs("select",{className:"w-full rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-sm text-text-primary",value:i,onChange:g=>c(g.target.value),disabled:r||m.length===0,children:[s.jsx("option",{value:"",children:m.length?"Select provider…":"No additional detected CLI providers"}),m.map(g=>s.jsxs("option",{value:g.type,children:[g.label," (",g.type,")"]},g.type))]})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",disabled:r||!i,onClick:f,children:o("settings.providerPriority.addProvider")}),a]}),s.jsxs("div",{className:"mt-2 text-[11px] text-text-muted",children:["Launches use this order, top to bottom.",u>0?` ${u} provider${u===1?"":"s"} not detected here — kept in order, skipped until available.`:""]})]})}function xS(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 Cp(e,t){const n=xS(e);return{daemonId:n.daemonId,payload:{...t,...n.targetSessionId&&!t.targetSessionId?{targetSessionId:n.targetSessionId}:{}}}}const jp=[{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:"🏄"}],Np=[{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:"◆"}],Ap=[{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:"🟠"}],vS=jp,yS=Np,wS=Ap;function kS({icon:e,title:t,subtitle:n,badge:r,actions:a,className:o}){return s.jsxs("div",{className:Ft("dashboard-header",o),children:[s.jsxs("div",{children:[s.jsxs("h1",{className:"header-title flex items-center gap-2",children:[s.jsx("span",{className:"flex items-center text-lg",children:e})," ",t,r&&s.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-px rounded-full bg-accent/10 text-accent-light",children:[r.count!==void 0?r.count:""," ",r.text]})]}),n&&s.jsx("div",{className:"header-subtitle mt-1 text-xs text-text-muted",children:n})]}),a&&s.jsx("div",{className:"flex gap-2",children:a})]})}function gr({icon:e,title:t,subtitle:n,badge:r,actions:a,widthClassName:o="max-w-6xl",contentClassName:i,children:c}){return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsx(kS,{icon:e,title:t,subtitle:n,badge:r,actions:a}),s.jsx("div",{className:"page-content",children:s.jsx("div",{className:Ft("mx-auto flex w-full flex-col gap-4",o,i),children:c})})]})}const ii="adhdev:themechange";function SS(){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"?SS():e}function Ip(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(ii,{detail:{preference:e,theme:t}}))}function CS(){const e=ln(),t=cn(e);Ip(t),zr(e,t)}function Ls(){const[e,t]=l.useState(ln),[n,r]=l.useState(()=>cn(ln()));l.useEffect(()=>{Ip(n)},[n]),l.useEffect(()=>{const i=window.matchMedia("(prefers-color-scheme: light)"),c=d=>{if(e==="system"){const p=d.matches?"light":"dark";r(p),zr("system",p)}};return i.addEventListener("change",c),()=>i.removeEventListener("change",c)},[e]),l.useEffect(()=>{const i=d=>{const p=d.detail||{},u=p.preference,m=p.theme;t(u==="dark"||u==="light"||u==="system"?u:ln()),r(m==="dark"||m==="light"?m:cn(ln()))},c=d=>{if(d.key!=="theme")return;const p=ln(),u=cn(p);t(p),r(u)};return window.addEventListener(ii,i),window.addEventListener("storage",c),()=>{window.removeEventListener(ii,i),window.removeEventListener("storage",c)}},[]);const a=l.useCallback(i=>{const c=cn(i);t(i),r(c);try{localStorage.setItem("theme",i)}catch{}zr(i,c)},[]),o=l.useCallback(()=>{t(i=>{const c=i==="dark"?"light":i==="light"?"system":"dark",d=cn(c);r(d);try{localStorage.setItem("theme",c)}catch{}return zr(c,d),c})},[]);return{theme:n,preference:e,setPreference:a,cycleTheme:o,isDark:n==="dark"}}const Nc={dark:"Dark",light:"Light",system:"System"};function jS({collapsed:e}){const{preference:t,cycleTheme:n}=Ls(),r=t==="dark"?s.jsx(Uf,{size:16}):t==="light"?s.jsx(Wf,{size:16}):s.jsx(Gf,{size:16});return s.jsxs("div",{className:`nav-item cursor-pointer ${e?"justify-center py-2.5 px-0":""}`,onClick:n,title:`Theme: ${Nc[t]} (click to cycle)`,children:[s.jsx("span",{className:"nav-icon",children:r}),!e&&s.jsx("span",{className:"text-xs",children:Nc[t]})]})}const li="adhdev:langchange";function NS(){const e=wt.language;return un(e)?e:fu()}function AS(e){typeof window>"u"||window.dispatchEvent(new CustomEvent(li,{detail:{language:e}}))}function IS(){const[e,t]=l.useState(NS);l.useEffect(()=>{const r=i=>{un(i)&&t(i)},a=i=>{const c=i.detail||{};un(c.language)&&t(c.language)},o=i=>{if(i.key!==Ko)return;const c=i.newValue;un(c)&&c!==wt.language&&(wt.changeLanguage(c),Vo(c))};return wt.on("languageChanged",r),window.addEventListener(li,a),window.addEventListener("storage",o),()=>{wt.off("languageChanged",r),window.removeEventListener(li,a),window.removeEventListener("storage",o)}},[]);const n=l.useCallback(r=>{if(un(r)){t(r);try{localStorage.setItem(Ko,r)}catch{}wt.changeLanguage(r),Vo(r),AS(r)}},[]);return{language:e,setLanguage:n}}function TS({collapsed:e}){const{language:t,setLanguage:n}=IS(),{t:r}=Ne("common"),a=Va.find(i=>i.code===t)??Va[0],o=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"})}: ${a.label}`,children:[s.jsx("span",{className:"nav-icon",children:s.jsx(Zf,{size:16})}),!e&&s.jsx("span",{className:"text-xs",children:a.label}),s.jsx("select",{"aria-label":o,value:t,onChange:i=>n(i.target.value),className:"absolute inset-0 w-full h-full opacity-0 cursor-pointer",children:Va.map(i=>s.jsx("option",{value:i.code,children:i.label},i.code))})]})}function ao(e,t){return e?typeof e=="function"?e(t):e:null}function MS({children:e,brand:t,navItems:n,sidebarSections:r=[],footerItems:a=[],footerInfo:o,footerActions:i,preMainContent:c,collapsedStorageKey:d="sidebar-collapsed"}){const{t:p}=Ne("common"),[u,m]=l.useState(!1),[f,g]=l.useState(()=>{try{return localStorage.getItem(d)==="1"}catch{return!1}}),C=()=>m(!0),h=()=>m(!1),x=()=>{g(k=>{const w=!k;try{localStorage.setItem(d,w?"1":"0")}catch{}return w})},y=l.useMemo(()=>({collapsed:f,mobileMenuOpen:u,openMobileMenu:C,closeMobileMenu:h,toggleCollapsed:x}),[f,u]),b=k=>`nav-item${k.active?" active":""} cursor-pointer ${f?"justify-center py-2.5 px-0":""}${k.className?` ${k.className}`:""}`,S=k=>s.jsxs("div",{className:b(k),id:`nav-${k.id}`,onClick:()=>{k.onSelect(),h()},title:f?k.title??(typeof k.label=="string"?k.label:void 0):k.title,children:[s.jsx("span",{className:"nav-icon",children:k.icon}),!f&&k.label]},k.id);return s.jsxs("div",{className:`app-layout${u?" mobile-menu-open":""}${f?" sidebar-collapsed":""}`,children:[s.jsxs("button",{type:"button",className:"mobile-menu-btn","aria-label":p("app.openMenu"),onClick:C,children:[s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"}),s.jsx("span",{className:"mobile-menu-icon"})]}),u&&s.jsx("div",{className:"sidebar-overlay",role:"button",tabIndex:0,"aria-label":p("app.closeMenu"),onClick:h,onKeyDown:k=>k.key==="Escape"&&h()}),s.jsxs("aside",{className:`sidebar ${u?"sidebar-open":""}`,children:[s.jsxs("div",{className:"sidebar-header",children:[s.jsx("div",{className:`sidebar-logo ${f?"justify-center gap-0":""}`,children:ao(t,y)}),s.jsx("button",{type:"button",className:"sidebar-close-btn","aria-label":p("app.closeMenu"),onClick:h,children:s.jsx(At,{size:16})})]}),s.jsx("nav",{className:"sidebar-nav",children:n.map(S)}),r.map(k=>s.jsxs("div",{className:k.className??"border-t border-border-subtle pt-2 mt-2",children:[!f&&k.title?s.jsx("div",{className:"px-3 py-1 text-[10px] text-text-muted uppercase tracking-widest",children:k.title}):null,k.items.map(S)]},k.key)),s.jsxs("div",{className:"border-t border-border-subtle pt-4 mt-2",children:[a.map(S),ao(o,y),s.jsx(jS,{collapsed:f}),s.jsx(TS,{collapsed:f}),ao(i,y)]})]}),s.jsx("main",{className:"main-content relative",children:s.jsxs("div",{className:"main-content-inner",children:[c,e]})})]})}function bt({title:e,icon:t,description:n,accentColor:r,className:a,collapsible:o,defaultOpen:i=!0,badge:c,children:d}){const[p,u]=l.useState(i),m=o?p:!0,f=(e||n)&&s.jsxs("div",{className:Ft("flex items-start justify-between gap-3",m&&"mb-4"),children:[s.jsxs("div",{className:"min-w-0",children:[e&&s.jsxs("h3",{className:"text-base font-semibold text-text-primary flex items-center gap-1.5",children:[t&&s.jsx("span",{children:t}),s.jsx("span",{children:e}),c]}),n&&s.jsx("p",{className:"text-[13px] text-text-muted mt-1",children:n})]}),o&&s.jsx("span",{className:Ft("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:Ft("bg-bg-card border border-border-subtle rounded-2xl p-5 backdrop-blur-xl transition-all","hover:border-border-default hover:shadow-glow",r&&"border-l-[3px]",a),style:r?{borderLeftColor:r}:void 0,children:[o&&f?s.jsx("button",{type:"button",className:"w-full bg-transparent border-none p-0 text-left cursor-pointer",onClick:()=>u(g=>!g),"aria-expanded":m,children:f}):f,m&&d]})}function La({icon:e,title:t,description:n,action:r,className:a}){return s.jsxs("div",{className:Ft("py-16 px-5 text-center bg-bg-glass border-2 border-dashed border-border-subtle rounded-2xl",a),children:[s.jsx("div",{className:"text-5xl mb-4 opacity-50",children:e}),s.jsx("h3",{className:"text-lg font-bold text-text-secondary mb-2",children:t}),s.jsx("p",{className:"text-sm text-text-muted max-w-sm mx-auto mb-5 leading-relaxed",children:n}),r]})}const DS={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"},PS={error:"⚠️",warning:"🧪",success:"✅",info:"💡"};function Gt({variant:e,children:t,onDismiss:n,className:r}){return s.jsxs("div",{className:Ft("flex items-center justify-between gap-3 px-4 py-3 rounded-xl border text-[13px]",DS[e],r),children:[s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{children:PS[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:Ft("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:Ft("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 LS={primary:"btn-primary",secondary:"btn-secondary",warning:"btn-warning",danger:"btn-danger",ghost:"btn-ghost"},ks=l.forwardRef(function({variant:t="secondary",size:n="md",type:r,className:a,...o},i){return s.jsx("button",{ref:i,type:r??"button",className:Ft("btn",LS[t],n==="sm"&&"btn-sm",a),...o})}),RS=l.forwardRef(function({options:t,children:n,className:r,...a},o){return s.jsx("select",{ref:o,className:Ft("w-full px-4 py-3 rounded-xl border border-border-subtle bg-bg-secondary","text-text-primary text-sm outline-none cursor-pointer","focus:border-accent transition-colors",r),...a,children:n??(t==null?void 0:t.map(i=>s.jsx("option",{value:i.value,disabled:i.disabled,children:i.label},i.value)))})}),ES={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"},_S={online:"bg-green-500",idle:"bg-yellow-500",busy:"bg-orange-500",error:"bg-red-500",offline:"bg-gray-500"};function $S({status:e,label:t,className:n}){const r=t||e;return s.jsxs("span",{className:Ft("inline-flex items-center gap-1.5 text-xs font-medium px-2.5 py-1 rounded-full border",ES[e],n),children:[s.jsx("span",{className:Ft("w-2 h-2 rounded-full animate-[pulse-dot_2s_ease-in-out_infinite]",_S[e])}),r]})}function Bs({label:e,description:t,checked:n,disabled:r,onChange:a,extra:o}){return s.jsxs("div",{className:`flex justify-between items-center ${r?"opacity-60":""}`,children:[s.jsxs("div",{className:"pr-4",children:[s.jsx("div",{className:"font-medium text-sm",children:e}),s.jsx("div",{className:"text-[11px] text-text-muted mt-0.5",children:t})]}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[o,s.jsxs("button",{type:"button",role:"switch","aria-checked":n,"aria-disabled":r,disabled:r,onClick:()=>a(!n),className:`relative inline-flex items-center ${r?"cursor-not-allowed":"cursor-pointer"}`,children:[s.jsx("div",{className:"w-[40px] h-[22px] rounded-full transition-colors duration-200 ease-in-out",style:{backgroundColor:n?"var(--accent-primary)":"color-mix(in srgb, var(--surface-primary) 60%, var(--border-default))"}}),s.jsx("div",{className:`absolute left-[1.5px] top-[1.5px] w-[19px] h-[19px] bg-white rounded-full transition-transform duration-200 ease-in-out shadow-[0_1px_2px_rgba(0,0,0,0.15)] ${n?"translate-x-[18px]":"translate-x-0"}`})]})]})]})}function HS({onPrefChange:e}){const{t}=Ne("common"),[n,r]=Ky(),[a,o]=l.useState(()=>typeof window>"u"||!("Notification"in window)?"unsupported":Notification.permission);l.useEffect(()=>{const c=()=>{if(typeof window>"u"||!("Notification"in window)){o("unsupported");return}o(Notification.permission)};return c(),window.addEventListener("focus",c),document.addEventListener("visibilitychange",c),()=>{window.removeEventListener("focus",c),document.removeEventListener("visibilitychange",c)}},[]);const i=(c,d)=>{r({[c]:d}),e==null||e(c,d)};return s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx(Bs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Nn,{size:15})," ",t("notifications.masterToggleLabel")]}),description:t("notifications.masterToggleDesc"),checked:n.globalEnabled,onChange:c=>i("globalEnabled",c)}),n.globalEnabled&&s.jsx("div",{className:"border-t border-border-subtle my-0.5"}),n.globalEnabled&&s.jsx(Bs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(us,{size:15})," ",t("notifications.browserNotificationsLabel")]}),description:t("notifications.browserNotificationsDesc"),checked:n.browserNotifications,onChange:c=>i("browserNotifications",c)}),n.globalEnabled&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:t("notifications.standaloneBackgroundInfo")}),a==="default"&&s.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-[11px] text-status-warning",children:[s.jsx("span",{children:t("notifications.standalonePermissionDefault")}),s.jsx("button",{onClick:()=>{Cu().then(o)},className:"px-2 py-0.5 rounded border border-border-default bg-bg-glass text-text-secondary hover:text-text-primary transition-colors",children:t("notifications.allowNotifications")})]}),a==="denied"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:t("notifications.permissionDenied")}),a==="unsupported"&&s.jsx("div",{className:"text-[11px] text-status-warning",children:t("notifications.standalonePermissionUnsupported")})]}),n.globalEnabled&&n.browserNotifications&&s.jsxs("div",{className:"ml-5 pl-3 border-l-2 border-border-subtle flex flex-col gap-2",children:[s.jsx(Bs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(eu,{size:15})," ",t("notifications.completionAlertsLabel")]}),description:t("notifications.completionAlertsDesc"),checked:n.completionAlert,onChange:c=>i("completionAlert",c)}),s.jsx(Bs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(qf,{size:15})," ",t("notifications.approvalAlertsLabel")]}),description:t("notifications.approvalAlertsDesc"),checked:n.approvalAlert,onChange:c=>i("approvalAlert",c)}),s.jsx(Bs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(or,{size:15})," ",t("notifications.connectionAlertsLabel")]}),description:t("notifications.connectionAlertsDesc"),checked:n.disconnectAlert,onChange:c=>i("disconnectAlert",c)})]}),!n.globalEnabled&&s.jsx("p",{className:"text-[11px] text-text-muted italic",children:t("notifications.allDisabled")})]})}function ci(e){const t=e.trim().match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+.*)?$/);if(!t)return null;const n=t[4]??null;let r=null;if(n){const a=n.match(/(?:^|\.)(\d+)$/);r=a?Number(a[1]):null}return{base:[Number(t[1]),Number(t[2]),Number(t[3])],prereleaseNumber:r,isPrerelease:n!==null}}function fa(e){var t;return((t=ci(e))==null?void 0:t.base)??null}function BS(e,t){const n=fa(e),r=fa(t);if(!n||!r)return e.localeCompare(t);for(let a=0;a<3;a+=1){if(n[a]<r[a])return-1;if(n[a]>r[a])return 1}return 0}function FS(e,t){const n=ci(e),r=ci(t);if(!n||!r)return e!==t;for(let a=0;a<3;a+=1){if(n.base[a]<r.base[a])return!0;if(n.base[a]>r.base[a])return!1}return n.isPrerelease&&r.isPrerelease?n.prereleaseNumber===null||r.prereleaseNumber===null?!1:n.prereleaseNumber<r.prereleaseNumber:!1}function Yi(e,t){const n=e.version||null;return e.versionMismatch===!0?!0:!n||!t?!1:FS(n,t)}function tr(e,t){if(e.versionUpdateRequired===!0)return!0;const n=e.version||null;if(!n||!t||n===t||BS(n,t)>=0)return!1;const r=fa(n),a=fa(t);return!r||!a?!1:r[0]!==a[0]||r[1]!==a[1]}function OS(e){return!e||typeof e!="object"?{}:"result"in e&&e.result&&typeof e.result=="object"?e.result:e}function oo(e,t){return e instanceof Error?e.message:t}function WS({ides:e,emptyMessage:t,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:a}){const{t:o}=Ne("common"),i=e.filter(c=>c.type==="adhdev-daemon");return i.length===0?s.jsx(La,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain mx-auto opacity-90"}),title:o("machine.connectedMachines.noMachines"),description:t||o("machine.connectedMachines.defaultDescription")}):s.jsx("div",{className:"flex flex-col gap-2",children:i.map(c=>s.jsx(GS,{ide:c,allIdes:e,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:a},c.id))})}function Ac({title:e,message:t,confirmLabel:n,confirmColor:r,onConfirm:a,onCancel:o}){const{t:i}=Ne("common"),c=r==="red"?"bg-status-error/20 text-status-error border-status-error/40 hover:bg-status-error/30":"";return fn.createPortal(s.jsx("div",{className:"fixed inset-0 flex items-center justify-center bg-black/60 backdrop-blur-sm",style:{zIndex:"var(--z-modal)"},onClick:o,children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl p-5 max-w-sm w-full mx-4 shadow-2xl",onClick:d=>d.stopPropagation(),children:[s.jsx("div",{className:"font-semibold text-sm mb-3",children:e}),s.jsx("div",{className:"text-xs text-text-muted leading-relaxed mb-5 whitespace-pre-line",children:t}),s.jsxs("div",{className:"flex gap-2 justify-end",children:[s.jsx("button",{onClick:o,className:"text-xs px-3 py-1.5 rounded-lg font-medium bg-bg-secondary text-text-secondary border border-border-subtle hover:bg-bg-glass transition-colors",children:i("common.cancel")}),s.jsx("button",{onClick:a,className:`text-xs px-3 py-1.5 rounded-lg font-medium border transition-colors ${c}`,style:r==="amber"?{background:"color-mix(in srgb, var(--status-warning) 20%, transparent)",color:"var(--status-warning)",borderColor:"color-mix(in srgb, var(--status-warning) 30%, transparent)"}:void 0,children:n})]})]})}),document.body)}function US(e){const t=e.replace(/^ide-/,"").replace(/-provider$/,"").toLowerCase(),r=[...vS,...yS,...wS].find(a=>a.id===t||t.includes(a.id)||a.id.includes(t));return r?{icon:r.icon,name:r.name}:{icon:"📝",name:e}}function GS({ide:e,allIdes:t,sendDaemonCommand:n,onDisconnect:r,onRevokeToken:a}){var q,B;const{t:o}=Ne("common"),[i,c]=l.useState("idle"),[d,p]=l.useState(""),[u,m]=l.useState(null),[f,g]=l.useState("idle"),[C,h]=l.useState(""),x=e.version||null,y=((q=e.machine)==null?void 0:q.platform)||((B=e.system)==null?void 0:B.platform)||"",b=ts(e,{fallbackId:e.id}),S=y==="win32"?"🪟":y==="darwin"?"🍎":"🐧",k=t.filter(E=>E.daemonId===e.id&&E.transport==="cdp-page"),w=t.filter(E=>E.daemonId===e.id&&E.transport==="pty"),v=t.filter(E=>E.daemonId===e.id&&E.transport==="acp"),N=e.p2p,j=async()=>{if(n){c("upgrading"),p(o("machine.connectedMachines.startingUpgrade"));try{const E=OS(await n(e.id,"daemon_upgrade",{}));E.alreadyLatest?(c("done"),p(`Already on v${E.version||"latest"}.`)):E.upgraded||E.success?(c("done"),p(`Upgrade to v${E.version||"latest"} started. Daemon is restarting...`)):(c("error"),p(E.error||"Upgrade failed"))}catch(E){c("error"),p(oo(E,"Connection lost during upgrade"))}}},A=async()=>{if(m(null),!!r){g("loading");try{await r(e.id),g("done"),h(o("machine.connectedMachines.machineDisconnected"))}catch(E){g("error"),h(oo(E,o("machine.connectedMachines.failedToDisconnect")))}}},I=async()=>{if(m(null),!!a){g("loading");try{await a(e.id),g("done"),h(o("machine.connectedMachines.tokenRevoked"))}catch(E){g("error"),h(oo(E,o("machine.connectedMachines.failedToRevokeToken")))}}},D="0.9.82",L=Yi(e,D),P=tr(e,D),_=k.length+w.length+v.length;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"bg-bg-glass rounded-lg px-4 py-3 border border-border-subtle",children:[s.jsxs("div",{className:"flex justify-between items-center",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx("span",{className:"text-xl",children:S}),s.jsxs("div",{children:[s.jsx("div",{className:"font-medium text-sm",children:b}),s.jsxs("div",{className:"text-xs text-text-muted font-mono flex items-center gap-2",children:[s.jsxs("span",{children:[e.id.substring(0,12),"…"]}),x&&s.jsxs("span",{className:`px-1.5 py-0.5 rounded text-[10px] ${L?"":"bg-bg-secondary"}`,style:L?{background:"color-mix(in srgb, var(--status-warning) 15%, transparent)",color:"var(--status-warning)"}:void 0,children:["v",x,!L&&" ✓"]})]})]})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[n&&L&&s.jsx("button",{onClick:j,disabled:i==="upgrading"||i==="done",className:"btn btn-sm btn-primary disabled:opacity-50 disabled:cursor-not-allowed",title:`Update to v${D}`,children:i==="upgrading"?s.jsxs("span",{className:"flex items-center gap-1",children:[s.jsx("span",{className:"animate-spin",children:"⟳"})," ",o("machine.connectedMachines.upgrading")]}):i==="done"?o("machine.connectedMachines.updated"):P?o("machine.connectedMachines.updateNow"):o("machine.connectedMachines.updateTo",{version:D})}),r&&s.jsx("button",{onClick:()=>m("disconnect"),disabled:f==="loading",className:"btn btn-sm btn-warning disabled:opacity-50 disabled:cursor-not-allowed",title:"Disconnect this machine",children:o("machine.connectedMachines.disconnect")}),a&&s.jsx("button",{onClick:()=>m("revoke"),disabled:f==="loading",className:"btn btn-sm btn-danger disabled:opacity-50 disabled:cursor-not-allowed",title:"Remove machine (requires re-setup)",children:o("machine.connectedMachines.remove")}),s.jsx($S,{status:e.status==="online"?"online":"error"})]})]}),s.jsxs("div",{className:"flex items-center gap-3 mt-2.5 pt-2.5 border-t border-border-subtle/50",children:[N&&s.jsxs("div",{className:"flex items-center gap-1.5 text-[11px]",children:[s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${N.state==="connected"?"bg-status-online":"bg-text-muted/30"} ${N.state==="connecting"||N.state==="new"?"animate-pulse":""}`,style:N.state==="connecting"||N.state==="new"?{background:"var(--status-warning)"}:void 0}),s.jsxs("span",{className:"text-text-muted",children:["P2P ",N.state==="connected"?"connected":N.state==="connecting"||N.state==="new"?o("machine.connectedMachines.connecting"):N.state||"off"]}),N.peers!==void 0&&N.peers>0&&s.jsxs("span",{className:"text-text-muted/60",children:["(",N.peers," peer",N.peers!==1?"s":"",")"]})]}),N&&_>0&&s.jsx("span",{className:"text-border-subtle",children:"·"}),_>0?s.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-text-muted",children:[k.map(E=>{const K=US(E.type),R=E.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:K.icon}),s.jsx("span",{children:K.name}),R!==void 0&&s.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${R?"bg-status-online":"animate-pulse"}`,style:R?void 0:{background:"var(--status-warning)"},title:o(R?"machine.connectedMachines.cdpConnected":"machine.connectedMachines.cdpConnecting")})]},E.id)}),w.map(E=>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:E.cliName||"CLI"})]},E.id)),v.map(E=>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:E.cliName||"ACP"})]},E.id))]}):s.jsx("span",{className:"text-[11px] text-text-muted/60 italic",children:o("machine.connectedMachines.noIdesConnected")})]}),(d||C)&&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:C||d})]}),u==="disconnect"&&s.jsx(Ac,{title:o("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:o("machine.connectedMachines.disconnect"),confirmColor:"amber",onConfirm:A,onCancel:()=>m(null)}),u==="revoke"&&s.jsx(Ac,{title:o("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:o("machine.connectedMachines.remove"),confirmColor:"red",onConfirm:I,onCancel:()=>m(null)})]})}const qS=["default","claude-cli","codex-cli","antigravity-cli","hermes-cli","gemini-cli"];function zS({daemonId:e,knownCliTypes:t=qS}){const{t:n}=Ne("common"),{sendCommand:r}=vt(),[a,o]=l.useState({}),[i,c]=l.useState({}),[d,p]=l.useState(!0),[u,m]=l.useState(null),[f,g]=l.useState(null),[C,h]=l.useState(""),x=l.useCallback(async()=>{if(e){p(!0),g(null);try{const S=await r(e,"list_coordinator_prompts",{}),k=S!=null&&S.result&&typeof S.result=="object"?S.result:S;if(!(k!=null&&k.success)){g((k==null?void 0:k.error)||"Failed to load");return}const w=k.entries||{};h(k.dir||"");const v={};for(const N of t)v[N]=w[N]||{override:"",append:""};for(const N of Object.keys(w))v[N]||(v[N]=w[N]);o(v),c(JSON.parse(JSON.stringify(v)))}catch(S){g((S==null?void 0:S.message)||String(S))}finally{p(!1)}}},[r,e,t]);l.useEffect(()=>{x()},[x]);const y=l.useCallback(async(S,k)=>{var w;if(e){m(`${S}:${k}`),g(null);try{const v=((w=a[S])==null?void 0:w[k])||"",N=await r(e,"write_coordinator_prompt",{key:S,kind:k,content:v}),j=N!=null&&N.result&&typeof N.result=="object"?N.result:N;if(!(j!=null&&j.success)){g((j==null?void 0:j.error)||"Save failed");return}c(A=>({...A,[S]:{...A[S]||{override:"",append:""},[k]:v}}))}catch(v){g((v==null?void 0:v.message)||String(v))}finally{m(null)}}},[r,e,a]),b=l.useMemo(()=>(S,k)=>{var w,v;return(((w=a[S])==null?void 0:w[k])||"")!==(((v=i[S])==null?void 0:v[k])||"")},[a,i]);return e?s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsxs("div",{className:"text-[12px] text-text-muted",children:[s.jsxs("p",{children:["Customize the coordinator prompt this daemon's mesh coordinator sessions get. ",s.jsx("span",{className:"font-mono text-[11px]",children:C||"~/.adhdev/coordinator-prompts/"})]}),s.jsxs("p",{className:"mt-1",children:[s.jsx(Bo,{i18nKey:"settings.coordinatorPrompts.overrideDesc",ns:"common",components:{strong:s.jsx("strong",{})}})," ",s.jsx(Bo,{i18nKey:"settings.coordinatorPrompts.appendDesc",ns:"common",components:{strong:s.jsx("strong",{})}}),"Leave a field empty + Save to remove it (reset to default). Supports placeholders: ","{{meshName}}",", ","{{repo}}",", ","{{nodes}}",", ","{{rules}}",", etc."]})]}),f&&s.jsx("div",{className:"text-[12px] text-status-error bg-status-error/10 border border-status-error/40 rounded px-3 py-2",children:f}),d&&s.jsx("div",{className:"text-[12px] text-text-muted",children:"Loading…"}),s.jsx("div",{className:"flex flex-col gap-6",children:Object.entries(a).map(([S,k])=>s.jsxs("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary/40 p-3",children:[s.jsx("div",{className:"text-[13px] font-semibold mb-2",children:S}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:n("settings.coordinatorPrompts.overrideLabel")}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:4,value:k.override,onChange:w=>o(v=>({...v,[S]:{...v[S],override:w.target.value}})),placeholder:"(empty — use daemon default base prompt)",disabled:u===`${S}:override`}),s.jsx("div",{className:"mt-1 mb-3 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void y(S,"override"),disabled:u===`${S}:override`||!b(S,"override"),children:u===`${S}:override`?"Saving…":b(S,"override")?"Save override":"Saved"})}),s.jsx("label",{className:"block text-[11px] uppercase tracking-wide text-text-muted mb-1",children:n("settings.coordinatorPrompts.appendLabel")}),s.jsx("textarea",{className:"w-full px-3 py-2 rounded bg-bg-secondary border border-border-subtle text-[12px] font-mono text-text-primary",rows:3,value:k.append,onChange:w=>o(v=>({...v,[S]:{...v[S],append:w.target.value}})),placeholder:"(empty — nothing appended at this layer)",disabled:u===`${S}:append`}),s.jsx("div",{className:"mt-1 flex justify-end",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>void y(S,"append"),disabled:u===`${S}:append`||!b(S,"append"),children:u===`${S}:append`?"Saving…":b(S,"append")?"Save append":"Saved"})})]},S))})]}):s.jsx("div",{className:"text-[12px] text-text-muted",children:"Connect a daemon to edit coordinator prompts."})}const KS=[{id:"dark",label:"Dark",icon:"🌙"},{id:"light",label:"Light",icon:"☀️"},{id:"system",label:"System",icon:"💻"}];function VS(){const{preference:e,setPreference:t}=Ls();return s.jsx("div",{className:"flex gap-2",children:KS.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 YS(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 JS(e){return{r:parseInt(e.slice(1,3),16),g:parseInt(e.slice(3,5),16),b:parseInt(e.slice(5,7),16)}}function io(e){const t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4}function Ic(e){const{r:t,g:n,b:r}=JS(e);return .2126*io(t)+.7152*io(n)+.0722*io(r)}function Tc(e,t){const n=Ic(e),r=Ic(t),a=Math.max(n,r),o=Math.min(n,r);return(a+.05)/(o+.05)}function Tp(e){const t=YS(e);if(!t)return"#111827";const n="#111827",r="#ffffff";return Tc(t,n)>=Tc(t,r)?n:r}const di={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},ui={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},QS=[{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"}}}],Mp="adhdev-chat-theme",Dp="adhdev-chat-theme-custom";function Kr(){if(typeof window>"u")return"ember";try{return localStorage.getItem(Mp)||"ember"}catch{return"ember"}}function os(e){try{const t=localStorage.getItem(Dp);if(t){const n=JSON.parse(t);return{...e==="dark"?di:ui,...n[e]}}}catch{}return e==="dark"?di:ui}function Tr(e,t){try{localStorage.setItem(Dp,JSON.stringify({dark:e,light:t}))}catch{}}function Qt(e,t){const n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),a=parseInt(e.slice(5,7),16);return`rgba(${n}, ${r}, ${a}, ${t})`}function ba(e,t){const n=Math.min(255,parseInt(e.slice(1,3),16)+t),r=Math.min(255,parseInt(e.slice(3,5),16)+t),a=Math.min(255,parseInt(e.slice(5,7),16)+t);return`#${n.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}`}const XS={midnight:{dark:"#8b5cf6",light:"#7c3aed"},ember:{dark:"#d97706",light:"#d97706"},aurora:{dark:"#ec4899",light:"#ec4899"},honey:{dark:"#fbbf24",light:"#fbbf24"}};function sr(e,t){var a;const n=(a=XS[e])==null?void 0:a[t];if(!n)return;const r=document.documentElement;r.style.setProperty("--accent-primary",n),r.style.setProperty("--accent-primary-light",ba(n,24)),r.style.setProperty("--accent-on-primary",Tp(n)),r.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${n}, ${ba(n,18)})`),r.style.setProperty("--border-accent",Qt(n,.35)),r.style.setProperty("--nav-active-bg",Qt(n,.1)),r.style.setProperty("--nav-active-shadow",`inset 3px 0 0 ${n}, 0 0 12px ${Qt(n,.06)}`)}function qs(e){const t=document.documentElement;t.style.setProperty("--bg-primary",e.bgPrimary),t.style.setProperty("--bg-secondary",e.bgSecondary),t.style.setProperty("--bg-card",Qt(e.surfacePrimary,.92)),t.style.setProperty("--surface-primary",e.surfacePrimary),t.style.setProperty("--surface-secondary",e.bgSecondary),t.style.setProperty("--bg-glass",Qt(e.borderSubtle,.15)),t.style.setProperty("--bg-glass-hover",Qt(e.borderSubtle,.25)),t.style.setProperty("--text-primary",e.textPrimary),t.style.setProperty("--text-secondary",e.textSecondary),t.style.setProperty("--text-muted",e.textMuted),t.style.setProperty("--border-subtle",Qt(e.borderSubtle,.5)),t.style.setProperty("--border-default",Qt(e.borderDefault,.5)),t.style.setProperty("--accent-primary",e.accentColor),t.style.setProperty("--accent-primary-light",ba(e.accentColor,30)),t.style.setProperty("--accent-on-primary",Tp(e.accentColor)),t.style.setProperty("--accent-gradient",`linear-gradient(135deg, ${e.accentColor}, ${ba(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 Ji(){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 ZS(e){try{localStorage.setItem(Mp,e)}catch{}if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=zs()?"dark":"light";qs(os(t))}else Ji(),sr(e,zs()?"dark":"light")}function eC(){try{localStorage.removeItem("adhdev-accent-color")}catch{}const e=Kr();if(document.documentElement.setAttribute("data-chat-theme",e),e==="custom"){const t=zs()?"dark":"light";qs(os(t))}else Ji(),sr(e,zs()?"dark":"light")}function zs(){const e=document.documentElement.getAttribute("data-theme");return e?e==="dark":window.matchMedia("(prefers-color-scheme: dark)").matches}function Ht({label:e,value:t,onChange:n}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:e}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexShrink:0},children:[s.jsx("input",{type:"color",value:t,onChange:r=>n(r.target.value),style:{width:28,height:28,border:"none",borderRadius:6,cursor:"pointer",background:"transparent",padding:0}}),s.jsx("input",{type:"text",value:t,onChange:r=>{/^#[0-9a-fA-F]{0,6}$/.test(r.target.value)&&n(r.target.value)},style:{width:68,fontSize:"0.7rem",fontFamily:"monospace",background:"var(--bg-primary)",border:"1px solid var(--border-subtle)",borderRadius:4,padding:"3px 6px",color:"var(--text-primary)"}})]})]})}function Bn({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 tC({dark:e,onColorsChange:t}){const{t:n}=Ne("common"),r=e?"dark":"light",[a,o]=l.useState(()=>os(r));l.useEffect(()=>{o(os(r))},[r]);const i=l.useCallback((c,d)=>{o(p=>{const u={...p,[c]:d},f=os(r==="dark"?"light":"dark");return r==="dark"?Tr(u,f):Tr(f,u),qs(u),t(u),u})},[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(Bn,{title:n("settings.theme.sectionAppBackground"),children:[s.jsx(Ht,{label:n("settings.theme.colorBackground"),value:a.bgPrimary,onChange:c=>i("bgPrimary",c)}),s.jsx(Ht,{label:n("settings.theme.colorSurface"),value:a.bgSecondary,onChange:c=>i("bgSecondary",c)}),s.jsx(Ht,{label:n("settings.theme.colorCard"),value:a.surfacePrimary,onChange:c=>i("surfacePrimary",c)})]}),s.jsxs(Bn,{title:n("settings.theme.sectionAppText"),children:[s.jsx(Ht,{label:n("settings.theme.colorPrimary"),value:a.textPrimary,onChange:c=>i("textPrimary",c)}),s.jsx(Ht,{label:n("settings.theme.colorSecondary"),value:a.textSecondary,onChange:c=>i("textSecondary",c)}),s.jsx(Ht,{label:n("settings.theme.colorMuted"),value:a.textMuted,onChange:c=>i("textMuted",c)})]}),s.jsxs(Bn,{title:n("settings.theme.sectionBordersAccent"),children:[s.jsx(Ht,{label:n("settings.theme.colorBorderSubtle"),value:a.borderSubtle,onChange:c=>i("borderSubtle",c)}),s.jsx(Ht,{label:n("settings.theme.colorBorderDefault"),value:a.borderDefault,onChange:c=>i("borderDefault",c)}),s.jsx(Ht,{label:n("settings.theme.colorAccent"),value:a.accentColor,onChange:c=>i("accentColor",c)})]})]}),s.jsxs("div",{children:[s.jsxs(Bn,{title:n("settings.theme.sectionChatBubbles"),children:[s.jsx(Ht,{label:n("settings.theme.colorUserBubble"),value:a.userBubble,onChange:c=>i("userBubble",c)}),s.jsx(Ht,{label:n("settings.theme.colorUserText"),value:a.userText,onChange:c=>i("userText",c)}),s.jsx(Ht,{label:n("settings.theme.colorAgentBubble"),value:a.assistantBubble,onChange:c=>i("assistantBubble",c)}),s.jsx(Ht,{label:n("settings.theme.colorAgentText"),value:a.assistantText,onChange:c=>i("assistantText",c)})]}),s.jsxs(Bn,{title:n("settings.theme.sectionChatLayout"),children:[s.jsx(Ht,{label:n("settings.theme.colorChatBg"),value:a.containerBg,onChange:c=>i("containerBg",c)}),s.jsx(Ht,{label:n("settings.theme.colorSendButton"),value:a.sendButton,onChange:c=>i("sendButton",c)}),s.jsx(Ht,{label:n("settings.theme.colorInputBorder"),value:a.inputBorder,onChange:c=>i("inputBorder",c)}),s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},children:[s.jsx("span",{style:{fontSize:"0.75rem",color:"var(--text-secondary)",flex:"1 1 0",minWidth:0},children:n("settings.theme.labelBubbleRadius")}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flex:1},children:[s.jsx("input",{type:"range",min:4,max:24,value:a.bubbleRadius,onChange:c=>i("bubbleRadius",Number(c.target.value)),style:{flex:1,accentColor:"var(--accent-primary)"}}),s.jsxs("span",{style:{fontSize:"0.7rem",color:"var(--text-muted)",width:28,textAlign:"right"},children:[a.bubbleRadius,"px"]})]})]})]})]})]}),s.jsx("button",{onClick:()=>{const c=e?di:ui,p=os(e?"light":"dark");e?Tr(c,p):Tr(p,c),o(c),qs(c),t(c)},style:{marginTop:10,fontSize:"0.7rem",color:"var(--text-muted)",background:"transparent",border:"1px solid var(--border-subtle)",borderRadius:6,padding:"4px 10px",cursor:"pointer"},children:n("settings.theme.resetToDefaults")})]})}function sC(){const{t:e}=Ne("common"),[t,n]=l.useState(Kr),[r,a]=l.useState(!0),[o,i]=l.useState(()=>os("dark"));l.useEffect(()=>{a(zs());const p=new MutationObserver(()=>{const f=zs();a(f);const g=Kr();g==="custom"?qs(os(f?"dark":"light")):sr(g,f?"dark":"light")});p.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]});const u=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{const f=zs();a(f);const g=Kr();g==="custom"?qs(os(f?"dark":"light")):sr(g,f?"dark":"light")};return u.addEventListener("change",m),()=>{p.disconnect(),u.removeEventListener("change",m)}},[]),l.useEffect(()=>{document.documentElement.setAttribute("data-chat-theme",t),t==="custom"?qs(os(r?"dark":"light")):(Ji(),sr(t,r?"dark":"light"))},[t,r]),l.useEffect(()=>{i(os(r?"dark":"light"))},[r]);const c=p=>{n(p),ZS(p)},d=[...QS,{id:"custom",name:"Custom",description:"Full app + chat customization",preview:{dark:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText},light:{userBubble:o.userBubble,assistantBubble:o.assistantBubble,assistantBorder:`1px solid ${o.accentColor}22`,containerBg:o.containerBg,textColor:o.assistantText}}}];return s.jsxs("div",{children:[s.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-4 gap-3",children:d.map(p=>{const u=t===p.id,m=r?p.preview.dark:p.preview.light,f=p.id==="honey"||p.id==="ember"?"#1a1a1a":p.id==="custom"?o.userText:"#fff";return s.jsxs("button",{onClick:()=>c(p.id),className:"text-left rounded-xl p-3 transition-all",style:{background:u?"var(--bg-glass-hover)":"var(--bg-glass)",border:u?"2px solid var(--accent-primary)":"2px solid var(--border-subtle)",opacity:u?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:[u&&s.jsx("span",{className:"w-2 h-2 rounded-full bg-accent shrink-0"}),s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-bold text-text-primary",children:p.id==="custom"?e("settings.theme.customLabel"):p.name}),s.jsx("div",{className:"text-[10px] text-text-muted",children:p.description})]})]})]},p.id)})}),t==="custom"&&s.jsx(tC,{dark:r,onColorsChange:p=>i(p)})]})}const Qi="adhdev_mobileDashboardMode_v1",pi="adhdev:mobile-dashboard-mode-change";function Xi(){try{return localStorage.getItem(Qi)==="workspace"?"workspace":"chat"}catch{return"chat"}}function nC(e){if(typeof window>"u")return()=>{};const t=a=>{e(a??Xi())},n=a=>{const o=a.detail;t(o)},r=a=>{a.key&&a.key!==Qi||t()};return window.addEventListener(pi,n),window.addEventListener("storage",r),()=>{window.removeEventListener(pi,n),window.removeEventListener("storage",r)}}function rC(e){try{localStorage.setItem(Qi,e)}catch{}typeof window<"u"&&window.dispatchEvent(new CustomEvent(pi,{detail:e}))}function aC(){const[e,t]=l.useState(!0);return l.useEffect(()=>{t(Xi()==="chat")},[]),s.jsx(Bs,{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),rC(n?"chat":"workspace")},extra:s.jsx("span",{className:"text-[11px] text-text-muted",children:e?"Chat mode":"Workspace"})})}const oC="Choose a preset or create a fully custom theme. Custom themes control the entire app — backgrounds, text, borders, and chat bubbles.",iC="Choose whether the dashboard opens like a chat app on phones or keeps the full workspace layout.";function lC({themeDescription:e=oC,mobileDescription:t=iC,fontsSlot:n}){const{t:r}=Ne("common");return s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-xs text-text-muted mb-2 font-medium",children:r("settings.appearance.modeLabel")}),s.jsx(VS,{})]}),s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:r("settings.appearance.themeLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:e}),s.jsx(sC,{})]}),n,s.jsxs("div",{className:"border-t border-border-subtle pt-4",children:[s.jsx("div",{className:"text-xs text-text-muted mb-1 font-medium",children:r("settings.appearance.mobileLabel")}),s.jsx("p",{className:"text-[11px] text-text-muted mb-3",children:t}),s.jsx(aC,{})]})]})}const lo=new Map,Mc=new Map;function cC(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 dC(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 Pp(){const{sendCommand:e}=vt(),{injectEntries:t,getIdes:n}=ar();return l.useCallback(async(r,a)=>{if(!r)return;const o=(a==null?void 0:a.minFreshMs)??C0,i=Mc.get(r)||0;if(!(a!=null&&a.force)&&i>0&&Date.now()-i<o)return;const c=lo.get(r);if(c)return c;const d=(async()=>{const p=await e(r,"get_machine_runtime_stats"),u=cC(p);if(!u)return;const m=n().find(g=>g.id===r),f=dC(m,r,u.machine,u.timestamp||Date.now());t([f]),Mc.set(r,Date.now())})().finally(()=>{lo.delete(r)});return lo.set(r,d),d},[n,t,e])}function uC(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 pC(e,t){const{sendData:n}=vt(),{injectEntries:r,getIdes:a}=ar(),o=Array.from(new Set(e.filter(Boolean))).join("|");l.useEffect(()=>{if(!(t!=null&&t.enabled)||!n)return;const i=o?o.split("|"):[];if(i.length===0)return;const c=i.map(d=>ls.subscribe({sendData:n},d,{type:"subscribe",topic:"machine.runtime",key:`machine:${d}`,params:{intervalMs:t==null?void 0:t.intervalMs}},u=>{const m=a().find(g=>g.id===d),f=uC(m,d,u);r([f])}));return()=>{c.forEach(d=>d())}},[o,a,r,t==null?void 0:t.enabled,t==null?void 0:t.intervalMs,n])}function mC(e,t){const{sendData:n}=vt(),[r,a]=l.useState(null),[o,i]=l.useState(!1);return l.useEffect(()=>{if(!e){a(null),i(!1);return}if(!(t!=null&&t.enabled)||!n){i(!1);return}a(null),i(!0);let c=null;const d=ls.subscribe({sendData:n},e,{type:"subscribe",topic:"session_host.diagnostics",key:`session_host:${e}`,params:{includeSessions:(t==null?void 0:t.includeSessions)!==!1,...typeof(t==null?void 0:t.limit)=="number"?{limit:t.limit}:{},...typeof(t==null?void 0:t.intervalMs)=="number"?{intervalMs:t.intervalMs}:{}}},p=>{c&&(clearTimeout(c),c=null),a(p.diagnostics),i(!1)});return d.initialSendAccepted?c=setTimeout(()=>{i(!1)},A0):i(!1),()=>{c&&clearTimeout(c),d()}},[e,t==null?void 0:t.enabled,t==null?void 0:t.includeSessions,t==null?void 0:t.intervalMs,t==null?void 0:t.limit,n]),{diagnostics:r,loading:o,applyDiagnostics:a}}function hC(e){return e.daemonId||(e.routeId.includes(":")?e.routeId.split(":")[0]||null:e.routeId||null)}function Lp(e){const{sendData:t}=vt(),[n,r]=l.useState({});return l.useEffect(()=>{const a=hC(e);if(!a||!e.sessionId||!t){r({});return}const o=ls.subscribe({sendData:t},a,{type:"subscribe",topic:"session.modal",key:`daemon:${a}:session-modal:${e.sessionId}`,params:{targetSessionId:e.sessionId}},i=>{r({status:i.status,modalMessage:i.modalMessage,modalButtons:i.modalButtons}),bn.record({interactionId:i.interactionId,kind:"dashboard.session_modal_applied",topic:"session.modal",payload:{sessionId:e.sessionId,status:i.status,modalButtonCount:Array.isArray(i.modalButtons)?i.modalButtons.length:0}})});return o.initialSendAccepted||r({}),()=>{o()}},[e.daemonId,e.routeId,e.sessionId,t]),n}function fC(e){if(!e||typeof e!="object")return!1;const t=e.result??e;return!!t&&typeof t=="object"&&t.success!==!1}function bC(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 gC(e,t,n){const r=await n(`/api/v1/sessions/${encodeURIComponent(e)}/interactive-prompt/resolve`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let a=`HTTP ${r.status}`;try{const o=await r.json();typeof(o==null?void 0:o.error)=="string"&&(a=o.error)}catch{}throw new Error(a)}}async function xC({promptSession:e,response:t,useP2PCommand:n,sendCommand:r,fetchImpl:a=fetch}){if(n){const o=await r(e.routeId,"interactive_prompt_response",{targetSessionId:e.sessionId,sessionId:e.sessionId,response:t});if(!fC(o))throw new Error(bC(o));return}await gC(e.sessionId,t,a)}function Rp(e){const{ides:t,isP2PActive:n,p2pStates:r}=gs(),{sendCommand:a}=vt(),[o,i]=l.useState(null),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useRef(!1),f=l.useMemo(()=>Tb(t,e),[t,e]),g=!!f,C=l.useMemo(()=>f?f.prompt.promptId===o?null:f:null,[o,f]),h=l.useCallback(async b=>{if(!C||m.current)return;m.current=!0;const S=cu(C.prompt,b);d(!0),u(null);try{const k=(r==null?void 0:r[C.daemonId])==="connected"||n===!0;await xC({promptSession:C,response:S,useP2PCommand:k,sendCommand:a}),i(C.prompt.promptId)}catch(k){throw u(k instanceof Error?k.message:String(k)),k}finally{d(!1),m.current=!1}},[n,r,C,a]),x=l.useCallback(()=>{C&&i(C.prompt.promptId)},[C]),y=l.useCallback(()=>{i(null),u(null)},[]);return{promptSession:C,hasActivePrompt:g,responseError:p,isSubmitting:c,submit:h,cancel:x,reopen:y}}function Ep(e){return e instanceof Error?e.message:String(e||"")}function vC(e){const t=Ep(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 yC(e){const t=Ep(e);return t.includes("P2P command timeout")||t.includes("P2P data channel closed")||t.includes("P2P receiver stopped")}async function _p({conversation:e,mode:t,ides:n,sendDaemonCommand:r,setCliViewModeOverrides:a}){if(!e||!ct(e)||lt(e))return;const o=In(e);if(o===t)return;const i=e.sessionId;i&&a(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 d=yC(c);i&&!d&&a(p=>{const u={...p};return o===kC(n,i)?delete u[i]:u[i]=o,u}),vC(c)?console.warn(d?"CLI view mode result was lost after send; keeping optimistic mode override:":"Skipped CLI view mode switch:",c instanceof Error?c.message:String(c)):console.error("Failed to switch CLI view mode:",c)}}function Dc(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 wC(e,t){if(!Array.isArray(e)||e.length===0||!t||Object.keys(t).length===0)return e;let n=!1;const r=e.map(a=>{const o=Dc(a,t),i=Array.isArray(a.childSessions)?a.childSessions.map(d=>Dc(d,t)):a.childSessions,c=i!==a.childSessions;return o!==a||c?(n=!0,{...o,...c?{childSessions:i}:{}}):a});return n?r:e}function kC(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 SC({visibleConversations:e,clearedTabs:t,setClearedTabs:n,setActionLogs:r,isConversationMuted:a}){l.useEffect(()=>{Cu()},[]);const o=l.useMemo(()=>e.map(i=>({id:i.tabKey,name:cp(i),status:i.status,activeModal:i.modalMessage?{message:i.modalMessage,buttons:i.modalButtons}:null,target:{providerSessionId:i.providerSessionId,sessionId:i.sessionId,tabKey:i.tabKey,routeId:i.routeId},muted:a?a(i):!1})),[e,a]);return Qy(o),l.useEffect(()=>{if(Object.keys(t).length===0)return;const c=setTimeout(()=>{n(d=>{const p=Date.now(),u={};for(const[m,f]of Object.entries(d))p-f<5e3&&(u[m]=f);return Object.keys(u).length===Object.keys(d).length?d:u})},5500);return()=>clearTimeout(c)},[t,n]),l.useEffect(()=>{const i=setInterval(()=>{const c=Date.now()-3e5;r(d=>{const p=d.filter(u=>u.timestamp>c).slice(-100);return p.length===d.length?d:p})},6e4);return()=>clearInterval(i)},[r]),null}function Pc(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"){const t=Date.parse(e);if(Number.isFinite(t))return t}return 0}function Ks(e){const t=[...e.messages].reverse().find(a=>!(a!=null&&a._localId))||e.messages[e.messages.length-1],n=typeof e.lastMessageAt=="number"&&Number.isFinite(e.lastMessageAt)?e.lastMessageAt:0,r=Pc(t==null?void 0:t.receivedAt)||Pc(t==null?void 0:t.timestamp)||0;return Math.max(n,r)}function mi(e,t=0){return Ks(e)||e.lastUpdated||t||0}function $p(e){return Ks(e)||e.lastUpdated||0}function Hp(e,t,n=$p){const r=n(t)-n(e);if(r!==0)return r;const a=(e.machineName||"").localeCompare(t.machineName||"");if(a!==0)return a;const o=e.displayPrimary.localeCompare(t.displayPrimary);if(o!==0)return o;const i=e.displaySecondary.localeCompare(t.displaySecondary);return i!==0?i:e.tabKey.localeCompare(t.tabKey)}function hi(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 CC(e){var t;return e.messages.length===0&&!((t=e.modalButtons)!=null&&t.length)&&!hi(e)&&!e.title.trim()}function jC(e){return e.length===0?null:[...e].sort((t,n)=>{const r=Number(hi(n))-Number(hi(t));if(r!==0)return r;const a=n.messages.length-t.messages.length;return a!==0?a:Hp(t,n)})[0]||null}function cs(e,t){const n=e.filter(i=>i.routeId===t);if(n.length===0)return null;const r=n.find(i=>i.streamSource==="native")||null,a=n.filter(i=>i.streamSource==="agent-stream"),o=jC(a);return r?o&&CC(r)?o:r:o||n[0]||null}function NC(e){const t=e.filter(a=>a.type!=="adhdev-daemon"),n=new Set;for(const a of t){if(!Xo(a))continue;const o=xu(a);o&&n.add(o)}const r=new Map;for(const a of t){const o=Iy(a,n),i=r.get(o);if(!i){r.set(o,a);continue}const c=m=>(m.workspace?1:0)+(m.activeChat?1:0)+(m.lastMessagePreview?1:0),d=c(i),p=c(a),u=p>d||p===d&&(a.timestamp||0)>(i.timestamp||0)?a:i;r.set(o,AC(u,u===a?i:a))}return Array.from(r.values())}function AC(e,t){const n=Xo(t),r=Xo(e);if(!n&&!r)return e;const a=r?n?void 0:t:e,o=r?e:n?t:void 0,i=a&&String(a.daemonId||"").trim()||String(e.ownerDaemonId||"").trim()||String(t.ownerDaemonId||"").trim()||void 0,c=String(e.ownerMachineName||"").trim()||String(t.ownerMachineName||"").trim()||void 0,d=o==null?void 0:o.settings;return{...e,...i&&{ownerDaemonId:i},...c&&!e.ownerMachineName&&{ownerMachineName:c},...d&&!r&&{settings:{...d,...e.settings??{}}}}}function co(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function IC(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 Lc(e){if(!e)return"";const t=Array.isArray(e.messages)?e.messages:[],n=t[t.length-1],r=n?IC(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 TC(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||""),Lc(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||""),Lc(n.activeChat)].join(":"))].join("|")}function MC(e,t){const n=Date.now();return e.map(r=>{const a=t[r.tabKey];return a&&n-a<5e3?{...r,messages:[],title:""}:r})}function DC(e,t){const n=new Map;for(const r of e){const a=t.get(r.routeId)||r;for(const o of Xn({routeId:r.routeId}))n.set(o,a);for(const o of Xn({providerSessionId:r.providerSessionId,sessionId:r.sessionId}))n.set(o,r.streamSource==="native"?a:r);for(const o of Xn({tabKey:r.tabKey}))n.set(o,r)}return n}function PC(e){return[...e.messages].reverse().find(t=>!(t!=null&&t._localId))||e.messages[e.messages.length-1]}function LC(e){const t=PC(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 RC({ides:e,connectionStates:t,clearedTabs:n}){const r=l.useMemo(()=>NC(e),[e]),a=l.useMemo(()=>pu(e),[e]),o=l.useMemo(()=>yp(e),[e]),i=l.useRef([]),c=l.useRef([]),d=l.useRef([]),p=l.useRef(new Map),u=l.useRef(new Map),m=l.useMemo(()=>{const k=new Map,w=[];for(const A of r){const{connectionState:I="new",machineName:D}=wp(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),L=TC(A),P=p.current.get(A.id);if(P&&P.ide===A&&P.sourceSignature===L&&P.connectionState===I&&P.machineName===D){k.set(A.id,P),w.push(...P.conversations);continue}const _=Vi(A,{machineNames:o,connectionStates:t,defaultConnectionState:"new"}),q={ide:A,sourceSignature:L,connectionState:I,machineName:D,conversations:_};k.set(A.id,q),w.push(..._)}p.current=k;const v=new Map,N=A=>{const I=LC(A),D=u.current.get(A.tabKey);if(D&&D.signature===I)return v.set(A.tabKey,D),D.timestamp;const L={signature:I,timestamp:$p(A)||(D==null?void 0:D.timestamp)||0};return v.set(A.tabKey,L),L.timestamp},j=[...w].sort((A,I)=>Hp(A,I,N));return u.current=v,j},[r,t,o]),f=l.useMemo(()=>{const k=MC(m,n);return co(i.current,k)?i.current:(i.current=k,k)},[m,n]),g=l.useMemo(()=>{const k=new Map,w=Array.from(new Set(f.map(v=>v.routeId)));for(const v of w){const N=cs(f,v);N&&k.set(v,N)}return k},[f]),C=l.useMemo(()=>{const k=new Map;for(const w of f){const v=g.get(w.routeId),N=w.streamSource==="native"&&v?v:w;for(const j of Xn({providerSessionId:w.providerSessionId,sessionId:w.sessionId,tabKey:w.tabKey}))k.set(j,N)}return k},[f,g]),h=l.useMemo(()=>DC(f,g),[f,g]),x=l.useCallback(k=>{if(k)return C.get(k)},[C]),y=l.useCallback(k=>{if(k)return h.get(k)},[h]),b=l.useMemo(()=>{const k=f.filter(w=>!Ds(w,a).surfaceHidden);return co(c.current,k)?c.current:(c.current=k,k)},[f,a]),S=l.useMemo(()=>{const k=b.map(w=>w.tabKey);return co(d.current,k)?d.current:(d.current=k,k)},[b]);return{chatIdes:r,conversations:f,visibleConversations:b,visibleTabKeys:S,resolveConversationBySessionId:x,resolveConversationByTarget:y}}function EC({isMobile:e,urlActiveTab:t,resolveConversationBySessionId:n,setSearchParams:r}){const a=l.useMemo(()=>{var c;return e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),o=l.useMemo(()=>{var c;return!e||!t?null:((c=n(t))==null?void 0:c.tabKey)??null},[e,n,t]),i=l.useCallback(()=>{t&&r(c=>{const d=new URLSearchParams(c);return d.delete("activeTab"),d},{replace:!0})},[r,t]);return{requestedDesktopTabKey:a,requestedMobileTabKey:o,consumeRequestedActiveTab:i}}function _C({ides:e,sendDaemonCommand:t,setToasts:n,resolveConversationByTarget:r}){l.useEffect(()=>{mt.setIdes(e)},[e]),l.useEffect(()=>{mt.setResolveAction((a,o,i)=>{t(a,o,i).catch(()=>{})})},[t]),l.useEffect(()=>{const a=mt.onToast(o=>{n(c=>c.some(p=>p.message===o.message&&o.timestamp-p.timestamp<3e3)?c:[...c.slice(-4),{id:o.id,message:o.message,type:o.type,timestamp:o.timestamp,targetKey:o.targetKey,actions:o.actions}]);const i=o.duration||5e3;setTimeout(()=>n(c=>c.filter(d=>d.id!==o.id)),i)});return()=>{a()}},[n]),l.useEffect(()=>{const a=ap.on("status_event",o=>{mt.handleRawEvent(o,"ws")});return()=>{a()}},[]),l.useEffect(()=>{var o;const a=i=>{var h;const c=i.data;if((c==null?void 0:c.type)!=="notification_action"||typeof c.action!="string"||!c.action.startsWith("approval_")||!(c.daemonId||c.targetSessionId||c.targetKey))return;const d=c.targetSessionId||c.targetKey||c.daemonId,p=r(d),u=(p==null?void 0:p.routeId)||c.daemonId;if(!u)return;const m=Number(c.buttonIndex),f=c.button||((h=p==null?void 0:p.modalButtons)==null?void 0:h[m])||"Approve",g=String(f).replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),C=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(g);t(u,"resolve_action",{action:C?"approve":"reject",button:f,...Number.isFinite(m)&&{buttonIndex:m},...(p==null?void 0:p.sessionId)&&{targetSessionId:p.sessionId},...c.targetSessionId&&{targetSessionId:c.targetSessionId}}).catch(x=>console.error("[SW Action] approval failed:",x))};return(o=navigator.serviceWorker)==null||o.addEventListener("message",a),()=>{var i;return(i=navigator.serviceWorker)==null?void 0:i.removeEventListener("message",a)}},[r,t])}const $C="adhdev_dashboardLayout_v1",HC="adhdev_dashboardDockview_v1",BC="adhdev_dashboardDockviewHiddenRestore_v1",Fn={groupAssignments:[],focusedGroup:0,groupActiveTabIds:{},groupTabOrders:{},groupSizes:[]};function Zi(e,t){try{const n=localStorage.getItem(e);return n?JSON.parse(n):t}catch{return t}}function FC(e){return e<768?"mobile":e<1280?"desktop-narrow":"desktop-wide"}function Bp(e){return`${$C}:${e}`}function OC(e){const t=Bp(e);return Zi(t,null)}function WC(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=Bp(e);if(n){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(t))}catch{}}function Fp(e){return`${HC}:${e}`}function UC(e){const t=Fp(e);return Zi(t,null)}function GC(e,t){try{const n=Fp(e);if(!t){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function Op(e){return`${BC}:${e}`}function qC(e){const t=Op(e);return Zi(t,{})}function zC(e,t){try{const n=Op(e);if(Object.keys(t).length===0){localStorage.removeItem(n);return}localStorage.setItem(n,JSON.stringify(t))}catch{}}function KC(){return{groupAssignments:[...Fn.groupAssignments],focusedGroup:Fn.focusedGroup,groupActiveTabIds:{...Fn.groupActiveTabIds},groupTabOrders:{...Fn.groupTabOrders},groupSizes:[...Fn.groupSizes]}}function VC(e,t){return e?e.length===t.length&&e.every((n,r)=>n===t[r]):t.length===0}function YC(){const[e]=l.useState(()=>FC(typeof window<"u"?window.innerWidth:1280)),[t,n]=l.useState(()=>new Map),[r,a]=l.useState(0),[o,i]=l.useState({}),[c,d]=l.useState({}),[p,u]=l.useState([]),[m,f]=l.useState(()=>typeof window<"u"&&window.innerWidth<768),[g,C]=l.useState(!1),h=l.useCallback(()=>{if(g)return;const A=OC(e)??KC();n(new Map(A.groupAssignments)),a(A.focusedGroup),i(A.groupActiveTabIds),d(A.groupTabOrders),u(A.groupSizes),C(!0)},[g,e]);l.useEffect(()=>{g&&WC(e,{groupAssignments:[...t.entries()],focusedGroup:r,groupActiveTabIds:o,groupTabOrders:c,groupSizes:p})},[g,e,t,r,o,c,p]),l.useEffect(()=>{const A=window.matchMedia("(max-width: 767px)"),I=D=>f(D.matches);return A.addEventListener("change",I),()=>A.removeEventListener("change",I)},[]);const x=l.useCallback(A=>{n(A)},[]),y=l.useCallback(A=>{a(A)},[]),b=l.useCallback(A=>{i(A)},[]),S=l.useCallback(A=>{d(A)},[]),k=l.useCallback(A=>{u(A)},[]),w=l.useCallback(A=>{y(A)},[y]),v=l.useCallback((A,I)=>{i(D=>(D[A]??null)===(I??null)?D:{...D,[A]:I})},[]),N=l.useCallback((A,I)=>{d(D=>{const L=D[A];return VC(L,I)?D:{...D,[A]:I}})},[]),j=l.useCallback((A,I)=>{const D=I.get(A)??0;return v(D,A),w(D),D},[w,v]);return{layoutProfile:e,groupAssignments:t,updateGroupAssignments:x,focusedGroup:r,updateFocusedGroup:y,focusGroup:w,groupActiveTabIds:o,updateGroupActiveTabIds:b,setGroupActiveTab:v,groupTabOrders:c,updateGroupTabOrders:S,setGroupTabOrder:N,groupSizes:p,updateGroupSizes:k,isMobile:m,hasHydratedStoredLayout:g,hydrateStoredLayout:h,focusConversationTab:j}}function JC(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0],r=Na(t);return typeof(n==null?void 0:n.id)=="string"&&r.includes(n.id)}function QC({urlActiveTab:e,conversations:t,resolveConversationBySessionId:n,normalizedGroupAssignments:r,hasHydratedStoredLayout:a,hydrateStoredLayout:o,focusConversationTab:i,setSearchParams:c,historyModalOpen:d,activeConv:p,isRefreshingHistory:u,ides:m,handleRefreshHistory:f}){const g=l.useRef(!1),C=l.useRef(!1),h=l.useRef(null),x=l.useRef(!1);l.useEffect(()=>{if(!e||g.current||t.length===0)return;if(!a){o();return}const y=n(e);y&&(i(y.tabKey,r),g.current=!0,C.current=!0,h.current!=null&&(window.clearTimeout(h.current),h.current=null),c(b=>{const S=new URLSearchParams(b);return S.delete("activeTab"),S},{replace:!0}))},[e,t,n,r,a,o,i,c]),l.useEffect(()=>{if(!(C.current||a)&&t.length!==0){if(!e){o(),C.current=!0;return}if(g.current){C.current=!0;return}if(h.current==null)return h.current=window.setTimeout(()=>{h.current=null,!(C.current||a)&&(o(),C.current=!0)},1500),()=>{h.current!=null&&(window.clearTimeout(h.current),h.current=null)}}},[e,t.length,a,o]),l.useEffect(()=>{if(!d){x.current=!1;return}if(!p||x.current||u)return;const y=m.find(b=>b.id===p.routeId);y&&(!y.chats||y.chats.length===0||JC(y.chats,p))&&(x.current=!0,f())},[d,p,u,m,f])}function uo(e,t){if(!Array.isArray(e)||e.length!==1||!t)return!1;const n=e[0];if((n==null?void 0:n.active)===!0)return!0;const r=Na(t);return typeof(n==null?void 0:n.id)=="string"&&r.includes(n.id)}function Wp({sendDaemonCommand:e,activeConv:t,chats:n,updateRouteChats:r,setToasts:a,setClearedTabs:o}){const[i,c]=l.useState(!1),[d,p]=l.useState(!1),u=l.useCallback(async C=>{try{await e("standalone","launch_ide",{ideType:C,enableCdp:!0})}catch(h){console.error("Launch failed",h)}},[e]),m=l.useCallback(async(C,h)=>{try{const x=C||(t==null?void 0:t.daemonId)||"",y=await e(x,"switch_chat",{id:h,sessionId:h,...Ws(t)}),b=y==null?void 0:y.result;if((y==null?void 0:y.success)===!0||b==="switched"||b==="switched-by-title")return;b===!1||b==="not_found"?on(a,"⚠️ Session tab not found — try refreshing history"):typeof b=="string"&&b.startsWith("error:")?on(a,`⚠️ Switch error: ${b}`):on(a,"⚠️ Session switch failed")}catch(x){console.error("Switch failed",x),on(a,`❌ Switch failed: ${x.message||"connection error"}`)}},[t,e,a]),f=l.useCallback(async()=>{if(!(!t||i)){c(!0);try{const C=Us(t);await e(C,"new_chat",{...Ws(t)}),z0(C,t.sessionId,Na(t)[0]),o(h=>({...h,[t.tabKey]:Date.now()}))}catch(C){console.error("New chat failed",C)}finally{c(!1)}}},[t,i,e,o]),g=l.useCallback(async()=>{var C,h;if(!(!t||d)){p(!0);try{const x=Us(t),y=async()=>e(x,"list_chats",{forceExpand:!0,...Ws(t)});let b=await y(),S=(b==null?void 0:b.chats)||((C=b==null?void 0:b.result)==null?void 0:C.chats);uo(S,t)&&(await new Promise(k=>setTimeout(k,450)),b=await y(),S=(b==null?void 0:b.chats)||((h=b==null?void 0:b.result)==null?void 0:h.chats)),b!=null&&b.success&&Array.isArray(S)&&(r(t.routeId,S),uo(S,t)&&!uo(n,t)&&on(a,"⚠️ History dialog did not fully open — try once more"))}catch(x){console.error("Refresh history failed",x)}finally{p(!1)}}},[t,n,d,e,r,a]);return{isCreatingChat:i,isRefreshingHistory:d,handleLaunchIde:u,handleSwitchSession:m,handleNewChat:f,handleRefreshHistory:g}}function XC(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 ZC(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function Rc(e,t){const n=Object.keys(e),r=Object.keys(t);return n.length!==r.length?!1:n.every(a=>t[Number(a)]===e[Number(a)])}function 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 a={};r.forEach((i,c)=>{a[i]=c}),r.length===0&&(a[0]=0);const o=new Map;for(const[i,c]of e){if(!n.has(i)||c<=0)continue;const d=a[c];typeof d=="number"&&d>0&&o.set(i,d)}return{assignments:o,groupCount:Math.max(1,r.length),mapping:a,usedGroups:r}}function Ec(e,t){const n={};for(const[r,a]of Object.entries(e)){const o=t[Number(r)];typeof o=="number"&&(n[o]=a)}return n}function ej(e,t,n){if(t.length===0)return 0;if(typeof n[e]=="number")return n[e];const r=[...t].reverse().find(a=>a<e)??t[0];return n[r]??0}function tj(e,t,n){if(t.length<=1)return[];const r=t.map(i=>e[i]).filter(i=>Number.isFinite(i)),a=r.length===t.length?r:Array(n).fill(100/n),o=a.reduce((i,c)=>i+c,0);return o>0?a.map(i=>i/o*100):Array(n).fill(100/n)}function _c(e,t){const n={};for(const[r,a]of Object.entries(e)){const o=Number(r);n[o>=t?o+1:o]=a}return n}function $c(e){return Array(e).fill(100/e)}function sj({groupAssignments:e,updateGroupAssignments:t,updateFocusedGroup:n,updateGroupActiveTabIds:r,updateGroupTabOrders:a,groupSizes:o,updateGroupSizes:i,isMobile:c,visibleConversations:d,visibleTabKeys:p}){const u=l.useRef(null),m=l.useMemo(()=>Mr(e,p),[e,p]),f=m.assignments,g=l.useMemo(()=>c?1:m.groupCount,[m.groupCount,c]),C=g>1,h=l.useCallback((w,v)=>{t(N=>{const j=new Map(Mr(N,p).assignments);return v===0?j.delete(w):j.set(w,v),j}),r(N=>({...N,[v]:w})),n(v)},[t,p,r,n]),x=l.useCallback(w=>{t(v=>{const N=Mr(v,p).assignments,j=new Map;for(const[A,I]of N)I!==w&&(I>w?j.set(A,I-1):j.set(A,I));return j}),i(v=>{if(v.length<=1)return[];const N=[...v];N.splice(w,1);const j=N.reduce((A,I)=>A+I,0);return j>0?N.map(A=>A/j*100):[]}),n(0)},[t,p,i,n]),y=l.useCallback((w,v)=>{v.preventDefault();const N=u.current;if(!N)return;const j=v.clientX,A=N.offsetWidth,I=o.length===g?[...o]:$c(g),D=P=>{const q=(P.clientX-j)/A*100,B=[...I];B[w]=Math.max(15,I[w]+q),B[w+1]=Math.max(15,I[w+1]-q),i(B)},L=()=>{document.removeEventListener("mousemove",D),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",D),document.addEventListener("mouseup",L)},[o,g,i]),b=l.useCallback((w,v,N)=>{if(g>=4)return;const j=N==="left"?v:v+1;t(A=>{const I=Mr(A,p).assignments,D=new Map;for(const L of d){const P=I.get(L.tabKey)??0,_=P>=j?P+1:P;_>0&&D.set(L.tabKey,_)}return j>0&&D.set(w,j),D}),i(A=>{const I=A.length===g?[...A]:$c(g),D=I[v]??100/g,L=Math.max(15,D/2),P=Math.max(15,D/2),_=[...I];_[v]=L,_.splice(j,0,P);const q=_.reduce((B,E)=>B+E,0);return _.map(B=>B/q*100)}),r(A=>{const I=_c(A,j);return I[j]=w,I}),a(A=>{const I=_c(A,j);return I[j]=[w],I}),n(j)},[g,t,p,d,i,r,a,n]);l.useEffect(()=>{XC(e,f)||t(f)},[e,f,t]),l.useEffect(()=>{const{mapping:w,usedGroups:v}=m;r(N=>{const j=Ec(N,w);return Rc(N,j)?N:j}),a(N=>{const j=Ec(N,w);return Rc(N,j)?N:j}),n(N=>{const j=c?0:ej(N,v,w);return N===j?N:j}),i(N=>{const j=c?[]:tj(N,v,m.groupCount);return ZC(N,j)?N:j})},[m,c,r,a,n,i]);const S=l.useMemo(()=>{const w=Array.from({length:g},()=>[]);for(const v of d){const N=f.get(v.tabKey)??0,j=Math.min(N,g-1);w[j].push(v)}return w},[d,f,g]),k=l.useCallback(()=>{t(new Map),n(0)},[t,n]);return{containerRef:u,normalizedGroupAssignments:f,numGroups:g,isSplitMode:C,groupedConvs:S,moveTabToGroup:h,closeGroup:x,handleResizeStart:y,splitTabRelative:b,clearAllSplits:k}}function po(e){if(typeof e!="string")return null;const t=e.trim().toLowerCase();return t==="stable"||t==="latest"?"stable":t==="preview"||t==="next"?"preview":null}function nj(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 el(e){const t=e.updatePolicy&&typeof e.updatePolicy=="object"?e.updatePolicy:{},n=po(t.channel)||po(e.updateChannel)||po(e.releaseChannel)||void 0,r=nj(t.npmTag)||(n==="preview"?"next":n==="stable"?"latest":void 0),a=Dr(t.targetVersion)||Dr(e.serverVersion)||void 0,o=Dr(t.minVersion)||void 0,i=Dr(t.updateCommand)||(n?`adhdev update --channel ${n}`:void 0);return{...n?{channel:n}:{},...r?{npmTag:r}:{},...a?{targetVersion:a}:{},...o?{minVersion:o}:{},...i?{updateCommand:i}:{}}}function dn(e,t=null){return el(e).targetVersion||t}function Up(e){return el(e).channel||null}function Gp(e){const t=el(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 rj({ides:e,sendDaemonCommand:t}){const n="0.9.82",r=l.useMemo(()=>e.filter(m=>m.type!=="adhdev-daemon"?!1:Yi(m,dn(m,n))).sort((m,f)=>Number(tr(f,dn(f,n)))-Number(tr(m,dn(m,n)))),[n,e]),a=l.useMemo(()=>r.some(m=>tr(m,dn(m,n))),[n,r]),o=l.useMemo(()=>r.map(m=>dn(m,n)).find(m=>typeof m=="string"&&m.trim().length>0)||n,[n,r]),[i,c]=l.useState(!1),[d,p]=l.useState({}),u=l.useCallback(async m=>{var g,C;const f=e.find(h=>h.id===m);if(f){p(h=>({...h,[m]:"upgrading"}));try{const h=await t(m,"daemon_upgrade",Gp(f));(g=h==null?void 0:h.result)!=null&&g.upgraded||(C=h==null?void 0:h.result)!=null&&C.success?p(x=>({...x,[m]:"done"})):p(x=>({...x,[m]:"error"}))}catch{p(h=>({...h,[m]:"error"}))}}},[e,t]);return{versionMismatchDaemons:r,hasRequiredVersionDaemons:a,targetVersion:o,versionBannerDismissed:i,setVersionBannerDismissed:c,upgradingDaemons:d,handleBannerUpgrade:u}}const qp=80;function Vr(e,t=Date.now()){return typeof e=="number"&&Number.isFinite(e)?e:t}function aj(e){return{...e,createdAt:Vr(e.createdAt),updatedAt:Vr(e.updatedAt,e.createdAt),lastEventAt:Vr(e.lastEventAt,e.updatedAt||e.createdAt)}}function oj(e){const t=gu(e);return t==="unknown:"?e.id:t}function ij(e){return[e.type,bu(e)||"",e.lastMessageHash||"",String(e.lastMessageAt||e.lastUpdated||0)].join("|")}function lj(e,t=qp){const n=new Map;for(const r of e){if(r.deletedAt)continue;const a=oj(r),o=n.get(a);if(!o){n.set(a,r);continue}(r.updatedAt>o.updatedAt||r.updatedAt===o.updatedAt&&r.createdAt>o.createdAt)&&n.set(a,r)}return Array.from(n.values()).sort((r,a)=>{const o=a.updatedAt-r.updatedAt;return o!==0?o:a.createdAt-r.createdAt}).slice(0,Math.max(0,t))}function cj(e,t){const n=Date.now(),r=[];for(const a of e){const o=a.sessionId?t.get(a.sessionId):void 0;if(o!=null&&o.surfaceHidden||o!=null&&o.muted)continue;const i=ja(a,t),c=i.inboxBucket==="needs_attention"?"needs_attention":i.inboxBucket==="task_complete"&&i.unread?"task_complete":null;if(!c)continue;const d=Vr(a.lastMessageAt||(o==null?void 0:o.lastUpdated)||a.lastUpdated,n),p=ij({type:c,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,lastMessageHash:a.lastMessageHash,lastMessageAt:a.lastMessageAt,lastUpdated:(o==null?void 0:o.lastUpdated)||a.lastUpdated});r.push(aj({id:p,dedupKey:p,type:c,routeId:a.routeId,machineId:a.daemonId||a.routeId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,tabKey:a.tabKey,title:$u(a),preview:r0(a),createdAt:d,updatedAt:d,lastEventAt:d}))}return lj(r)}function dj(e){return e.filter(t=>!t.readAt&&!t.deletedAt).length}function uj(e){const{conversations:t,liveSessionInboxState:n,maxItems:r=qp}=e,a=l.useMemo(()=>cj(t,n).slice(0,Math.max(0,r)),[t,n,r]),o=l.useMemo(()=>dj(a),[a]);return{notifications:a,unreadCount:o}}function pj({notifications:e,sendDaemonCommand:t}){const n=l.useCallback(o=>{const i=e.find(d=>d.id===o),c=Math.max(Date.now(),(i==null?void 0:i.updatedAt)||0);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_session_seen",{sessionId:i.sessionId,seenAt:c}).catch(()=>{})},[e,t]),r=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"mark_notification_unread",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]),a=l.useCallback(o=>{const i=e.find(c=>c.id===o);i!=null&&i.sessionId&&t(i.machineId||i.routeId,"delete_notification",{sessionId:i.sessionId,notificationId:i.id}).catch(()=>{})},[e,t]);return{handleMarkDashboardNotificationRead:n,handleMarkDashboardNotificationUnread:r,handleDeleteDashboardNotification:a}}function tl(...e){const t=new Set,n=[],r=a=>{const o=typeof a=="string"?a.trim():"";if(!o)return;const i=o.toLowerCase();t.has(i)||(t.add(i),n.push(o))};for(const a of e){if(Array.isArray(a)){for(const o of a)r(o);continue}r(a)}return n}function mj(e){const t=e.trim();if(!t)return null;if(t.startsWith("~"))return t;if(/^[A-Za-z]:$/.test(t))return`${t[0].toUpperCase()}:\\`;if(/^[A-Za-z]:[\\/]/.test(t))return`${t[0].toUpperCase()}:${t.slice(2).replace(/\//g,"\\")}`;if(/^[A-Za-z]:[^\\/].*$/.test(t))return`${t[0].toUpperCase()}:\\${t.slice(2).replace(/[\\/]+/g,"\\")}`;const n=t.match(/^[/\\]([A-Za-z])(?:[/\\](.*))?$/);if(n){const r=n[1].toUpperCase(),a=(n[2]||"").replace(/[\\/]+/g,"\\");return a?`${r}:\\${a}`:`${r}:\\`}return null}function sl(e,t=[]){if(e==="win32"){for(const n of t){if(typeof n!="string")continue;const r=mj(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 hj(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 fj(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}async function nl(e,t,n){const r=await e(t,"file_list_browse",{path:n}),a=fj(r);if(!(a!=null&&a.success))throw new Error((a==null?void 0:a.error)||(r==null?void 0:r.error)||"Could not browse folder");const o=typeof(a==null?void 0:a.path)=="string"?a.path:n,i=o.includes("\\")?"\\":"/",c=(p,u)=>/^[A-Za-z]:\\?$/.test(p)?`${p.replace(/\\?$/,"\\")}${u}`:p==="/"||p==="\\"?`${i}${u}`:`${p.replace(/[\\/]+$/,"")}${i}${u}`,d=Array.isArray(a==null?void 0:a.files)?a.files.filter(p=>(p==null?void 0:p.type)==="directory"&&typeof(p==null?void 0:p.name)=="string").map(p=>({name:p.name,path:typeof(p==null?void 0:p.path)=="string"&&p.path.trim()?p.path:c(o,p.name)})).sort((p,u)=>p.name.localeCompare(u.name)):[];return{path:o,directories:d}}function Hc(e,t){const n=t.meshId||"",r={meshId:n,workspace:t.workspace||"",serverName:t.serverName||"adhdev-mesh",adhdevMcpCommand:t.adhdevMcpCommand||"adhdev-mcp",adhdevMcpArgs:t.adhdevMcpArgs||`mcp --mode ipc --repo-mesh ${n}`};return e.replace(/\{\{\s*(meshId|workspace|serverName|adhdevMcpCommand|adhdevMcpArgs)\s*\}\}/g,(a,o)=>r[o]||"")}function zp(e,t={}){const n=e==null?void 0:e.mcpConfig;if((n==null?void 0:n.mode)!=="manual")return null;const a=Hc(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"}).trim();return!a.includes(`
70
+ `)&&!a.startsWith("{")?null:{serverName:n.serverName||"adhdev-mesh",configFormat:n.format,configPathCommand:n.configPathCommand,requiresRestart:n.requiresRestart===!0,instructions:n.instructions||"This provider requires manual MCP setup before it can act as a Repo Mesh coordinator.",template:Hc(n.template||"",{...t,serverName:n.serverName||"adhdev-mesh"})}}function bj(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 Kp(e){return Aa(e)||e.tabKey||e.routeId||null}function Vp(e){const t=typeof e.entrySessionId=="string"?e.entrySessionId.trim():"",n=typeof e.entryInstanceId=="string"?e.entryInstanceId.trim():"",r=typeof e.entryRouteId=="string"?e.entryRouteId.trim():"",a=e.conversations.find(o=>{if(r&&o.routeId!==r)return!1;const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey].map(c=>typeof c=="string"?c.trim():"").filter(Boolean);return!!(t&&i.includes(t)||n&&i.includes(n)||r&&o.routeId===r)});if(a!=null&&a.tabKey)return a.tabKey;if(r){const o=cs(e.conversations,r)||e.conversations.find(i=>i.routeId===r);if(o!=null&&o.tabKey)return o.tabKey}return t||n||r||null}function Ns(e){return String(e||"").trim()}function Yp(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function ga(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function gj(e,t){return!e||!t?!1:e===t||e.endsWith(`/${t}`)||t.endsWith(`/${e}`)}function xj(e,t){const n=Ns(e.providerSessionId),r=Ns(e.targetSessionId),a=t.find(o=>{const i=[o.providerSessionId,o.sessionId,o.nativeSessionId,o.tabKey,o.routeId].map(Ns).filter(Boolean);return!!(n&&i.includes(n)||r&&i.includes(r))});return a?a.tabKey:r||n||null}function vj(e,t,n){if(t.event!=="agent:generating_completed")return null;const r=Yp(t.daemonId);if(r&&r!==e.machineId)return null;const a=Ns(t.providerType);if(e.providerType&&a!==e.providerType)return null;const o=Ns(e.resumeSessionId),i=Ns(e.launchedSessionId),c=Ns(t.providerSessionId),d=Ns(t.targetSessionId);if(o&&o!==c&&o!==d||i&&i!==c&&i!==d)return null;const p=ga(e.workspacePath);if(p){const u=ga(t.workspaceName);if(u&&!gj(u,p))return null}return xj(t,n)}function Bc(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function yj({ides:e,conversations:t,onOpenSession:n}){const[r,a]=l.useState(null),o=l.useRef(null),i=l.useCallback(()=>{o.current=null,a(null)},[]),c=l.useCallback(d=>{o.current=d,a(d)},[]);return l.useEffect(()=>{if(!r)return;const d=ga(r.workspacePath),p=e.find(m=>{var x,y,b,S;if(!m||m.type==="adhdev-daemon"||Yp(m.daemonId||m.id)!==r.machineId||(ir(m)?"cli":mn(m)?"acp":"ide")!==r.kind)return!1;const C=String(m.agentType||m.type||"");if(r.providerType&&C!==r.providerType)return!1;if(r.resumeSessionId)return String(m.providerSessionId||"")===r.resumeSessionId;if(r.launchedSessionId){const k=String(r.launchedSessionId||"");return[m.providerSessionId,m.sessionId,m.instanceId,m.id].map(v=>String(v||"")).filter(Boolean).includes(k)}if(d){const k=ga(m.workspace||m.runtimeWorkspaceLabel);return k?k===d:!1}return Number(m.lastUpdated||m._lastUpdate||m.timestamp||((S=(b=(y=(x=m.activeChat)==null?void 0:x.messages)==null?void 0:y.at)==null?void 0:b.call(y,-1))==null?void 0:S.timestamp)||0)>=r.startedAt-5e3});if(!p)return;const u=Vp({entrySessionId:p.sessionId,entryInstanceId:p.instanceId,entryRouteId:p.id,conversations:t});u&&(i(),n(u))},[i,t,e,n,r]),l.useEffect(()=>mt.onStatusEvent(d=>{const p=o.current;if(!p)return;const u=vj(p,d,t);u&&(i(),n(u))}),[i,t,n]),l.useEffect(()=>{if(!r)return;const d=window.setTimeout(()=>{a(p=>!p||p.startedAt!==r.startedAt?p:(o.current=null,null))},45e3);return()=>window.clearTimeout(d)},[r]),{trackPendingLaunch:c}}function wj({sendDaemonCommand:e,trackPendingLaunch:t,onOpenSession:n,activeConv:r,ides:a,setCliViewModeOverrides:o}){const i=Bi(),{launchCli:c}=wa(),d=l.useCallback(async(x,y)=>nl(e,x,y),[e]),p=l.useCallback(async(x,y)=>{if(!y.trim())return{ok:!1,error:"Choose a workspace path first."};try{const b=await e(x,"workspace_add",{path:y.trim()});return b!=null&&b.success?{ok:!0}:{ok:!1,error:(b==null?void 0:b.error)||"Could not save workspace"}}catch(b){return{ok:!1,error:b instanceof Error?b.message:"Could not save workspace"}}},[e]),u=l.useCallback(async(x,y,b)=>{var S;try{const k={ideType:y,enableCdp:!0};(S=b==null?void 0:b.workspacePath)!=null&&S.trim()&&(k.workspace=b.workspacePath.trim());const w=await e(x,"launch_ide",k);return!(w!=null&&w.success)&&(w==null?void 0:w.success)!==void 0?{ok:!1,error:(w==null?void 0:w.error)||"Could not launch IDE"}:(t({machineId:x,kind:"ide",providerType:y,workspacePath:(b==null?void 0:b.workspacePath)||null,startedAt:Date.now()}),{ok:!0})}catch(k){return{ok:!1,error:k instanceof Error?k.message:"Could not launch IDE"}}},[e,t]),m=l.useCallback(async(x,y,b,S)=>{var w,v,N,j;const k=Date.now();try{const A={cliType:b};(w=S==null?void 0:S.workspacePath)!=null&&w.trim()?A.dir=S.workspacePath.trim():S!=null&&S.workspaceId&&(A.workspaceId=S.workspaceId),(v=S==null?void 0:S.resumeSessionId)!=null&&v.trim()&&(A.resumeSessionId=S.resumeSessionId.trim()),Array.isArray(S==null?void 0:S.cliArgs)&&S.cliArgs.length>0&&(A.cliArgs=S.cliArgs),(N=S==null?void 0:S.initialModel)!=null&&N.trim()&&(A.initialModel=S.initialModel.trim()),(j=S==null?void 0:S.initialThinkingLevel)!=null&&j.trim()&&(A.initialThinkingLevel=S.initialThinkingLevel.trim());const I=await c(x,A),D=(I==null?void 0:I.result)||I,L=(D==null?void 0:D.sessionId)||(D==null?void 0:D.id);return I!=null&&I.success&&L?(t({machineId:x,kind:y,providerType:b,workspacePath:(S==null?void 0:S.workspacePath)||null,resumeSessionId:(S==null?void 0:S.resumeSessionId)||null,launchedSessionId:L,startedAt:k}),{ok:!0}):I!=null&&I.success?(t({machineId:x,kind:y,providerType:b,workspacePath:(S==null?void 0:S.workspacePath)||null,resumeSessionId:(S==null?void 0:S.resumeSessionId)||null,startedAt:k}),{ok:!0}):{ok:!1,error:(I==null?void 0:I.error)||(D==null?void 0:D.error)||`Could not launch ${y.toUpperCase()} session`}}catch(A){return Bc(A)?(t({machineId:x,kind:y,providerType:b,workspacePath:(S==null?void 0:S.workspacePath)||null,resumeSessionId:(S==null?void 0:S.resumeSessionId)||null,startedAt:k}),{ok:!0}):{ok:!1,error:A instanceof Error?A.message:`Could not launch ${y.toUpperCase()} session`}}},[c,e,t]),f=l.useCallback(async x=>{var y;if(i!=null&&i.listMeshes)return i.listMeshes(x);if(!x)return[];try{const b=await e(x,"list_meshes",{}),S=(b==null?void 0:b.result)??b;if((S==null?void 0:S.success)===!1)throw new Error((S==null?void 0:S.error)||"Could not load meshes");return(Array.isArray(S==null?void 0:S.meshes)?S.meshes:Array.isArray((y=S==null?void 0:S.result)==null?void 0:y.meshes)?S.result.meshes:[]).map(w=>{var v;return{id:String((w==null?void 0:w.id)||""),name:String((w==null?void 0:w.name)||(w==null?void 0:w.id)||"Untitled mesh"),repoIdentity:(w==null?void 0:w.repoIdentity)||(w==null?void 0:w.repo_identity)||null,workspace:Array.isArray(w==null?void 0:w.nodes)&&w.nodes.length>0?String(((v=w.nodes[0])==null?void 0:v.workspace)||""):null,nodesCount:Array.isArray(w==null?void 0:w.nodes)?w.nodes.length:void 0,status:(w==null?void 0:w.status)||null}}).filter(w=>w.id)}catch(b){throw console.error("List meshes failed",b),b}},[i,e]),g=l.useCallback(async(x,y,b,S)=>{var w,v;if(!y.trim())return{ok:!1,error:"Choose a mesh first."};if(i!=null&&i.launchMeshCoordinator)return i.launchMeshCoordinator(x,y,b,S);const k=Date.now();try{const N={meshId:y.trim()};b.trim()&&(N.cliType=b.trim());const j=(w=S==null?void 0:S.initialModel)==null?void 0:w.trim(),A=(v=S==null?void 0:S.initialThinkingLevel)==null?void 0:v.trim();j&&(N.initialModel=j),A&&(N.initialThinkingLevel=A);const I=await e(x,"launch_mesh_coordinator",N),D=(I==null?void 0:I.result)??I;if((D==null?void 0:D.success)===!1||(I==null?void 0:I.success)===!1){const P=String((D==null?void 0:D.code)||(I==null?void 0:I.code)||""),_=bj((D==null?void 0:D.meshCoordinatorSetup)||(D==null?void 0:D.manualSetup)||(I==null?void 0:I.meshCoordinatorSetup)||(I==null?void 0:I.manualSetup));return{ok:!1,error:(D==null?void 0:D.error)||(I==null?void 0:I.error)||"Could not launch mesh coordinator",code:P||void 0,manualSetup:_}}const L=(D==null?void 0:D.sessionId)||(D==null?void 0:D.id);return L?n(L):t({machineId:x,kind:"cli",providerType:(D==null?void 0:D.cliType)||b.trim()||void 0,workspacePath:(D==null?void 0:D.workspace)||null,startedAt:k}),{ok:!0}}catch(N){return Bc(N)?(t({machineId:x,kind:"cli",providerType:b.trim()||void 0,startedAt:k}),{ok:!0}):{ok:!1,error:N instanceof Error?N.message:"Could not launch mesh coordinator"}}},[i,n,e,t]),C=l.useCallback(async(x,y)=>{if(!x||!y)return[];try{const b=await e(x,"list_saved_sessions",{providerType:y,kind:"cli",limit:30}),S=(b==null?void 0:b.result)??b;return Array.isArray(S==null?void 0:S.sessions)?S.sessions:[]}catch(b){return console.error("List saved sessions failed",b),[]}},[e]),h=l.useCallback(async x=>{await _p({conversation:r,mode:x,ides:a,sendDaemonCommand:e,setCliViewModeOverrides:o})},[r,a,e,o]);return{handleBrowseMachineDirectory:d,handleSaveMachineWorkspace:p,handleLaunchMachineIde:u,handleLaunchMachineProvider:m,handleListMachineMeshes:f,handleLaunchMeshCoordinator:g,handleListMachineSavedSessions:C,setActiveCliViewMode:h}}function kj(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 Sj(e,t,n=Date.now()){return!e||!kj(t)?null:{tabKey:e,nonce:n}}function Cj({isMobile:e,conversations:t,visibleConversations:n,groupActiveTabIds:r,focusedGroup:a,groupedConvs:o,setSearchParams:i}){const[c,d]=l.useState(null),[p,u]=l.useState(null),m=l.useMemo(()=>{var x,y;if(!e){if(c){const b=t.find(S=>S.tabKey===c);if(b)return b}return n[0]}const h=r[a];if(h){const b=t.find(S=>S.tabKey===h);if(b)return b}return((x=o[a])==null?void 0:x[0])||((y=o[0])==null?void 0:y[0])},[t,c,a,r,o,e,n]),f=l.useCallback(h=>{d(h)},[]),g=l.useCallback(h=>{d(h.tabKey),i(x=>{const y=new URLSearchParams(x),b=o0(h);return b?y.set("activeTab",b):y.delete("activeTab"),y},{replace:!0})},[i]),C=l.useCallback((h,x)=>{const y=Sj(h,x);y&&u(y)},[]);return{activeConv:m,openDesktopConversation:g,requestScrollToBottom:C,scrollToBottomRequest:p,setDesktopActiveTab:f}}function jj(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 Nj(e){const t=String(e.liveState.completionMarker||""),n=String(e.liveState.seenCompletionMarker||""),r=String(e.liveState.inboxBucket||"idle"),a=!!e.liveState.unread,o=[e.tabKey,e.historySessionId||"",t,n,r,a?"1":"0"].join(":");return{shouldMarkSeen:!!(r==="task_complete"&&a&&(!t||t!==n)),autoReadKey:o,completionMarker:t,readAt:Math.max(Date.now(),e.timestamp||0,e.liveState.lastUpdated||0)}}function Aj({activeConv:e,isMobile:t,liveSessionInboxState:n,sendDaemonCommand:r}){const a=l.useRef(null),o=l.useRef(null),i=l.useRef(null),c=l.useRef(null),d=l.useRef(null);l.useEffect(()=>{const p=()=>{i.current&&(clearTimeout(i.current),i.current=null),c.current&&(clearTimeout(c.current),c.current=null),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null),o.current=null};if(t){p(),a.current=null;return}if(!(e!=null&&e.sessionId)){p(),a.current=null;return}const u=Ds(e,n),m=Nj({tabKey:e.tabKey,historySessionId:Aa(e)||"",lastMessageHash:e.lastMessageHash||"",lastMessageAt:Number(e.lastMessageAt||0),timestamp:Ks(e),liveState:u}),f=m.autoReadKey,g=jj({autoReadKey:f,shouldMarkSeen:m.shouldMarkSeen,completedKey:a.current,pendingKey:o.current});if(!m.shouldMarkSeen){g.shouldCancelPending&&p(),a.current=f;return}if(!g.shouldSchedule)return;g.shouldCancelPending&&p();const C=()=>{if(document.visibilityState!=="visible"||a.current===f)return;a.current=f,o.current=null,i.current=null,c.current=null,d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null);const x=m.readAt;r(e.daemonId||e.routeId,"mark_session_seen",{sessionId:e.sessionId,providerSessionId:e.providerSessionId,seenAt:x,completionMarker:m.completionMarker}).catch(()=>{})};if(o.current=g.nextPendingKey,document.visibilityState==="visible"){i.current=setTimeout(C,1500);const x=()=>{document.visibilityState!=="visible"&&i.current&&(clearTimeout(i.current),i.current=null)};d.current=x,document.addEventListener("visibilitychange",x);return}const h=()=>{document.visibilityState==="visible"&&(c.current&&clearTimeout(c.current),c.current=setTimeout(C,800),d.current&&(document.removeEventListener("visibilitychange",d.current),d.current=null))};d.current=h,document.addEventListener("visibilitychange",h)},[e,t,n,r]),l.useEffect(()=>()=>{i.current&&clearTimeout(i.current),c.current&&clearTimeout(c.current),d.current&&document.removeEventListener("visibilitychange",d.current)},[])}function mo(e){if(!e)return"";const t=String(e.workspacePath||"").trim();if(t)return t;const n=String(e.workspaceName||"").trim();return/^(?:~\/|\/|[A-Za-z]:[\\/])/.test(n)?n:""}function Ij({activeConv:e,remoteDialogConv:t,remoteDialogActiveConv:n,ides:r,sendDaemonCommand:a,updateRouteChats:o,setToasts:i,setClearedTabs:c,setSearchParams:d}){var K;const{launchCli:p}=wa(),[u,m]=l.useState(!1),[f,g]=l.useState([]),[C,h]=l.useState(()=>Bt()),[x,y]=l.useState(!1),[b,S]=l.useState(null),k=l.useRef(null),w=l.useMemo(()=>n||t||e,[e,n,t]),v=!!w&&ct(w)&&!lt(w),N=l.useMemo(()=>{if(!w||!v)return null;const R=w.daemonId||w.routeId||"",T=bs(w),H=mo(w);return`${R}:${T}:${w.providerSessionId||""}:${H}`},[w,v]),j=l.useMemo(()=>!w||!v?"":mo(w),[w,v]),{isCreatingChat:A,isRefreshingHistory:I,handleSwitchSession:D,handleNewChat:L,handleRefreshHistory:P}=Wp({sendDaemonCommand:a,activeConv:w,chats:(K=r.find(R=>R.id===(w==null?void 0:w.routeId)))==null?void 0:K.chats,updateRouteChats:o,setToasts:i,setClearedTabs:c}),_=l.useCallback(()=>{m(!0)},[]),q=l.useCallback(()=>{m(!1)},[]),B=l.useCallback(async()=>{if(!(!w||!v||x)){y(!0);try{const R=w.daemonId||w.routeId,T=bs(w),H=mo(w),M=await a(R,"list_saved_sessions",{agentType:T,providerType:T,kind:"cli",limit:50,...w.providerSessionId?{providerSessionId:w.providerSessionId}:{},...H?{workspace:H}:{}}),W=(M==null?void 0:M.result)??M;g(Array.isArray(W==null?void 0:W.sessions)?W.sessions:[])}catch(R){console.error("Refresh saved sessions failed",R),g([])}finally{y(!1)}}},[w,x,v,a]);l.useEffect(()=>{if(!u){k.current=null;return}if(!v){k.current=null,g([]),y(!1);return}!N||x||k.current!==N&&(k.current=N,B())},[B,u,x,v,N]);const E=l.useCallback(async R=>{if(!w||!v||!R.providerSessionId||!R.workspace)return;const T=w.daemonId||w.routeId,H=bs(w);try{S(R.providerSessionId);const M=await p(T,{cliType:H,dir:R.workspace,resumeSessionId:R.providerSessionId,initialModel:ku(R.summaryMetadata,"model",{preferShortValue:!0})||void 0}),W=(M==null?void 0:M.result)??M,J=typeof(W==null?void 0:W.sessionId)=="string"?W.sessionId:typeof(W==null?void 0:W.id)=="string"?W.id:"";J&&d(re=>{const V=new URLSearchParams(re);return V.set("activeTab",J),V},{replace:!0}),q()}catch(M){console.error("Resume saved session failed",M)}finally{S(null)}},[q,w,v,a,d]);return{historyModalOpen:u,openHistoryModal:_,closeHistoryModal:q,historyTargetConv:w,isSavedSessionHistoryTarget:v,isHistoryCreatingChat:A,isHistoryRefreshingHistory:I,handleHistorySwitchSession:D,handleHistoryNewChat:L,handleHistoryRefresh:P,savedHistorySessions:f,savedHistoryFilters:C,setSavedHistoryFilters:h,missingWorkspaceResumePath:j,isSavedHistoryLoading:x,resumingSavedHistorySessionId:b,handleRefreshSavedHistory:B,handleResumeSavedHistorySession:E}}function Tj({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}){const[d,p]=l.useState(null),[u,m]=l.useState(null),f=l.useMemo(()=>{if(e||!r)return null;const y=c(r);return y&&!ct(y)&&!lt(y)?y:null},[e,r,c]),g=l.useMemo(()=>{const y=d==null?void 0:d.routeId;if(!y)return null;const b=d!=null&&d.tabKey?o.find(S=>S.tabKey===d.tabKey):a?o.find(S=>S.tabKey===a):null;return(b==null?void 0:b.routeId)===y?b:cs(o,y)},[o,d,a]),C=l.useMemo(()=>{if(g)return i.find(y=>y.id===g.routeId)},[i,g]);l.useEffect(()=>{f&&(p({routeId:f.routeId,tabKey:tc(f)}),m(f),n({pathname:t.pathname,search:t.search},{replace:!0,state:null}))},[t.pathname,t.search,n,f]);const h=l.useCallback(y=>{y&&(p({routeId:y.routeId,tabKey:tc(y)}),m(y))},[]),x=l.useCallback(()=>{p(null),m(null)},[]);return{remoteDialogConv:g,remoteDialogIdeEntry:C,remoteDialogActiveConv:u,setRemoteDialogActiveConv:m,openRemoteDialog:h,closeRemoteDialog:x}}function Mj({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c,activeConv:d,sendDaemonCommand:p}){const{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:g,openRemoteDialog:C,closeRemoteDialog:h}=Tj({isMobile:e,location:t,navigate:n,requestedRemoteTabTarget:r,requestedDesktopTabKey:a,conversations:o,ides:i,resolveConversationByTarget:c}),[x,y]=l.useState(!1),[b,S]=l.useState(null),k=l.useCallback(async N=>{const j=N||d;!j||!ct(j)&&!lt(j)||(S(j),y(!0))},[d]),w=l.useCallback(()=>{y(!1),S(null)},[]),v=l.useCallback(async N=>{const j=b||d;if(!j||!ct(j)&&!lt(j)){w();return}y(!1);try{const A=bs(j),I=j.routeId||j.daemonId||"";await p(I,"stop_cli",{cliType:A,targetSessionId:j.sessionId,mode:N,...Ma(j)})}catch(A){console.error("Stop CLI failed:",A)}finally{S(null)}},[d,w,b,p]);return{remoteDialogConv:u,remoteDialogIdeEntry:m,remoteDialogActiveConv:f,setRemoteDialogActiveConv:g,openRemoteDialog:C,closeRemoteDialog:h,cliStopDialogOpen:x,cliStopTargetConv:b,requestCliStop:k,cancelCliStop:w,confirmCliStop:v}}function ho(e,t=!0){return(e??!0)&&t}const rl=l.memo(function({activeConv:t,clearToken:n,isCliTerminal:r,ideEntry:a,terminalRef:o,handleModalButton:i,handleRelaunch:c,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m=null,handleFocusAgent:f,isFocusingAgent:g,actionLogs:C,userName:h,scrollToBottomRequestNonce:x,isInputActive:y=!0,isVisible:b=!0}){const S=r,k=!r,w=ho(b,S),v=ho(b,k),N=ho(b),j=Lp(t),A=j.status||j.modalMessage||j.modalButtons?{...t,...j.status?{status:j.status}:{},...j.modalMessage!==void 0?{modalMessage:j.modalMessage}:{},...j.modalButtons!==void 0?{modalButtons:j.modalButtons}:{}}:t;return s.jsxs(s.Fragment,{children:[s.jsx(mu,{activeConv:A,onModalButton:i}),A.transport!=="pty"&&A.transport!=="acp"&&A.cdpConnected===!1?s.jsx("div",{className:"desktop-only px-3 pt-1 pb-2",children:s.jsxs("div",{className:"flex items-center gap-2.5 px-3.5 py-2 bg-yellow-500/[0.08] border border-yellow-500/20 rounded-lg text-xs text-text-secondary",children:[s.jsx("span",{className:"text-sm",children:s.jsx(Ys,{size:14})}),s.jsx("span",{className:"flex-1",children:"CDP not connected — chat history & screenshots unavailable."}),s.jsx("button",{className:"btn btn-sm bg-yellow-500/15 text-yellow-500 border border-yellow-500/30 text-[10px] whitespace-nowrap shrink-0",onClick:c,children:"Relaunch with CDP"})]})}):null,A.transport==="pty"?s.jsxs("div",{style:{position:"relative",minHeight:0,flex:"1 1 0%",width:"100%",overflow:"hidden"},children:[s.jsx("div",{"aria-hidden":!r,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:S?"visible":"hidden",pointerEvents:S?"auto":"none"},children:s.jsx(Hk,{activeConv:A,clearToken:n,terminalRef:o,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,isVisible:w,isInputActive:y&&w})}),s.jsx("div",{"aria-hidden":r,style:{position:"absolute",inset:0,display:"flex",minHeight:0,width:"100%",flexDirection:"column",visibility:k?"visible":"hidden",pointerEvents:k?"auto":"none"},children:s.jsx(ai,{activeConv:A,ideEntry:a,handleSendChat:d,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:C,userName:h,scrollToBottomRequestNonce:x,isInputActive:y&&v,isVisible:v})})]}):s.jsx(ai,{activeConv:A,ideEntry:a,handleSendChat:d,handleForceSendChat:p,isSendingChat:u,sendFeedbackMessage:m,handleFocusAgent:f,isFocusingAgent:g,actionLogs:C,userName:h,scrollToBottomRequestNonce:x,isInputActive:y&&N,isVisible:N})]})},(e,t)=>e.activeConv===t.activeConv&&e.isCliTerminal===t.isCliTerminal&&e.ideEntry===t.ideEntry&&e.terminalRef===t.terminalRef&&e.handleModalButton===t.handleModalButton&&e.handleRelaunch===t.handleRelaunch&&e.handleSendChat===t.handleSendChat&&e.handleForceSendChat===t.handleForceSendChat&&e.isSendingChat===t.isSendingChat&&e.sendFeedbackMessage===t.sendFeedbackMessage&&e.handleFocusAgent===t.handleFocusAgent&&e.isFocusingAgent===t.isFocusingAgent&&e.actionLogs===t.actionLogs&&e.userName===t.userName&&e.scrollToBottomRequestNonce===t.scrollToBottomRequestNonce&&e.isInputActive===t.isInputActive&&e.isVisible===t.isVisible);function Dj({conversation:e,className:t="",onOpenNativeConversation:n,onOpenMachine:r,interactive:a=!0,meshOnly:o=!1}){var k,w,v;const{t:i}=Ne("common"),c=mr(),d=Ps(e),p=o?null:_u(e),u=!o&&(e.transport==="cdp-page"||e.transport==="cdp-webview"),m=!o&&e.streamSource==="agent-stream"&&!!e.agentName,f=!o&&!m&&(e.transport==="pty"||e.transport==="acp"),g=vn(e),C=a0(e),h=(k=e.settings)==null?void 0:k.meshNodeFor,x=e.meshQueueStats,y=((w=e.coordinator)==null?void 0:w.meshId)||((v=e.settings)==null?void 0:v.meshCoordinatorFor),b=l.useCallback(()=>{if(r){r();return}d&&c("/dashboard",{state:{openMachineId:d}})},[d,c,r]),S=l.useCallback(()=>{if(n){n();return}const N=Kp(e);N&&c(dr(N))},[e,c,n]);return!u&&!m&&!f&&!p&&!h&&!x?null:s.jsxs("div",{className:`conversation-meta-chips ${t}`.trim(),children:[u&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:S,title:C,children:[s.jsx(us,{size:12}),s.jsx("span",{children:C})]}):s.jsxs("span",{className:"conversation-meta-chip",title:C,children:[s.jsx(us,{size:12}),s.jsx("span",{children:C})]})),m&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(or,{size:12}),s.jsx("span",{children:g})]}),f&&s.jsxs("span",{className:"conversation-meta-chip is-active",title:g,children:[s.jsx(or,{size:12}),s.jsx("span",{children:g})]}),p&&(a?s.jsxs("button",{type:"button",className:"conversation-meta-chip is-clickable",onClick:b,title:p,children:[s.jsx(Ts,{size:12}),s.jsx("span",{children:p})]}):s.jsxs("span",{className:"conversation-meta-chip",title:p,children:[s.jsx(Ts,{size:12}),s.jsx("span",{children:p})]})),h&&s.jsxs("span",{className:"conversation-meta-chip",title:"Mesh node",children:[s.jsx(Ts,{size:12}),s.jsx("span",{children:i("dashboard.metaChips.meshNode")})]}),y&&x&&s.jsxs("span",{className:`conversation-meta-chip ${x.pending>0?"is-active":""}`,style:x.failed>0?{color:"var(--color-red-400)",borderColor:"var(--color-red-400)"}:void 0,title:`Queue: ${x.pending} pending, ${x.assigned} assigned, ${x.completed} completed, ${x.failed} failed`,children:[s.jsx(Ef,{size:12}),s.jsxs("span",{children:[x.pending," Pending"]})]})]})}function Pj({selectedConversation:e,isAcp:t,isStandalone:n,selectedIdeEntry:r,actionLogs:a,userName:o,isSendingChat:i,sendFeedbackMessage:c=null,isFocusingAgent:d,onBack:p,onOpenNativeConversation:u,onOpenMachine:m,onOpenHistory:f,onOpenRemote:g,onOpenMeshGraph:C,onStopCli:h,cliViewMode:x,onSetCliViewMode:y,handleSendChat:b,handleForceSendChat:S,handleFocusAgent:k,handleModalButton:w,handleRelaunch:v}){var L,P;const N=l.useRef(null),j=ct(e)&&!t,A=j&&x==="terminal",I=!!e.daemonId&&!!((L=e.coordinator)!=null&&L.meshId||(P=e.settings)!=null&&P.meshCoordinatorFor),D=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 ${D} border-b border-border-subtle/70 bg-bg-primary backdrop-blur-md`,children:[s.jsxs("div",{className:"flex items-center gap-2.5 min-w-0 flex-1",children:[s.jsx("button",{className:"w-[34px] h-[34px] rounded-full border border-border-default bg-surface-primary/70 text-text-secondary shrink-0 inline-flex items-center justify-center hover:bg-surface-primary transition-colors",onClick:p,type:"button","aria-label":"Back",children:s.jsx(Ni,{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(Dj,{conversation:e,className:"is-mobile-header",interactive:!1,onOpenNativeConversation:()=>u(e),onOpenMachine:()=>m(e)})})]})]}),s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[j&&x&&s.jsx(pp,{mode:x,onChange:y,compact:!0}),j&&h&&s.jsx("button",{onClick:()=>{h(e)},className:"btn btn-secondary btn-sm",title:"Stop CLI process",style:{color:"var(--status-error, #ef4444)",borderColor:"color-mix(in srgb, var(--status-error, #ef4444) 25%, transparent)"},children:s.jsx(At,{size:14})}),I&&C&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>C(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(Ii,{size:14})}),!t&&!j&&s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>g(e),type:"button",children:s.jsx(us,{size:14})})]})]}),s.jsx("div",{className:"flex-1 min-h-0 flex flex-col bg-bg-primary relative",children:s.jsx(rl,{activeConv:e,clearToken:0,isCliTerminal:A,ideEntry:r,terminalRef:N,handleModalButton:w,handleRelaunch:v,handleSendChat:b,handleForceSendChat:S,isSendingChat:i,sendFeedbackMessage:c,handleFocusAgent:k,isFocusingAgent:d,actionLogs:a,userName:o})})]})}const fo={unix:{cmd:"curl -fsSL https://adhf.dev/install | sh",shell:"Terminal",prompt:"$ "},powershell:{cmd:"irm https://adhf.dev/install.ps1 | iex",shell:"PowerShell",prompt:"PS> "},cmd:{cmd:"curl -fsSL https://adhf.dev/install.cmd -o %TEMP%\\adhdev.cmd && %TEMP%\\adhdev.cmd",shell:"CMD",prompt:"> "}};function Lj(){return typeof navigator>"u"?"unix":navigator.userAgent.toLowerCase().includes("win")?"windows":"unix"}function Jp(){const[e,t]=l.useState("unix"),[n,r]=l.useState("powershell"),[a,o]=l.useState(!1),i=e==="unix"?"unix":n;l.useEffect(()=>{t(Lj())},[]);const c=l.useCallback(()=>{navigator.clipboard.writeText(fo[i].cmd).catch(()=>{}),o(!0),setTimeout(()=>o(!1),2e3)},[i]);return s.jsxs("div",{className:"text-left bg-bg-secondary border border-border-subtle rounded-xl p-4 font-mono text-[13px] shadow-lg w-full mx-auto leading-relaxed relative select-all",children:[s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="unix"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("unix"),children:"🍎🐧 macOS / Linux"}),s.jsx("button",{className:`text-[10px] px-2.5 py-1 rounded-md font-bold transition-all cursor-pointer ${e==="windows"?"bg-accent-primary/12 text-accent-primary border border-accent-primary/25":"bg-transparent text-text-muted border border-transparent hover:text-text-secondary"}`,onClick:()=>t("windows"),children:"🪟 Windows"})]}),e==="windows"&&s.jsxs("div",{className:"flex gap-1 mb-3 font-sans",children:[s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${n==="powershell"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>r("powershell"),children:"⚡ PowerShell"}),s.jsx("button",{className:`text-[9px] px-2 py-0.5 rounded font-semibold cursor-pointer transition-all ${n==="cmd"?"bg-accent-primary/10 text-accent-primary":"text-text-muted hover:text-text-secondary"}`,onClick:()=>r("cmd"),children:">_ CMD"})]}),s.jsxs("div",{className:"flex items-center gap-3 text-text-primary cursor-pointer group",onClick:c,title:"Click to copy",children:[s.jsx("span",{className:"text-text-muted select-none",children:fo[i].prompt}),s.jsx("span",{className:"flex-1 break-all",children:fo[i].cmd}),s.jsx("span",{className:"text-[9px] font-sans text-accent-primary opacity-0 group-hover:opacity-100 transition-opacity shrink-0 select-none",children:a?"✓":"📋"})]}),s.jsxs("div",{className:"text-text-muted text-[10px] font-sans mt-2",children:["Or via npm: ",s.jsx("span",{className:"text-text-secondary font-mono",children:"npm i -g @adhdev/daemon-standalone && adhdev-standalone"})]})]})}function Qp({section:e,onSectionChange:t}){const n=[{key:"machines",label:"Machines",icon:us},{key:"chats",label:"Chats",icon:Zs}];return s.jsx("div",{className:"px-3 py-2.5 pb-[calc(10px+env(safe-area-inset-bottom,0px))] border-t border-border-subtle/70 bg-bg-secondary/88 backdrop-blur-md shrink-0",children:s.jsx("div",{className:"grid grid-cols-2 gap-1.5 rounded-[20px] border p-1 shadow-[0_10px_28px_rgba(15,23,42,0.08)]",style:{background:"color-mix(in srgb, var(--bg-glass) 82%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--border-subtle) 88%, var(--accent-primary) 12%)"},children:n.map(({key:r,label:a,icon:o})=>{const i=e===r;return s.jsxs("button",{className:`min-h-[46px] rounded-[16px] px-3 flex items-center justify-center gap-2.5 text-[13px] font-semibold tracking-tight transition-all border ${i?"bg-surface-primary border-border-default/90 text-text-primary shadow-[0_4px_14px_rgba(15,23,42,0.08)]":"bg-transparent border-transparent text-text-muted hover:text-text-primary"}`,style:i?{background:"color-mix(in srgb, var(--accent-primary) 10%, var(--surface-primary))",borderColor:"color-mix(in srgb, var(--accent-primary) 24%, var(--border-default))",boxShadow:"0 8px 22px color-mix(in srgb, var(--accent-primary) 10%, transparent)"}:void 0,onClick:()=>t(r),type:"button","aria-pressed":i,children:[s.jsx("span",{className:`inline-flex items-center justify-center w-7 h-7 rounded-full transition-colors ${i?"text-accent-primary":"bg-transparent text-current"}`,style:i?{background:"color-mix(in srgb, var(--accent-primary) 14%, transparent)"}:void 0,children:s.jsx(o,{size:15})}),s.jsx("span",{children:a})]},r)})})})}function 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 On({icon:e,title:t,subtitle:n,children:r}){return s.jsxs("div",{className:"flex w-full min-w-0 flex-col items-center justify-center gap-2 px-6 pt-12 pb-8 text-center",children:[s.jsx("div",{className:"mb-2 rounded-2xl border border-accent-primary/10 bg-[color:color-mix(in_oklab,var(--bg-secondary)_90%,var(--accent-primary)_10%)] p-3 shadow-[0_12px_32px_rgba(0,0,0,0.08)]",children:e}),s.jsx("div",{className:"text-lg font-bold tracking-tight text-text-primary",children:t}),s.jsx("div",{className:"text-[13px] leading-relaxed text-text-secondary max-w-[320px]",children:n}),r]})}function Rj({conversation:e,onCancel:t,onConfirm:n}){const{t:r}=Ne(),a=xt(e);return s.jsxs("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",children:[s.jsx("div",{onClick:t,className:"absolute inset-0 bg-black/60 backdrop-blur-sm"}),s.jsxs("div",{role:"dialog","aria-modal":"true","aria-labelledby":"mobile-hide-confirm-title",className:"card fade-in mobile-compact-dialog relative w-full sm:w-[min(92vw,420px)] md:w-[92%] md:max-w-[420px] max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] flex flex-col overflow-hidden rounded-[24px] sm:rounded-[18px] shadow-[0_20px_40px_rgba(0,0,0,0.4)]",children:[s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 border-b border-border-subtle bg-bg-primary",children:[s.jsx("h3",{id:"mobile-hide-confirm-title",className:"m-0 text-base md:text-lg font-extrabold",children:r("mobileInbox.hideTitle",{title:a})}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:r("mobileInbox.hideDescription")})]}),s.jsxs("div",{className:"px-4 py-4 md:px-6 md:py-5 bg-bg-primary flex flex-col gap-2.5",children:[s.jsx("button",{onClick:n,className:"btn btn-primary w-full justify-center min-h-[42px]",children:r("mobileInbox.hide")}),s.jsx("button",{onClick:t,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:r("common.cancel")})]})]})]})}function Lr({item:e,type:t,getAvatarText:n,onOpenConversation:r,onRequestHideConversation:a,onRequestStopCli:o,onOpenMeshGraph:i,onCollectChatDebugBundle:c,isMuted:d,onToggleMute:p}){const{t:u}=Ne(),m=t==="needs_attention"||t==="task_complete",f=t==="working",g=t==="earlier",C=t==="task_complete",{isReconnecting:h,isConnecting:x}=An(e.conversation),y=xt(e.conversation),b=yn(e.conversation),S=lp(e.conversation,{requiresAction:t==="needs_attention"}),k=m?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_92%,var(--accent-primary)_8%)]":f?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_94%,var(--accent-primary)_6%)]":g?"bg-[color:color-mix(in_oklab,var(--bg-secondary)_97%,var(--text-muted)_3%)]":"bg-transparent",w=m?"bg-accent-primary shadow-glow":f?"bg-[color:color-mix(in_oklab,var(--bg-primary)_82%,var(--accent-primary)_18%)] border border-accent-primary/22 text-accent-primary":g?"bg-[color:color-mix(in_oklab,var(--bg-primary)_95%,var(--text-muted)_5%)] border border-border-subtle/80 text-text-muted":"bg-bg-primary border border-border-subtle text-text-secondary",v=g?"text-text-secondary":"text-text-primary",N=g?"text-text-muted":"text-text-secondary",j=g?"text-text-secondary opacity-80":"text-text-muted",A=g?"text-text-muted opacity-80":"text-text-muted",I=!f&&!C,D=op(e.conversation),L="text-[color:var(--status-warning)]",P=_=>{if(!c)return;_.preventDefault(),_.stopPropagation();const q=c==null?void 0:c(e.conversation);Promise.resolve(q).catch(B=>{console.warn("[chat-debug-bundle] failed to collect mobile inbox debug bundle",B)})};return s.jsx("div",{className:`group relative overflow-hidden transition-colors active:scale-[0.995] ${k}`,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 ${w}`,style:m?{color:"var(--accent-on-primary)"}:void 0,children:n(y)}),D&&i&&s.jsx("button",{type:"button",className:"mobile-inbox-mesh-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:_=>{_.preventDefault(),_.stopPropagation(),i(e.conversation)},"aria-label":u("mobileInbox.openMeshGraphFor",{title:y}),title:u("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 ${v}`,children:y})}),s.jsxs("div",{className:`text-[12px] font-medium truncate flex items-center ${N}`,children:[s.jsx("span",{className:"truncate",children:b}),s.jsx(ca,{git:e.conversation.git,compact:!0,className:"ml-1 max-w-[6.5rem] shrink-0"}),h?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:`${L} animate-pulse`,children:u("mobileInbox.reconnectingItem")})]}):x?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:"text-text-muted",children:u("mobileInbox.connectingItem")})]}):S==="Action needed"&&s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"mx-1 opacity-50",children:"·"}),s.jsx("span",{className:L,children:u("mobileInbox.actionNeeded")})]})]}),s.jsx("div",{className:`mt-0.5 truncate text-[13px] ${j}`,children:e.preview})]}),s.jsxs("div",{className:"mobile-inbox-corner-actions absolute top-3 right-3 flex items-center gap-1.5",children:[I&&s.jsx("span",{className:`mr-0.5 text-[11px] font-medium shrink-0 ${A}`,children:uu(e.timestamp)}),C&&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:u("mobileInbox.done")}),p&&s.jsx("button",{type:"button",className:`mobile-inbox-mute-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border transition-colors ${d?"border-amber-500/60 bg-amber-500 text-white hover:bg-amber-600":"border-border-subtle bg-bg-primary/70 text-text-muted hover:border-border-default hover:text-text-primary"}`,onClick:_=>{_.preventDefault(),_.stopPropagation(),p()},"aria-label":d?u("mobileInbox.unmute",{title:y}):u("mobileInbox.mute",{title:y}),title:u(d?"mobileInbox.mutedTitle":"mobileInbox.muteNotifications"),children:d?s.jsx(Zd,{size:13}):s.jsx(Nn,{size:13})}),a&&s.jsx("button",{type:"button",className:"mobile-inbox-hide-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-border-subtle bg-bg-primary/70 text-text-muted transition-colors hover:border-border-default hover:text-text-primary",onClick:_=>{_.preventDefault(),_.stopPropagation(),a()},"aria-label":u("mobileInbox.hideConversationAria",{title:y}),title:u("mobileInbox.hideConversationTitle"),children:s.jsx(Ti,{size:13})}),o&&s.jsx("button",{type:"button",className:"mobile-inbox-stop-button inline-flex h-7 w-7 shrink-0 items-center justify-center rounded-full border border-status-error/30 bg-bg-primary/70 text-status-error transition-colors hover:border-status-error/60 hover:bg-status-error/10",onClick:_=>{_.preventDefault(),_.stopPropagation(),o()},"aria-label":u("mobileInbox.stopSessionAria",{title:y}),title:u("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 Ej({section:e,attentionItems:t,unreadItems:n,workingItems:r,completedItems:a,hiddenConversations:o,machineCards:i,getAvatarText:c,actionLogs:d,sendDaemonCommand:p,onOpenConversation:u,onShowAllHidden:m,onHideConversation:f,onOpenMeshGraph:g,onStopCli:C,onOpenNewSession:h,onOpenMachine:x,onOpenSettings:y,onSectionChange:b,wsStatus:S="connected",isStandalone:k=!1,onCollectChatDebugBundle:w,isConversationMuted:v,onToggleMuteConversation:N}){const{t:j}=Ne(),[A,I]=l.useState(null),D=S==="disconnected"||S==="reconnecting"||S==="offline"||S==="auth_failed",L=i.length>0,P=t.length>0||n.length>0||r.length>0||a.length>0,_=j(e==="machines"?"mobileInbox.machines":"mobileInbox.chats"),q=k?"px-5 pt-4 pb-4":"px-5 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-4",B=k?"px-3 pb-3":"px-3 pb-[calc(12px+env(safe-area-inset-bottom,0px))]",E=l.useCallback(async T=>{const H=Us(T);if(!H)return;const M=Array.isArray(T.messages)?T.messages:[],W=Wu({activeConv:T,visibleMessages:M,actionLogs:d,visibleBarControlCount:0,chatTailState:{hasMoreHistory:!1,historyError:null,historyMessages:[]},ui:{controlsVisible:!1,visibleLiveCount:M.length,hiddenLiveCount:0,isInputActive:!1,isVisible:!0}}),J=await p(H,"get_chat_debug_bundle",{...Ws(T),delivery:"daemon_file",frontendSnapshot:W}),re=er(J),V=qu(re),X=await Gu(V);X==="failed"&&console.warn("[chat-debug-bundle] failed to copy or present mobile inbox debug bundle locator"),mt.showToast(Uu(re,{locatorCopyStatus:X}),X==="failed"?"warning":"success")},[d,p]),K=w||E,R=l.useCallback(()=>{A&&(f==null||f(A),I(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 ${q}`,children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsx("div",{className:"text-2xl font-black tracking-tight text-text-primary px-1",children:_}),s.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e==="chats"&&(t.length>0||n.length>0)&&s.jsxs("div",{className:"flex items-center gap-1.5 px-2.5 py-1 rounded-full border border-accent-primary/16 bg-accent-primary/10 text-accent-primary text-[11px] font-bold shadow-[0_8px_20px_rgba(0,0,0,0.05)]",children:[s.jsx(Nn,{size:13}),s.jsx("span",{children:t.length+n.length})]}),s.jsx("button",{onClick:y,className:"w-8 h-8 flex items-center justify-center rounded-full border border-border-subtle bg-bg-secondary/70 text-text-secondary hover:text-text-primary hover:border-border-default transition-colors",children:s.jsx(ka,{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] ${B}`,children:[e==="machines"&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:D?s.jsx(On,{icon:s.jsx(Fc,{}),title:j(S==="offline"?"mobileInbox.networkOffline":S==="auth_failed"?"mobileInbox.sessionExpired":"mobileInbox.reconnecting"),subtitle:j(S==="offline"?"mobileInbox.waitingForNetwork":S==="auth_failed"?"mobileInbox.pleaseLogInAgain":"mobileInbox.restoringConnection")}):i.length===0?s.jsx(On,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-12 h-12 object-contain animate-bounce",style:{animationDuration:"3s"}}),title:j(k?"mobileInbox.waitingForDaemon":"mobileInbox.connectYourMachines"),subtitle:j(k?"mobileInbox.waitingForDaemonSubtitle":"mobileInbox.connectYourMachinesSubtitle"),children:!k&&s.jsx("div",{className:"w-full max-w-[360px] mt-4",children:s.jsx(Jp,{})})}):s.jsx(nn,{children:i.map((T,H)=>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] ${H>0?"border-t border-border-subtle/70":""}`,onClick:()=>x(T.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(T.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:T.label}),s.jsx("span",{className:"text-[11px] font-medium text-text-muted shrink-0",children:T.unread>0?s.jsx("span",{className:"text-accent-primary",children:j("mobileInbox.newCount",{count:T.unread})}):T.total>0?j("mobileInbox.chatCount",{count:T.total}):j("mobileInbox.idle")})]}),s.jsx("div",{className:"text-[12px] font-medium text-text-secondary truncate",children:T.subtitle}),T.total>0?s.jsxs("div",{className:"text-[13px] text-text-muted mt-0.5",children:[j("mobileInbox.chatCount",{count:T.total}),T.unread>0?j("mobileInbox.unreadSuffix",{count:T.unread}):""]}):s.jsx("div",{className:"text-[13px] text-text-muted mt-0.5 italic opacity-70",children:j("mobileInbox.noActiveChats")})]})]},T.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:j("mobileInbox.needsAttention"),className:"mb-0"}),s.jsx(nn,{children:t.map((T,H)=>s.jsx("div",{className:H>0?"border-t border-border-subtle/70":"",children:s.jsx(Lr,{item:T,type:"needs_attention",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>I(T.conversation):void 0,onRequestStopCli:C?()=>C(T.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:K,isMuted:v==null?void 0:v(T.conversation),onToggleMute:N?()=>N(T.conversation):void 0})},T.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:j("mobileInbox.taskComplete"),className:"mb-0 mt-2"}),s.jsx(nn,{children:n.map((T,H)=>s.jsx("div",{className:H>0?"border-t border-border-subtle/70":"",children:s.jsx(Lr,{item:T,type:"task_complete",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>I(T.conversation):void 0,onRequestStopCli:C?()=>C(T.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:K,isMuted:v==null?void 0:v(T.conversation),onToggleMute:N?()=>N(T.conversation):void 0})},T.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:j("mobileInbox.workingNow"),className:"mb-0 mt-2"}),s.jsx(nn,{children:r.map((T,H)=>s.jsx("div",{className:H>0?"border-t border-border-subtle/70":"",children:s.jsx(Lr,{item:T,type:"working",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>I(T.conversation):void 0,onRequestStopCli:C?()=>C(T.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:K,isMuted:v==null?void 0:v(T.conversation),onToggleMute:N?()=>N(T.conversation):void 0})},T.conversation.tabKey))})]}),e==="chats"&&s.jsxs("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:[a.length>0&&s.jsx(Pr,{title:j("mobileInbox.earlier"),className:"mb-0 mt-2 border-border-subtle/80 bg-bg-secondary/35"}),a.length>0?s.jsx(nn,{children:a.map((T,H)=>s.jsx("div",{className:H>0?"border-t border-border-subtle/70":"",children:s.jsx(Lr,{item:T,type:"earlier",getAvatarText:c,onOpenConversation:u,onRequestHideConversation:f?()=>I(T.conversation):void 0,onRequestStopCli:C?()=>C(T.conversation):void 0,onOpenMeshGraph:g,onCollectChatDebugBundle:K,isMuted:v==null?void 0:v(T.conversation),onToggleMute:N?()=>N(T.conversation):void 0})},T.conversation.tabKey))}):P?s.jsx("div",{className:"py-8 text-center text-sm font-medium text-text-muted",children:j("mobileInbox.allCaughtUp")}):D?s.jsx(On,{icon:s.jsx(Fc,{size:28}),title:j("mobileInbox.connecting"),subtitle:j("mobileInbox.connectingSubtitle")}):L?s.jsx(On,{icon:s.jsx("div",{className:"w-11 h-11 rounded-xl flex items-center justify-center bg-accent-primary/10 text-accent-primary-light",children:s.jsx(Zs,{size:20})}),title:j("mobileInbox.noConversations"),subtitle:Uk,children:h&&s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-2 mt-4",onClick:h,"aria-label":Hs,title:Hs,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:Hs})]})}):s.jsx(On,{icon:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-10 h-10 object-contain opacity-70"}),title:j("mobileInbox.noMachinesConnected"),subtitle:j("mobileInbox.noMachinesSubtitle")})]}),e==="chats"&&o.length>0&&s.jsx("section",{className:"flex w-full min-w-0 flex-col gap-2 self-stretch",children:s.jsx(nn,{className:"mt-4 border-dashed bg-bg-secondary/20",children:s.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 text-left",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"text-[12px] font-bold uppercase tracking-wider text-text-secondary",children:j("mobileInbox.hiddenTabs")}),s.jsx("div",{className:"mt-0.5 text-[13px] text-text-muted",children:j("mobileInbox.collapsedCount",{count:o.length})})]}),s.jsx("button",{type:"button",className:"shrink-0 rounded-full border border-border-subtle bg-bg-primary/70 px-3 py-1.5 text-[12px] font-semibold text-accent-primary hover:border-border-default",onClick:m,children:j("mobileInbox.restoreAll")})]})})})]}),e==="chats"&&h&&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:h,"aria-label":Hs,title:Hs,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(Rj,{conversation:A,onCancel:()=>I(null),onConfirm:R}),s.jsx(Qp,{section:e,onSectionChange:b})]})}function _j(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 Xp(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=_j(e.lastMessageAt);return{title:e.title||e.providerSessionId,providerSessionId:e.providerSessionId,metaLine:t.join(" · "),updatedLabel:r?`Updated ${r}`:"",preview:(e.preview||"").trim()}}function al({title:e,description:t,currentPath:n,directories:r,busy:a=!1,error:o="",confirmLabel:i="Use this folder",onClose:c,onNavigate:d,onConfirm:p}){const[u,m]=l.useState(n),{t:f}=Ne("common");l.useEffect(()=>{m(n)},[n]);const g=hj(n),C=u.trim();return s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"workspace-browse-title",children:s.jsxs("div",{className:"w-full max-w-2xl max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(86vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"workspace-browse-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:c,"aria-label":"Close folder browser",children:s.jsx(At,{size:16})})]}),s.jsxs("div",{className:"px-5 py-3 border-b border-border-subtle bg-bg-primary/60 flex items-start gap-2",children:[s.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 min-h-[34px] px-3 rounded-lg border border-border-subtle bg-bg-secondary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors",onClick:()=>{!g||a||d(g)},disabled:!g||a,children:[s.jsx(Ni,{size:15}),"Parent"]}),s.jsxs("div",{className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:f("machine.workspaceBrowse.currentFolder")}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("input",{type:"text",value:u,onChange:h=>m(h.target.value),onKeyDown:h=>{h.key!=="Enter"||!C||a||(h.preventDefault(),d(C))},placeholder:"Type a folder path",className:"min-w-0 flex-1 rounded-lg border border-border-subtle bg-bg-primary px-3 py-2 text-sm text-text-primary"}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center min-h-[36px] px-3 rounded-lg border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary disabled:opacity-40 transition-colors text-xs font-semibold shrink-0",onClick:()=>{!C||a||d(C)},disabled:!C||a,children:"Go"})]})]})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto bg-bg-primary/40",children:a?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"Loading folders…"}):o?s.jsx("div",{className:"px-5 py-5 text-sm text-status-error",children:o}):r.length===0?s.jsx("div",{className:"px-5 py-5 text-sm text-text-secondary",children:"No subfolders here."}):s.jsx("div",{className:"p-3",children:r.map(h=>s.jsxs("button",{type:"button",className:"w-full flex items-center gap-3 px-3.5 py-3 rounded-xl text-left border border-transparent hover:border-border-subtle hover:bg-bg-secondary transition-colors",onClick:()=>d(h.path),children:[s.jsx("span",{className:"inline-flex items-center justify-center w-9 h-9 rounded-xl bg-accent-primary/10 text-accent-primary shrink-0",children:s.jsx(xn,{size:17})}),s.jsxs("span",{className:"min-w-0 flex-1",children:[s.jsx("span",{className:"block text-sm font-medium text-text-primary truncate",children:h.name}),s.jsx("span",{className:"block text-[11px] text-text-muted truncate",children:h.path})]})]},h.path))})}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:c,children:"Cancel"}),s.jsx("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold",onClick:()=>p(C||n),disabled:!C&&!n||a,children:i})]})]})})}function Zp({title:e,description:t,details:n,workspaceOptions:r,selectedWorkspaceKey:a,onWorkspaceChange:o,confirmLabel:i,busyLabel:c,busy:d=!1,showArgsInput:p,argsValue:u,onArgsChange:m,showModelInput:f,modelValue:g,onModelChange:C,historyProviderNode:h,onConfirm:x,onCancel:y}){const{t:b}=Ne("common"),S=i??b("machine.launchConfirm.launch"),k=c??b("machine.launchConfirm.launching"),w=r==null?void 0:r.find(v=>v.key===a);return s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-[2px] px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",role:"dialog","aria-modal":"true","aria-labelledby":"launch-confirm-title",children:s.jsxs("div",{className:"w-full max-w-lg max-h-[calc(100dvh-env(safe-area-inset-top,0px)-env(safe-area-inset-bottom,0px)-16px)] sm:max-h-[min(88vh,720px)] rounded-[24px] sm:rounded-2xl border border-border-subtle bg-bg-secondary shadow-xl overflow-hidden flex flex-col",children:[s.jsxs("div",{className:"flex items-start justify-between gap-3 px-5 py-4 border-b border-border-subtle",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("h2",{id:"launch-confirm-title",className:"m-0 text-base font-semibold text-text-primary",children:e}),s.jsx("p",{className:"m-0 mt-1 text-xs leading-relaxed text-text-muted",children:t})]}),s.jsx("button",{type:"button",className:"inline-flex items-center justify-center w-8 h-8 rounded-full border border-border-subtle bg-bg-primary text-text-secondary hover:text-text-primary hover:bg-surface-primary transition-colors shrink-0",onClick:y,"aria-label":b("machine.launchConfirm.closeAria"),children:s.jsx(At,{size:16})})]}),s.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3 sm:px-5 sm:py-4 flex flex-col gap-3",children:[r&&r.length>0&&o&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.workspace")}),s.jsx("select",{value:a||"",onChange:v=>o(v.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:d,children:r.map(v=>s.jsx("option",{value:v.key,children:v.label},v.key))}),(w==null?void 0:w.description)&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:w.description})]}),h,n.map(v=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:v.label}),s.jsx("div",{className:"text-sm text-text-primary break-all",children:v.value})]},`${v.label}:${v.value}`)),f&&C&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.languageModel")}),s.jsx("input",{type:"text",value:g||"",onChange:v=>C(v.target.value),placeholder:b("machine.launchConfirm.autoDetect"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]}),p&&m&&s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-3",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted mb-1",children:b("machine.launchConfirm.cliArgs")}),s.jsx("input",{type:"text",value:u||"",onChange:v=>m(v.target.value),placeholder:b("machine.launchConfirm.cliArgsPlaceholder"),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm placeholder:text-text-muted",disabled:d})]})]}),s.jsxs("div",{className:"flex items-center justify-end gap-2 px-4 py-[calc(12px+env(safe-area-inset-bottom,0px))] sm:px-5 sm:py-4 border-t border-border-subtle bg-bg-secondary shrink-0",children:[s.jsx("button",{type:"button",className:"machine-btn text-xs",onClick:y,disabled:d,children:b("machine.launchConfirm.cancel")}),s.jsxs("button",{type:"button",className:"btn btn-primary h-9 px-4 text-sm font-semibold inline-flex items-center gap-2",onClick:x,disabled:d,children:[s.jsx(Xd,{size:14}),d?k:S]})]})]})})}function Oc(e,t){return t||e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean).pop()||e}function em(e){const{machine:t,currentWorkspacePath:n,currentWorkspaceId:r,includeHome:a=!0}=e,o=[];a&&o.push({key:"__home__",label:"Home directory",description:"Launch without a workspace",workspaceId:null,workspacePath:null});for(const d of t.workspaces||[])o.push({key:`saved:${d.id}`,label:`${d.id===t.defaultWorkspaceId?"⭐ ":""}${Oc(d.path,d.label)}`,description:d.path,workspaceId:d.id,workspacePath:d.path});const i=(n==null?void 0:n.trim())||"",c=i?(t.workspaces||[]).find(d=>d.path===i):null;if(i&&!c&&o.push({key:`custom:${i}`,label:Oc(i),description:i,workspaceId:null,workspacePath:i}),r){const d=`saved:${r}`;if(o.some(p=>p.key===d))return{options:o,selectedKey:d}}return c?{options:o,selectedKey:`saved:${c.id}`}:i?{options:o,selectedKey:`custom:${i}`}:{options:o,selectedKey:"__home__"}}function $j(e){return e==="ide"?"IDE":e==="cli"?"CLI":"ACP"}function Hj(e){return[$j(e.kind),e.subtitle||"",e.providerSessionId?"Saved history":""].filter(Boolean).join(" · ")}function Bj(e){return e.lastLaunchedAt?Ca(e.lastLaunchedAt):""}function tm(e){return{metaText:Hj(e),updatedLabel:Bj(e)}}function bo(e,t,n){return e?"ide":t>0?"cli":n>0?"acp":null}function Fj({selectedMachineEntry:e,cliProviders:t,acpProviders:n,machineAction:r,onBrowseDirectory:a,onListSavedSessions:o}){var he,$e,Be,Me;const i=Tn(),[c,d]=l.useState(!1),p=(((he=e.detectedIdes)==null?void 0:he.length)||0)>0,u=l.useMemo(()=>(e.workspaces||[]).map(ve=>({id:ve.id,path:ve.path,label:ve.label})),[e]),m=e.defaultWorkspaceId||null,[f,g]=l.useState(m||(($e=u[0])==null?void 0:$e.id)||""),[C,h]=l.useState(""),[x,y]=l.useState(""),[b,S]=l.useState([]),[k,w]=l.useState(!1),[v,N]=l.useState(""),[j,A]=l.useState(!1),[I,D]=l.useState(bo(p,t.length,n.length)),L=l.useRef(null),[P,_]=l.useState(null),q=l.useRef("__home__"),[B,E]=l.useState("__home__"),[K,R]=l.useState(""),[T,H]=l.useState(""),[M,W]=l.useState(""),[J,re]=l.useState([]),[V,X]=l.useState(()=>Bt().textQuery),[de,ne]=l.useState(()=>Bt().workspaceQuery),[O,ie]=l.useState(()=>Bt().modelQuery),[z,ae]=l.useState(()=>Bt().resumableOnly),[Ce,ye]=l.useState(()=>Bt().sortMode),[ke,me]=l.useState(!1),[G,U]=l.useState(!1),Z=l.useRef(null),Y=l.useRef(null);l.useEffect(()=>{(!e.workspaces||!e.availableProviders||!e.detectedIdes||!e.recentLaunches)&&i(e.id,{minFreshMs:3e4}).catch(()=>{})},[i,e]);const fe=f==="__custom__"?C.trim():((Be=u.find(ve=>ve.id===f))==null?void 0:Be.path)||"",Te=f==="__custom__"&&!!fe&&r.state==="error"&&/(Directory path is not valid or does not exist|Path does not exist)/i.test(r.message),ce=f!=="__custom__"&&((Me=u.find(ve=>ve.id===f))==null?void 0:Me.path)||"",$=l.useMemo(()=>(e.recentLaunches||[]).map(ve=>ve.workspace),[e]),pe=l.useCallback(async ve=>{w(!0),N("");try{const We=await a(ve);y(We.path),h(We.path),S(We.directories)}catch(We){N(We instanceof Error?We.message:"Could not load folder")}finally{w(!1)}},[a]),le=l.useCallback(()=>{var We;g("__custom__"),A(!0);const ve=sl(e.platform,tl(C.trim(),ce,$,e.defaultWorkspacePath,(We=u.find(ut=>ut.id===m))==null?void 0:We.path,u.map(ut=>ut.path)));pe(ve)},[C,m,pe,$,ce,e.platform,u]),F=l.useCallback(ve=>{if(ve!=null&&ve.workspaceId){g(ve.workspaceId),h("");return}if(ve!=null&&ve.workspacePath){g("__custom__"),h(ve.workspacePath);return}g(""),h("")},[]),be=l.useCallback(ve=>{if(g(ve),ve==="__custom__"){le();return}h("")},[le]),je=l.useCallback(ve=>{g("__custom__"),h(ve)},[]),Se=l.useCallback((ve,We)=>{L.current=We,q.current=ve.selectedWorkspaceKey||"__home__",E(ve.selectedWorkspaceKey||"__home__"),R(ve.initialArgs||""),H(ve.initialModel||""),W(""),re([]);const ut=ve.providerType?`${e.id}:${ve.providerType}`:null;if(Yk(Y.current,ut)){const ot=Bt();X(ot.textQuery),ne(ot.workspaceQuery),ie(ot.modelQuery),ae(ot.resumableOnly),ye(ot.sortMode)}Y.current=ut,_(ve),ve.providerType&&o&&(me(!0),o(ve.providerType).then(ot=>re(ot||[])).catch(ot=>console.warn("Failed to load saved sessions",ot)).finally(()=>me(!1)))},[o,e.id]),He=l.useMemo(()=>mp(J,{textQuery:V,workspaceQuery:de,modelQuery:O,resumableOnly:z,sortMode:Ce}),[O,z,J,Ce,V,de]);l.useEffect(()=>{M&&(He.some(ve=>ve.providerSessionId===M)||W(""))},[He,M]);const Xe=l.useCallback(()=>{L.current&&(U(!0),L.current().finally(()=>{L.current=null,U(!1),_(null)}))},[]),dt=l.useCallback(()=>{L.current=null,_(null)},[]),it=l.useCallback(ve=>{q.current=ve,E(ve)},[]);return l.useEffect(()=>{var ve;Z.current!==e.id&&(Z.current=e.id,g(m||((ve=u[0])==null?void 0:ve.id)||"__custom__"),h(""),y(""),S([]),N(""),A(!1),X(Bt().textQuery),ne(Bt().workspaceQuery),ie(Bt().modelQuery),ae(Bt().resumableOnly),ye(Bt().sortMode),Y.current=null,D(bo(p,t.length,n.length)))},[n.length,t.length,m,p,e.id,u]),l.useEffect(()=>{var ve;f!=="__custom__"&&(f&&u.some(We=>We.id===f)||g(m||((ve=u[0])==null?void 0:ve.id)||"__custom__"))},[m,f,u]),l.useEffect(()=>{I==="ide"&&p||I==="cli"&&t.length>0||I==="acp"&&n.length>0||D(bo(p,t.length,n.length))},[I,n.length,t.length,p]),{showAllRecent:c,setShowAllRecent:d,hasIdeOptions:p,workspaceRows:u,defaultWorkspaceId:m,workspaceChoice:f,customWorkspacePath:C,browseCurrentPath:x,browseDirectories:b,browseBusy:k,browseError:v,browseDialogOpen:j,activeLauncherKind:I,launchConfirm:P,launchConfirmWorkspaceKeyRef:q,launchConfirmWorkspaceKey:B,launchConfirmArgs:K,launchConfirmModel:T,launchConfirmResumeId:M,launchConfirmSavedSessions:J,launchConfirmTextFilter:V,launchConfirmWorkspaceFilter:de,launchConfirmModelFilter:O,launchConfirmResumableOnly:z,launchConfirmSortMode:Ce,filteredLaunchConfirmSavedSessions:He,launchConfirmSessionsLoading:ke,launchConfirmBusy:G,resolvedWorkspacePath:fe,canCreateMissingWorkspace:Te,openBrowseDialog:le,loadBrowsePath:pe,handleWorkspaceChoiceChange:be,chooseCustomWorkspacePath:je,setCustomWorkspacePath:h,setBrowseDialogOpen:A,setActiveLauncherKind:D,openLaunchConfirm:Se,handleConfirmLaunch:Xe,closeLaunchConfirm:dt,setWorkspaceSelectionFromOption:F,setLaunchConfirmWorkspaceKeyAndSync:it,setLaunchConfirmArgs:R,setLaunchConfirmModel:H,setLaunchConfirmResumeId:W,setLaunchConfirmTextFilter:X,setLaunchConfirmWorkspaceFilter:ne,setLaunchConfirmModelFilter:ie,setLaunchConfirmResumableOnly:ae,setLaunchConfirmSortMode:ye}}function Oj({selectedMachineEntry:e,selectedMachineConversations:t,selectedMachineRecentLaunches:n,cliProviders:r,acpProviders:a,selectedMachineNeedsUpgrade:o,appVersion:i,machineAction:c,isStandalone:d,section:p,showBottomNav:u,onBack:m,onSectionChange:f,onOpenConversation:g,onOpenRecent:C,onOpenMachineDetails:h,onMachineUpgrade:x,onLaunchDetectedIde:y,onAddWorkspace:b,onBrowseDirectory:S,onLaunchWorkspaceProvider:k,onListSavedSessions:w}){const{t:v}=Ne("common"),N=E=>E==="ide"?"IDE":E==="cli"?"CLI":"ACP",j=n.slice(0,4),A=t.slice(0,3),I=Fj({selectedMachineEntry:e,cliProviders:r,acpProviders:a,machineAction:c,onBrowseDirectory:S,onListSavedSessions:w}),D=l.useMemo(()=>j.map(E=>{const{metaText:K,updatedLabel:R}=tm(E);return{key:`recent-launch:${E.id}`,primary:E.label,secondary:K,updatedLabel:R,onClick:()=>{const{options:T,selectedKey:H}=em({machine:{workspaces:I.workspaceRows,defaultWorkspaceId:I.defaultWorkspaceId},currentWorkspacePath:E.workspace});I.openLaunchConfirm({title:E.kind==="ide"?da(v,"restart-ide",E.label):E.providerSessionId?fp(v,E.label):da(v,"start-fresh",E.label),description:E.kind==="ide"?ua(v,"restart-ide"):E.providerSessionId?bp(v):ua(v,"start-fresh"),confirmLabel:E.kind==="ide"?pa(v,"restart-ide"):E.providerSessionId?oi(v,!0):pa(v,"start-fresh"),busyLabel:E.kind==="ide"?ma(v,"restart-ide"):E.providerSessionId?hp(v,!0):ma(v,"start-fresh"),workspaceOptions:T,selectedWorkspaceKey:H,details:[{label:"Mode",value:N(E.kind)},...E.providerType?[{label:"Provider",value:E.providerType}]:[]]},async()=>{const M=T.find(W=>W.key===I.launchConfirmWorkspaceKeyRef.current);I.setWorkspaceSelectionFromOption(M),await C({...E,workspace:(M==null?void 0:M.workspacePath)??null})})}}}),[I,C,j,v]),L=l.useMemo(()=>A.map(E=>({key:`recent-chat:${E.conversation.tabKey}`,primary:xt(E.conversation),secondary:Ck(E.conversation,{timestampLabel:E.timestamp?uu(E.timestamp):null}),unread:E.unread,onClick:()=>g(E.conversation)})),[g,A]),P=I.showAllRecent?D:D.slice(0,4),_=D.length>0,q=L.length>0,B=d?"px-4 pt-4 pb-3":"px-4 pt-[calc(16px+env(safe-area-inset-top,0px))] pb-3";return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:`flex items-center justify-between gap-3 ${B} 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(Ni,{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:[q&&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(E=>s.jsxs("button",{className:`flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border ${E.unread?"border-accent-primary/25 bg-accent-primary/5":"border-border-default/80 bg-surface-primary/90"} text-text-primary`,type:"button",onClick:E.onClick,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:E.primary}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:E.secondary})]},E.key))})]}),_&&s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Recent Launches"}),s.jsx("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:P.map(E=>s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:E.onClick,children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-bold text-text-primary truncate",children:E.primary}),E.updatedLabel&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:E.updatedLabel})]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:E.secondary})]},E.key))}),D.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:()=>I.setShowAllRecent(E=>!E),children:I.showAllRecent?"Show fewer":`Show ${D.length-4} more`})})]}),!1,s.jsxs("section",{className:"flex flex-col gap-0",children:[s.jsx("div",{className:"text-[11px] font-extrabold tracking-[0.08em] uppercase text-text-muted px-4 pb-2",children:"Inspect"}),s.jsxs("div",{className:"grid grid-cols-1 gap-2.5 px-4",children:[o&&s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-accent-primary/25 bg-accent-primary/5 text-text-primary",type:"button",onClick:x,children:[s.jsxs("span",{className:"text-sm font-bold text-text-primary",children:["Update to v",i]}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Restart this machine with the latest daemon"})]}),s.jsxs("button",{className:"flex flex-col gap-1 w-full text-left p-[14px] rounded-2xl border border-border-default/80 bg-surface-primary/90 text-text-primary",type:"button",onClick:h,children:[s.jsx("span",{className:"text-sm font-bold text-text-primary",children:"Machine details"}),s.jsx("span",{className:"text-xs leading-relaxed text-text-secondary",children:"Sessions, providers, system info, and logs"})]})]})]})]}),I.browseDialogOpen&&s.jsx(al,{title:"Select workspace",description:"Move through folders like a normal explorer, then use the current folder for this machine.",currentPath:I.browseCurrentPath,directories:I.browseDirectories,busy:I.browseBusy,error:I.browseError,confirmLabel:"Use this folder",onClose:()=>I.setBrowseDialogOpen(!1),onNavigate:E=>{I.loadBrowsePath(E)},onConfirm:E=>{I.chooseCustomWorkspacePath(E),I.setBrowseDialogOpen(!1)}}),I.launchConfirm&&s.jsx(Zp,{title:I.launchConfirm.title,description:I.launchConfirm.description,details:I.launchConfirm.details,workspaceOptions:I.launchConfirm.workspaceOptions,selectedWorkspaceKey:I.launchConfirmWorkspaceKey,onWorkspaceChange:I.setLaunchConfirmWorkspaceKeyAndSync,confirmLabel:I.launchConfirm.providerType?oi(v,!!I.launchConfirmResumeId):I.launchConfirm.confirmLabel,busyLabel:I.launchConfirm.providerType?void 0:I.launchConfirm.busyLabel,busy:I.launchConfirmBusy,showArgsInput:I.launchConfirm.showArgsInput,argsValue:I.launchConfirmArgs,onArgsChange:I.setLaunchConfirmArgs,showModelInput:I.launchConfirm.showModelInput,modelValue:I.launchConfirmModel,onModelChange:I.setLaunchConfirmModel,historyProviderNode:I.launchConfirm.providerType&&(I.launchConfirmSessionsLoading||I.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"}),I.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:Ki(v)}),s.jsxs("div",{className:"grid grid-cols-1 gap-2 mb-2",children:[s.jsx("input",{type:"text",value:I.launchConfirmTextFilter,onChange:E=>I.setLaunchConfirmTextFilter(E.target.value),placeholder:"Search title or preview",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:I.launchConfirmBusy||I.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:I.launchConfirmWorkspaceFilter,onChange:E=>I.setLaunchConfirmWorkspaceFilter(E.target.value),placeholder:"Filter by workspace",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:I.launchConfirmBusy||I.launchConfirmSessionsLoading}),s.jsx("input",{type:"text",value:I.launchConfirmModelFilter,onChange:E=>I.setLaunchConfirmModelFilter(E.target.value),placeholder:"Filter by model",className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:I.launchConfirmBusy||I.launchConfirmSessionsLoading}),s.jsxs("select",{value:I.launchConfirmSortMode,onChange:E=>I.setLaunchConfirmSortMode(E.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:I.launchConfirmBusy||I.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:I.launchConfirmResumableOnly,onChange:E=>I.setLaunchConfirmResumableOnly(E.target.checked),disabled:I.launchConfirmBusy||I.launchConfirmSessionsLoading}),"Resume-ready only"]}),s.jsxs("select",{value:I.launchConfirmResumeId,onChange:E=>I.setLaunchConfirmResumeId(E.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2 text-sm",disabled:I.launchConfirmBusy||I.launchConfirmSessionsLoading,children:[s.jsx("option",{value:"",children:Xk(v)}),I.filteredLaunchConfirmSavedSessions.map(E=>s.jsxs("option",{value:E.providerSessionId,disabled:!E.canResume,children:[E.title||E.providerSessionId," ",E.canResume?"":"(workspace missing)"]},E.providerSessionId))]}),!I.launchConfirmSessionsLoading&&I.launchConfirmSavedSessions.length>0&&I.filteredLaunchConfirmSavedSessions.length===0&&s.jsx("div",{className:"mt-2 text-[11px] text-text-muted",children:"No saved history matches these filters."}),I.launchConfirmResumeId&&(()=>{const E=I.filteredLaunchConfirmSavedSessions.find(R=>R.providerSessionId===I.launchConfirmResumeId);if(!E)return null;const K=Xp(E);return s.jsxs("div",{className:"mt-2 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2.5 text-[11px] text-text-muted leading-relaxed",children:[s.jsx("div",{className:"font-semibold text-text-primary truncate",children:K.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:K.providerSessionId}),s.jsx("div",{className:"mt-1",children:K.metaLine}),K.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:K.updatedLabel}),K.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:K.preview})]})})()]}),onConfirm:I.handleConfirmLaunch,onCancel:I.closeLaunchConfirm}),u&&s.jsx(Qp,{section:p,onSectionChange:f})]})}const Wc=8e3;function Wj(e){const t=e&&typeof e=="object"&&"result"in e?e.result:e,n=t&&typeof t=="object",r=n&&t.success===!1,a=n&&t.mirrorStale===!0;return!r&&!a?{confirmed:!0}:{confirmed:!1,reason:r&&typeof t.error=="string"?t.error:a?"the coordinator did not confirm the change":"command was rejected"}}function sm(e,t,n){const r=l.useRef(new Map),[,a]=l.useState(0),o=l.useCallback(()=>a(g=>g+1),[]);l.useEffect(()=>{const g=r.current;if(g.size===0)return;const C=Date.now();let h=!1;for(const[x,y]of g){const b=e.get(x),S=y.muted===void 0||(b?b.muted===y.muted:!1),k=y.hidden===void 0||(b?b.surfaceHidden===y.hidden:!1),w=C-y.at>Wc;(S&&k||w)&&(g.delete(x),h=!0)}h&&o()},[e,o]),l.useEffect(()=>{if(r.current.size===0)return;const g=setInterval(()=>{const C=r.current,h=Date.now();let x=!1;for(const[y,b]of C)h-b.at>Wc&&(C.delete(y),x=!0);x&&o(),C.size===0&&clearInterval(g)},1e3);return()=>clearInterval(g)});const i=l.useCallback((g,C)=>{const h=r.current.get(g);r.current.set(g,{...h,...C,at:Date.now()}),o()},[o]),c=l.useCallback(g=>{const C=g.sessionId,h=C?r.current.get(C):void 0;return(h==null?void 0:h.muted)!==void 0?h.muted:Ds(g,e).muted},[e]),d=l.useCallback(g=>{const C=g.sessionId,h=C?r.current.get(C):void 0;return(h==null?void 0:h.hidden)!==void 0?h.hidden:Ds(g,e).surfaceHidden},[e]),p=l.useCallback((g,C)=>{const h=Ps(g),x=g.sessionId;!h||!x||(i(x,C),t(h,"set_conversation_prefs",{sessionId:x,...C,...Ma(g)}).then(y=>{const b=Wj(y);b.confirmed||(console.warn("[conversation-prefs] set_conversation_prefs not confirmed",b.reason),r.current.delete(x),o(),n==null||n(`Couldn't update conversation — ${b.reason}`))}).catch(y=>{console.warn("[conversation-prefs] set_conversation_prefs failed",y),r.current.delete(x),o();const b=y instanceof Error?y.message:String(y??"the daemon is unreachable");n==null||n(`Couldn't update conversation — ${b}`)}))},[t,i,o,n]),u=l.useCallback(g=>{p(g,{muted:!c(g)})},[p,c]),m=l.useCallback((g,C)=>{p(g,{hidden:C})},[p]),f=l.useCallback(g=>{p(g,{hidden:!d(g)})},[p,d]);return{isMuted:c,isHidden:d,toggleMute:u,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 Uj(e,t=[]){const n=new Map(e.map(a=>[a.conversation.tabKey,a])),r=t.map(a=>n.get(a)).filter(a=>!!a);return r.length===e.length?r:Yr(e)}function Gj(e){var r,a,o;const t=((r=e.p2p)==null?void 0:r.state)||"";return t==="connected"?"Connected":t==="connecting"||t==="new"||t==="checking"?"Connecting":!(!!((a=e.p2p)!=null&&a.available)||!!((o=e.p2p)!=null&&o.state))&&e.status&&e.status!=="offline"?"Connected":"Offline"}function qj(e,t){if(!e)return[];const n=e.recentLaunches||[];return n.length>0?n.map(r=>({id:r.id,label:r.title||r.providerName||r.providerType,kind:r.kind,providerType:r.providerType,providerSessionId:r.providerSessionId,subtitle:Js(r.summaryMetadata)||r.workspace||void 0,workspace:r.workspace,summaryMetadata:r.summaryMetadata})):t.filter(r=>r.type!=="adhdev-daemon"&&r.daemonId===e.id).map(r=>{var i;const a=ir(r)?"cli":mn(r)?"acp":"ide",o=Js(r.summaryMetadata);return{id:`${a}:${r.type}:${r.workspace||""}`,label:((i=r.activeChat)==null?void 0:i.title)||(ir(r)?r.cliName||r.type:mn(r)&&r.cliName||r.type),kind:a,providerType:r.type,providerSessionId:r.providerSessionId,subtitle:mn(r)?o||r.workspace||void 0:r.workspace||void 0,workspace:r.workspace||void 0,timestamp:r.lastMessageAt||0}}).sort((r,a)=>a.timestamp-r.timestamp).map(({timestamp:r,...a})=>a)}function zj(e,t){const n=new Map;for(const r of t){const a=Ps(r.conversation),o=n.get(a);o?o.push(r):n.set(a,[r])}return e.map(r=>{const a=n.get(r.id)||[],o=[...a].sort((m,f)=>f.timestamp-m.timestamp)[0]||null,i=(o==null?void 0:o.conversation)||null,c=Zo(r),d=a.filter(m=>m.unread||m.requiresAction).length,p=Gj(r),u=[r.platform||"machine",p].filter(Boolean);return{id:r.id,label:ts(r,{fallbackId:r.id}),subtitle:u.join(" · "),unread:d,total:a.length,latestConversation:i,latestTimestamp:(o==null?void 0:o.timestamp)||0,fallbackActivityAt:c,preview:i?jk(i,ep(i)):"No active conversations yet. Open the machine, choose a workspace, then launch an IDE, CLI, or ACP session."}}).sort((r,a)=>{const o=r.latestTimestamp||r.fallbackActivityAt||0,i=a.latestTimestamp||a.fallbackActivityAt||0;return i!==o?i-o:r.label.localeCompare(a.label)})}function Kj(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 Vj({conversations:e,machineEntries:t,items:n,selectedConversation:r,selectedTabKey:a,screen:o,liveSessionInboxState:i,sendDaemonCommand:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:C,setScreen:h,setSelectedMachineId:x,setSection:y,setMachineBackTarget:b,resetMachineAction:S}){const k=l.useRef(null),w=l.useCallback(v=>{if(!(v!=null&&v.sessionId))return;const N=Ds(v,i),j=Math.max(Date.now(),Ks(v),N.lastUpdated||0);Rr("mark_read:start",{tabKey:v.tabKey,sessionId:v.sessionId,displayPrimary:xt(v),inboxBucket:N.inboxBucket,unread:N.unread,lastSeenAt:N.lastSeenAt,lastUpdated:N.lastUpdated,activityAt:Ks(v),readAt:j}),c(Ps(v)||v.routeId,"mark_session_seen",{sessionId:v.sessionId,providerSessionId:v.providerSessionId,seenAt:j,completionMarker:N.completionMarker}).then(A=>{Rr("mark_read:result",{tabKey:v.tabKey,sessionId:v.sessionId,result:A})}).catch(A=>{Rr("mark_read:error",{tabKey:v.tabKey,sessionId:v.sessionId,error:A instanceof Error?A.message:String(A)})})},[i,c]);return l.useEffect(()=>{var N;if(!r){Kj(o)&&h("inbox"),C(((N=e[0])==null?void 0:N.tabKey)||null),k.current=null;return}if(o!=="chat"){k.current=null;return}const v=`${r.tabKey}:${r.sessionId||""}`;k.current!==v&&(k.current=v,w(r))},[e,w,o,r,h,C]),l.useEffect(()=>{if(!d)return;const v=e.find(N=>N.tabKey===d);v&&(C(v.tabKey),h("chat"),p==null||p())},[e,p,d,h,C]),l.useEffect(()=>{if(!u)return;const v=t.find(N=>N.id===u);v&&(x(v.id),S(),y("machines"),b("inbox"),h("machine"),m==null||m())},[t,m,u,S,b,h,y,x]),l.useEffect(()=>{f&&(y(f),h("inbox"),g==null||g())},[g,f,h,y]),l.useEffect(()=>{const v=n.filter(N=>N.inboxBucket==="task_complete"||N.unread);v.length!==0&&Rr("inbox_state",{screen:o,selectedTabKey:a,items:v.map(N=>{const j=Ds(N.conversation,i);return{liveState:j,tabKey:N.conversation.tabKey,sessionId:N.conversation.sessionId,displayPrimary:xt(N.conversation),serverBucket:j.inboxBucket,computedBucket:N.inboxBucket,serverUnread:j.unread,computedUnread:N.unread,lastSeenAt:j.lastSeenAt,lastUpdated:j.lastUpdated,activityAt:Ks(N.conversation)}})})},[n,i,o,a]),{markConversationRead:w}}function Yj(e){if(!e)return"";const t=String(e);return t.includes(":")&&t.split(":")[0]||t}function Uc(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function Jj(e){return(e instanceof Error?e.message:String(e||"")).includes("P2P command timeout")}function Qj({sendDaemonCommand:e,navigate:t,ides:n,conversations:r}){const{launchCli:a}=wa(),[o,i]=l.useState("idle"),[c,d]=l.useState(""),[p,u]=l.useState(null),m=l.useCallback(()=>{i("idle"),d(""),u(null)},[]),f=l.useCallback(async(S,k,w)=>{var v;try{i("loading"),d(`Launching ${k}…`);const N={ideType:k,enableCdp:!0};(v=w==null?void 0:w.workspacePath)!=null&&v.trim()&&(N.workspace=w.workspacePath.trim()),await e(S,"launch_ide",N),i("done"),d(`${k} launch requested`)}catch(N){i("error"),d(N instanceof Error?N.message:"Launch IDE failed"),console.error("Launch IDE failed",N)}},[e]),g=l.useCallback(async(S,k,w)=>{if(k.trim())try{i("loading"),d(w!=null&&w.createIfMissing?"Creating folder…":"Saving workspace…");const v=await e(S,"workspace_add",{path:k.trim(),createIfMissing:(w==null?void 0:w.createIfMissing)===!0});if(v!=null&&v.success){i("done"),d(w!=null&&w.createIfMissing?"Folder created and workspace saved":"Workspace saved");return}i("error"),d((v==null?void 0:v.error)||"Could not save workspace")}catch(v){i("error"),d(v instanceof Error?v.message:"Could not save workspace")}},[e]),C=l.useCallback(async S=>{var k,w,v,N,j,A;try{i("loading"),d("Starting daemon upgrade…");const I=await e(S,"daemon_upgrade",{});if((k=I==null?void 0:I.result)!=null&&k.alreadyLatest){i("done"),d(`Already on v${((w=I==null?void 0:I.result)==null?void 0:w.version)||"latest"}.`);return}if((v=I==null?void 0:I.result)!=null&&v.upgraded||(N=I==null?void 0:I.result)!=null&&N.success){i("done"),d(`Upgrade to v${((j=I==null?void 0:I.result)==null?void 0:j.version)||"latest"} started. Daemon is restarting…`);return}i("error"),d(((A=I==null?void 0:I.result)==null?void 0:A.error)||"Upgrade failed")}catch(I){i("error"),d(I instanceof Error?I.message:"Upgrade failed")}},[e]),h=l.useCallback(async(S,k,w,v)=>{var A,I,D;const N=Date.now(),j={machineId:S,kind:k,providerType:w,workspaceId:(v==null?void 0:v.workspaceId)||null,workspacePath:(v==null?void 0:v.workspacePath)||null,resumeSessionId:(v==null?void 0:v.resumeSessionId)||null,startedAt:N};try{i("loading"),d(`Launching ${w}…`),u(j);const L={cliType:w};(A=v==null?void 0:v.workspacePath)!=null&&A.trim()?L.dir=v.workspacePath.trim():v!=null&&v.workspaceId&&(L.workspaceId=v.workspaceId),v!=null&&v.resumeSessionId&&(L.resumeSessionId=v.resumeSessionId),(I=v==null?void 0:v.args)!=null&&I.trim()&&(L.cliArgs=v.args.trim().split(/\s+/).filter(Boolean)),(D=v==null?void 0:v.model)!=null&&D.trim()&&(L.initialModel=v.model.trim());const P=await a(S,L),_=(P==null?void 0:P.result)||P,q=(_==null?void 0:_.sessionId)||(_==null?void 0:_.id);if(P!=null&&P.success&&q){u(null),i("done"),d(`${w} launched`),t(dr(q));return}if(P!=null&&P.success){i("loading"),d(`${w} launch requested — waiting for session…`);return}u(null),i("error"),d((P==null?void 0:P.error)||(_==null?void 0:_.error)||`Could not launch ${k.toUpperCase()} workspace`)}catch(L){if(Jj(L)){i("loading"),d(`${w} launch requested — waiting for session…`);return}u(null),i("error"),d(L instanceof Error?L.message:`Could not launch ${k.toUpperCase()} workspace`)}},[t,e]),x=l.useCallback(async(S,k)=>{try{const w=await e(S,"list_saved_sessions",{providerType:k,kind:"cli",limit:30}),v=(w==null?void 0:w.result)??w;return Array.isArray(v==null?void 0:v.sessions)?v.sessions:[]}catch(w){return console.error("Failed to list saved sessions on mobile:",w),[]}},[e]),y=l.useCallback(async(S,k)=>nl(e,S,k),[e]);l.useEffect(()=>{if(!p)return;const S=Uc(p.workspacePath),k=n.find(v=>{var L,P,_,q;if(!v||v.type==="adhdev-daemon"||Yj(v.daemonId||v.id)!==p.machineId||(v.transport==="acp"?"acp":v.transport==="pty"?"cli":null)!==p.kind||String(v.agentType||v.type||"")!==p.providerType)return!1;const I=String(v.providerSessionId||"");if(p.resumeSessionId&&I)return I===p.resumeSessionId;if(S){const B=Uc(v.workspace||v.runtimeWorkspaceLabel);return B?B===S:!1}return Number(v.lastUpdated||v._lastUpdate||v.timestamp||((q=(_=(P=(L=v.activeChat)==null?void 0:L.messages)==null?void 0:P.at)==null?void 0:_.call(P,-1))==null?void 0:q.timestamp)||0)>=p.startedAt-5e3});if(!k)return;const w=Vp({entrySessionId:k.sessionId,entryInstanceId:k.instanceId,entryRouteId:k.id,conversations:r});w&&(u(null),i("done"),d(`${p.providerType} launched`),t(dr(w)))},[r,n,t,p]),l.useEffect(()=>{if(!p)return;const S=window.setTimeout(()=>{u(k=>!k||k.startedAt!==p.startedAt?k:(i("error"),d("Launch response timed out. The session may already be running in Dashboard."),null))},45e3);return()=>window.clearTimeout(S)},[p]);const b=l.useCallback(async(S,k)=>{if(k.kind==="ide"&&k.providerType){await f(S,k.providerType,{workspacePath:k.workspace||null});return}(k.kind==="cli"||k.kind==="acp")&&k.providerType&&await h(S,k.kind,k.providerType,{workspacePath:k.workspace||null,resumeSessionId:k.providerSessionId||null})},[f,h]);return{machineAction:{state:o,message:c},resetMachineAction:m,handleLaunchDetectedIde:f,handleAddWorkspace:g,handleMachineUpgrade:C,handleLaunchWorkspaceProvider:h,handleListSavedSessions:x,handleBrowseDirectory:y,handleOpenRecent:b}}function Xj({conversations:e,selectedConversation:t,machineBackTarget:n,markConversationRead:r,resetMachineAction:a,setSelectedTabKey:o,setScreen:i,setSelectedMachineId:c,setSection:d,setMachineBackTarget:p}){const u=l.useCallback(y=>{o(y.tabKey),i("chat"),r(y)},[r,i,o]),m=l.useCallback(y=>{const b=e.find(S=>S.routeId===y.routeId&&S.streamSource==="native");b&&(o(b.tabKey),i("chat"),r(b))},[e,r,i,o]),f=l.useCallback(()=>{r(t),i("inbox")},[r,t,i]),g=l.useCallback((y,b="inbox")=>{c(y),a(),d("machines"),p(b),i("machine")},[a,p,i,d,c]),C=l.useCallback(y=>{const b=Ps(y);b&&g(b,"chat")},[g]),h=l.useCallback(()=>{a(),i(n)},[n,a,i]),x=l.useCallback(y=>{d(y),i("inbox")},[i,d]);return{openConversation:u,openNativeConversation:m,backFromConversation:f,openMachine:g,openConversationMachine:C,backFromMachine:h,changeMachineSection:x}}function Sn(e,t){return e.category!==t?!1:t==="ide"?!0:e.enabled===!0}function Zj(e){const t=e.trim();return t?t[0].toUpperCase():"?"}function e1({conversations:e,hiddenConversations:t,ides:n,actionLogs:r,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,userName:c,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,onOpenHistory:C,onOpenRemote:h,onStopCli:x,wsStatus:y,isConnected:b,onShowAllHiddenConversations:S,onHideConversation:k,onOpenMeshGraph:w,onOpenNewSession:v,liveSessionInboxState:N,setCliViewModeOverrides:j}){const[A,I]=l.useState(()=>{var F;return((F=e[0])==null?void 0:F.tabKey)||null}),[D,L]=l.useState(()=>e[0]?"chat":"inbox"),[P,_]=l.useState("chats"),[q,B]=l.useState(null),[E,K]=l.useState("inbox"),R=l.useRef([]),T=mr(),H="0.9.82",M=l.useMemo(()=>e.find(F=>F.tabKey===A)||e[0]||null,[e,A]),W=l.useMemo(()=>M?n.find(F=>F.id===M.routeId):void 0,[n,M]),J=l.useMemo(()=>!M||lt(M)||!ct(M)?null:In(M),[M]),re=l.useMemo(()=>n.filter(F=>F.type==="adhdev-daemon").sort(_i),[n]),V=l.useMemo(()=>re.find(F=>F.id===q)||null,[re,q]),X=Da({sendDaemonCommand:a,activeConv:M||void 0,setActionLogs:o,isStandalone:i}),de=Qj({sendDaemonCommand:a,navigate:T,ides:n,conversations:e}),ne=ek(e),O=l.useMemo(()=>e.map(F=>{const be=D==="chat"&&(M==null?void 0:M.tabKey)===F.tabKey,je=ja(F,N,{hideOpenTaskCompleteUnread:!0,isOpenConversation:be}),Se=Ks(F),He=ep(F),Xe=ip(F,He);return{conversation:F,timestamp:Se,preview:Xe,unread:je.unread,requiresAction:je.requiresAction,isWorking:je.isWorking,inboxBucket:je.inboxBucket}}),[e,N,D,M,ne]),{markConversationRead:ie}=Vj({conversations:e,machineEntries:re,items:O,selectedConversation:M,selectedTabKey:A,screen:D,liveSessionInboxState:N,sendDaemonCommand:a,requestedActiveTabKey:d,onRequestedActiveTabConsumed:p,requestedMachineId:u,onRequestedMachineConsumed:m,requestedMobileSection:f,onRequestedMobileSectionConsumed:g,setSelectedTabKey:I,setScreen:L,setSelectedMachineId:B,setSection:_,setMachineBackTarget:K,resetMachineAction:de.resetMachineAction}),z=Xj({conversations:e,selectedConversation:M,machineBackTarget:E,markConversationRead:ie,resetMachineAction:de.resetMachineAction,setSelectedTabKey:I,setScreen:L,setSelectedMachineId:B,setSection:_,setMachineBackTarget:K}),{isMuted:ae,toggleMute:Ce}=sm(N,a),ye=l.useMemo(()=>Yr(O.filter(F=>F.requiresAction&&!ae(F.conversation))),[O,ae]),ke=l.useMemo(()=>Yr(O.filter(F=>F.unread&&!F.requiresAction&&!ae(F.conversation))),[O,ae]),me=l.useMemo(()=>Uj(O.filter(F=>!F.unread&&!F.requiresAction&&F.isWorking),R.current),[O]);l.useEffect(()=>{R.current=me.map(F=>F.conversation.tabKey)},[me]);const G=l.useMemo(()=>Yr(O.filter(F=>!F.unread&&!F.requiresAction&&!F.isWorking)),[O]),U=l.useMemo(()=>V?O.filter(F=>Ps(F.conversation)===V.id):[],[O,V]),Z=l.useMemo(()=>qj(V,n),[n,V]),Y=(V==null?void 0:V.version)||null,fe=!!V&&!!Y&&!0&&Y!==H,Te=l.useMemo(()=>(V==null?void 0:V.availableProviders)||[],[V]),ce=l.useMemo(()=>Te.filter(F=>Sn(F,"cli")).map(F=>({type:F.type,displayName:F.displayName||F.type,icon:F.icon})),[Te]),$=l.useMemo(()=>Te.filter(F=>Sn(F,"acp")).map(F=>({type:F.type,displayName:F.displayName||F.type,icon:F.icon})),[Te]),pe=l.useMemo(()=>zj(re,O),[O,re]),le=l.useCallback(async F=>{V&&await de.handleOpenRecent(V.id,F)},[de,V]);return s.jsx("div",{className:"dashboard-mobile-chat w-full min-w-0",children:D==="chat"&&M?s.jsx(Pj,{selectedConversation:M,isAcp:lt(M),isStandalone:i,selectedIdeEntry:W,actionLogs:r,userName:c,isSendingChat:X.isSendingChat,sendFeedbackMessage:X.sendFeedbackMessage,isFocusingAgent:X.isFocusingAgent,handleModalButton:X.handleModalButton,handleRelaunch:X.handleRelaunch,onBack:z.backFromConversation,onOpenNativeConversation:z.openNativeConversation,onOpenMachine:z.openConversationMachine,onOpenHistory:C,onOpenRemote:h,onOpenMeshGraph:w,onStopCli:x,cliViewMode:J,onSetCliViewMode:async F=>{await _p({conversation:M,mode:F,ides:n,sendDaemonCommand:a,setCliViewModeOverrides:j})},handleSendChat:X.handleSendChat,handleForceSendChat:X.handleForceSendChat,handleFocusAgent:X.handleFocusAgent}):D==="machine"&&V?s.jsx(Oj,{selectedMachineEntry:V,selectedMachineConversations:U,selectedMachineRecentLaunches:Z,cliProviders:ce,acpProviders:$,selectedMachineNeedsUpgrade:fe,appVersion:H,machineAction:de.machineAction,isStandalone:i,section:P,showBottomNav:E==="inbox",onBack:z.backFromMachine,onSectionChange:z.changeMachineSection,onOpenConversation:z.openConversation,onOpenRecent:le,onOpenMachineDetails:()=>T(`/machines/${V.id}`),onMachineUpgrade:()=>de.handleMachineUpgrade(V.id),onLaunchDetectedIde:(F,be)=>de.handleLaunchDetectedIde(V.id,F,be),onAddWorkspace:(F,be)=>de.handleAddWorkspace(V.id,F,be),onBrowseDirectory:F=>de.handleBrowseDirectory(V.id,F),onLaunchWorkspaceProvider:(F,be,je)=>de.handleLaunchWorkspaceProvider(V.id,F,be,je),onListSavedSessions:F=>de.handleListSavedSessions(V.id,F)}):s.jsx(Ej,{section:P,attentionItems:ye,unreadItems:ke,workingItems:me,completedItems:G,hiddenConversations:t,machineCards:pe,getAvatarText:Zj,actionLogs:r,sendDaemonCommand:a,onOpenConversation:z.openConversation,onShowAllHidden:S,onHideConversation:k,onOpenMeshGraph:w,onStopCli:x,onOpenNewSession:v,onOpenMachine:z.openMachine,onOpenSettings:()=>T("/settings"),onSectionChange:_,wsStatus:y,isConnected:b,isStandalone:i,isConversationMuted:ae,onToggleMuteConversation:Ce})})}function go(e,t){return!!(e<4&&t&&window.innerWidth>=768)}function t1({conversations:e,numGroups:t,onMoveTab:n,onReceiveTab:r,onOwnTabDrop:a,onClearPreviewOrder:o}){const i=l.useRef(0),[c,d]=l.useState(!1),[p,u]=l.useState(null),m=l.useCallback(()=>{i.current=0,d(!1),u(null)},[]);l.useEffect(()=>(window.addEventListener("dragend",m),window.addEventListener("drop",m),()=>{window.removeEventListener("dragend",m),window.removeEventListener("drop",m)}),[m]);const f=l.useCallback(x=>{x.dataTransfer.types.includes("text/tab-key")&&(i.current+=1,d(!0))},[]),g=l.useCallback(x=>{if(!x.dataTransfer.types.includes("text/tab-key"))return;if(x.preventDefault(),!go(t,n)){u("merge");return}const y=x.currentTarget.getBoundingClientRect(),b=x.clientX-y.left,S=y.width/3;b<S?u("split-left"):b>S*2?u("split-right"):u("merge")},[t,n]),C=l.useCallback(()=>{i.current-=1,!(i.current>0)&&(i.current=0,d(!1),u(null))},[]),h=l.useCallback(x=>{i.current=0,d(!1);const y=x.dataTransfer.getData("text/tab-key"),b=y?e.some(k=>k.tabKey===y):!1,S=p;if(u(null),o(),!!y){if(x.preventDefault(),S==="split-left"&&go(t,n)){n==null||n(y,"split-left");return}if(S==="split-right"&&go(t,n)){n==null||n(y,"split-right");return}if(b){a(y);return}r==null||r(y)}},[e,p,t,n,r,a,o]);return{dragOver:c,dropAction:p,resetDragState:m,handleDragEnter:f,handleDragOver:g,handleDragLeave:C,handleDrop:h}}function s1(e,t){const n=new Set(t.map(o=>o.tabKey)),r=e.filter(o=>n.has(o)),a=t.filter(o=>!e.includes(o.tabKey)).map(o=>o.tabKey);return[...r,...a]}function n1({conversations:e,initialActiveTabId:t,initialTabOrder:n,onActiveTabChange:r,onTabOrderChange:a}){const[o,i]=l.useState(t??null),[c,d]=l.useState(n??[]),[p,u]=l.useState(null),m=l.useRef(null),f=l.useRef(null),g=l.useRef(r),C=l.useRef(a);l.useEffect(()=>{g.current=r},[r]),l.useEffect(()=>{C.current=a},[a]),l.useEffect(()=>{t&&t!==o&&i(t)},[t,o]),l.useEffect(()=>{d(N=>{const j=s1(N,e);return j.length===N.length&&j.every((A,I)=>A===N[I])?N:j})},[e]);const h=l.useMemo(()=>{const N=p??c;if(N.length===0)return e;const j=new Map(N.map((A,I)=>[A,I]));return[...e].sort((A,I)=>{const D=j.get(A.tabKey)??999,L=j.get(I.tabKey)??999;return D-L})},[e,p,c]);l.useEffect(()=>{var j,A;if(h.length===0){o!==null&&(i(null),(j=g.current)==null||j.call(g,null));return}if(o&&h.some(I=>I.tabKey===o))return;const N=h[0].tabKey;N!==o&&(i(N),(A=g.current)==null||A.call(g,N))},[h,o]);const x=l.useMemo(()=>h.find(N=>N.tabKey===o),[h,o]),y=l.useCallback(N=>{var j;i(N),(j=g.current)==null||j.call(g,N)},[]),b=l.useCallback((N,j,A)=>{d(I=>{var _;const D=I.filter(q=>q!==N),L=D.indexOf(j);if(L<0)return I;const P=A==="left"?L:L+1;return D.splice(P,0,N),(_=C.current)==null||_.call(C,D),D}),u(null)},[]),S=l.useCallback((N,j,A)=>{const D=(c.length>0?c:e.map(_=>_.tabKey)).filter(_=>_!==N),L=D.indexOf(j);if(L<0)return;const P=A==="left"?L:L+1;D.splice(P,0,N),m.current=D,u(D)},[c,e]),k=l.useCallback(()=>{var j;const N=m.current;N&&(d(N),(j=C.current)==null||j.call(C,N))},[]),w=l.useCallback(()=>{m.current=null,u(null)},[]),v=l.useCallback(N=>{d(j=>{var I;const A=j.filter(D=>D!==N);return A.push(N),(I=C.current)==null||I.call(C,A),A})},[]);return{activeTabId:o,activeConv:x,sortedConversations:h,previewOrderRef:m,draggingTabRef:f,selectTab:y,handleTabReorder:b,updatePreviewOrder:S,commitPreviewOrder:k,clearPreviewOrder:w,moveTabToEnd:v,setDraggingTabKey:N=>{f.current=N}}}function r1({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:a=!1,onOpenNewSession:o}){const{t:i}=Ne("common");if(a)return s.jsx("div",{className:"text-sm text-text-muted opacity-0 select-none","aria-hidden":"true",children:"No active agent"});const c=!n&&!r,d=r&&!!o,p=i(r?"paneGroup.noConversations":n?"paneGroup.waitingForDaemon":"paneGroup.connectYourMachines"),u=i(r?"paneGroup.newSessionDescription":n?"paneGroup.daemonDescription":"paneGroup.installDescription");return e===0&&!t?s.jsxs("div",{className:"empty-dashboard flex-1 flex flex-col items-center justify-center -mt-8",children:[s.jsx("div",{className:"glow-orb mb-6 opacity-90 animate-bounce",style:{animationDuration:"3s"},children:s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-16 h-16 object-contain"})}),s.jsxs("div",{className:"text-center max-w-lg",children:[s.jsx("h2",{className:"font-bold text-2xl mb-2.5 tracking-tight text-text-primary",children:p}),s.jsx("p",{className:"text-[14px] text-text-secondary mb-8 leading-relaxed max-w-md mx-auto",children:u}),d&&s.jsx("div",{className:"flex items-center justify-center mb-4",children:s.jsxs("button",{type:"button",onClick:o,className:"btn btn-secondary btn-sm inline-flex items-center gap-2",title:i("paneGroup.newSession"),"aria-label":i("paneGroup.newSession"),children:[s.jsx(Di,{size:14}),s.jsx("span",{children:i("paneGroup.newSession")})]})}),c&&s.jsx(Jp,{}),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 nm="adhdev-tab-shortcuts";function rm(){try{return JSON.parse(localStorage.getItem(nm)||"{}")}catch{return{}}}function am({enabled:e=!0,sortedTabKeys:t,onFocus:n,onSelectTab:r}){const a=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent),[o,i]=l.useState(()=>rm()),[c,d]=l.useState(null),p=l.useCallback(m=>{const f=[];return m.metaKey&&f.push(a?"⌘":"Meta"),m.ctrlKey&&f.push("Ctrl"),m.altKey&&f.push(a?"⌥":"Alt"),m.shiftKey&&f.push(a?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(m.key)?null:(f.push(m.key.length===1?m.key.toUpperCase():m.key),f.join("+"))},[a]),u=l.useCallback(m=>{i(m);try{localStorage.setItem(nm,JSON.stringify(m))}catch{}},[]);return l.useEffect(()=>{if(!e||!c)return;const m=f=>{if(f.preventDefault(),f.stopPropagation(),f.key==="Escape"){d(null);return}const g=p(f);if(!g)return;const C={...o};for(const[h,x]of Object.entries(C))x===g&&delete C[h];C[c]=g,u(C),d(null)};return window.addEventListener("keydown",m,!0),()=>window.removeEventListener("keydown",m,!0)},[e,c,o,u,p]),l.useEffect(()=>{if(!e)return;const m=f=>{if(!(!f.ctrlKey&&!f.metaKey&&!f.altKey)){for(const[g,C]of Object.entries(o))if(t.includes(g)&&p(f)===C){f.preventDefault(),n(),r(g);return}}};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[e,o,t,n,r,p]),{isMac:a,tabShortcuts:o,shortcutListening:c,setShortcutListening:d,saveShortcuts:u}}const xo=e=>{e.preventDefault()},a1=l.memo(function({conv:t,isActive:n,isDraggedTab:r,isTaskCompleteUnread:a,shortcut:o,conversationKeys:i,draggingTabRef:c,onFocus:d,onSelectTab:p,onConversationActivated:u,onPreviewReorder:m,onReorderTab:f,onCommitPreviewOrder:g,onClearPreviewOrder:C,onDragStateReset:h,onDragTabKeyChange:x,onReceiveTab:y,onOpenContextMenu:b,longPressTimer:S,isGroupActive:k}){const w=An(t),v=w.isGenerating?"agent-tab-generating":w.isWaiting?"agent-tab-waiting":"",N=w.isReconnecting,j=kk(t),A=Sk(t),I=op(t),D=l.useCallback(T=>{c.current=t.tabKey,x(t.tabKey),T.dataTransfer.setData("text/tab-key",t.tabKey),T.dataTransfer.effectAllowed="move"},[t.tabKey,c,x]),L=l.useCallback(()=>{c.current=null,x(null),g(),C(),h()},[c,x,g,C,h]),P=l.useCallback(T=>{const H=c.current;if(!(!H||H===t.tabKey)&&T.dataTransfer.types.includes("text/tab-key")){T.preventDefault(),T.stopPropagation();const M=T.currentTarget.getBoundingClientRect(),W=T.clientX<M.left+M.width/2?"left":"right";m(H,t.tabKey,W)}},[t.tabKey,c,m]),_=l.useCallback(T=>{T.preventDefault(),T.stopPropagation();const H=T.dataTransfer.getData("text/tab-key");if(H&&H!==t.tabKey){const M=T.currentTarget.getBoundingClientRect(),W=T.clientX<M.left+M.width/2?"left":"right";i.includes(H)?f(H,t.tabKey,W):y&&y(H)}C()},[t.tabKey,i,f,y,C]),q=l.useCallback(T=>{T.stopPropagation(),d(),p(t.tabKey),u(t)},[t,u,d,p]),B=l.useCallback(T=>{T.preventDefault(),b(T.clientX,T.clientY,t.tabKey)},[t.tabKey,b]),E=l.useCallback(T=>{const H=T.touches[0];S.current=setTimeout(()=>{b(H.clientX,H.clientY,t.tabKey)},600)},[t.tabKey,S,b]),K=l.useCallback(()=>{S.current&&clearTimeout(S.current)},[S]),R=["adhdev-dockview-tab",v,n&&"is-active",k&&"is-group-active",N&&"is-reconnecting"].filter(Boolean).join(" ");return s.jsxs("div",{"data-tabkey":t.tabKey,className:R,draggable:!0,onDragStart:D,onDragEnd:L,onDragOver:P,onDrop:_,onClick:q,onContextMenu:B,onTouchStart:E,onTouchEnd:K,onTouchMove:K,style:{position:"relative",cursor:"pointer",opacity:r?.4:void 0},children:[I&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-badge pointer-events-none absolute top-0.5 right-0.5 text-text-muted",title:"Mesh chat","aria-label":"Mesh chat",children:s.jsx(es,{size:11})}),a&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status",children:w.isGenerating?s.jsx("div",{className:"tab-spinner"}):w.isWaiting?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):N?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:"○"}):w.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:"○"})}),j.length>0&&s.jsx("span",{className:"adhdev-dockview-tab-mesh-role",title:A,"aria-label":A||j.join(" · "),children:j.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)}):w.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(ca,{git:t.git,compact:!0,className:"max-w-[6.5rem] shrink-0"})]})]}),o&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:`Ctrl+${o}`,children:o})]})},(e,t)=>e.conv===t.conv&&e.isActive===t.isActive&&e.isDraggedTab===t.isDraggedTab&&e.isTaskCompleteUnread===t.isTaskCompleteUnread&&e.shortcut===t.shortcut&&e.conversationKeys===t.conversationKeys&&e.isGroupActive===t.isGroupActive);function o1({conversations:e,activeTabId:t,groupIndex:n,unreadTabKeys:r,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:g,onReceiveTab:C,onHideTab:h,isGroupActive:x,allowTabShortcuts:y=!0}){const{t:b}=Ne("common"),[S,k]=l.useState(null),w=l.useRef(null),v=l.useRef(null),N=l.useMemo(()=>e.map(_=>_.tabKey),[e]);hr("PaneGroupTabBar",{groupIndex:n,activeTabId:t,tabCount:e.length,ctxMenuTab:(S==null?void 0:S.tabKey)||null});const{isMac:j,tabShortcuts:A,shortcutListening:I,setShortcutListening:D,saveShortcuts:L}=am({enabled:y,sortedTabKeys:e.map(_=>_.tabKey),onFocus:o,onSelectTab:i});l.useEffect(()=>{if(!S)return;const _=q=>{const B=document.querySelector("[data-pane-context-menu]");B&&B.contains(q.target)||k(null)};return window.addEventListener("mousedown",_,!0),()=>window.removeEventListener("mousedown",_,!0)},[S]),l.useEffect(()=>{const _=v.current;if(!_)return;const q=B=>{Math.abs(B.deltaY)<=Math.abs(B.deltaX)||(B.preventDefault(),_.scrollLeft+=B.deltaY)};return _.addEventListener("wheel",q,{passive:!1}),()=>_.removeEventListener("wheel",q)},[]);const P=l.useCallback((_,q,B)=>{k({x:_,y:q,tabKey:B})},[]);return s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-end shrink-0 gap-0",style:{background:"var(--surface-secondary)",paddingInline:8,paddingTop:6,paddingBottom:0},children:s.jsxs("div",{ref:v,className:"flex-1 flex overflow-x-auto overflow-y-visible gap-1.5 select-none",style:{scrollbarWidth:"none",overscrollBehaviorX:"contain"},children:[e.map(_=>s.jsx(a1,{conv:_,isActive:t===_.tabKey,isDraggedTab:a.current===_.tabKey,isTaskCompleteUnread:r.has(_.tabKey),shortcut:y?A[_.tabKey]:void 0,conversationKeys:N,draggingTabRef:a,onFocus:o,onSelectTab:i,onConversationActivated:c,onPreviewReorder:d,onReorderTab:p,onCommitPreviewOrder:u,onClearPreviewOrder:m,onDragStateReset:f,onDragTabKeyChange:g,onReceiveTab:C,onOpenContextMenu:P,longPressTimer:w,isGroupActive:x},_.tabKey)),e.length===0&&s.jsx("div",{className:"p-2 text-xs opacity-40",children:b("paneGroup.noTabsInGroup")})]})}),S&&s.jsxs("div",{"data-pane-context-menu":!0,className:"fixed z-50 bg-bg-primary border border-border-subtle rounded-lg shadow-lg py-1 min-w-[160px]",style:{left:S.x,top:S.y},children:[y&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors ",onMouseDown:xo,onClick:_=>{_.stopPropagation(),D(S.tabKey),k(null)},children:["⌨ ",A[S.tabKey]?`Change shortcut (${A[S.tabKey]})`:"Set shortcut"]}),A[S.tabKey]&&s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted ",onMouseDown:xo,onClick:()=>{const _={...A};delete _[S.tabKey],L(_),k(null)},children:"✕ Remove shortcut"})]}),h&&s.jsxs(s.Fragment,{children:[y&&s.jsx("div",{className:"border-t border-border-subtle my-1"}),s.jsx("button",{type:"button",className:"w-full text-left px-3 py-1.5 text-xs hover:bg-bg-secondary transition-colors text-text-muted",onMouseDown:xo,onClick:()=>{h(S.tabKey),k(null)},children:"🚫 Hide from Dashboard"})]})]}),y&&I&&s.jsx("div",{className:"fixed inset-0 z-[var(--z-modal)] flex items-center justify-center bg-black/50",style:{backdropFilter:"blur(2px)"},onClick:()=>D(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:_=>_.stopPropagation(),children:[s.jsx("div",{className:"text-sm font-bold text-text-primary mb-2",children:"⌨ Set shortcut"}),s.jsxs("div",{className:"text-xs text-text-secondary mb-4",children:["Press a key combo (e.g. ",j?"⌘+1":"Ctrl+1",", ",j?"⌥+A":"Alt+A",")"]}),s.jsx("div",{className:"text-lg font-mono text-accent animate-pulse",children:"Listening..."}),s.jsx("div",{className:"text-[10px] text-text-muted mt-3",children:b("paneGroup.pressEscToCancel")})]})})]})}function i1({conversations:e,ides:t,clearedTabs:n,actionLogs:r,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,userName:d,groupIndex:p,onFocus:u,isSplitMode:m,numGroups:f,onMoveTab:g,onReceiveTab:C,style:h,onActiveTabChange:x,initialActiveTabId:y,initialTabOrder:b,onTabOrderChange:S,onHideTab:k,isFocused:w,allowTabShortcuts:v=!0,onOpenNewSession:N,liveSessionInboxState:j}){const{sendCommand:A}=vt(),I=l.useRef(null),{activeTabId:D,activeConv:L,sortedConversations:P,draggingTabRef:_,selectTab:q,handleTabReorder:B,updatePreviewOrder:E,commitPreviewOrder:K,clearPreviewOrder:R,moveTabToEnd:T,setDraggingTabKey:H}=n1({conversations:e,initialActiveTabId:y,initialTabOrder:b,onActiveTabChange:x,onTabOrderChange:S}),M=Da({sendDaemonCommand:a,activeConv:L,setActionLogs:o,isStandalone:i}),{dragOver:W,dropAction:J,resetDragState:re,handleDragEnter:V,handleDragOver:X,handleDragLeave:de,handleDrop:ne}=t1({conversations:e,numGroups:f,onMoveTab:g,onReceiveTab:C,onOwnTabDrop:T,onClearPreviewOrder:R}),O=L&&!lt(L)&&In(L)==="terminal",ie=l.useMemo(()=>L?t.find(ye=>ye.id===L.routeId):void 0,[t,L]),z=l.useMemo(()=>L?r.filter(ye=>ye.routeId===L.tabKey):[],[r,L]),ae=l.useMemo(()=>new Set(P.filter(ye=>Lb(ye,j,{isOpenConversation:ye.tabKey===D})).map(ye=>ye.tabKey)),[D,j,P]);hr("PaneGroup",{groupIndex:p,conversationCount:e.length,activeTabId:D,dragOver:W});const Ce=l.useCallback(ye=>{ye.streamSource==="agent-stream"&&ye.agentType&&A(ye.routeId,Ou(),{agentType:ye.agentType,...ye.sessionId&&{targetSessionId:ye.sessionId}}).catch(()=>{})},[A]);return s.jsxs("div",{className:"flex flex-col min-h-0 min-w-0 flex-1 overflow-hidden",onClick:u,style:{...h,outline:W?"2px dashed var(--accent-primary)":"none",outlineOffset:"-2px",transition:"outline 0.15s ease"},children:[s.jsx(o1,{conversations:P,activeTabId:D,groupIndex:p,numGroups:f,unreadTabKeys:ae,draggingTabRef:_,onFocus:u,onSelectTab:q,onConversationActivated:Ce,onPreviewReorder:E,onReorderTab:B,onCommitPreviewOrder:K,onClearPreviewOrder:R,onDragStateReset:re,onDragTabKeyChange:H,onMoveTab:g,onReceiveTab:C,onHideTab:k,isGroupActive:w??!1,allowTabShortcuts:v}),s.jsxs("div",{className:"flex-1 min-h-0 flex flex-col overflow-hidden relative",onDragEnter:V,onDragOver:X,onDragLeave:de,onDrop:ne,children:[W&&s.jsx(r1,{dropAction:J,canSplit:!!(f<4&&g)}),L?s.jsx(rl,{activeConv:L,clearToken:n[L.tabKey]||0,isCliTerminal:!!O,ideEntry:ie,terminalRef:I,handleModalButton:M.handleModalButton,handleRelaunch:M.handleRelaunch,handleSendChat:M.handleSendChat,handleForceSendChat:M.handleForceSendChat,isSendingChat:M.isSendingChat,sendFeedbackMessage:M.sendFeedbackMessage,handleFocusAgent:M.handleFocusAgent,isFocusingAgent:M.isFocusingAgent,actionLogs:z,userName:d,isInputActive:!m||!!w}):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 l1({containerRef:e,isSplitMode:t,numGroups:n,groupSizes:r,groupedConvs:a,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,userName:f,focusedGroup:g,focusGroup:C,moveTabToGroup:h,splitTabRelative:x,closeGroup:y,handleResizeStart:b,groupActiveTabIds:S,setGroupActiveTab:k,groupTabOrders:w,setGroupTabOrder:v,toggleHiddenTab:N,onOpenNewSession:j,allowTabShortcuts:A=!0,liveSessionInboxState:I}){return s.jsx("div",{ref:e,className:`flex-1 min-h-0 flex ${t?"flex-row":"flex-col"} overflow-hidden`,children:a.map((D,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(L-1,_),onDoubleClick:()=>y(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(i1,{style:t?{flexBasis:P??`${100/n}%`,flexGrow:P?0:1,flexShrink:P?0:1}:void 0,conversations:D,clearedTabs:o,ides:i,actionLogs:c,sendDaemonCommand:d,setActionLogs:p,isStandalone:u,hasRegisteredMachines:m,userName:f,groupIndex:L,isFocused:t&&g===L,onFocus:()=>C(L),isSplitMode:t,numGroups:n,onMoveTab:(_,q)=>{q==="left"&&L>0?h(_,L-1):q==="right"&&L<n-1?h(_,L+1):q==="split-left"&&n<4?x(_,L,"left"):q==="split-right"&&n<4&&x(_,L,"right")},onReceiveTab:_=>h(_,L),onActiveTabChange:_=>k(L,_),initialActiveTabId:S[L],initialTabOrder:w[L],onTabOrderChange:_=>v(L,_),onHideTab:N,onOpenNewSession:j,allowTabShortcuts:A,liveSessionInboxState:I})]},L)})})}const om="adhdev-dashboard-action-shortcuts",c1=1200,d1=[["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 u1(){return typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.userAgent)}function ht(e,t){switch(e){case"openShortcutHelp":return"?";case"openNewSession":return t?"⌘+⇧+Enter":"Ctrl+Shift+Enter";case"hideCurrentTab":return t?"⌥+X":"Ctrl+Alt+X";case"toggleHiddenTabs":return t?"⌥+H":"Ctrl+Alt+H";case"openHistoryForActiveTab":return t?"⌥+Y":"Ctrl+Alt+Y";case"openRemoteForActiveTab":return t?"⌥+R":"Ctrl+Alt+R";case"floatActiveTab":return t?"⌥+F":"Ctrl+Alt+F";case"popoutActiveTab":return t?"⌥+P":"Ctrl+Alt+P";case"dockActiveTab":return t?"⌥+D":"Ctrl+Alt+D";case"splitActiveTabRight":return t?"⌘+Ctrl+⇧+→":"Ctrl+Alt+Shift+→";case"splitActiveTabDown":return t?"⌘+Ctrl+⇧+↓":"Ctrl+Alt+Shift+↓";case"focusLeftPane":return"";case"focusRightPane":return"";case"focusUpPane":return"";case"focusDownPane":return"";case"moveActiveTabToLeftPane":return"";case"moveActiveTabToRightPane":return"";case"moveActiveTabToUpPane":return"";case"moveActiveTabToDownPane":return"";case"triggerPrimaryApprovalAction":return t?"⌥+J":"Ctrl+Alt+J";case"triggerSecondaryApprovalAction":return t?"⌥+K":"Ctrl+Alt+K";case"triggerTertiaryApprovalAction":return t?"⌥+L":"Ctrl+Alt+L";case"setActiveTabShortcut":return t?"⌥+S":"Ctrl+Alt+S";case"selectPreviousGroupTab":return t?"⌘+⇧+←":"Ctrl+Shift+←";case"selectNextGroupTab":return t?"⌘+⇧+→":"Ctrl+Shift+→";case"toggleCliView":return t?"⌥+T":"Ctrl+Alt+T"}}function im(e){return[{id:"openShortcutHelp",label:"Open shortcuts",description:"Show the keyboard shortcuts panel.",defaultShortcut:ht("openShortcutHelp",e)},{id:"openNewSession",label:"New session",description:"Open the new session launcher.",defaultShortcut:ht("openNewSession",e)},{id:"hideCurrentTab",label:"Hide current tab",description:"Hide the currently active tab into Hidden tabs.",defaultShortcut:ht("hideCurrentTab",e)},{id:"toggleHiddenTabs",label:"Toggle hidden tabs",description:"Open or close the hidden tabs popover.",defaultShortcut:ht("toggleHiddenTabs",e)},{id:"openHistoryForActiveTab",label:"Open history",description:"Open history for the active session.",defaultShortcut:ht("openHistoryForActiveTab",e)},{id:"openRemoteForActiveTab",label:"Open remote",description:"Open remote control for the active session when available.",defaultShortcut:ht("openRemoteForActiveTab",e)},{id:"floatActiveTab",label:"Float active tab",description:"Move the active tab into a floating panel.",defaultShortcut:ht("floatActiveTab",e)},{id:"popoutActiveTab",label:"Open active tab in new window",description:"Move the active tab into a detached popout window.",defaultShortcut:ht("popoutActiveTab",e)},{id:"dockActiveTab",label:"Dock active tab",description:"Dock a floating tab back into the grid, or move a popout tab back to the main window.",defaultShortcut:ht("dockActiveTab",e)},{id:"splitActiveTabRight",label:"Move active tab to new right pane",description:"Create a pane to the right and move the active tab into it.",defaultShortcut:ht("splitActiveTabRight",e)},{id:"splitActiveTabDown",label:"Move active tab to new lower pane",description:"Create a pane below and move the active tab into it.",defaultShortcut:ht("splitActiveTabDown",e)},{id:"focusLeftPane",label:"Focus left pane",description:"Move focus to the pane on the left.",defaultShortcut:ht("focusLeftPane",e)},{id:"focusRightPane",label:"Focus right pane",description:"Move focus to the pane on the right.",defaultShortcut:ht("focusRightPane",e)},{id:"focusUpPane",label:"Focus upper pane",description:"Move focus to the pane above.",defaultShortcut:ht("focusUpPane",e)},{id:"focusDownPane",label:"Focus lower pane",description:"Move focus to the pane below.",defaultShortcut:ht("focusDownPane",e)},{id:"moveActiveTabToLeftPane",label:"Move active tab left",description:"Move the active tab into the pane on the left.",defaultShortcut:ht("moveActiveTabToLeftPane",e)},{id:"moveActiveTabToRightPane",label:"Move active tab right",description:"Move the active tab into the pane on the right.",defaultShortcut:ht("moveActiveTabToRightPane",e)},{id:"moveActiveTabToUpPane",label:"Move active tab up",description:"Move the active tab into the pane above.",defaultShortcut:ht("moveActiveTabToUpPane",e)},{id:"moveActiveTabToDownPane",label:"Move active tab down",description:"Move the active tab into the pane below.",defaultShortcut:ht("moveActiveTabToDownPane",e)},{id:"triggerPrimaryApprovalAction",label:"Approval action 1",description:"Press the first approval/action button for the active session.",defaultShortcut:ht("triggerPrimaryApprovalAction",e)},{id:"triggerSecondaryApprovalAction",label:"Approval action 2",description:"Press the second approval/action button for the active session.",defaultShortcut:ht("triggerSecondaryApprovalAction",e)},{id:"triggerTertiaryApprovalAction",label:"Approval action 3",description:"Press the third approval/action button for the active session.",defaultShortcut:ht("triggerTertiaryApprovalAction",e)},{id:"setActiveTabShortcut",label:"Set active tab shortcut",description:"Start recording a direct shortcut for the active tab.",defaultShortcut:ht("setActiveTabShortcut",e)},{id:"selectPreviousGroupTab",label:"Previous tab in group",description:"Move to the previous tab inside the active Dockview group.",defaultShortcut:ht("selectPreviousGroupTab",e)},{id:"selectNextGroupTab",label:"Next tab in group",description:"Move to the next tab inside the active Dockview group.",defaultShortcut:ht("selectNextGroupTab",e)},{id:"toggleCliView",label:"Toggle CLI view",description:"Toggle the active CLI session between chat and terminal view.",defaultShortcut:ht("toggleCliView",e)}]}function fi(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"}function xa(e){const t=Object.fromEntries(im(e).map(n=>[n.id,n.defaultShortcut]));try{const n=JSON.parse(localStorage.getItem(om)||"{}"),r={...t,...n};for(const[a,o]of d1)r[a]===o&&(r[a]=t[a]);return r}catch{return t}}function lm(e){return e===" "?"Space":e==="Escape"?"Esc":e==="ArrowLeft"?"←":e==="ArrowRight"?"→":e==="ArrowUp"?"↑":e==="ArrowDown"?"↓":e.length===1?e.toUpperCase():e}function p1({enabled:e=!0,onTrigger:t}){const n=u1(),[r,a]=l.useState(()=>xa(n)),[o,i]=l.useState(null),[c,d]=l.useState([]),p=l.useRef({parts:[],timer:null}),u=l.useCallback(h=>{const x=[];return h.metaKey&&x.push(n?"⌘":"Meta"),h.ctrlKey&&x.push("Ctrl"),h.altKey&&x.push(n?"⌥":"Alt"),h.shiftKey&&h.key.length!==1&&x.push(n?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(h.key)?null:(x.push(lm(h.key)),x.join("+"))},[n]),m=l.useCallback(h=>{a(h);try{localStorage.setItem(om,JSON.stringify(h))}catch{}},[]);l.useEffect(()=>{const h=xa(n),x=Object.entries(r),y=Object.entries(h);x.length===y.length&&x.every(([b,S])=>h[b]===S)||m(h)},[r,n,m]);const f=l.useCallback(()=>{typeof window<"u"&&p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current={parts:[],timer:null}},[]),g=l.useCallback(()=>{typeof window>"u"||(p.current.timer!=null&&window.clearTimeout(p.current.timer),p.current.timer=window.setTimeout(()=>{p.current={parts:[],timer:null}},c1))},[]);l.useEffect(()=>{if(!o)return;const h=x=>{if(x.preventDefault(),x.stopPropagation(),x.key==="Escape"){i(null),d([]);return}const y=u(x);if(!y)return;const S=!(x.metaKey||x.ctrlKey||x.altKey)&&/^[A-Z0-9]$/.test(y);if(c.length===0&&S){d([y]);return}const w=[...c,y].slice(0,2).join(" "),v={...r};for(const[N,j]of Object.entries(v))j===w&&delete v[N];v[o]=w,m(v),i(null),d([])};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[r,u,m,o,c]),l.useEffect(()=>{if(!e||o)return;const h=x=>{if(x.defaultPrevented)return;const y=u(x);if(!y)return;const b=x.metaKey||x.ctrlKey||x.altKey;if(fi(x.target))return;const S=p.current.parts,k=b?[y]:[...S.slice(-1),y].slice(-2),w=k.join(" "),v=k[k.length-1],N=Object.entries(r).filter(([,L])=>!!L),j=N.find(([,L])=>L===w);if(j){x.preventDefault(),f(),t(j[0]);return}if(N.some(([,L])=>L.startsWith(`${w} `))){x.preventDefault(),p.current.parts=k,g();return}const I=N.find(([,L])=>L===v);if(I){x.preventDefault(),f(),t(I[0]);return}if(N.some(([,L])=>L.startsWith(`${v} `))){x.preventDefault(),p.current.parts=[v],g();return}f()};return window.addEventListener("keydown",h),()=>window.removeEventListener("keydown",h)},[r,g,e,u,t,f,o]),l.useEffect(()=>()=>f(),[f]);const C=l.useMemo(()=>im(n),[n]);return{isMac:n,actionDefinitions:C,actionShortcuts:r,shortcutListening:o,shortcutListeningDraft:c,setShortcutListening:i,setShortcutListeningDraft:d,saveShortcuts:m}}function m1({isTabInPopout:e,isTabFloating:t,tabShortcut:n,actionShortcuts:r}){const a=[];return e?(t&&a.push({type:"action",id:"dockInWindow",label:"Dock in window",shortcut:r.dockActiveTab}),a.push({type:"action",id:"moveBackToMain",label:"Move back to main window",shortcut:r.dockActiveTab})):t?a.push({type:"action",id:"dockBackToGrid",label:"Dock back to grid",shortcut:r.dockActiveTab}):a.push({type:"action",id:"floatAsPanel",label:"Float as panel",shortcut:r.floatActiveTab},{type:"action",id:"openInNewWindow",label:"Open in new window",shortcut:r.popoutActiveTab}),a.push({type:"separator",id:"before-shortcut-actions"},{type:"action",id:"setShortcut",label:n?`Change shortcut (${n})`:"Set shortcut",shortcut:r.setActiveTabShortcut}),n&&a.push({type:"action",id:"removeShortcut",label:"Remove shortcut",tone:"muted"}),a.push({type:"separator",id:"before-hide-tab"},{type:"action",id:"hideTab",label:"Hide tab",shortcut:r.hideCurrentTab,tone:"muted"}),a}function cm(e){return e.some(t=>t.type!=="adhdev-daemon")||e.some(t=>t.type==="adhdev-daemon"&&!!t.machine)}function Gc({hasStoredLayout:e,initialDataLoaded:t,visibleConversationCount:n,ides:r}){return!e||n>0?!1:t?!cm(r):!0}function h1({previousVisibleConversationCount:e,visibleConversationCount:t,ides:n}){return t>0||e<=0?!1:cm(n)}const dm=1e3,f1=4;function qc(e,t){return t?e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom:!1}function zc(e,t,n){return Math.abs(t.clientX-e.clientX)>n||Math.abs(t.clientY-e.clientY)>n}function b1({detachDelayMs:e=dm,stillnessThresholdPx:t=f1,onDetach:n,setTimeoutFn:r=globalThis.setTimeout.bind(globalThis),clearTimeoutFn:a=globalThis.clearTimeout.bind(globalThis)}){let o=null,i=null,c=null,d=null,p=null,u=!1;const m=()=>{p!=null&&(a(p),p=null)},f=()=>{m(),c=null},g=()=>{m(),o=null,i=null,c=null,d=null,u=!1},C=()=>{!o||!c||!d||u||p!=null||(p=r(()=>{p=null,!(!o||!c||!d||u)&&qc(d,i)&&(zc(c,d,t)||(u=!0,n({panelId:o,clientX:d.clientX,clientY:d.clientY})))},e))},h=y=>{if(!(!o||u)){if(!qc(y,i)){d={clientX:y.clientX,clientY:y.clientY},f();return}(!c||zc(c,y,t))&&(m(),c={clientX:y.clientX,clientY:y.clientY}),d={clientX:y.clientX,clientY:y.clientY},C()}},x=y=>{!o||u||(y&&(d={clientX:y.clientX,clientY:y.clientY}),f())};return{startDrag:y=>{m(),o=y.panelId,i=y.selfPanelBounds??null,c=null,d={clientX:y.clientX,clientY:y.clientY},u=!1},markSelfPanel:h,markNonSelfPanel:x,markNoDropTarget:x,markDockTarget:x,endDrag:g,isDragging:()=>o!=null,hasDetached:()=>u,dispose:g}}function g1(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 x1(e){return`remote:${e}`}function rs(e){return e.startsWith("remote:")}function Kc(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function vo(e){var r;const t=e==null?void 0:e.defaultView;if(!t)return;const n=a=>{if(a)try{a.focus({preventScroll:!0})}catch{try{a.focus()}catch{}}};try{t.focus(),n(e==null?void 0:e.body),n(e==null?void 0:e.documentElement),(r=t.requestAnimationFrame)==null||r.call(t,()=>{try{t.focus(),n(e==null?void 0:e.body)}catch{}})}catch{}}function yo(e,t){e.classList.remove(Fo.className,Oo.className),e.classList.add(t==="light"?Fo.className:Oo.className)}function Vc(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 v1(e,t,n){var i;const r=[t];let a;for(const c of r){let d;for(const p of c){const u=e.addPanel({id:p.tabKey,component:"conversation",title:Jr(p),params:{kind:"conversation",tabKey:p.tabKey},...d?{position:{referencePanel:d,direction:"within"},inactive:!0}:a?{position:{referencePanel:a,direction:"right"},inactive:!0}:{}});d||(d=u.id)}a=d??a}return n??((i=t[0])==null?void 0:i.tabKey)??null}function Yc(e,t){const n=new Set(t.map(a=>a.tabKey)),r=new Map;for(const a of t)r.set(a.tabKey,(r.get(a.tabKey)||0)+1);for(const a of[...e.panels])rs(a.id)||n.has(a.id)||e.removePanel(a);for(const a of t){const o=e.getPanel(a.tabKey);if(o){(r.get(a.tabKey)||0)>1&&console.warn("[dashboard-conversations] Dockview panel already exists for duplicate tabKey",{tabKey:a.tabKey,daemonId:a.daemonId,sessionId:a.sessionId,providerSessionId:a.providerSessionId,panelId:o.id}),o.update({params:{tabKey:a.tabKey}}),o.title!==Jr(a)&&o.api.setTitle(Jr(a));continue}e.addPanel({id:a.tabKey,component:"conversation",title:Jr(a),params:{kind:"conversation",tabKey:a.tabKey},...e.activePanel?{position:{referencePanel:e.activePanel.id,direction:"within"},inactive:!0}:e.panels[0]?{position:{referencePanel:e.panels[0].id,direction:"within"},inactive:!0}:{}})}}function Jc(e,t,n){var d,p;const r=n?x1(n):null;for(const u of[...e.panels])rs(u.id)&&(!r||u.id!==r)&&e.removePanel(u);if(!n||!r)return;const a=cs(t,n);if(!a&&e.totalPanels===0)return;const o=e.getPanel(r),i=dp(a);if(o){o.title!==i&&o.api.setTitle(i);return}const c=(a==null?void 0:a.tabKey)??((d=e.activePanel)==null?void 0:d.id)??((p=e.panels.find(u=>!rs(u.id)))==null?void 0:p.id);e.addPanel({id:r,component:"remote",title:i,params:{kind:"remote",routeId:n},...c?{position:{referencePanel:c,direction:"right"},inactive:!0}:{}})}function um({doId:e,targetSessionId:t,connState:n,viewMode:r}){const[a,o]=l.useState(null),[i,c]=l.useState(null);l.useEffect(()=>e?kt.onScreenshot("ide-page",(u,m)=>{if(u!==e)return;const f=new FileReader;f.onload=()=>o(f.result),f.readAsDataURL(m)}):void 0,[e]),l.useEffect(()=>{n!=="connected"&&o(null)},[n]),l.useEffect(()=>{var u;return e?((u=kt.onStatus)==null?void 0:u.call(kt,(m,f)=>{m===e&&f!=null&&f.screenshotUsage&&c(f.screenshotUsage)}))||(()=>{}):void 0},[e]),l.useEffect(()=>{o(null)},[e,t]),l.useEffect(()=>{const p=e?kt.get(e):null;if(!(!p||n!=="connected"))return r!=="chat"&&t?p.startScreenshots(t):p.stopScreenshots(t),()=>{p.stopScreenshots(t)}},[r,n,t,e]);const d=l.useCallback(async(p,u)=>{const m=e?kt.get(e):null;return!m||n!=="connected"?(console.warn("[RemoteInput] P2P not connected"),{success:!1,error:"P2P not connected"}):m.sendInput(p,u,t)},[e,n,t]);return{connScreenshot:a,screenshotUsage:i,handleRemoteAction:d}}const pm=l.createContext(null);function Ra(){const e=l.useContext(pm);if(!e)throw new Error("DashboardDockviewContext missing");return e}function y1(e){const[,t]=l.useState(0);l.useEffect(()=>{const n=()=>t(a=>a+1),r=[e.api.onDidActiveGroupChange(n),e.api.onDidTitleChange(n),e.api.onDidGroupChange(n),e.containerApi.onDidActivePanelChange(n)];return()=>{for(const a of r)a.dispose()}},[e.api,e.containerApi])}function w1({params:e}){var d;const t=Ra(),n=l.useMemo(()=>cs([...t.conversationsByTabKey.values()],e.routeId),[t.conversationsByTabKey,e.routeId]),r=l.useMemo(()=>t.ides.find(p=>p.id===e.routeId),[t.ides,e.routeId]),a=(n==null?void 0:n.daemonId)||((d=n==null?void 0:n.routeId)==null?void 0:d.split(":")[0])||e.routeId.split(":")[0]||e.routeId,{connScreenshot:o,screenshotUsage:i,handleRemoteAction:c}=um({doId:a,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(lu,{addLog:()=>{},connState:n.connectionState||"new",connScreenshot:o,screenshotUsage:i,transportType:n.transport,onAction:c})}):s.jsx("div",{className:"h-full min-h-0 min-w-0 flex items-center justify-center text-sm text-text-muted",children:"Remote view unavailable"})}function k1(){const e=Ra();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 S1(e){var b,S;y1(e);const t=Ra(),n=l.useCallback(k=>{"button"in k&&k.button!==0||e.api.setActive()},[e.api]),r=e.params.kind==="remote"?void 0:t.conversationsByTabKey.get(e.params.tabKey),a=r==null?void 0:r.sessionId,o=l.useCallback(k=>rk(k),[]),i=l.useCallback(()=>nk(a),[a]),c=l.useSyncExternalStore(o,i,i);if(e.params.kind==="remote"){const k=cs([...t.conversationsByTabKey.values()],e.params.routeId),w=((b=e.api.group.activePanel)==null?void 0:b.id)===e.api.id,v=e.api.isGroupActive;return s.jsxs("div",{className:`adhdev-dockview-tab${w?" is-active":""}${v?" is-group-active":""}`,title:e.api.title||"Remote","data-tab-key":(k==null?void 0:k.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:k!=null&&k.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:k.machineName})]}):s.jsx("span",{children:"Live remote view"})})]})]})}const d=t.conversationsByTabKey.get(e.params.tabKey);if(!d)return s.jsx("div",{className:"adhdev-dockview-tab adhdev-dockview-tab-empty","data-tab-key":e.params.tabKey||"",children:s.jsx("div",{className:"adhdev-dockview-tab-copy",children:s.jsx("div",{className:"adhdev-dockview-tab-primary",children:e.api.title||e.params.tabKey})})});const p=((S=e.api.group.activePanel)==null?void 0:S.id)===e.api.id,u=e.api.isGroupActive,m=ja(d,t.liveSessionInboxState,{isOpenConversation:p}),f=m.isReconnecting,g=m.isConnecting,C=m.isGenerating||c,h=m.isWaiting,x=m.unread,y=t.tabShortcuts[d.tabKey];return s.jsxs("div",{className:`adhdev-dockview-tab${p?" is-active":""}${u?" is-group-active":""}${f?" is-reconnecting":""}`,title:xt(d),"data-tab-key":e.params.tabKey,onMouseDown:n,onTouchStart:n,onContextMenu:k=>{var w;k.preventDefault(),n(k),t.openTabContextMenu({x:k.clientX,y:k.clientY,tabKey:d.tabKey,sourceDocument:((w=k.target)==null?void 0:w.ownerDocument)??document})},children:[x&&s.jsx("span",{className:"adhdev-dockview-tab-unread-dot","aria-hidden":"true"}),s.jsx("div",{className:"adhdev-dockview-tab-status","aria-hidden":"true",children:C?s.jsx("div",{className:"tab-spinner"}):h?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-waiting",children:"▲"}):f?s.jsx("span",{className:"adhdev-dockview-tab-status-text is-reconnecting",children:"○"}):g?s.jsx("div",{className:"tab-connecting-spinner"}):d.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(d)}),s.jsx("div",{className:"adhdev-dockview-tab-meta",children:f?s.jsx("span",{className:"adhdev-dockview-tab-reconnecting",children:Gs(d)}):g?s.jsx("span",{className:"adhdev-dockview-tab-connecting",children:Gs(d)}):s.jsx("span",{children:Gs(d)})})]}),y&&s.jsx("span",{className:"text-[9px] opacity-50 font-mono ml-0.5 shrink-0 bg-bg-secondary px-1 rounded",title:y,children:y})]})}function Er(e){return e.isActive}function Qc(e){return e.isVisible}function C1(e){e.preventDefault()}function j1({params:e,api:t}){var g;const n=Ra(),r=l.useRef(null),[a,o]=l.useState(()=>Er(t)),[i,c]=l.useState(()=>Qc(t)),d=n.conversationsByTabKey.get(e.tabKey),p=Da({sendDaemonCommand:n.sendDaemonCommand,activeConv:d,setActionLogs:n.setActionLogs,isStandalone:n.isStandalone});l.useEffect(()=>{o(Er(t)),c(Qc(t));const C=[t.onDidActiveChange(h=>o(h.isActive)),t.onDidActiveGroupChange(h=>{if(!Er(t)&&!h.isActive){o(!1);return}o(Er(t))}),t.onDidVisibilityChange(h=>c(h.isVisible))];return()=>{for(const h of C)h.dispose()}},[t]);const u=l.useMemo(()=>d?n.ides.find(C=>C.id===d.routeId):void 0,[n.ides,d]),m=l.useMemo(()=>d?n.actionLogs.filter(C=>C.routeId===d.tabKey):[],[n.actionLogs,d]);if(!d)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(d)&&In(d)==="terminal";return s.jsx("div",{className:"h-full min-h-0 min-w-0 flex flex-col overflow-hidden",children:s.jsx(rl,{activeConv:d,clearToken:n.clearedTabs[d.tabKey]||0,isCliTerminal:f,ideEntry:u,terminalRef:r,handleModalButton:p.handleModalButton,handleRelaunch:p.handleRelaunch,handleSendChat:p.handleSendChat,handleForceSendChat:p.handleForceSendChat,isSendingChat:p.isSendingChat,handleFocusAgent:p.handleFocusAgent,isFocusingAgent:p.isFocusingAgent,actionLogs:m,userName:n.userName,scrollToBottomRequestNonce:((g=n.scrollToBottomRequest)==null?void 0:g.tabKey)===d.tabKey?n.scrollToBottomRequest.nonce:void 0,isInputActive:a,isVisible:i})})}function N1({visibleConversations:e,clearedTabs:t,ides:n,actionLogs:r,sendDaemonCommand:a,setActionLogs:o,isStandalone:i,hasRegisteredMachines:c,initialDataLoaded:d,userName:p,toggleHiddenTab:u,actionShortcuts:m,registerActionHandlers:f,onActiveTabChange:g,onOpenNewSession:C,onRequestScrollToBottom:h,requestedActiveTabKey:x,requestedRemoteIdeId:y,onRequestedActiveTabConsumed:b,scrollToBottomRequest:S,liveSessionInboxState:k,layoutProfile:w}){var ut,ot,pt;const{theme:v}=Ls(),{sendCommand:N}=vt(),j=l.useRef(null),A=l.useRef(null),I=l.useRef(null),D=l.useRef(!1),L=l.useRef(!1),P=l.useRef(!1),_=l.useRef(null),q=l.useRef([]),[B,E]=l.useState(null),[K,R]=l.useState(0),T=l.useRef(typeof window>"u"?{}:qC(w)),H=l.useMemo(()=>new Map(e.map(Q=>[Q.tabKey,Q])),[e]),M=l.useMemo(()=>{const Q=j.current;return Q?Q.groups.some(ee=>{try{const oe=ee.model.location.type;return oe!=="floating"&&oe!=="popout"?!1:ee.panels.some(ue=>H.has(ue.id))}catch{return!1}}):!1},[H,K,e]),W=l.useCallback(()=>{var Q;(Q=j.current)==null||Q.focus()},[]),J=l.useCallback((Q,ee)=>{h==null||h(Q,ee)},[h]),re=l.useCallback(Q=>{const ee=document,oe=Q.document;for(const Ae of ee.querySelectorAll('link[rel="stylesheet"]')){const Fe=oe.createElement("link");Fe.rel="stylesheet",Fe.href=Ae.href,Ae.crossOrigin&&(Fe.crossOrigin=Ae.crossOrigin),oe.head.appendChild(Fe)}for(const Ae of ee.querySelectorAll("style")){const Fe=oe.createElement("style");Fe.textContent=Ae.textContent,oe.head.appendChild(Fe)}const ue=[];for(const Ae of ee.styleSheets)try{for(const Fe of Ae.cssRules)Fe instanceof CSSStyleRule&&(Fe.selectorText===":root"||Fe.selectorText==="html")&&ue.push(Fe.cssText)}catch{}if(ue.length>0){const Ae=oe.createElement("style");Ae.textContent=ue.join(`
71
+ `),oe.head.appendChild(Ae)}const xe=ee.documentElement.getAttribute("data-theme");xe&&oe.documentElement.setAttribute("data-theme",xe),oe.documentElement.style.colorScheme=xe==="light"?"light":"dark",oe.body.className=ee.body.className;const Ie=ee.documentElement.getAttribute("style");Ie&&oe.documentElement.setAttribute("style",Ie);const Le=oe.getElementById("dv-popout-window");Le instanceof HTMLElement&&(Le.classList.add("adhdev-dockview"),yo(Le,v))},[v]),V=l.useCallback(()=>{var ee;const Q=j.current;if(Q)for(const oe of Q.groups)try{const ue=(ee=oe.element)==null?void 0:ee.ownerDocument;if(!ue||ue===document)continue;const xe=ue.getElementById("dv-popout-window");xe instanceof HTMLElement&&(xe.classList.add("adhdev-dockview"),yo(xe,v));const Ie=document.documentElement.getAttribute("data-theme");Ie&&ue.documentElement.setAttribute("data-theme",Ie),ue.documentElement.style.colorScheme=Ie==="light"?"light":"dark",ue.body.className=document.body.className;const Le=document.documentElement.getAttribute("style");Le?ue.documentElement.setAttribute("style",Le):ue.documentElement.removeAttribute("style")}catch{}},[v]),X=l.useCallback(Q=>{const ee=j.current;if(!ee)return;const oe=ee.getPanel(Q);oe&&ee.addPopoutGroup(oe,{popoutUrl:"/popout.html",onDidOpen:({window:ue})=>{re(ue),ke();const xe=H.get(Q);ue.document.title=xe?`${xt(xe)} — ADHDev`:"ADHDev — Popout"}})},[H,re]),de=l.useCallback(Q=>{const ee=j.current,oe=ee==null?void 0:ee.getPanel(Q);if(!ee||!oe)return;const ue=ee.groups.filter(xe=>{var Ie;try{return((Ie=xe.element)==null?void 0:Ie.ownerDocument)===document}catch{return!0}});ue.length>0?oe.api.moveTo({group:ue[0],position:"center"}):oe.api.moveTo({position:"center"}),oe.api.setActive()},[]),ne=l.useCallback(Q=>{var ue;const ee=j.current;if(!ee)return!1;const oe=ee.getPanel(Q);if(!oe)return!1;try{return((ue=oe.group.element)==null?void 0:ue.ownerDocument)!==document}catch{return!1}},[]),O=l.useCallback(Q=>{ne(Q)&&de(Q),u(Q)},[ne,de,u]),ie=l.useCallback(Q=>{const ee=j.current,oe=ee==null?void 0:ee.getPanel(Q);!ee||!oe||ee.addFloatingGroup(oe,{width:600,height:500})},[]),z=l.useCallback(Q=>{var oe;const ee=(oe=j.current)==null?void 0:oe.getPanel(Q);if(!ee)return!1;try{return ee.group.model.location.type==="floating"}catch{return!1}},[]),ae=l.useCallback(()=>{var ee,oe;const Q=(oe=(ee=j.current)==null?void 0:ee.activePanel)==null?void 0:oe.id;return!Q||rs(Q)?null:H.has(Q)?Q:null},[H]),Ce=l.useCallback(Q=>{const ee=j.current,oe=ee==null?void 0:ee.getPanel(Q);if(!ee||!oe)return;const ue=ee.groups.filter(xe=>{try{return xe.model.location.type==="grid"}catch{return!0}});ue.length>0?oe.api.moveTo({group:ue[0],position:"center"}):oe.api.moveTo({position:"center"}),oe.api.setActive()},[]),ye=l.useCallback(()=>{var Ie;const Q=j.current;if(!Q)return;const oe=Q.groups.filter(Le=>{var Ae;try{return((Ae=Le.element)==null?void 0:Ae.ownerDocument)===document&&Le.model.location.type==="grid"}catch{return!1}})[0]||null,ue=[...Q.panels];for(const Le of ue){const Ae=(Ie=Le.group.element)==null?void 0:Ie.ownerDocument,Fe=Le.group.model.location.type;Ae===document&&Fe==="grid"||(oe&&oe.id!==Le.group.id?Le.api.moveTo({group:oe,position:"center"}):Le.api.moveTo({position:"center"}))}const xe=Q.activePanel;xe&&(xe.group.model.openPanel(xe),xe.api.setActive()),vo(document)},[]),ke=l.useCallback(()=>{var ee,oe;const Q=j.current;if(Q)for(const ue of Q.groups){const xe=(ee=ue.element)==null?void 0:ee.ownerDocument;if(!xe||xe===document)continue;const Ie=xe.getElementById("dv-popout-window");if(!(Ie instanceof HTMLElement))continue;let Le=null,Ae=xe.title||"ADHDev",Fe="Popout workspace";const qe=ue.activePanel;if(qe)if(Le=qe.id,rs(qe.id)){const te=((oe=qe.params)==null?void 0:oe.routeId)||qe.id.slice(7),ge=cs([...H.values()],te);Ae=dp(ge),Fe=ge!=null&&ge.machineName?`Remote view · ${ge.machineName}`:"Remote view"}else{const te=H.get(qe.id);Ae=te?xt(te):qe.title||qe.id,Fe=te?Gs(te):"Dockview panel"}xe.title=`${Ae} — ADHDev`;const Ze=Array.from(xe.querySelectorAll("#adhdev-popout-header"));for(const te of Ze)te.remove();const _e=xe.createElement("div");_e.id="adhdev-popout-header",xe.body.appendChild(_e),_e.setAttribute("style",["position:absolute","top:0","left:0","right:0","height:52px","display:flex","align-items:center","justify-content:space-between","gap:12px","padding:0 14px","box-sizing:border-box","background:var(--surface-secondary)","border-bottom:1px solid var(--border-subtle)","z-index:5","backdrop-filter:blur(14px)"].join(";")),_e.innerHTML=`
72
+ <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;">${Kc(Ae)}</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;">${Kc(Fe)}</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
+ `,Ie.style.top="52px",Ie.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=!Le,et.style.opacity=Le?"1":"0.5",et.style.cursor=Le?"pointer":"default",et.onclick=()=>{var te;Le&&de(Le),(te=xe.defaultView)==null||te.focus()})}},[H,de]),me=l.useCallback(Q=>{var ue;const ee=j.current,oe=ee==null?void 0:ee.getPanel(Q);if(!(!ee||!oe)){oe.group.model.openPanel(oe),oe.api.setActive(),J(Q,"dockview-shortcut");try{const xe=oe.group.model.location;xe.type==="popout"?xe.getWindow().focus():vo((ue=oe.group.element)==null?void 0:ue.ownerDocument)}catch{}}},[J]),G=l.useCallback(Q=>{const ee=j.current,oe=ee==null?void 0:ee.activePanel,ue=(ee==null?void 0:ee.activeGroup)||(oe==null?void 0:oe.group);if(!ee||!oe||!ue)return;const xe=ue.panels||[];if(xe.length<=1)return;const Ie=xe.findIndex(Fe=>Fe.id===oe.id);if(Ie<0)return;const Le=(Ie+Q+xe.length)%xe.length,Ae=xe[Le];Ae&&(Ae.group.model.openPanel(Ae),Ae.api.setActive(),rs(Ae.id)||J(Ae.id,"dockview-shortcut"))},[J]),U=l.useCallback(Q=>{var Ue;const ee=j.current,oe=(ee==null?void 0:ee.activeGroup)||((Ue=ee==null?void 0:ee.activePanel)==null?void 0:Ue.group);if(!ee||!oe)return;const ue=ee.groups||[],xe=ue.find(et=>et.id===oe.id);if(!xe)return;const Ie=xe.element.getBoundingClientRect(),Le=Ie.left+Ie.width/2,Ae=Ie.top+Ie.height/2,Fe=(et,te,ge,we)=>Math.max(0,Math.min(te,we)-Math.max(et,ge)),qe=et=>{const te=et.element.getBoundingClientRect(),ge=te.left+te.width/2,we=te.top+te.height/2;let ze=0,Oe=0,tt=0,Ke=!1;if(Q==="left"?(Ke=ge<Le,ze=Math.max(0,Ie.left-te.right),Oe=Math.abs(we-Ae),tt=Fe(Ie.top,Ie.bottom,te.top,te.bottom)):Q==="right"?(Ke=ge>Le,ze=Math.max(0,te.left-Ie.right),Oe=Math.abs(we-Ae),tt=Fe(Ie.top,Ie.bottom,te.top,te.bottom)):Q==="above"?(Ke=we<Ae,ze=Math.max(0,Ie.top-te.bottom),Oe=Math.abs(ge-Le),tt=Fe(Ie.left,Ie.right,te.left,te.right)):(Ke=we>Ae,ze=Math.max(0,te.top-Ie.bottom),Oe=Math.abs(ge-Le),tt=Fe(Ie.left,Ie.right,te.left,te.right)),!Ke)return Number.POSITIVE_INFINITY;const Ye=tt>0?0:120;return ze*3+Oe+Ye};let Ze=null,_e=Number.POSITIVE_INFINITY;for(const et of ue){if(et.id===xe.id)continue;const te=qe(et);Number.isFinite(te)&&(te>=_e||(_e=te,Ze=et))}return Ze||void 0},[]),Z=l.useCallback(Q=>{var ue;const ee=U(Q);if(!ee)return;const oe=ee.activePanel||ee.panels[0];oe&&(ee.model.openPanel(oe),oe.api.setActive(),rs(oe.id)||J(oe.id,"dockview-focus"),vo((ue=ee.element)==null?void 0:ue.ownerDocument))},[U,J]),Y=l.useCallback((Q,ee)=>{const oe=j.current,ue=oe==null?void 0:oe.activePanel,xe=(oe==null?void 0:oe.activeGroup)||(ue==null?void 0:ue.group);if(!oe||!ue||!xe)return;let Ie=U(Q);!Ie&&(ee!=null&&ee.createGroupIfMissing)&&(Ie=oe.addGroup({referenceGroup:xe,direction:Q})),Ie&&(ue.api.moveTo({group:Ie,position:"center"}),ue.group.model.openPanel(ue),ue.api.setActive(),rs(ue.id)||J(ue.id,ee!=null&&ee.createGroupIfMissing?"dockview-split":"dockview-move"))},[U,J]),{isMac:fe,tabShortcuts:Te,shortcutListening:ce,setShortcutListening:$,saveShortcuts:pe}=am({sortedTabKeys:e.map(Q=>Q.tabKey),onFocus:W,onSelectTab:me}),le=l.useCallback(()=>{var oe;const Q=j.current;if(!Q)return;const ee=Q.activePanel;if(ee){if(rs(ee.id)){const ue=((oe=ee.params)==null?void 0:oe.routeId)||ee.id.slice(7),xe=cs(e,ue);xe!=null&&xe.tabKey&&$(xe.tabKey);return}H.has(ee.id)&&$(ee.id)}},[H,me,$,e]),F=l.useCallback(Q=>{const ee=[];return Q.metaKey&&ee.push(fe?"⌘":"Meta"),Q.ctrlKey&&ee.push("Ctrl"),Q.altKey&&ee.push(fe?"⌥":"Alt"),Q.shiftKey&&Q.key.length!==1&&ee.push(fe?"⇧":"Shift"),["Control","Alt","Shift","Meta"].includes(Q.key)?null:(ee.push(lm(Q.key)),ee.join("+"))},[fe]),be=l.useCallback(Q=>{var ee,oe;switch(Q){case"splitActiveTabRight":Y("right",{createGroupIfMissing:!0});return;case"splitActiveTabDown":Y("below",{createGroupIfMissing:!0});return;case"floatActiveTab":{const ue=ae();ue&&ie(ue);return}case"popoutActiveTab":{const ue=ae();ue&&X(ue);return}case"dockActiveTab":{const ue=ae();if(!ue)return;ne(ue)?de(ue):z(ue)&&Ce(ue);return}case"focusLeftPane":Z("left");return;case"focusRightPane":Z("right");return;case"focusUpPane":Z("above");return;case"focusDownPane":Z("below");return;case"moveActiveTabToLeftPane":Y("left");return;case"moveActiveTabToRightPane":Y("right");return;case"moveActiveTabToUpPane":Y("above");return;case"moveActiveTabToDownPane":Y("below");return;case"selectPreviousGroupTab":G(-1);return;case"selectNextGroupTab":G(1);return;case"setActiveTabShortcut":le();return;case"hideCurrentTab":{const ue=(oe=(ee=j.current)==null?void 0:ee.activePanel)==null?void 0:oe.id;ue&&!rs(ue)&&O(ue);return}default:return}},[G,Ce,Z,ie,ae,O,z,ne,de,Y,X,le]);l.useEffect(()=>{if(!B)return;const Q=B.sourceDocument,ee=Q.defaultView??window,oe=ue=>{const xe=Q.querySelector("[data-dockview-tab-context-menu]");xe&&xe.contains(ue.target)||E(null)};return ee.addEventListener("mousedown",oe,!0),ee!==window&&window.addEventListener("mousedown",()=>E(null),!0),()=>{ee.removeEventListener("mousedown",oe,!0),ee!==window&&window.removeEventListener("mousedown",()=>E(null),!0)}},[B]);const je=l.useMemo(()=>({actionLogs:r,clearedTabs:t,conversationsByTabKey:H,hasDetachedConversationPanels:M,ides:n,isStandalone:i,hasRegisteredMachines:c,onOpenNewSession:C,liveSessionInboxState:k,sendDaemonCommand:a,setActionLogs:o,toggleHiddenTab:O,userName:p,scrollToBottomRequest:S,tabShortcuts:Te,openTabContextMenu:({x:Q,y:ee,tabKey:oe,sourceDocument:ue})=>E({x:Q,y:ee,tabKey:oe,sourceDocument:ue??document}),popoutTab:X,moveTabBackToMain:de,isTabInPopout:ne,floatTab:ie,isTabFloating:z}),[r,t,H,M,n,i,c,C,k,a,o,O,p,S,Te,X,de,ne,ie,z]),Se=B?m1({isTabInPopout:ne(B.tabKey),isTabFloating:z(B.tabKey),tabShortcut:Te[B.tabKey],actionShortcuts:m}):[],He=l.useCallback(Q=>{var ue;const ee=j.current;if((((ue=ee==null?void 0:ee.activePanel)==null?void 0:ue.id)??null)===Q.id){Q.group.model.openPanel(Q);return}Q.group.model.openPanel(Q),Q.api.setActive()},[]),Xe=l.useCallback((Q,ee="requested-tab")=>{if(!Q)return!1;const oe=j.current;if(!oe)return!1;const ue=oe.getPanel(Q);return ue?(He(ue),J(Q,ee),b==null||b(),!0):!1},[He,b,J]),dt=l.useCallback(()=>{if(P.current)return!1;const Q=Xe(_.current,"stored-layout-restore");return Q&&(P.current=!0),Q},[Xe]),it=l.useCallback(()=>{var ee;const Q=j.current;Q&&GC(w,{activeTabId:((ee=Q.activePanel)==null?void 0:ee.id)??null,layout:Q.toJSON()})},[w]),he=l.useCallback(()=>{zC(w,T.current)},[w]),$e=l.useCallback(Q=>{var ue,xe,Ie,Le;const ee=j.current;if(!ee)return{kind:"grid"};const oe=ee.toJSON();for(const Ae of oe.floatingGroups||[])if((xe=(ue=Ae.data)==null?void 0:ue.views)!=null&&xe.includes(Q)&&Ae.position)return{kind:"floating",position:Ae.position};for(const Ae of oe.popoutGroups||[])if((Le=(Ie=Ae.data)==null?void 0:Ie.views)!=null&&Le.includes(Q))return{kind:"popout",position:Ae.position,popoutUrl:Ae.url};return{kind:"grid"}},[]),Be=l.useCallback(Q=>{const ee=j.current;if(!ee)return;const oe=ee.getPanel(Q),ue=T.current[Q];if(!oe||!ue||ue.kind==="grid")return;if(oe.group.model.location.type===ue.kind){delete T.current[Q],he();return}if(ue.kind==="floating"){ee.addFloatingGroup(oe,{x:ue.position.left??24,y:ue.position.top??24,width:ue.position.width,height:ue.position.height}),delete T.current[Q],he();return}delete T.current[Q],he()},[he]);l.useEffect(()=>(f==null||f({setShortcutForActiveTab:le,restoreHiddenTabToSavedLocation:Be,activateConversationTab:me,resetAllPanelsToMain:ye,activatePreviousTabInGroup:()=>G(-1),activateNextTabInGroup:()=>G(1),floatActiveTab:()=>{const Q=ae();Q&&ie(Q)},popoutActiveTab:()=>{const Q=ae();Q&&X(Q)},dockActiveTab:()=>{const Q=ae();Q&&(ne(Q)?de(Q):z(Q)&&Ce(Q))},splitActiveTabRight:()=>Y("right",{createGroupIfMissing:!0}),splitActiveTabDown:()=>Y("below",{createGroupIfMissing:!0}),focusLeftPane:()=>Z("left"),focusRightPane:()=>Z("right"),focusUpPane:()=>Z("above"),focusDownPane:()=>Z("below"),moveActiveTabToLeftPane:()=>Y("left"),moveActiveTabToRightPane:()=>Y("right"),moveActiveTabToUpPane:()=>Y("above"),moveActiveTabToDownPane:()=>Y("below")}),()=>f==null?void 0:f(null)),[G,Ce,ie,Z,ae,z,ne,Y,de,X,f,ye,Be,me,le]),l.useEffect(()=>()=>{var Q;(Q=I.current)==null||Q.call(I),I.current=null},[]);const Me=l.useCallback(Q=>{var oe,ue;j.current=Q.api,(oe=I.current)==null||oe.call(I),I.current=null;const ee=UC(w);if(_.current=(ee==null?void 0:ee.activeTabId)??null,ee!=null&&ee.layout&&Q.api.fromJSON(ee.layout,{reuseExistingPanels:!1}),L.current=Gc({hasStoredLayout:!!(ee!=null&&ee.layout),initialDataLoaded:d,visibleConversationCount:e.length,ides:n}),L.current||(Yc(Q.api,e),Jc(Q.api,e,y)),Q.api.totalPanels===0&&e.length>0){const xe=v1(Q.api,e,x);if(xe){const Ie=Q.api.getPanel(xe);Ie&&He(Ie)}}else!L.current&&!Xe(x)&&dt();if(D.current=!0,Q.api.onDidActivePanelChange(xe=>{var Le;if(_.current=(xe==null?void 0:xe.id)??null,P.current=!0,ke(),xe&&rs(xe.id)){const Ae=((Le=xe.params)==null?void 0:Le.routeId)||xe.id.slice(7),Fe=cs(e,Ae);g((Fe==null?void 0:Fe.tabKey)??null),it();return}if(g((xe==null?void 0:xe.id)??null),it(),!xe)return;const Ie=H.get(xe.id);(Ie==null?void 0:Ie.streamSource)==="agent-stream"&&Ie.agentType&&N(Ie.routeId,Ou(),{agentType:Ie.agentType,...Ie.sessionId&&{targetSessionId:Ie.sessionId}}).catch(()=>{})}),Q.api.onDidLayoutChange(()=>{it(),ke(),R(xe=>xe+1)}),g1()){const xe=_e=>({clientX:_e.clientX,clientY:_e.clientY}),Ie=_e=>{const Ue=_e==null?void 0:_e.getBoundingClientRect();return Ue?{left:Ue.left,right:Ue.right,top:Ue.top,bottom:Ue.bottom}:null},Le=_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},Ae=b1({detachDelayMs:dm,onDetach:({panelId:_e,clientX:Ue,clientY:et})=>{var tt,Ke;const te=Q.api.getPanel(_e);if(!te)return;try{if(te.group.model.location.type!=="grid")return}catch{return}const ge=(tt=A.current)==null?void 0:tt.getBoundingClientRect(),we=(Ke=te.group.element)==null?void 0:Ke.getBoundingClientRect(),ze=Math.round(Math.min(Math.max((we==null?void 0:we.width)??600,360),720)),Oe=Math.round(Math.min(Math.max((we==null?void 0:we.height)??500,260),640));Q.api.addFloatingGroup(te,{x:ge?Math.max(0,Ue-ge.left-32):void 0,y:ge?Math.max(0,et-ge.top-18):void 0,width:ze,height:Oe}),te.api.setActive(),it(),ke(),R(Ye=>Ye+1)}}),Fe=[Q.api.onWillDragPanel(_e=>{if(!(_e.nativeEvent.defaultPrevented||_e.nativeEvent.shiftKey)){try{if(_e.panel.group.model.location.type!=="grid")return}catch{return}Ae.startDrag({panelId:_e.panel.id,selfPanelBounds:Ie(_e.panel.group.element),...xe(_e.nativeEvent)})}}),Q.api.onWillShowOverlay(_e=>{if(Ae.hasDetached()){_e.preventDefault();return}Ae.markDockTarget(xe(_e.nativeEvent))}),Q.api.onWillDrop(_e=>{if(Ae.hasDetached()){_e.preventDefault(),Ae.endDrag();return}Ae.markDockTarget(xe(_e.nativeEvent))}),Q.api.onDidDrop(()=>Ae.endDrag()),Q.api.onUnhandledDragOverEvent(_e=>{Ae.isDragging()&&Ae.markSelfPanel(xe(_e.nativeEvent))})],qe=_e=>{if(!Ae.isDragging())return;const Ue=xe(_e);Le(Ue)&&Ae.markNonSelfPanel(Ue)},Ze=()=>Ae.endDrag();window.addEventListener("dragover",qe,!0),window.addEventListener("drop",Ze,!0),window.addEventListener("dragend",Ze,!0),I.current=()=>{Ae.dispose();for(const _e of Fe)_e.dispose();window.removeEventListener("dragover",qe,!0),window.removeEventListener("drop",Ze,!0),window.removeEventListener("dragend",Ze,!0)}}Q.api.onDidAddGroup(xe=>{requestAnimationFrame(()=>{var Ie,Le;try{const Ae=(Ie=xe.element)==null?void 0:Ie.ownerDocument;if(!Ae||Ae===document)return;(Le=Ae.getElementById("dv-popout-window"))==null||Le.classList.add("adhdev-dockview");const Fe=document.documentElement.getAttribute("data-theme");Fe&&Ae.documentElement.setAttribute("data-theme",Fe),Ae.body.className=document.body.className;const qe=document.documentElement.getAttribute("style");qe&&Ae.documentElement.setAttribute("style",qe)}catch{}ke(),R(Ae=>Ae+1)})}),g(((ue=Q.api.activePanel)==null?void 0:ue.id)??null)},[He,Xe,H,n,d,w,g,it,x,y,N,ke,e]);l.useLayoutEffect(()=>{const Q=j.current;if(!Q||!D.current||L.current&&Gc({hasStoredLayout:!0,initialDataLoaded:d,visibleConversationCount:e.length,ides:n}))return;L.current&&(L.current=!1);const ee=q.current,oe=new Set(ee),ue=e.map(Ze=>Ze.tabKey),xe=new Set(ue),Ie=h1({previousVisibleConversationCount:ee.length,visibleConversationCount:e.length,ides:n});let Le=!1;for(const Ze of ee)xe.has(Ze)||Ie||(T.current[Ze]=$e(Ze),Le=!0);Le&&he(),Ie||(Yc(Q,e),Jc(Q,e,y));const Ae=ue.filter(Ze=>!oe.has(Ze));let Fe=!1;for(const Ze of Ae){const _e=Q.getPanel(Ze),Ue=T.current[Ze];if(!_e||!Ue||Ue.kind==="grid")continue;if(_e.group.model.location.type===Ue.kind){delete T.current[Ze],Fe=!0;continue}if(Ue.kind==="floating"){Q.addFloatingGroup(_e,{x:Ue.position.left??24,y:Ue.position.top??24,width:Ue.position.width,height:Ue.position.height}),delete T.current[Ze],Fe=!0;continue}}if(Fe&&he(),q.current=ue,x&&Xe(x))return;!Q.activePanel&&Q.panels[0]&&He(Q.panels[0]),!!(Q.activePanel&&Q.getPanel(Q.activePanel.id))||dt()},[He,Xe,dt,n,d,he,$e,x,y,e]),l.useEffect(()=>{D.current&&Xe(x)},[Xe,x]),l.useEffect(()=>{const Q=oe=>{const ue=oe.target;if(!ue)return;const xe=ue.querySelector("[data-tab-key]")||ue.closest("[data-tab-key]");if(xe){const Ie=xe.getAttribute("data-tab-key");if(Ie&&oe.dataTransfer){const Le=ue.closest(".dv-tab")||xe.closest(".dv-tab")||xe;oe.dataTransfer.effectAllowed="move",oe.dataTransfer.setData("text/tab-key",Ie),Le instanceof HTMLElement&&oe.dataTransfer.setDragImage(Le,Math.max(12,Math.round(Le.clientWidth/2)),Math.max(10,Math.round(Le.clientHeight/2)))}}};window.addEventListener("dragstart",Q);const ee=Vc(j.current);for(const oe of ee)oe.addEventListener("dragstart",Q);return()=>{window.removeEventListener("dragstart",Q);for(const oe of ee)oe.removeEventListener("dragstart",Q)}},[K]),l.useEffect(()=>{var ee;const Q=(ee=A.current)==null?void 0:ee.querySelector(".adhdev-dockview");Q instanceof HTMLElement&&yo(Q,v),V(),ke()},[ke,V,v]),l.useEffect(()=>{ke()},[ke]),l.useEffect(()=>{const Q=ee=>{if(ee.defaultPrevented||ce)return;const oe=F(ee);if(!oe)return;const ue=ee.metaKey||ee.ctrlKey||ee.altKey;fi(ee.target)&&!ue||xa(fe).setActiveTabShortcut!==oe||(ee.preventDefault(),ee.stopPropagation(),le())};return window.addEventListener("keydown",Q,!0),()=>window.removeEventListener("keydown",Q,!0)},[F,fe,ce,le]),l.useEffect(()=>{const Q=A.current;if(!Q)return;const ee=oe=>{var Ae,Fe;if(!oe.isTrusted)return;const ue=(Fe=(Ae=oe.target)==null?void 0:Ae.closest)==null?void 0:Fe.call(Ae,".dv-scrollable");if(!ue)return;oe.preventDefault(),oe.stopPropagation();const xe=Math.abs(oe.deltaX),Ie=Math.abs(oe.deltaY),Le=xe>Ie?oe.deltaX:oe.deltaY;ue.dispatchEvent(new WheelEvent("wheel",{deltaY:Le,deltaMode:oe.deltaMode,bubbles:!1,cancelable:!0}))};return Q.addEventListener("wheel",ee,{passive:!1,capture:!0}),()=>Q.removeEventListener("wheel",ee,{capture:!0})},[]),l.useEffect(()=>{const Q=Vc(j.current);if(Q.length===0)return;const ee=Q.map(oe=>{let ue=[],xe=null;const Ie=()=>{xe!=null&&oe.clearTimeout(xe),xe=null,ue=[]},Le=()=>{xe!=null&&oe.clearTimeout(xe),xe=oe.setTimeout(()=>{xe=null,ue=[]},1200)},Ae=qe=>{if(!qe.ctrlKey&&!qe.metaKey&&!qe.altKey)return;const Ze=F(qe);if(!Ze)return;const _e=rm();for(const[Ue,et]of Object.entries(_e))if(e.some(te=>te.tabKey===Ue)&&et===Ze){qe.preventDefault(),me(Ue);return}},Fe=qe=>{if(qe.defaultPrevented||ce)return;const Ze=F(qe);if(!Ze)return;const _e=qe.metaKey||qe.ctrlKey||qe.altKey;if(fi(qe.target))return;const Ue=xa(fe),et=Object.entries(Ue).filter(([Ye,It])=>!!It&&(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")),te=_e?[Ze]:[...ue.slice(-1),Ze].slice(-2),ge=te.join(" "),we=te[te.length-1],ze=et.find(([,Ye])=>Ye===ge);if(ze){qe.preventDefault(),Ie(),be(ze[0]);return}if(et.some(([,Ye])=>Ye.startsWith(`${ge} `))){qe.preventDefault(),ue=te,Le();return}const tt=et.find(([,Ye])=>Ye===we);if(tt){qe.preventDefault(),Ie(),be(tt[0]);return}if(et.some(([,Ye])=>Ye.startsWith(`${we} `))){qe.preventDefault(),ue=[we],Le();return}Ie()};return oe.addEventListener("keydown",Ae),oe.addEventListener("keydown",Fe),()=>{Ie(),oe.removeEventListener("keydown",Ae),oe.removeEventListener("keydown",Fe)}});return()=>{for(const oe of ee)oe()}},[F,fe,K,me,ce,be,e]);const ve=v==="light"?Fo:Oo,We=((pt=(ot=(ut=j.current)==null?void 0:ut.activePanel)==null?void 0:ot.group.element)==null?void 0:pt.ownerDocument)??document;return s.jsxs(pm.Provider,{value:je,children:[s.jsx("div",{ref:A,className:"flex-1 min-h-0 min-w-0 overflow-hidden",children:s.jsx(Nh,{className:"h-full min-h-0 min-w-0 adhdev-dockview",components:{conversation:j1,remote:w1},defaultTabComponent:S1,watermarkComponent:k1,onReady:Me,singleTabMode:"default",tabAnimation:"smooth",theme:ve,popoutUrl:"/popout.html"})}),B&&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:B.x,top:B.y},children:Se.map(Q=>{if(Q.type==="separator")return s.jsx("div",{className:"border-t border-border-subtle my-1"},Q.id);let ee=s.jsx(Jf,{size:13,className:"shrink-0 opacity-70"}),oe=()=>{};switch(Q.id){case"dockInWindow":case"dockBackToGrid":ee=s.jsx(Xf,{size:13,className:"shrink-0 opacity-70"}),oe=()=>{Ce(B.tabKey),E(null)};break;case"moveBackToMain":ee=s.jsx(Yf,{size:13,className:"shrink-0 opacity-70"}),oe=()=>{de(B.tabKey),E(null)};break;case"floatAsPanel":ee=s.jsx(Qf,{size:13,className:"shrink-0 opacity-70"}),oe=()=>{ie(B.tabKey),E(null)};break;case"openInNewWindow":ee=s.jsx(Vf,{size:13,className:"shrink-0 opacity-70"}),oe=()=>{X(B.tabKey),E(null)};break;case"setShortcut":oe=ue=>{ue.stopPropagation(),$(B.tabKey),E(null)};break;case"removeShortcut":ee=s.jsx(At,{size:13,className:"shrink-0 opacity-70"}),oe=()=>{const ue={...Te};delete ue[B.tabKey],pe(ue),E(null)};break;case"hideTab":ee=s.jsx(Ti,{size:13,className:"shrink-0 opacity-70"}),oe=()=>{O(B.tabKey),E(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 ${Q.tone==="muted"?"text-text-muted":""}`,onMouseDown:C1,onClick:oe,children:[ee,s.jsx("span",{className:"flex-1 min-w-0",children:Q.label}),Q.shortcut?s.jsx("span",{className:"dashboard-dockview-menu-shortcut",children:Q.shortcut}):null]},Q.id)})}),B.sourceDocument.body),ce&&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:()=>$(null),children:s.jsxs("div",{className:"bg-bg-primary border border-border-subtle rounded-xl px-8 py-6 text-center shadow-xl",onClick:Q=>Q.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. ",fe?"⌘+1":"Ctrl+1",", ",fe?"⌥+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"})]})}),We.body)]})}const mm="adhdev-recent-launch-args-v1",A1=8;function I1(e){return String(e||"").trim().replace(/\s+/g," ")}function hm(e,t){return`${e.trim()}::${t.trim()}`}function fm(){if(typeof window>"u")return{byKey:{}};try{const e=JSON.parse(window.localStorage.getItem(mm)||"{}");return{byKey:typeof e.byKey=="object"&&e.byKey?e.byKey:{}}}catch{return{byKey:{}}}}function T1(e){if(!(typeof window>"u"))try{window.localStorage.setItem(mm,JSON.stringify(e))}catch{}}function M1(e,t){var o;const n=String(e||"").trim(),r=String(t||"").trim();return!n||!r?[]:((o=fm().byKey[hm(n,r)])==null?void 0:o.items)||[]}function D1(e,t,n){var u;const r=String(e||"").trim(),a=String(t||"").trim(),o=I1(n);if(!r||!a||!o)return;const i=fm(),c=hm(r,a),d=((u=i.byKey[c])==null?void 0:u.items)||[],p=[o,...d.filter(m=>m!==o)].slice(0,A1);i.byKey[c]={items:p},T1(i)}function P1(e){return!e.hasLoadedInitialResults&&!e.isLoading}function Vn({title:e,description:t,action:n,children:r,className:a="",contentClassName:o=""}){return s.jsxs("div",{className:`rounded-xl border border-border-subtle bg-bg-primary px-4 py-3 ${a}`.trim(),children:[s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-[0.08em] text-text-muted",children:e}),t&&s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:t})]}),n?s.jsx("div",{className:"flex items-center gap-2",children:n}):null]}),r?s.jsx("div",{className:t||n?`mt-3 ${o}`.trim():o,children:r}):null]})}function L1({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 R1({busy:e,savedSessionsLoading:t,savedSessionsError:n,savedSessionsLoaded:r,savedSessionsCount:a=0,selectedSession:o,onRefresh:i,onOpenHistory:c,onClearSelection:d}){const{t:p}=Ne("common"),u=o?Xp(o):null,m=L1({savedSessionsLoading:t,savedSessionsLoaded:r,savedSessionsCount:a});return s.jsxs(Vn,{title:"Saved history",description:Ki(p),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:eS(p)})]}),children:[u?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:u.title}),s.jsx("div",{className:"font-mono break-all mt-0.5",children:u.providerSessionId}),s.jsx("div",{className:"mt-1",children:u.metaLine}),u.updatedLabel&&s.jsx("div",{className:"mt-1 text-text-secondary",children:u.updatedLabel}),u.preview&&s.jsx("div",{className:"mt-2 line-clamp-2 text-text-secondary",children:u.preview})]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:d,disabled:e,children:"Clear"})]})}):s.jsx("div",{className:"text-[11px] text-text-muted","aria-live":"polite",children:m}),n&&s.jsx("div",{className:"mt-2 text-[11px] text-status-error",children:n})]})}function bm({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 wo={cli:"CLI",ide:"IDE",acp:"ACP"};function E1({workspaceMode:e,activeKind:t,cliEnabled:n,ideEnabled:r,acpEnabled:a,busy:o,onSelect:i}){const{t:c}=Ne();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:wo.cli,enabled:n},{id:"ide",label:wo.ide,enabled:r},{id:"acp",label:wo.acp,enabled:a}].map(d=>s.jsx("button",{type:"button",className:`btn btn-sm ${t===d.id?"btn-primary":"btn-secondary"}`,onClick:()=>i(d.id),disabled:!d.enabled||o,children:d.label},d.id))})]})}function ko(e){var r;if(!e)return null;const t=e.availableProviders||[];return t.some(a=>Sn(a,"cli"))?"cli":(((r=e.detectedIdes)==null?void 0:r.length)||0)>0?"ide":t.some(a=>Sn(a,"acp"))?"acp":null}function _r(e){return String(e||"").trim().replace(/\\/g,"/").replace(/\/+$/,"").toLowerCase()}function _1({machines:e,ides:t,onClose:n,onBrowseDirectory:r,onSaveWorkspace:a,onLaunchIde:o,onLaunchProvider:i,onListMeshes:c,onLaunchMeshCoordinator:d,onListSavedSessions:p}){var jt,Wt;const{t:u}=Ne(),m=Tn(),f=l.useMemo(()=>[...e].sort(_i),[e]),[g,C]=l.useState(((jt=f[0])==null?void 0:jt.id)||""),h=l.useMemo(()=>f.find(se=>se.id===g)||f[0],[g,f]),x=l.useMemo(()=>((h==null?void 0:h.workspaces)||[]).map(se=>({id:se.id,path:se.path,label:se.label})),[h]),y=(h==null?void 0:h.defaultWorkspaceId)||null,[b,S]=l.useState("workspace"),[k,w]=l.useState(""),[v,N]=l.useState(""),[j,A]=l.useState([]),[I,D]=l.useState(""),[L,P]=l.useState(!1),[_,q]=l.useState(null),[B,E]=l.useState(""),[K,R]=l.useState(ko(f[0])),[T,H]=l.useState(""),[M,W]=l.useState(""),[J,re]=l.useState(""),[V,X]=l.useState(""),[de,ne]=l.useState(!1),[O,ie]=l.useState([]),[z,ae]=l.useState(""),[Ce,ye]=l.useState([]),[ke,me]=l.useState(!1),[G,U]=l.useState(!1),[Z,Y]=l.useState(""),[fe,Te]=l.useState(!1),[ce,$]=l.useState(()=>Bt()),[pe,le]=l.useState(null),[F,be]=l.useState(!1),[je,Se]=l.useState(""),[He,Xe]=l.useState("error"),[dt,it]=l.useState(null),[he,$e]=l.useState(!1),[Be,Me]=l.useState(""),[ve,We]=l.useState([]),[ut,ot]=l.useState(!1),[pt,Q]=l.useState(""),[ee,oe]=l.useState(!1),ue=l.useRef(null),xe=l.useRef(0);l.useEffect(()=>{var se;!g&&((se=f[0])!=null&&se.id)&&C(f[0].id)},[g,f]),l.useEffect(()=>{!h||!(!h.workspaces||!h.availableProviders||!h.detectedIdes||!h.recentLaunches)||m(h.id,{minFreshMs:3e4}).catch(()=>{})},[m,h]);const Ie=l.useCallback(se=>{se&&m(se,{minFreshMs:3e4}).catch(()=>{})},[m]),Le=l.useMemo(()=>((h==null?void 0:h.availableProviders)||[]).filter(se=>Sn(se,"cli")),[h]),Ae=l.useMemo(()=>((h==null?void 0:h.availableProviders)||[]).filter(se=>Sn(se,"acp")),[h]),Fe=l.useMemo(()=>((h==null?void 0:h.detectedIdes)||[]).map(se=>({id:se.type,label:se.name||se.type,meta:se.running?u("newSession.detectedLocally"):u("newSession.availableToOpen")})),[h,u]),qe=l.useMemo(()=>K==="cli"?Le.map(se=>({id:se.type,label:se.displayName||se.type,meta:""})):K==="acp"?Ae.map(se=>({id:se.type,label:se.displayName||se.type,meta:""})):Fe,[Ae,K,Le,Fe]),Ze=l.useMemo(()=>j.find(se=>se.id===I)||null,[j,I]),_e=l.useMemo(()=>Le.find(se=>se.type===T)||null,[Le,T]),Ue=l.useMemo(()=>[...Le,...Ae].find(se=>se.type===T),[Le,Ae,T]),et=l.useMemo(()=>pS(Ue?[Ue]:[],Ue==null?void 0:Ue.type),[Ue]),te=l.useMemo(()=>{const se=mS(Ue?[Ue]:[],Ue==null?void 0:Ue.type);return se.length?se:["low","medium","high"]},[Ue]),ge=l.useMemo(()=>zp(_e==null?void 0:_e.meshCoordinator,{meshId:(Ze==null?void 0:Ze.id)||"",workspace:(Ze==null?void 0:Ze.workspace)||""}),[_e,Ze]),we=dt||ge,ze=l.useCallback(async se=>{P(!0),E("");try{const Ge=await c(se);A(Ge),D(Ee=>{var yt;return Ge.some(Jt=>Jt.id===Ee)?Ee:((yt=Ge[0])==null?void 0:yt.id)||""}),q(se)}catch(Ge){A([]),D(""),q(se),E(Ge instanceof Error?Ge.message:u("newSession.errorLoadMeshes"))}finally{P(!1)}},[c,u]);l.useEffect(()=>{var Ge;if(!h)return;if(ue.current!==h.id){ue.current=h.id,S("workspace"),w(y||((Ge=x[0])==null?void 0:Ge.id)||"__home__"),N(""),A([]),D(""),q(null),E(""),R(ko(h)),H(""),W(""),re(""),X(""),ne(!1),ae(""),ye([]),U(!1),Y(""),$(Bt()),Se(""),it(null);return}w(Ee=>{var yt;return Ee==="__custom__"||Ee==="__home__"||x.some(Jt=>Jt.id===Ee)?Ee:y||((yt=x[0])==null?void 0:yt.id)||"__home__"}),R(Ee=>Ee==="ide"&&Fe.length>0||Ee==="cli"&&Le.length>0||Ee==="acp"&&Ae.length>0?Ee:ko(h))},[Ae.length,Le.length,y,Fe.length,h,x]),l.useEffect(()=>{!h||b!=="mesh"||_===h.id||L||ze(h.id)},[ze,_,L,h,b]),l.useEffect(()=>{b==="mesh"&&K!=="cli"&&Le.length>0&&R("cli")},[K,Le.length,b]),l.useEffect(()=>{var se;K&&(qe.some(Ge=>Ge.id===T)||H(((se=qe[0])==null?void 0:se.id)||""))},[K,qe,T]),l.useEffect(()=>{it(null)},[h==null?void 0:h.id,I,T,b]),l.useEffect(()=>{re(""),X(""),ne(!1)},[T]);const Oe=l.useCallback(async(se,Ge)=>{const Ee=xe.current+1;return xe.current=Ee,me(!0),Y(""),p(se,Ge).then(yt=>{xe.current===Ee&&ye(yt)}).catch(yt=>{xe.current===Ee&&(ye([]),Y(yt instanceof Error?yt.message:u("newSession.errorLoadSavedSessions")))}).finally(()=>{xe.current===Ee&&(me(!1),U(!0))})},[p,u]),tt=l.useCallback((se,Ge)=>{ie(M1(se,Ge))},[]);l.useEffect(()=>{xe.current+=1,ae(""),$(Bt()),!h||!T||K==="ide"?ie([]):tt(h.id,T),U(!1),ye([]),Y(""),me(!1)},[K,tt,Oe,h,T]),l.useEffect(()=>{if(!z)return;const se=Ce.find(Ge=>Ge.providerSessionId===z);se!=null&&se.canResume||ae("")},[Ce,z]);const Ke=k==="__custom__"?v.trim():k==="__home__"?"":((Wt=x.find(se=>se.id===k))==null?void 0:Wt.path)||"",Ye=l.useMemo(()=>h?t.filter(se=>se.id!==h.id&&se.daemonId===h.id).map(se=>se.workspace):[],[t,h]),It=l.useMemo(()=>((h==null?void 0:h.recentLaunches)||[]).map(se=>se.workspace),[h]),Ot=l.useCallback(se=>{const Ge=String(se.workspace||"").trim();if(!Ge)return;const Ee=x.find(yt=>_r(yt.path)===_r(Ge));if(Ee){w(Ee.id),N("");return}w("__custom__"),N(Ge)},[x]),ss=l.useCallback(se=>{const Ge=String(se.workspace||"").trim();if(!Ge)return{workspaceId:null,workspacePath:null};const Ee=x.find(yt=>_r(yt.path)===_r(Ge));return Ee?{workspaceId:Ee.id,workspacePath:null}:{workspaceId:null,workspacePath:Ge}},[x]),De=l.useMemo(()=>Ce.find(se=>se.providerSessionId===z)||null,[Ce,z]),Qe=l.useMemo(()=>{var Ge;if(K!=="cli"||!h||!T)return null;const se=((Ge=Le.find(Ee=>Ee.type===T))==null?void 0:Ge.displayName)||T;return{routeId:h.id,daemonId:h.id,providerSessionId:z||void 0,transport:"pty",mode:"chat",agentName:se,agentType:T,status:"idle",title:se,messages:[],ideType:T,workspaceName:Ke,workspacePath:Ke,displayPrimary:se,displaySecondary:"CLI",streamSource:"native",tabKey:`dashboard:new-session:resume-history:${h.id}:${T}`,machineName:ts(h,{fallbackId:h.id})}},[K,Le,Ke,h,z,T]),Dt=l.useCallback(()=>{var Ge;if(!h)return;w("__custom__"),$e(!0),Q("");const se=sl(h.platform,tl(v.trim(),Ke,Ye,It,h.defaultWorkspacePath,(Ge=x.find(Ee=>Ee.id===y))==null?void 0:Ge.path,x.map(Ee=>Ee.path)));ot(!0),r(h.id,se).then(Ee=>{Me(Ee.path),N(Ee.path),We(Ee.directories)}).catch(Ee=>{Q(Ee instanceof Error?Ee.message:u("newSession.errorLoadFolder"))}).finally(()=>ot(!1))},[v,y,It,Ye,r,Ke,h,x]),Tt=l.useCallback(se=>{h&&(ot(!0),Q(""),r(h.id,se).then(Ge=>{Me(Ge.path),N(Ge.path),We(Ge.directories)}).catch(Ge=>{Q(Ge instanceof Error?Ge.message:u("newSession.errorLoadFolder"))}).finally(()=>ot(!1)))},[r,h]),Kt=l.useCallback(async()=>{if(!h||!Ke)return;oe(!0),Se("");const se=await a(h.id,Ke);if(oe(!1),!se.ok){Xe("error"),Se(se.error||u("newSession.errorSaveWorkspace"));return}Xe("info"),Se(u("newSession.workspaceSaved"))},[a,Ke,h,u]),Vt=l.useCallback(async()=>{if(!h)return;if(b==="mesh"){if(!I||!T)return;be(!0),Se(""),it(null);const Ee=await d(h.id,I,T,{initialModel:J.trim()?J.trim():null,initialThinkingLevel:V.trim()?V.trim():null});if(be(!1),!Ee.ok){if(Ee.code==="mesh_coordinator_manual_mcp_setup_required"&&Ee.manualSetup){it(Ee.manualSetup),Xe("info"),Se(u("newSession.errorManualMcpSetup"));return}Xe("error"),Se(Ee.error||u("newSession.errorStartMeshCoordinator"));return}n();return}if(!K||!T)return;be(!0),Se("");const se=M.trim()?M.trim().split(/\s+/).filter(Boolean):[],Ge=K==="ide"?await o(h.id,T,{workspacePath:Ke||null}):await i(h.id,K,T,{workspaceId:k!=="__home__"&&k!=="__custom__"?k:null,workspacePath:k==="__custom__"&&Ke||null,resumeSessionId:K==="cli"&&z?z:null,cliArgs:se,initialModel:J.trim()?J.trim():null,initialThinkingLevel:V.trim()?V.trim():null});if(be(!1),!Ge.ok){Xe("error"),Se(Ge.error||u("newSession.errorStartSession"));return}K!=="ide"&&M.trim()&&(D1(h.id,T,M),tt(h.id,T)),n()},[K,M,J,V,tt,n,o,d,i,Ke,h,I,z,T,k,b,u]),Yt=K==="cli"&&!!z,xs=u(b==="mesh"?"newSession.startMeshCoordinator":K==="cli"?Yt?"newSession.resumeSavedHistory":"newSession.startFresh":K==="ide"?"newSession.startIde":K==="acp"?"newSession.startAcpSession":"newSession.start"),Re=u(b==="mesh"?"newSession.startingCoordinator":K==="cli"?Yt?"newSession.resumingSavedHistory":"newSession.startingFresh":K==="ide"?"newSession.startingIde":K==="acp"?"newSession.startingAcpSession":"newSession.starting"),rt=f.length>5;return h?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:u("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":u("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:u("newSession.machine"),children:rt?s.jsx("select",{"aria-label":u("newSession.machine"),value:h.id,onChange:se=>C(se.target.value),onFocus:()=>f.forEach(se=>Ie(se.id)),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:F,children:f.map(se=>s.jsx("option",{value:se.id,children:ts(se,{fallbackId:se.id})},se.id))}):s.jsx("div",{className:"flex flex-wrap gap-2",role:"group","aria-label":u("newSession.machine"),children:f.map(se=>{const Ge=ts(se,{fallbackId:se.id}),Ee=h.id===se.id;return s.jsxs("button",{type:"button","aria-label":u("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:()=>C(se.id),onMouseEnter:()=>Ie(se.id),onFocus:()=>Ie(se.id),disabled:F,title:Ge,children:[s.jsx("span",{className:`h-2 w-2 shrink-0 rounded-full ${se.status==="offline"?"bg-text-muted":"bg-emerald-500"}`}),s.jsx("span",{className:"truncate",children:Ge})]},se.id)})})}),s.jsxs(Vn,{title:u("newSession.workspace"),action:b==="workspace"?s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Dt,disabled:F,children:u("newSession.browse")}):void 0,children:[s.jsx("div",{className:"mb-3 grid grid-cols-2 gap-2",role:"radiogroup","aria-label":u("newSession.launchTargetType"),children:[{id:"workspace",label:u("newSession.modeWorkspace"),desc:u("newSession.modeWorkspaceDesc")},{id:"mesh",label:u("newSession.modeMesh"),desc:u("newSession.modeMeshDesc")}].map(se=>s.jsxs("button",{type:"button",role:"radio","aria-checked":b===se.id,className:`rounded-xl border px-3 py-2.5 text-left transition-colors ${b===se.id?"border-accent bg-accent/10 text-text-primary":"border-border-subtle bg-bg-secondary/40 text-text-secondary hover:bg-bg-secondary/70 hover:text-text-primary"}`,onClick:()=>{S(se.id),Se(""),se.id==="mesh"&&h&&_!==h.id&&!L&&ze(h.id)},disabled:F,children:[s.jsx("div",{className:"text-sm font-semibold",children:se.label}),s.jsx("div",{className:"mt-0.5 text-[11px] opacity-80",children:se.desc})]},se.id))}),b==="workspace"?s.jsxs(s.Fragment,{children:[s.jsxs("select",{value:k,onChange:se=>{const Ge=se.target.value;w(Ge),Ge==="__custom__"?Dt():Se("")},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:F,children:[s.jsx("option",{value:"__home__",children:u("newSession.homeDirectory")}),x.map(se=>s.jsxs("option",{value:se.id,children:[se.id===y?"⭐ ":"",vu(se.path,se.label)||se.path]},se.id)),s.jsx("option",{value:"__custom__",children:u("newSession.customFolder")})]}),s.jsx("div",{className:"mt-2 text-[11px] text-text-muted break-all",children:k==="__home__"?u("newSession.launchWithoutWorkspace"):Ke||u("newSession.selectWorkspaceFolder")}),k==="__custom__"&&Ke&&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:F,children:[s.jsx(xn,{size:14}),u("newSession.selectFolder")]}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Kt,disabled:F||ee,children:u(ee?"newSession.saving":"newSession.saveWorkspace")})]})]}):s.jsxs("div",{className:"space-y-3",children:[L&&s.jsx("div",{className:"text-sm text-text-muted",children:u("newSession.loadingMeshes")}),!L&&B&&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:B}),!L&&!B&&j.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:u("newSession.noMeshes")}),j.length>0&&s.jsx("div",{className:"grid grid-cols-1 gap-2",role:"radiogroup","aria-label":u("newSession.mesh"),children:j.map(se=>s.jsxs("button",{type:"button",role:"radio","aria-checked":I===se.id,className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${I===se.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>D(se.id),disabled:F,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:se.name}),s.jsxs("div",{className:"mt-1 text-xs text-text-secondary",children:[se.repoIdentity||u("newSession.repoMesh"),typeof se.nodesCount=="number"?` · ${u("newSession.nodeCount",{count:se.nodesCount})}`:""]}),se.workspace&&s.jsx("div",{className:"mt-1 text-[11px] text-text-muted break-all",children:u("newSession.coordinatorWorkspace",{path:se.workspace})})]},se.id))})]})]}),s.jsx(E1,{workspaceMode:b,activeKind:K,cliEnabled:Le.length>0,ideEnabled:Fe.length>0,acpEnabled:Ae.length>0,busy:F,onSelect:R}),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:u(K==="ide"?"newSession.chooseIde":K==="cli"?"newSession.chooseCliProvider":"newSession.chooseAcpProvider")}),s.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[qe.map(se=>s.jsxs("button",{type:"button",className:`w-full rounded-xl border px-3.5 py-3 text-left transition-colors ${T===se.id?"border-accent bg-accent/10":"border-border-subtle bg-bg-secondary/40 hover:bg-bg-secondary/70"}`,onClick:()=>H(se.id),disabled:F,children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:se.label}),se.meta&&s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:se.meta})]},se.id)),qe.length===0&&s.jsx("div",{className:"text-sm text-text-muted",children:u("newSession.noProviders")})]})]}),b==="mesh"&&we&&s.jsx(bm,{setup:we,providerName:(_e==null?void 0:_e.displayName)||(_e==null?void 0:_e.name)||T}),b!=="mesh"&&K!=="ide"&&s.jsxs(Vn,{title:u("newSession.startupArguments"),children:[s.jsx("input",{type:"text",value:M,onChange:se=>W(se.target.value),placeholder:u("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:F}),O.length>0&&s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:O.map(se=>s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>W(se),disabled:F,title:se,children:se},se))})]}),(b==="mesh"&&!!T||b!=="mesh"&&K!=="ide")&&s.jsx(Vn,{title:u("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:u("newSession.model")}),et.length>0&&!de?s.jsxs("select",{value:et.includes(J)?J:"",onChange:se=>{se.target.value==="__custom__"?(ne(!0),re("")):re(se.target.value)},className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:F,children:[s.jsx("option",{value:"",children:u("newSession.providerDefault")}),et.map(se=>s.jsx("option",{value:se,children:se},se)),s.jsx("option",{value:"__custom__",children:u("newSession.custom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:J,onChange:se=>re(se.target.value),placeholder:u("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:F,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:()=>{ne(!1),re("")},disabled:F,children:u("newSession.backToModelList")})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:u("newSession.thinkingLevel")}),s.jsxs("select",{value:V,onChange:se=>X(se.target.value),className:"w-full rounded-lg border border-border-subtle bg-bg-secondary text-text-primary px-3 py-2.5 text-sm",disabled:F,children:[s.jsx("option",{value:"",children:u("newSession.providerDefault")}),te.map(se=>s.jsx("option",{value:se,children:se},se))]})]})]})}),b!=="mesh"&&K==="cli"&&s.jsx(R1,{busy:F,savedSessionsLoading:ke,savedSessionsError:Z,selectedSession:De,onRefresh:()=>{!h||!T||Oe(h.id,T)},onOpenHistory:()=>{!h||!T||(Te(!0),P1({hasLoadedInitialResults:G,isLoading:ke})&&Oe(h.id,T))},onClearSelection:()=>ae("")}),je&&s.jsx("div",{className:`rounded-xl border px-4 py-3 text-sm ${He==="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:F,children:u("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:F||(b==="mesh"?!I||!T||K!=="cli"||L:!K||!T||k==="__custom__"&&!Ke),children:[s.jsx(Xd,{size:14}),F?Re:xs]})]})]})}),he&&s.jsx(al,{title:u("newSession.selectWorkspaceTitle"),description:u("newSession.selectWorkspaceDescription"),currentPath:Be,directories:ve,busy:ut,error:pt,onClose:()=>$e(!1),onNavigate:Tt,onConfirm:se=>{N(se),Me(se),w("__custom__"),$e(!1)}}),fe&&Qe&&s.jsx(gp,{activeConv:Qe,ides:[],isCreatingChat:!1,isRefreshingHistory:ke,savedSessions:Ce,isSavedSessionsLoading:ke,isResumingSavedSessionId:pe,savedHistoryFilters:ce,missingWorkspaceResumePath:Ke||null,onSavedHistoryFiltersChange:$,onClose:()=>Te(!1),onNewChat:()=>{ae(""),Te(!1)},onSwitchSession:()=>{},onRefreshHistory:()=>{!h||!T||Oe(h.id,T)},onResumeSavedSession:se=>{if(!h||!T||pe||!se.canResume)return;const Ge=ss(se);ae(se.providerSessionId),Ot(se),le(se.providerSessionId),Te(!1),be(!0),Se(""),i(h.id,"cli",T,{workspaceId:Ge.workspaceId,workspacePath:Ge.workspacePath,resumeSessionId:se.providerSessionId}).then(Ee=>{if(!Ee.ok){Xe("error"),Se(Ee.error||u("newSession.errorResumeSession"));return}n()}).finally(()=>{be(!1),le(Ee=>Ee===se.providerSessionId?null:Ee)})}})]}):null}function gm(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 il(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=gm(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 ll(e){var t;return e.nextStepHint??((t=e.branchConvergence)==null?void 0:t.nextStep)??null}function xm(e){var t;return!ll(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 $1(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),a=e.nodes.filter(i=>i.type!=="submoduleNode"&&!i.isOrphan),o=e.nodes.filter(i=>i.type!=="submoduleNode");return t||r.length>0?$r([t==null?void 0:t.id,...r.map(i=>i.id)]):a.length>0?$r(a.map(i=>i.id)):o.length>0?$r(o.map(i=>i.id)):$r(e.nodes.map(i=>i.id))}function vm(e){const t=[...e.nodes].sort((r,a)=>r.id.localeCompare(a.id)).map(r=>[r.id,r.type,r.branch??"",r.parentNodeId??"",r.submodulePath??""].join(":")).join("|"),n=[...e.edges].sort((r,a)=>r.id.localeCompare(a.id)).map(r=>[r.id,r.source,r.target,r.type].join(":")).join("|");return`${e.meshId}::${t}::${n}`}function H1(e,t,n){const r=Math.max(0,Math.round(t)),a=Math.max(0,Math.round(n));return`${vm(e)}::${r}x${a}`}const B1={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"},F1={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"},O1={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"},W1={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=>F1[t],actionButton:t=>W1[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=>B1[t],actionButton:t=>O1[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},U1={maxWidth:180};function G1(e){return e==="TB"?"DOWN":"RIGHT"}function cl(e,t){return{"elk.algorithm":"layered","elk.direction":G1(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 q1=cl(Cn,"LR");cl(xr,"LR");function z1(e){const t=e.nodes.length;if(t<8)return"LR";const n=new Map;for(const a of e.edges)n.set(a.source,(n.get(a.source)??0)+1);let r=0;for(const a of n.values())a>r&&(r=a);return r>=Math.max(6,Math.floor(t/2))?"TB":"LR"}const K1=new Ah;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=gm(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 ym(e,t=!1){const n=t?xr:Cn,r=ur(e,t),a=t?e.type==="submoduleNode"?20:22:e.type==="submoduleNode"?24:30,o=t?(e.type==="submoduleNode",2):e.type==="submoduleNode"?2:3,i=Math.ceil(V1(e)/o),c=Hr(e.label,a,2),d=Hr(e.type==="submoduleNode"?e.submodulePath:e.machineLabel||e.workspace,a,2),p=Hr(Qr(e),a+(t?1:4),t?2:3),u=il(e),m=xm(e)?ll(e):null,f=t?0:Hr(m,Math.max(24,Math.floor(r/8)),4),g=t?40+c*16+d*12+(u?22:0)+Math.max(0,i-1)*18+Math.max(18,p*16):52+c*18+d*14+(u?30:0)+i*24+Math.max(22,p*18)+(f>0?22+f*16:0),C=e.type==="submoduleNode"?n.minSubmoduleCardHeight:n.minWorktreeCardHeight;return Math.min(n.maxEstimatedCardHeight,Math.max(C,Math.ceil(g)))}function Hr(e,t,n){const r=(e||"").trim();return r?Math.max(1,Math.min(n,Math.ceil(r.length/t))):0}function V1(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 Y1(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 J1(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.id.localeCompare(t.id)}function Q1(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 X1(e,t,n){return{id:e.id,x:t,y:n,width:ur(e),height:ym(e)}}function Z1(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 wm(e){const t=[...e.nodes].sort(Y1),n=t.find(a=>a.type==="defaultBranchNode")??null,r=t.some(a=>a.id!==(n==null?void 0:n.id)&&a.type!=="submoduleNode");return!n||r?t:[...t,Z1(n,e)]}function eN(e,t=q1,n=!1,r="LR"){const a=wm(e),o=new Set(a.map(d=>d.id)),i=a.map(d=>({id:d.id,width:ur(d,n),height:ym(d,n)})),c=e.edges.filter(d=>o.has(d.source)&&o.has(d.target)).sort(J1).map(d=>({id:d.id,sources:[d.source],targets:[d.target]}));return{id:`${e.meshId||"mesh"}__elk_root`,layoutOptions:{...t},children:i,edges:c}}function tN(e,t=!1){const n=[...new Set(e.map(a=>Math.round(a.x)))].sort((a,o)=>a-o),r=t?xr.layerGap:Cn.layerGap;return n.length<2?r:Math.min(...n.slice(1).map((a,o)=>a-n[o]))}async function km(e,t=!1,n="LR",r){var C,h;const o=cl(t?xr:Cn,n),i=wm(e),c=new Map(i.map(x=>[x.id,x])),d=eN(e,o,t,n);if(r&&r.size>0)for(const x of d.children??[]){const y=r.get(x.id);y&&y>0&&(x.height=y)}const p=await K1.layout(d),u=(p.children??[]).map(x=>{const y=c.get(x.id);return y?Q1(y,Math.round(x.x??0),Math.round(x.y??Cn.placeholderTopOffset),!x.id.endsWith("__placeholder")):null}).filter(Boolean),m=new Map(i.map((x,y)=>[x.id,y]));u.sort((x,y)=>(m.get(x.id)??0)-(m.get(y.id)??0));const f=u.map(x=>X1(x.graphNode,x.position.x,x.position.y)),g=new Map;for(const x of p.edges??[]){const y=x.sections;if(!y||y.length===0)continue;const b=y[0],S=(C=x.sources)==null?void 0:C[0],k=(h=x.targets)==null?void 0:h[0];if(!S||!k)continue;const w=[];w.push({x:Math.round(b.startPoint.x),y:Math.round(b.startPoint.y)});for(const v of b.bendPoints??[])w.push({x:Math.round(v.x),y:Math.round(v.y)});w.push({x:Math.round(b.endPoint.x),y:Math.round(b.endPoint.y)}),g.set(x.id,{id:x.id,source:S,target:k,points:w})}return{nodes:u,bounds:f,edgeRoutes:g,columnGap:tN(f,t),layoutOptions:{...o}}}function sN(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 Sm(e){return[e.id,e.source,e.target,e.type,e.label??"",e.direction].join("|")}function nN(e){return[e.meshId,e.refreshedAt,e.nodes.length,e.edges.length,...e.nodes.map(sN),...e.edges.map(Sm)].join("::")}function rN(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(Sm)].join("::")}const aN=5*60*1e3;function Cm(e){return typeof e.daemonId=="string"&&e.daemonId.trim()?e.daemonId.trim():null}function jm(e){return typeof e.machineId=="string"&&e.machineId.trim()?e.machineId.trim():null}function oN(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"||Cm(e)||jm(e)?"remote":"unknown"}function iN(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 Nm(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 lN(e){if(e.connectionTransport==="local"||e.connectionState==="self")return null;const t=Nm(e);return!t||t==="local"||typeof e.connectionRttMs!="number"||!Number.isFinite(e.connectionRttMs)?null:`${Math.round(e.connectionRttMs)}ms`}function cN(e){return Fi(e)}function Am(e){var t;return cN(e)?!1:!!(e.gitProbePending||((t=e.connection)==null?void 0:t.state)==="connecting")}function Im(e){if(!e)return null;const t=Date.parse(e);return Number.isNaN(t)?null:t}function dN(e){return e.activeSessionDetails&&e.activeSessionDetails.length>0?e.activeSessionDetails:(e.activeSessions??[]).map(t=>({sessionId:t,workspace:e.workspace,isCached:!0}))}function Tm(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed>0:!1}function Mm(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.dirty)}function dl(e){return((e==null?void 0:e.submodules)??[]).some(t=>t.outOfSync||!!t.error)}function uN(e){return dl(e)?"degraded":Mm(e)?"dirty":"online"}function pN(e){return e?e.staged+e.modified+e.untracked+e.deleted+e.renamed:0}function Xc(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 So(e){return e.length===0?"unknown":e.reduce((t,n)=>Xc(n)>Xc(t)?n:t)}function mN(e){var o,i,c,d,p;const t=new Map,n=new Map;for(const u of e){const m=(i=(o=u.git)==null?void 0:o.branch)==null?void 0:i.trim();m&&(n.set(m,(n.get(m)??0)+1),(c=u.git)!=null&&c.upstream&&t.set(m,(t.get(m)??0)+1))}const r=[...t.entries()].sort((u,m)=>{if(m[1]!==u[1])return m[1]-u[1];const f=["main","master","develop","dev"],g=f.indexOf(u[0]),C=f.indexOf(m[0]);return g!==-1||C!==-1?g===-1?1:C===-1?-1:g-C:u[0].localeCompare(m[0])});return(d=r[0])!=null&&d[0]?r[0][0]:((p=[...n.entries()].sort((u,m)=>m[1]-u[1])[0])==null?void 0:p[0])??null}function hN(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 Zc(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 fN(e){return e.reduce((t,n)=>Zc(n.status)>Zc(t.status)?n:t)}function bN(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 gN(e){var a,o,i;const t=e.sourceOfTruth,n=[],r=(a=t==null?void 0:t.fallback)==null?void 0:a.warning;return typeof r=="string"&&r.trim()&&n.push(r.trim()),(t==null?void 0:t.currentStatus)==="bootstrap_inventory_fallback"&&((o=t.directPeerTruth)==null?void 0:o.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 xN(e){const t=e.asyncRefineJobs;if(!Array.isArray(t))return[];const n=[];for(const r of t){if(!r||typeof r!="object")continue;const a=r,o=typeof a.jobId=="string"?a.jobId:null,i=a.status;o&&(i!=="accepted"&&i!=="running"&&i!=="completed"&&i!=="failed"||n.push({jobId:o,status:i,nodeId:typeof a.nodeId=="string"?a.nodeId:void 0,targetNodeId:typeof a.targetNodeId=="string"?a.targetNodeId:void 0,workspace:typeof a.workspace=="string"?a.workspace:void 0,branch:typeof a.branch=="string"?a.branch:void 0,into:typeof a.into=="string"?a.into:void 0,lastUpdatedAt:typeof a.lastUpdatedAt=="string"?a.lastUpdatedAt:void 0,startedAt:typeof a.startedAt=="string"?a.startedAt:void 0,completedAt:typeof a.completedAt=="string"?a.completedAt:void 0}))}return n}function ed(e){switch(e){case"running":case"accepted":return 0;case"failed":return 1;case"completed":default:return 2}}function td(e){const t=e.lastUpdatedAt||e.completedAt||e.startedAt||"";return Im(t)??0}function vN(e){return e.length===0?null:e.reduce((t,n)=>{const r=ed(t.status),a=ed(n.status);return a!==r?a<r?n:t:td(n)>td(t)?n:t})}function yN(e){var n,r;const t=new Map;for(const a of e){const o=((n=a.nodeId)==null?void 0:n.trim())||((r=a.targetNodeId)==null?void 0:r.trim());if(!o)continue;const i=t.get(o)??[];i.push(a),t.set(o,i)}return t}function wN(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 kN(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(a=>a.upstream))==null?void 0:n.upstream)??null,upstreamStatus:((r=t.find(a=>a.upstreamStatus))==null?void 0:r.upstreamStatus)??null,ahead:0,behind:0,dirty:!1,hasConflicts:!1}}function SN(e,t){if(Am(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 a=e.git,o=Tm(a)||Mm(a),i=!!(a!=null&&a.hasConflicts)||dl(a),c=(a==null?void 0:a.ahead)??0,d=(a==null?void 0:a.behind)??0,p=(a==null?void 0:a.branch)??null,u=(a==null?void 0:a.upstream)??null,m=(a==null?void 0:a.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??p,defaultBranch:f,upstream:n.upstream??u,upstreamStatus:n.upstreamStatus??m,ahead:n.ahead??c,behind:n.behind??d,dirty:n.dirty??o,hasConflicts:n.hasConflicts??i}}function CN(e,t){const n=SN(e,t);return n?{...n,defaultBranch:n.defaultBranch??t}:null}function jN(e){return e.error||e.outOfSync?"degraded":e.dirty?"dirty":"online"}function NN(e){var d,p,u;const{nodeStatus:t,expectedSubmodulePaths:n,refreshedAtMs:r}=e,a=[],o=t.machineLabel||t.nodeId,i=t.git;if(!i){if(Am(t))return a.push(`${o} is still waiting for a live peer git snapshot from the selected coordinator.`),{snapshotCompleteness:"pending_git",snapshotWarnings:a};const m=t.health==="online"||t.machineStatus==="online"||((d=t.connection)==null?void 0:d.state)==="connected"||((p=t.connection)==null?void 0:p.state)==="self";return a.push(m?`${o} is online but no peer git snapshot is visible yet.`:`${o} has no peer git snapshot visible yet.`),{snapshotCompleteness:"missing_git",snapshotWarnings:a}}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&&a.push(`${o} is missing submodule visibility for ${m.join(", ")} even though another peer reported it.`)}return((u=t.connection)==null?void 0:u.state)!=="self"&&r!==null&&typeof i.lastCheckedAt=="number"&&r-i.lastCheckedAt>aN&&a.push(`${o} is relying on a peer git snapshot older than 5m; re-probe before trusting convergence.`),a.some(m=>m.includes("submodule visibility"))?{snapshotCompleteness:"missing_submodule_report",snapshotWarnings:a}:a.some(m=>m.includes("older than 5m"))?{snapshotCompleteness:"stale",snapshotWarnings:a}:{snapshotCompleteness:"complete",snapshotWarnings:a}}function Dm(e){const t=Du(e),r=(typeof t.defaultBranch=="string"&&t.defaultBranch.trim().length>0?t.defaultBranch.trim():null)??mN(t.nodes),a=Im(t.refreshedAt),o=new Set(t.nodes.flatMap(B=>{var E;return(((E=B.git)==null?void 0:E.submodules)??[]).map(K=>K.path)})),i=[],c=[],d=gN(t),p=new Map,u=yN(xN(t));for(const B of t.nodes){const E=B.git,K=(E==null?void 0:E.branch)??null,R=uN(E),T=Tm(E)||R==="dirty",H=hN(B,r),M=CN(B,r),W=NN({nodeStatus:B,expectedSubmodulePaths:o,refreshedAtMs:a}),J=typeof B.clonedFromNodeId=="string"?B.clonedFromNodeId:null,re=dN(B),V=vN(u.get(B.nodeId)??[]),X=iN(B),de={id:B.nodeId,type:H.length>0?"orphanNode":"worktreeNode",label:B.machineLabel||B.nodeId.slice(0,8),workspace:B.workspace,branch:K,upstream:(E==null?void 0:E.upstream)??null,upstreamStatus:(E==null?void 0:E.upstreamStatus)??null,daemonId:Cm(B),machineId:jm(B),machineLabel:B.machineLabel||null,locality:oN(B),connectionTransport:X.connectionTransport,connectionState:X.connectionState,connectionReason:X.connectionReason,connectionReported:X.connectionReported,connectionRttMs:X.connectionRttMs,health:So([B.health,R]),ahead:(E==null?void 0:E.ahead)??0,behind:(E==null?void 0:E.behind)??0,dirty:T,dirtyFiles:pN(E),hasConflicts:(E==null?void 0:E.hasConflicts)??!1,activeSessionCount:re.length,activeSessions:re.map(ne=>ne.sessionId),sessionDetails:re,providers:B.providers??[],isOrphan:H.length>0,orphanReasons:H,error:B.error,nextStepHint:W.snapshotWarnings[0]??H[0]??(M==null?void 0:M.nextStep)??void 0,parentNodeId:null,clonedFromNodeId:J,worktreeBranch:B.worktreeBranch??null,submodulePath:null,submoduleCommit:(E==null?void 0:E.headCommit)??null,outOfSync:dl(E),snapshotCompleteness:W.snapshotCompleteness,snapshotWarnings:W.snapshotWarnings,branchConvergence:M,refineJobStatus:(V==null?void 0:V.status)??null,refineJobId:(V==null?void 0:V.jobId)??null,refineJobBranch:(V==null?void 0:V.branch)??null,refineJobInto:(V==null?void 0:V.into)??null,source:B};if(i.push(de),K){const ne=p.get(K)??[];ne.push(de.id),p.set(K,ne)}for(const ne of(E==null?void 0:E.submodules)??[]){const O=`${de.id}::submodule::${ne.path}`,ie=ne.path.split("/").filter(Boolean).pop()||ne.path;i.push({id:O,type:"submoduleNode",label:ie,workspace:ne.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:jN(ne),ahead:0,behind:0,dirty:ne.dirty,dirtyFiles:ne.dirty?1:0,hasConflicts:!1,activeSessionCount:0,activeSessions:[],sessionDetails:[],providers:[],isOrphan:!1,orphanReasons:[],error:ne.error,nextStepHint:ne.error||(ne.outOfSync?`${ne.path} is out of sync with the parent checkout`:ne.dirty?`${ne.path} has local changes`:`${ne.path} is in sync with the parent checkout`),parentNodeId:de.id,submodulePath:ne.path,submoduleCommit:ne.commit,outOfSync:ne.outOfSync,snapshotCompleteness:"complete",snapshotWarnings:[],branchConvergence:null,source:{kind:"synthetic-submodule",parentNodeId:de.id,parentWorkspace:B.workspace,submodule:ne}}),c.push({id:`${de.id}--${O}`,source:de.id,target:O,type:"submoduleLink",label:ne.outOfSync?"submodule out of sync":"submodule",direction:"directed"})}}const m=r?`__branch_${r}`:null;if(m&&r){const E=(p.get(r)??[]).map(J=>i.find(re=>re.id===J)).filter(Boolean),K=E.map(J=>J.branchConvergence).filter(Boolean),R=bN(t),T=E.length>0&&E.every(J=>wN(J,r)),H=(R==null?void 0:R.length)===0&&T?kN(r,E):K.length>0?fN(K):null,M=(R==null?void 0:R.length)===0&&T?0:K.filter(J=>J.needsConvergence).length,W={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:So(E.map(J=>J.health)),ahead:0,behind:0,dirty:E.some(J=>J.dirty),dirtyFiles:E.reduce((J,re)=>J+re.dirtyFiles,0),hasConflicts:E.some(J=>J.hasConflicts),activeSessionCount:E.reduce((J,re)=>J+re.activeSessionCount,0),activeSessions:E.flatMap(J=>J.activeSessions),sessionDetails:E.flatMap(J=>J.sessionDetails),providers:[...new Set(E.flatMap(J=>J.providers))],isOrphan:!1,orphanReasons:[],nextStepHint:M>0?`${M} workspace(s) on ${r} still need follow-up`:E.length>0?`${E.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:H,source:{nodeId:m,machineLabel:r,workspace:t.repoIdentity,health:So(E.map(J=>J.health)),providers:[],activeSessions:[],activeSessionDetails:[]}};i.push(W);for(const J of i)if(!(J.id===m||J.type==="submoduleNode")){if(J.branch===r){c.push({id:`${m}--${J.id}`,source:m,target:J.id,type:"parentBranch",label:"checked out",direction:"undirected"});continue}if(J.branch){c.push({id:`${m}--${J.id}`,source:m,target:J.id,type:J.isOrphan?"orphanLink":"parentBranch",label:J.branch,direction:"undirected"});continue}J.isOrphan&&c.push({id:`${m}--${J.id}`,source:m,target:J.id,type:"orphanLink",label:"detached",direction:"undirected"})}}const f=new Set(i.map(B=>B.id)),g=new Set;for(const B of i){if(!B.clonedFromNodeId||B.type==="submoduleNode"||!f.has(B.clonedFromNodeId))continue;const E=`clone_${B.clonedFromNodeId}--${B.id}`;if(g.has(E))continue;g.add(E);const K=B.worktreeBranch??B.branch??void 0;c.push({id:E,source:B.clonedFromNodeId,target:B.id,type:"cloneLink",label:K?`cloned · ${K}`:"cloned",direction:"directed"})}const C=i.filter(B=>B.type!=="defaultBranchNode"),h=C.filter(B=>B.isOrphan).length,x=C.filter(B=>B.hasConflicts).length,y=C.filter(B=>B.health==="offline").length,b=C.filter(B=>B.type==="submoduleNode"&&B.outOfSync).length,S=C.filter(B=>{var E;return B.type!=="submoduleNode"&&((E=B.branchConvergence)==null?void 0:E.needsConvergence)}).length,k=C.filter(B=>{var E;return((E=B.branchConvergence)==null?void 0:E.status)==="blocked_review"}).length,w=C.filter(B=>{var E;return((E=B.branchConvergence)==null?void 0:E.status)==="pushed_feature_branch_needs_merge"}).length,v=C.filter(B=>{var E;return((E=B.branchConvergence)==null?void 0:E.status)==="cleanup_candidate"}).length,N=C.filter(B=>{var E;return((E=B.branchConvergence)==null?void 0:E.status)==="not_mergeable"}).length,j=C.filter(B=>B.snapshotWarnings.length>0).length,A=C.filter(B=>B.snapshotCompleteness==="pending_git").length,I=C.filter(B=>B.snapshotCompleteness==="missing_git").length,D=C.filter(B=>B.snapshotCompleteness==="missing_submodule_report").length,L=C.filter(B=>B.snapshotCompleteness==="stale").length,P=C.filter(B=>B.refineJobStatus==="running"||B.refineJobStatus==="accepted").length,_=C.filter(B=>B.refineJobStatus==="failed").length,q=[A>0?`${A} node(s) are still waiting for a live peer git snapshot`:null,I>0?`${I} node(s) have no visible peer git snapshot`:null,D>0?`${D} 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 S>0&&d.push(`${S} workspace(s) still need follow-up before the mesh is converged`),h>0&&d.push(`${h} workspace(s) need attention before safe coordination`),k>0&&d.push(`${k} workspace(s) are blocked on branch convergence or upstream sync`),w>0&&d.push(`${w} clean feature branch workspace(s) still need merge follow-up`),v>0&&d.push(`${v} worktree workspace(s) are ready for refine / cleanup`),N>0&&d.push(`${N} workspace(s) have local changes or conflicts blocking convergence`),x>0&&d.push(`${x} workspace(s) report merge conflicts`),y>0&&d.push(`${y} node(s) are currently offline`),b>0&&d.push(`${b} submodule(s) are out of sync with their parent checkout`),d.push(...q),r||d.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:C.length,onlineNodes:C.filter(B=>B.health==="online").length,dirtyNodes:C.filter(B=>B.dirty).length,orphanNodes:h,errorNodes:C.filter(B=>!!B.error||B.outOfSync).length,offlineNodes:y,followUpNodes:S,blockedReviewNodes:k,mergeReadyNodes:w,cleanupCandidateNodes:v,notMergeableNodes:N,incompleteSnapshotNodes:j,pendingGitSnapshotNodes:A,missingGitSnapshotNodes:I,missingSubmoduleSnapshotNodes:D,staleGitSnapshotNodes:L,activeRefineNodes:P,failedRefineNodes:_,totalActiveSessions:C.reduce((B,E)=>B+E.activeSessionCount,0)},warnings:d,snapshotWarnings:q}}function AN(e){return!e.nodes.some(t=>t.snapshotCompleteness==="pending_git"||t.snapshotCompleteness==="missing_git"||t.snapshotCompleteness==="missing_submodule_report")}const IN=7,TN=640,ul=l.createContext(Rs("dark")),Pm=l.createContext(!1),Lm=l.createContext("LR"),Rm={overflowWrap:"anywhere",wordBreak:"break-word"},MN={...Rm,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:3,overflow:"hidden"},DN={...Rm,display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:4,overflow:"hidden"};function Em(e){return e.activeSessionCount>0}function PN(e){return e.health==="offline"||e.snapshotCompleteness==="stale"&&e.activeSessionCount===0}function sd(e,t,n){const r=Em(e),a=PN(e);let o;t?o="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?o=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)]":a?o=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":o=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=il(e);if((i==null?void 0:i.tone)==="danger")return`${o} ${n?"bg-rose-500/12":"bg-rose-50/95"}`;if((i==null?void 0:i.tone)==="warn")return`${o} ${n?"bg-amber-500/10":"bg-amber-50/95"}`;if((i==null?void 0:i.tone)==="info")return`${o} ${n?"bg-violet-500/10":"bg-violet-50/95"}`;switch(e.health){case"online":return`${o} ${n?r?"bg-emerald-500/10":"bg-emerald-500/8":r?"bg-emerald-50":"bg-emerald-50/95"}`;case"dirty":return`${o} ${n?"bg-amber-500/8":"bg-amber-50/95"}`;case"degraded":return`${o} ${n?"bg-rose-500/10":"bg-rose-50/95"}`;case"wrong_branch":return`${o} ${n?"bg-violet-500/10":"bg-violet-50/95"}`;case"offline":return`${o} ${n?"bg-slate-500/10":"bg-slate-100/90"}`;default:return`${o} ${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 nd(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 rd(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 LN(e){return e.replace(/_/g," ")}function ps(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 RN(e){var t;return((t=e.sessionDetails)==null?void 0:t.some(n=>ps(n)==="generating"))??!1}function Co(e,t){const n=ps(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 EN(e){if(!e)return null;const t=Date.parse(e);return Number.isFinite(t)?t:null}function ad(e){const t=EN(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 a=Math.floor(r/60);return a<48?`${a}h ${r%60}m`:`${Math.floor(a/24)}d ${a%24}h`}function jo(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function Wn(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function _N(e){if(e.sessionDetails.length===0)return null;const t=e.sessionDetails.filter(o=>ps(o)==="generating").length,n=e.sessionDetails.filter(o=>o.isSelfCoordinator).length,r=e.sessionDetails.length-n,a=[`${e.sessionDetails.length} chat${e.sessionDetails.length===1?"":"s"}`];return t>0&&a.push(`${t} generating`),n>0&&a.push(n===1?"coordinator attached":`${n} coordinators`),r>0&&a.push(`${r} worker${r===1?"":"s"}`),t===0&&n>0&&a.push("sampled status"),a.join(" · ")}function od(e){return e==="local"?"local":e==="remote"?"remote":"machine unknown"}function $N(e){return e.locality==="remote"?"meta":"health"}function HN({data:e,selected:t}){const{t:n}=Ne("common"),r=l.useContext(ul),a=l.useContext(Pm),o=l.useContext(Lm),i=e.graphNode,c=i.type==="defaultBranchNode",d=i.type==="submoduleNode",p=xm(i),u=c?"default branch anchor":d?i.submodulePath||"submodule checkout":[i.machineLabel,od(i.locality)].filter(Boolean).join(" · ")||i.workspace,m=i.submoduleCommit?i.submoduleCommit.slice(0,7):null,f=!d&&!c&&i.connectionState!=="self",g=f?Nm(i):null,C=g==="local"?null:g,h=f?lN(i):null,x=il(i),y=ll(i),b=Em(i),S=i.sessionDetails,k=i.sessionDetails,w=_N(i),v=i.sessionDetails.map(j=>{const A=ps(j),I=j.providerType||"provider unknown",D=Wn(j),L=j.startedAt||j.createdAt||null,P=j.statusNote?` · ${j.statusNote}`:"";return`Session: ${j.sessionId} · ${I} · ${A} · ${D} · ${ad(L)}${P}`});if(a)return s.jsxs("div",{className:`rounded-xl border px-3 py-2.5 backdrop-blur-sm transition-all ${sd(i,t,r.isDark)}`,style:{width:ur(i,!0)},title:[i.label,i.branch?`${n("meshGraph.panel.tooltipPrefixBranch")} ${i.branch}`:null,i.machineLabel?`Machine: ${i.machineLabel}`:null,i.workspace?`Workspace: ${i.workspace}`:null,x?`${n("meshGraph.panel.tooltipPrefixStatus")} ${x.label}`:null,Qr(i),...v].filter(Boolean).join(`
82
+ `),children:[s.jsx(yr,{type:"target",position:o==="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:u})]}),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:rd(i.health)},"aria-hidden":!0})]})]}),i.health==="unknown"&&!x&&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")})}),x&&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] ${nd(x.tone,r.isDark)}`,title:x.label,children:s.jsx("span",{className:"truncate",children:x.label})}),!x&&i.branch&&!d&&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}),w&&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:v.join(`
83
+ `),children:w}),k.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:k.map(j=>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: ${j.sessionId}`,j.providerType?`Provider: ${j.providerType}`:null,`${n("meshGraph.panel.tooltipPrefixStatus")} ${ps(j)}`,`Role: ${Wn(j)}`].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:j.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] ${Co(j,r.isDark)}`,children:ps(j)})]}),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:jo(j.sessionId)}),s.jsx("span",{className:"shrink-0",children:Wn(j)})]})]},j.sessionId))}),s.jsx(yr,{type:"source",position:o==="TB"?Cs.Bottom:Cs.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]});const N=[i.label,u,x?`${n("meshGraph.panel.tooltipPrefixStatus")} ${x.label}`:null,Qr(i),i.branch?`${n("meshGraph.panel.tooltipPrefixBranch")} ${i.branch}`:null,i.dirty?d?n("meshGraph.panel.tooltipLocalChanges"):`${i.dirtyFiles} dirty`:null,i.hasConflicts?n("meshGraph.panel.tooltipHasConflicts"):null,i.outOfSync?n("meshGraph.panel.tooltipOutOfSync"):null,!d&&i.upstream&&i.upstreamStatus!=="fresh"?n("meshGraph.panel.tooltipUpstreamUnverified"):null,i.isOrphan?n("meshGraph.panel.tooltipNeedsFollowUp"):null,p&&y?`${n("meshGraph.panel.tooltipPrefixNote")} ${y}`:null,...v].filter(Boolean).join(`
85
+ `);return s.jsxs("div",{className:`rounded-2xl border px-4 py-3 backdrop-blur-sm transition-all ${sd(i,t,r.isDark)}${RN(i)?" mesh-node-generating":""}`,style:{width:ur(i)},title:N,children:[s.jsx(yr,{type:"target",position:o==="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:u})]}),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:rd(i.health)},"aria-hidden":!0})]})]}),x?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] ${nd(x.tone,r.isDark)}`,title:x.label,children:s.jsx("span",{className:"truncate",children:x.label})}):i.branch&&!d?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,w&&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:v.join(`
86
+ `),children:s.jsx("span",{className:"truncate",children:w})}),k.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:k.map(j=>{const A=Wn(j);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: ${j.sessionId}`,j.providerType?`Provider: ${j.providerType}`:null,`${n("meshGraph.panel.tooltipPrefixStatus")} ${ps(j)}`,`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:j.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] ${Co(j,r.isDark)}`,children:ps(j)})]}),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:jo(j.sessionId)}),s.jsx("span",{children:A})]})]},j.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:LN(i.health)}),d&&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($N(i),r.isDark)}`,children:od(i.locality)}),C&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("meta",r.isDark)}`,title:C==="relay"?n("meshGraph.panel.tooltipP2PRelayed"):`P2P transport: ${C}`,children:C}),h&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("meta",r.isDark)}`,title:n("meshGraph.panel.tooltipP2PRtt"),children:h}),m&&d&&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:d?"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")}),!d&&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")}),!d&&i.refineJobStatus==="completed"&&s.jsx("span",{className:`rounded-full border px-2 py-0.5 ${Lt("refineDone",r.isDark)}`,title:i.refineJobBranch?n("meshGraph.panel.tooltipRefinedBranch",{branch:`${i.refineJobBranch}${i.refineJobInto?` → ${i.refineJobInto}`:""}`}):n("meshGraph.panel.tooltipRefineCompleted"),children:n("meshGraph.panel.refined")})]}),s.jsx("div",{className:`mt-3 text-[11px] leading-5 ${r.textSecondary}`,style:MN,children:Qr(i)}),S.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:S.map(j=>{const A=j.startedAt||j.createdAt||null,I=Wn(j);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: ${j.sessionId}`,j.providerType?`Provider: ${j.providerType}`:null,`${n("meshGraph.panel.tooltipPrefixStatus")} ${ps(j)}`,`Role: ${I}`,A?`Started: ${A}`:n("meshGraph.panel.tooltipStartedNotReported"),j.statusNote?`${n("meshGraph.panel.tooltipPrefixNote")} ${j.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:jo(j.sessionId)}),s.jsx("span",{className:`shrink-0 rounded-full border px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-[0.12em] ${Co(j,r.isDark)}`,children:ps(j)})]}),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:j.providerType||n("meshGraph.panel.providerUnknown")}),s.jsx("span",{children:I}),s.jsx("span",{children:ad(A)})]}),j.statusNote&&s.jsx("div",{className:`mt-1 text-[9px] leading-4 ${r.textMuted}`,children:j.statusNote})]},j.sessionId)})})]}),p&&y&&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:DN,children:y})]}),s.jsx(yr,{type:"source",position:o==="TB"?Cs.Bottom:Cs.Right,isConnectable:!1,style:{opacity:0,pointerEvents:"none"}})]})}const BN={meshNode:HN},FN=8;function ON(e){if(e.length<2)return null;if(e.length===2){const[p,u]=e;return{d:`M ${p.x},${p.y} L ${u.x},${u.y}`,labelX:(p.x+u.x)/2,labelY:(p.y+u.y)/2}}const t=FN,n=[`M ${e[0].x},${e[0].y}`];for(let p=1;p<e.length-1;p+=1){const u=e[p-1],m=e[p],f=e[p+1],g=Math.sign(m.x-u.x),C=Math.sign(m.y-u.y),h=Math.sign(f.x-m.x),x=Math.sign(f.y-m.y),y=Math.hypot(m.x-u.x,m.y-u.y),b=Math.hypot(f.x-m.x,f.y-m.y),S=Math.min(t,y/2,b/2);if(S<1||g===h&&C===x){n.push(`L ${m.x},${m.y}`);continue}const k=m.x-g*S,w=m.y-C*S,v=m.x+h*S,N=m.y+x*S;n.push(`L ${k},${w}`),n.push(`Q ${m.x},${m.y} ${v},${N}`)}const r=e[e.length-1];n.push(`L ${r.x},${r.y}`);let a=0;const o=[0];for(let p=1;p<e.length;p+=1)a+=Math.hypot(e[p].x-e[p-1].x,e[p].y-e[p-1].y),o.push(a);const i=a/2;let c=e[0].x,d=e[0].y;for(let p=1;p<e.length;p+=1)if(o[p]>=i){const u=o[p]-o[p-1],m=u===0?0:(i-o[p-1])/u;c=e[p-1].x+(e[p].x-e[p-1].x)*m,d=e[p-1].y+(e[p].y-e[p-1].y)*m;break}return{d:n.join(" "),labelX:c,labelY:d}}function WN(e){const t=e.data.routePoints;if(t&&t.length>=2){const o=ON(t);if(o)return[o.d,o.labelX,o.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 a;return r.type==="parentBranch"?a=Fh(n):r.type==="worktreeLink"||r.type==="submoduleLink"||r.type==="cloneLink"?a=Hh(n):a=Bh(n),[a[0],a[1],a[2]]}function UN(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 GN(e){const t=l.useContext(ul),n=e.data.graphEdge,[r,a,o]=WN(e),i=typeof e.label=="string"?e.label:void 0;return s.jsxs(s.Fragment,{children:[s.jsx(Lh,{id:e.id,path:r,markerEnd:e.markerEnd,style:e.style,interactionWidth:24}),e.label&&s.jsx(Rh,{children:s.jsx("div",{className:UN(n,t.isDark),title:i,style:{position:"absolute",transform:`translate(-50%, -50%) translate(${a}px, ${o}px)`,pointerEvents:"none",maxWidth:U1.maxWidth},children:s.jsx("span",{className:"block truncate",children:e.label})})})]})}const qN={meshEdge:GN};async function zN(e,t,n,r,a){const o=await km(e,n,r,a);return _m(e,o,t,n)}async function KN(e,t=Rs("dark"),n=!1,r="LR"){const a=await km(e,n,r);return _m(e,a,t,n)}function _m(e,t,n,r=!1){const a=new Set(t.nodes.map(p=>p.id)),o=t.nodes.map(p=>({id:p.id,type:p.type,position:p.position,data:{graphNode:p.graphNode,compact:r},selected:p.selected,draggable:p.draggable,selectable:p.selectable})),i=e.edges.filter(p=>a.has(p.source)&&a.has(p.target)),c=JN(i),d=i.map(p=>{var u;return{id:p.id,source:p.source,target:p.target,label:c.has(p.id)?p.label:void 0,type:"meshEdge",data:{graphEdge:p,routePoints:(u=t.edgeRoutes.get(p.id))==null?void 0:u.points},animated:p.type==="orphanLink",markerEnd:p.direction==="directed"?{type:$h.ArrowClosed,width:p.type==="submoduleLink"?16:18,height:p.type==="submoduleLink"?16:18,color:ld(p)}:void 0,style:{stroke:ld(p),strokeWidth:p.type==="orphanLink"?2.25:p.type==="submoduleLink"?1.7:p.type==="worktreeLink"?1.8:p.type==="cloneLink"?1.6:2,strokeDasharray:p.type==="orphanLink"?"5 4":p.type==="submoduleLink"?"4 3":p.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:o,edges:d}}const VN=3,YN=2;function id(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 JN(e){const t=new Set,n=new Map;for(const r of e){if(!r.label)continue;const a=n.get(r.source);a?a.push(r):n.set(r.source,[r])}for(const r of n.values()){if(r.length<VN){for(const o of r)t.add(o.id);continue}const a=[...r].sort((o,i)=>{const c=id(i)-id(o);return c!==0?c:o.id.localeCompare(i.id)});for(const o of a.slice(0,YN))t.add(o.id)}return t}function ld(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 QN(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 XN(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 ZN({data:e,viewportKey:t}){const n=Eh(),r=_h(),a=l.useRef(null),o=l.useMemo(()=>vm(e),[e]),i=l.useMemo(()=>$1(e),[e]);return l.useEffect(()=>{if(!n||e.nodes.length===0||a.current===t)return;let c=!1;const d=requestAnimationFrame(()=>{if(c)return;const p=i.length>0&&i.length<e.nodes.length;r.fitView({nodes:p?i.map(u=>({id:u})):void 0,padding:p?.24:.2,maxZoom:p?.98:.9,duration:260}),a.current=t});return()=>{c=!0,cancelAnimationFrame(d)}},[e.nodes.length,i,o,n,r,t]),null}const eA=12;function tA(e){return e>=16?"min-h-[720px]":e>=10?"min-h-[580px]":"min-h-[460px]"}function sA({data:e,selectedNodeId:t=null,directionPref:n,onNodeClick:r,onEdgeClick:a,onNodeHoverChange:o,onEdgeHoverChange:i}){const{theme:c}=Ls(),d=l.useMemo(()=>Rs(c),[c]),p=l.useMemo(()=>nN(e),[e]),u=l.useMemo(()=>rN(e),[e]),m=l.useRef(null),[f,g]=l.useState({width:0,height:0}),C=f.width>0&&f.width<TN,h=e.nodes.length>=IN||C,[x]=l.useState("LR"),y=n??x,b=l.useMemo(()=>n==="LR"||n==="TB"?n:C?"TB":y==="auto"?z1(e):y,[y,n,p,e,C]),S=e.nodes.length>=eA,[k,w]=l.useState({nodes:[],edges:[]}),v=l.useMemo(()=>`${H1(e,f.width,f.height)}::${b}`,[p,e,f.height,f.width,b]);l.useEffect(()=>{let j=!1;return KN(e,d,h,b).then(A=>{if(j)return;w(A);const I=requestAnimationFrame(()=>{if(j)return;const D=m.current;if(!D)return;const L=new Map;for(const P of A.nodes){const _=D.querySelector(`.react-flow__node[data-id="${CSS.escape(P.id)}"]`);_&&_.offsetHeight>0&&L.set(P.id,_.offsetHeight)}L.size!==0&&zN(e,d,h,b,L).then(P=>{j||w(P)})});return()=>cancelAnimationFrame(I)}),()=>{j=!0}},[e,u,d,h,b]);const N=l.useMemo(()=>k.nodes.map(j=>({...j,selected:j.id===t})),[k.nodes,t]);return l.useEffect(()=>{const j=m.current;if(!j)return;const A=()=>{const D=Math.max(0,Math.round(j.clientWidth)),L=Math.max(0,Math.round(j.clientHeight));g(P=>P.width===D&&P.height===L?P:{width:D,height:L})};A();const I=typeof ResizeObserver=="function"?new ResizeObserver(()=>A()):null;return I==null||I.observe(j),window.addEventListener("resize",A),()=>{I==null||I.disconnect(),window.removeEventListener("resize",A)}},[]),s.jsx(ul.Provider,{value:d,children:s.jsx(Pm.Provider,{value:h,children:s.jsx(Lm.Provider,{value:b,children:s.jsxs("div",{ref:m,className:`${d.graphShellClass} ${tA(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] ${d.graphStatChipClass}`,children:"drag or scroll to pan"}),s.jsx("div",{className:"w-full min-w-0 flex-1",style:{height:"100%"},children:s.jsxs(Ih,{nodes:N,edges:k.edges,nodeTypes:BN,edgeTypes:qN,minZoom:C?.3:.18,maxZoom:1.35,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!0,panOnDrag:!0,panOnScroll:!0,zoomOnScroll:!1,zoomOnPinch:!0,zoomOnDoubleClick:!1,selectionOnDrag:!1,onNodeClick:(j,A)=>r==null?void 0:r(A.data.graphNode),onEdgeClick:(j,A)=>{var D;const I=(D=A.data)==null?void 0:D.graphEdge;I&&(a==null||a(I))},onNodeMouseEnter:(j,A)=>o==null?void 0:o(A.data.graphNode),onNodeMouseLeave:()=>o==null?void 0:o(null),onEdgeMouseEnter:(j,A)=>{var I;return i==null?void 0:i(((I=A.data)==null?void 0:I.graphEdge)??null)},onEdgeMouseLeave:()=>i==null?void 0:i(null),className:"h-full w-full",colorMode:d.flowColorMode,proOptions:{hideAttribution:!0},children:[s.jsx(ZN,{data:e,viewportKey:v}),s.jsx(Th,{className:d.graphControlsClass,position:"bottom-left",showZoom:!0,showFitView:!0,showInteractive:!1}),S&&s.jsx(Mh,{position:"bottom-right",pannable:!0,zoomable:!0,nodeColor:QN,nodeClassName:XN,nodeStrokeWidth:3,className:d.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(Dh,{variant:Ph.Dots,gap:18,size:1.2,color:d.graphBackgroundDotColor})]})})]})})})})}const nA="You are one independent member of a multi-agent cross-verification quorum";function rA(e){var r,a;const t=(e??"").trim();if(!t)return"";if(!t.startsWith(nA))return t;const n=(a=(r=t.match(/\n## Question\n([\s\S]*?)(?:\n## |$)/))==null?void 0:r[1])==null?void 0:a.trim().replace(/\s+/g," ");return n?`MAGI cross-verify — ${n}`:"MAGI cross-verification task"}function aA(e){return`${e.state??""} ${e.chatStatus??""} ${e.lifecycle??""}`.toLowerCase()}function oA(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){const r=n.activeSessionDetails;if(Array.isArray(r))for(const a of r)a!=null&&a.sessionId&&aA(a).includes("approval")&&t.push({nodeId:n.nodeId,sessionId:a.sessionId,providerType:a.providerType,machineLabel:n.machineLabel||n.nodeId,detail:a.statusNote??a.title??null})}return t}function iA({approvals:e,nodes:t,onResolve:n,hideWhenEmpty:r=!0}){const{t:a}=Ne(),o=l.useMemo(()=>e??oA(t),[e,t]),[i,c]=l.useState({});if(r&&o.length===0)return null;const d=(p,u)=>{i[p.sessionId]||(c(m=>({...m,[p.sessionId]:u})),Promise.resolve(n(p.nodeId,p.sessionId,u)).finally(()=>{c(m=>{const f={...m};return delete f[p.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}),a("meshGraph.approvals.title"),s.jsxs("span",{className:"opacity-70 font-semibold",children:["(",o.length,")"]})]}),o.length===0?s.jsx("div",{className:"text-[11px] opacity-70",children:a("meshGraph.approvals.empty")}):s.jsx("ul",{className:"flex flex-col gap-2",children:o.map(p=>{const u=i[p.sessionId]??null,m=u!==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:[p.machineLabel||p.nodeId,p.providerType&&s.jsx("span",{className:"ml-2 opacity-60 font-normal",children:p.providerType})]}),s.jsx("div",{className:"text-[10px] opacity-60 truncate",children:p.detail?p.detail.replace(/[\n\r]+/g," ").slice(0,120):a("meshGraph.approvals.sessionFallback",{id:p.sessionId})})]}),s.jsxs("div",{className:"flex gap-2 shrink-0",children:[s.jsx("button",{onClick:()=>d(p,"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:u==="approve"?"⏳ ...":a("meshGraph.approvals.approve")}),s.jsx("button",{onClick:()=>d(p,"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:u==="reject"?"⏳ ...":a("meshGraph.approvals.reject")})]})]},`${p.nodeId}:${p.sessionId}`)})})]})}const lA=5,cA=40,dA={meshId:"",totalEntries:0,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0};function Ea(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function $m(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 Hm(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 uA(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 Bm(e){switch(e){case"active":return"emerald";case"paused":return"amber";case"completed":return"sky";case"abandoned":return"rose";default:return"muted"}}function pA(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 Fm(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 cd(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 a=Math.floor(r/60);return a<48?`${a}h ago`:`${Math.floor(a/24)}d ago`}function dd(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),a=r%60,o=Math.floor(r/60),i=[];return o>0&&i.push(`${o}h`),a>0&&i.push(`${a}m`),(n>0||i.length===0)&&i.push(`${n}s`),i.join(" ")}function pl(e){return e.replace(/[_-]+/g," ")}function Om(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 Wm(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 mA({status:e,daemonId:t=null,meshId:n=null,sendDaemonCommand:r=null}){var k,w,v,N;const{theme:a}=Ls(),o=l.useMemo(()=>Rs(a),[a]),i=((k=e.queue)==null?void 0:k.summary)??null,c=((w=e.queue)==null?void 0:w.tasks)??[],d=((v=e.ledger)==null?void 0:v.summary)??dA,p=((N=e.ledger)==null?void 0:N.entries)??[],u=e.missions??[],m=u.filter(j=>j.status==="active"||j.status==="paused"),f=u.filter(j=>j.status==="completed"||j.status==="abandoned"),g=e.asyncRefineJobs??[],[C,h]=l.useState(null),x=l.useCallback(()=>h(null),[]),y=l.useCallback(async(j,A,I)=>{!t||!r||await r(t,"mesh_approve",{meshId:n??void 0,node_id:j,session_id:A,action:I})},[t,n,r]),b=l.useCallback(j=>{if(!j)return"";const A=e.nodes.find(I=>I.nodeId===j);return(A==null?void 0:A.machineLabel)||j},[e.nodes]),S=l.useMemo(()=>{const j=[];for(const A of e.nodes){const I=A.activeSessionDetails&&A.activeSessionDetails.length>0?A.activeSessionDetails:(A.activeSessions??[]).map(D=>({sessionId:D,workspace:A.workspace,isCached:!0}));for(const D of I)j.push({node:A,session:D})}return j},[e.nodes]);return s.jsxs("div",{className:"flex flex-col gap-3 pb-2",children:[s.jsx(iA,{nodes:e.nodes,onResolve:y}),s.jsx(kA,{meshTheme:o,liveMissions:m,historyMissions:f,hasMissionField:Array.isArray(e.missions),onSelect:j=>h({kind:"mission",mission:j})}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(SA,{meshTheme:o,ledgerSummary:d,entries:p,resolveNodeLabel:b,onSelect:j=>h({kind:"ledger",entry:j})}),s.jsx(CA,{meshTheme:o,queueSummary:i,tasks:c,onSelect:j=>h({kind:"queue",task:j})})]}),s.jsx(NA,{meshTheme:o,nodes:e.nodes}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[s.jsx(AA,{meshTheme:o,entries:S,onSelect:(j,A)=>h({kind:"session",node:j,session:A})}),s.jsx(IA,{meshTheme:o,jobs:g})]}),C&&s.jsx(fA,{meshTheme:o,detail:C,onClose:x,daemonId:t,meshId:n??e.meshId??null,sendDaemonCommand:r,resolveNodeLabel:b})]})}function Qs({meshTheme:e,title:t,count:n,children:r,action:a}){const o=e.isDark;return s.jsxs("div",{className:`flex min-w-0 flex-col overflow-hidden rounded-2xl border p-4 ${o?"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}),a&&s.jsx("span",{className:"ml-auto",children:a})]}),r]})}function qt({meshTheme:e,label:t,tone:n}){const r=e.isDark,a=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] ${a}`,children:t})}function St({meshTheme:e,label:t,value:n,tone:r}){const a=e.isDark,o=r==="rose"?a?"text-rose-300":"text-rose-600":r==="sky"?a?"text-sky-300":"text-sky-600":r==="amber"?a?"text-amber-300":"text-amber-600":r==="emerald"?a?"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 ${a?"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 ${o}`,children:n}),s.jsx("span",{className:`mt-1 text-[9px] uppercase tracking-wide ${e.textMuted}`,children:t})]})}function vr({meshTheme:e,children:t}){return s.jsx("div",{className:`text-xs ${e.textMuted}`,children:t})}function _a({meshTheme:e,onClick:t,children:n}){const r=e.isDark,a=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 ${a} ${t?"cursor-pointer":"cursor-default"}`,children:n})}function $a({meshTheme:e,expanded:t,hiddenCount:n,onToggle:r}){const{t:a}=Ne("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?a("mesh.overview.showFewer"):a("mesh.overview.showMore",{count:n})})}function Ha(e,t=lA){const[n,r]=l.useState(!1),a=n?e:e.slice(0,t),o=Math.max(0,e.length-t),i=l.useCallback(()=>r(c=>!c),[]);return{visible:a,hiddenCount:o,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 hA(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:pl(e.entry.kind)};case"queue":return{kicker:t("mesh.overview.detailKickerQueue"),title:e.task.id};case"session":return{kicker:t("mesh.overview.detailKickerSession"),title:Ea(e.session.sessionId)}}}function fA({meshTheme:e,detail:t,onClose:n,daemonId:r,meshId:a,sendDaemonCommand:o,resolveNodeLabel:i}){const{t:c}=Ne("common");l.useEffect(()=>{const g=C=>{C.key==="Escape"&&n()};return window.addEventListener("keydown",g),()=>window.removeEventListener("keydown",g)},[n]);const d=e.isDark,{kicker:p,title:u}=hA(t,c),m=d?"bg-[#030617]/[0.92]":"bg-[rgba(15,23,42,0.82)]",f=d?"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:g=>g.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 ${d?"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:p}),s.jsx("div",{className:`mt-0.5 break-all text-sm font-semibold ${e.textPrimary}`,children:u})]}),s.jsx("button",{type:"button",onClick:n,"aria-label":c("mesh.overview.closeDetail"),className:d?"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(xA,{meshTheme:e,mission:t.mission,daemonId:r,meshId:a,sendDaemonCommand:o}),t.kind==="ledger"&&s.jsx(vA,{meshTheme:e,entry:t.entry,resolveNodeLabel:i}),t.kind==="queue"&&s.jsx(yA,{meshTheme:e,task:t.task}),t.kind==="session"&&s.jsx(wA,{meshTheme:e,node:t.node,session:t.session})]})]})})}const bA=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function gA(e){const t=bA(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function xA({meshTheme:e,mission:t,daemonId:n,meshId:r,sendDaemonCommand:a}){var w;const{t:o}=Ne("common"),i=t.tasks,c="goal"in t&&typeof t.goal=="string"&&t.goal?t.goal:"goalPreview"in t?t.goalPreview:"",d="goalTruncated"in t?t.goalTruncated===!0:!1,[p,u]=l.useState(null),[m,f]=l.useState(!1),[g,C]=l.useState(null),h=d&&!p&&!!n&&!!a,x=l.useCallback(async()=>{if(!(!n||!a)){f(!0),C(null);try{const v=await a(n,"mesh_status",{meshId:r??void 0,verbose:!0}),N=gA(v),A=(Array.isArray(N==null?void 0:N.missions)?N.missions:[]).find(D=>(D==null?void 0:D.id)===t.id),I=typeof(A==null?void 0:A.goal)=="string"&&A.goal?A.goal:null;I?u(I):C("Full goal unavailable")}catch(v){C(v instanceof Error?v.message:"Failed to fetch full mission goal")}finally{f(!1)}}},[n,r,a,t.id]),y=p??c,b=d&&!p,S=t.stats??null,k=((w=S==null?void 0:S.incompleteTaskIds)==null?void 0:w.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(qt,{meshTheme:e,label:t.status,tone:Bm(t.status)}),s.jsx(qt,{meshTheme:e,label:`${i.total} tasks`,tone:"muted"})]}),y&&s.jsxs("div",{className:`max-h-64 overflow-y-auto whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:[y,b&&!h&&s.jsx("span",{className:e.textMuted,children:" … (truncated)"})]}),g&&s.jsx("div",{className:"text-[11px] text-amber-400",children:g}),h&&s.jsx("button",{type:"button",className:"self-start text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:x,disabled:m,children:o(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:o("mesh.overview.statCompleted"),value:i.completed,tone:"emerald"}),s.jsx(St,{meshTheme:e,label:o("mesh.overview.statAssigned"),value:i.assigned,tone:i.assigned>0?"sky":void 0}),s.jsx(St,{meshTheme:e,label:o("mesh.overview.statPending"),value:i.pending}),s.jsx(St,{meshTheme:e,label:o("mesh.overview.statFailed"),value:i.failed,tone:i.failed>0?"rose":void 0}),s.jsx(St,{meshTheme:e,label:o("mesh.overview.statBlocked"),value:i.blocked,tone:i.blocked>0?"amber":void 0}),s.jsx(St,{meshTheme:e,label:o("mesh.overview.statCancelled"),value:i.cancelled,tone:"muted"})]}),S&&s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(St,{meshTheme:e,label:o("mesh.overview.statWallClock"),value:dd(S.wallClockMs)??"—"}),s.jsx(St,{meshTheme:e,label:o("mesh.overview.statTotalRuntime"),value:dd(S.totalDurationMs)??"—"}),s.jsx(St,{meshTheme:e,label:o("mesh.overview.statRetries"),value:S.retries,tone:S.retries>0?"amber":void 0})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(gt,{meshTheme:e,label:o("mesh.overview.detailLabelMissionId"),value:t.id}),s.jsx(gt,{meshTheme:e,label:o("mesh.overview.detailLabelCreated"),value:ds(t.createdAt)??t.createdAt}),s.jsx(gt,{meshTheme:e,label:o("mesh.overview.detailLabelUpdated"),value:ds(t.updatedAt)??t.updatedAt}),i.lastActivityAt&&s.jsx(gt,{meshTheme:e,label:o("mesh.overview.detailLabelLastActivity"),value:ds(i.lastActivityAt)??i.lastActivityAt}),k>0&&S&&s.jsx(gt,{meshTheme:e,label:o("mesh.overview.detailLabelIncompleteEvidence"),value:s.jsxs("details",{children:[s.jsx("summary",{className:"cursor-pointer select-none",children:o("mesh.overview.incompleteTaskCount_other",{count:k})}),s.jsx("div",{className:"mt-1 flex flex-col gap-0.5 break-all",children:S.incompleteTaskIds.map(v=>s.jsx("span",{className:`font-mono text-[10px] ${e.textMuted}`,children:v},v))})]})})]})]})}function vA({meshTheme:e,entry:t,resolveNodeLabel:n}){const{t:r}=Ne("common"),a=Wm(t.payload);let o="";try{o=JSON.stringify(t.payload??{},null,2)}catch{o=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(qt,{meshTheme:e,label:pl(t.kind),tone:Om(t.kind)})}),a&&s.jsx("div",{className:`whitespace-pre-wrap text-xs leading-5 ${e.textSecondary}`,children:a}),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:Ea(t.sessionId)}),t.providerType&&s.jsx(gt,{meshTheme:e,label:r("mesh.overview.detailLabelProvider"),value:t.providerType})]}),o&&o!=="{}"&&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:o})]})]})}function yA({meshTheme:e,task:t}){const{t:n}=Ne("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(qt,{meshTheme:e,label:t.status,tone:Fm(t.status)}),(t.requeueCount??0)>0&&s.jsx(qt,{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:Ea(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 wA({meshTheme:e,node:t,session:n}){var o,i;const{t:r}=Ne("common"),a=$m(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(qt,{meshTheme:e,label:a,tone:Hm(a)}),s.jsx(qt,{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}),(((o=t.git)==null?void 0:o.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 ud({meshTheme:e,mission:t,onSelect:n}){const r=t.tasks,a=ds(r.lastActivityAt);return s.jsxs(_a,{meshTheme:e,onClick:n,children:[s.jsx(qt,{meshTheme:e,label:t.status,tone:Bm(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]}),a&&s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:a})]})}function kA({meshTheme:e,liveMissions:t,historyMissions:n,hasMissionField:r,onSelect:a}){const{t:o}=Ne("common"),[i,c]=l.useState(!1),d=e.isDark,p=Ha(t);return s.jsxs(Qs,{meshTheme:e,title:o("mesh.overview.missionCard"),count:t.length||void 0,children:[t.length>0?s.jsxs("div",{className:"flex flex-col gap-0.5",children:[p.visible.map(u=>s.jsx(ud,{meshTheme:e,mission:u,onSelect:()=>a(u)},u.id)),s.jsx($a,{meshTheme:e,expanded:p.expanded,hiddenCount:p.hiddenCount,onToggle:p.toggle})]}):s.jsx(vr,{meshTheme:e,children:o(r?"mesh.overview.noActiveMissions":"mesh.overview.missionDataUnavailable")}),n.length>0&&s.jsxs("div",{className:`mt-3 border-t pt-2 ${d?"border-white/8":"border-slate-200"}`,children:[s.jsxs("button",{type:"button",onClick:()=>c(u=>!u),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:o("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(u=>s.jsx(ud,{meshTheme:e,mission:u,onSelect:()=>a(u)},u.id))})]})]})}function SA({meshTheme:e,ledgerSummary:t,entries:n,resolveNodeLabel:r,onSelect:a}){const{t:o}=Ne("common"),i=ds(t.lastActivityAt),c=l.useMemo(()=>[...n].reverse(),[n]),d=Ha(c);return s.jsxs(Qs,{meshTheme:e,title:o("mesh.overview.ledgerCard"),children:[s.jsxs("div",{className:"grid grid-cols-3 gap-1.5",children:[s.jsx(St,{meshTheme:e,label:o("mesh.overview.statDispatched"),value:t.taskDispatched}),s.jsx(St,{meshTheme:e,label:o("mesh.overview.statCompleted"),value:t.taskCompleted,tone:"emerald"}),s.jsx(St,{meshTheme:e,label:o("mesh.overview.statFailed"),value:t.taskFailed,tone:t.taskFailed>0?"rose":void 0}),s.jsx(St,{meshTheme:e,label:o("mesh.overview.statStalled"),value:t.taskStalled,tone:t.taskStalled>0?"amber":void 0}),s.jsx(St,{meshTheme:e,label:o("mesh.overview.statSessions"),value:t.sessionLaunched}),s.jsx(St,{meshTheme:e,label:o("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:o("mesh.overview.recentActivity")}),s.jsxs("div",{className:"flex flex-col gap-0.5",children:[d.visible.map(p=>{const u=Wm(p.payload);return s.jsxs(_a,{meshTheme:e,onClick:()=>a(p),children:[s.jsx(qt,{meshTheme:e,label:pl(p.kind),tone:Om(p.kind)}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,title:p.nodeId||void 0,children:u||r(p.nodeId)||p.sessionId||"—"}),s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:ds(p.timestamp)??""})]},p.id)}),s.jsx($a,{meshTheme:e,expanded:d.expanded,hiddenCount:d.hiddenCount,onToggle:d.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:o("mesh.overview.recentFailures",{count:t.recentFailures})}):s.jsx("span",{}),i&&c.length===0&&s.jsx("span",{children:i})]})]})}function CA({meshTheme:e,queueSummary:t,tasks:n,onSelect:r}){const a=l.useMemo(()=>[...n].sort((c,d)=>{const p=cd(c.status)-cd(d.status);return p!==0?p:(d.updatedAt||"").localeCompare(c.updatedAt||"")}).slice(0,cA),[n]),o=Ha(a),{t:i}=Ne("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"})]}),a.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:[o.visible.map(c=>s.jsxs(_a,{meshTheme:e,onClick:()=>r(c),children:[s.jsx(qt,{meshTheme:e,label:c.status,tone:Fm(c.status)}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${e.textSecondary}`,title:c.message||void 0,children:rA(c.message)||c.id}),s.jsx("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:ds(c.updatedAt)??""})]},c.id)),s.jsx($a,{meshTheme:e,expanded:o.expanded,hiddenCount:o.hiddenCount,onToggle:o.toggle})]})]})]}):s.jsx(Qs,{meshTheme:e,title:i("mesh.overview.queueCard"),children:s.jsx(vr,{meshTheme:e,children:i("mesh.overview.noQueueActivity")})})}function jA(e){return e.autoFastForwardEligible||e.suggestedAction==="auto_fast_forward"?{label:"fast-forward",tone:"sky"}:e.launchBlockedReason?{label:"blocked",tone:"rose"}:null}function NA({meshTheme:e,nodes:t}){const{t:n}=Ne("common"),r=e.isDark;return s.jsx(Qs,{meshTheme:e,title:n("mesh.overview.nodesCard"),count:t.length,children:t.length===0?s.jsx(vr,{meshTheme:e,children:n("mesh.overview.noNodes")}):s.jsx("div",{className:"flex flex-col gap-1.5",children:t.map(a=>{var d,p,u;const o=(((d=a.activeSessionDetails)==null?void 0:d.length)??0)||(((p=a.activeSessions)==null?void 0:p.length)??0),i=jA(a),c=((u=a.git)==null?void 0:u.branch)??a.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(qt,{meshTheme:e,label:a.health,tone:pA(a.health)}),s.jsx("span",{className:`min-w-0 max-w-full flex-1 truncate text-sm font-medium ${e.textPrimary}`,title:a.workspace,children:a.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:uA(a)}),o>0&&s.jsxs("span",{className:`shrink-0 text-[10px] ${e.textMuted}`,children:[o," session",o>1?"s":""]}),typeof a.daemonBuildVersion=="string"&&a.daemonBuildVersion&&s.jsxs("span",{className:`shrink-0 font-mono text-[10px] ${e.textMuted}`,title:"Daemon build version reported by this node",children:["v",a.daemonBuildVersion]}),i&&s.jsx(qt,{meshTheme:e,label:i.label,tone:i.tone})]},a.nodeId)})})})}function AA({meshTheme:e,entries:t,onSelect:n}){const{t:r}=Ne("common"),a=Ha(t);return s.jsx(Qs,{meshTheme:e,title:r("mesh.overview.sessionsCard"),count:t.length||void 0,children:t.length===0?s.jsx(vr,{meshTheme:e,children:r("mesh.overview.noActiveSessions")}):s.jsxs("div",{className:"flex flex-col gap-0.5",children:[a.visible.map(({node:o,session:i})=>{const c=$m(i);return s.jsxs(_a,{meshTheme:e,onClick:()=>n(o,i),children:[s.jsx("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${e.textMuted}`,children:Ea(i.sessionId)}),s.jsx("span",{className:`shrink-0 ${e.textMuted}`,children:i.providerType||"?"}),s.jsx(qt,{meshTheme:e,label:c,tone:Hm(c)})]},i.sessionId)}),s.jsx($a,{meshTheme:e,expanded:a.expanded,hiddenCount:a.hiddenCount,onToggle:a.toggle})]})})}function IA({meshTheme:e,jobs:t}){const{t:n}=Ne("common"),r=e.isDark,a=t.filter(o=>o.status==="failed").length;return s.jsx(Qs,{meshTheme:e,title:n("mesh.overview.refineCard"),count:t.length||void 0,action:a>0?s.jsx(qt,{meshTheme:e,label:n("mesh.overview.failedCount",{count:a}),tone:"rose"}):void 0,children:t.length===0?s.jsx(vr,{meshTheme:e,children:n("mesh.overview.noRefineJobs")}):s.jsx("div",{className:"flex flex-col gap-1",children:t.slice(0,8).map(o=>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:[o.branch??o.jobId.slice(0,14),o.into?` → ${o.into}`:""]}),s.jsx("span",{className:`shrink-0 text-[10px] font-semibold ${o.status==="failed"?r?"text-rose-300":"text-rose-600":o.status==="running"||o.status==="accepted"?r?"text-sky-300":"text-sky-600":r?"text-emerald-300":"text-emerald-600"}`,children:o.status})]},o.jobId))})})}const TA=["node","p2p","session","task","mission","refinery","completion","magi","magiPanel","convergence"];function MA({meshTheme:e,open:t,onToggle:n}){const{t:r}=Ne(),a=e.isDark,o="inline-flex h-7 w-7 items-center justify-center rounded-lg border transition",i=t?a?"border-sky-400/40 bg-sky-500/15 text-sky-100":"border-sky-400 bg-sky-100 text-sky-800":a?"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:`${o} ${i}`,children:s.jsx(Lf,{size:15})})}function DA({meshTheme:e,onClose:t}){const{t:n}=Ne(),r=e.isDark,a=l.useMemo(()=>TA.map(o=>({term:n(`meshGraph.help.sections.${o}.term`),summary:n(`meshGraph.help.sections.${o}.summary`),details:n(`meshGraph.help.sections.${o}.details`,{returnObjects:!0})})),[n]);return l.useEffect(()=>{const o=i=>{i.key==="Escape"&&t()};return window.addEventListener("keydown",o),()=>window.removeEventListener("keydown",o)},[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:a.map(o=>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:o.term}),s.jsx("dd",{className:`mt-1 text-[11px] leading-5 ${e.textSecondary}`,children:o.summary}),o.details&&o.details.length>0&&s.jsx("ul",{className:`mt-1.5 flex flex-col gap-1 text-[11px] leading-5 ${e.textMuted}`,children:o.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))})]},o.term))})]})}const tn=l.createContext(Rs("dark"));function Ve({label:e,tone:t="default",className:n,title:r}){const a=l.useContext(tn);return s.jsx("span",{title:r,className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${a.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 PA={meshId:"",totalEntries:0,taskDispatched:0,taskCompleted:0,taskFailed:0,taskStalled:0,sessionLaunched:0,checkpointCreated:0,lastActivityAt:null,recentFailures:0};function Um(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 No(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 LA(e){return e.isSelfCoordinator?"coordinator":(typeof e.role=="string"?e.role.trim():"")||"worker"}function RA(e){return e.startedAt||e.createdAt||null}function EA(e){const t=RA(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 a=Math.floor(r/60);if(a<60)return`${a}m`;const o=Math.floor(a/60);return o<48?`${o}h ${a%60}m`:`${Math.floor(o/24)}d ${o%24}h`}function Gm(e){return e.length<=18?e:`${e.slice(0,10)}...${e.slice(-4)}`}function _A(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 $A(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 HA(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 a=(t.submodules??[]).filter(i=>i.dirty),o=(t.submodules??[]).filter(i=>i.outOfSync||i.error);return a.length>0&&r.push(`${a.length} submodule dirty`),o.length>0&&r.push(`${o.length} submodule drift`),t.hasConflicts&&r.push("conflicts"),r.join(" · ")||"Clean"}const BA={first_eligible:"In order",least_loaded:"Spread",round_robin:"Spread (round-robin)",priority_only:"Spread (priority)"};function FA(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 OA(e){var n;const t=[];for(const r of e.nodes){const a=r.activeSessionDetails&&r.activeSessionDetails.length>0?r.activeSessionDetails:(r.activeSessions??[]).map(o=>({sessionId:o,workspace:r.workspace,isCached:!0}));for(const o of a)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:o})}return t}function WA(e){return e.assignedNodeId||e.targetNodeId||null}function bi(e){return e?e.slice(0,7):null}function UA(e,t){var o,i,c;const n=bi((o=e==null?void 0:e.git)==null?void 0:o.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 a=t[0];return a?[bi(a.commit),a.message].filter(Boolean).join(" · "):null}function GA(e,t){const n=UA(e,t);return n||(e!=null&&e.gitProbePending?"Pending live git probe":null)}function qA(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 zA(e){var n,r,a,o,i,c;const t=((n=e.selectedSessionEntry)==null?void 0:n.session.workspace)||((r=e.selectedSessionEntry)==null?void 0:r.workspace)||((o=(a=e.selectedNodeStatus)==null?void 0:a.git)==null?void 0:o.workspace)||((i=e.selectedNodeStatus)==null?void 0:i.workspace)||null;if(t&&e.selectedSessionEntry){const d=((c=e.selectedNodeStatus)==null?void 0:c.daemonId)||e.coordinatorDaemonId;return d?{daemonId:d,workspace:t}:null}if(t&&e.selectedNodeStatus){const d=e.selectedNodeStatus.daemonId||e.coordinatorDaemonId;return d?{daemonId:d,workspace:t}:null}return null}function KA(e){return e.gitProbePending&&(!e.connection||e.connection.state==="unknown")?"mesh pending":$A(e.connection)}function VA(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 pd(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 YA(e){return e.direction==="directed"?"directed":"undirected"}function JA(e,t){return t?e.nodes.find(n=>n.id===t)??null:null}function QA(e){var t,n,r,a;return[e.meshId,e.refreshedAt,e.nodes.length,((n=(t=e.queue)==null?void 0:t.summary)==null?void 0:n.active)??"",((a=(r=e.ledger)==null?void 0:r.summary)==null?void 0:a.recentFailures)??"",...e.nodes.map(o=>{var i,c,d,p,u,m,f,g,C,h,x,y,b,S,k,w,v,N,j,A,I,D;return[o.nodeId,o.daemonId??"",o.machineId??"",o.machineLabel,o.machineStatus??"",((i=o.connection)==null?void 0:i.state)??"",((c=o.connection)==null?void 0:c.transport)??"",((d=o.connection)==null?void 0:d.source)??"",o.health,o.gitProbePending?1:0,((p=o.git)==null?void 0:p.branch)??"",((u=o.git)==null?void 0:u.upstream)??"",((m=o.git)==null?void 0:m.upstreamStatus)??"",((f=o.git)==null?void 0:f.ahead)??"",((g=o.git)==null?void 0:g.behind)??"",((C=o.git)==null?void 0:C.headCommit)??"",((h=o.git)==null?void 0:h.staged)??"",((x=o.git)==null?void 0:x.modified)??"",((y=o.git)==null?void 0:y.untracked)??"",((b=o.git)==null?void 0:b.deleted)??"",((S=o.git)==null?void 0:S.renamed)??"",(k=o.git)!=null&&k.hasConflicts?1:0,((w=o.git)==null?void 0:w.lastCheckedAt)??"",((v=o.activeSessions)==null?void 0:v.join(","))??"",((N=o.activeSessionDetails)==null?void 0:N.length)??"",((j=o.activeSessionDetails)==null?void 0:j.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=o.providers)==null?void 0:A.join(","))??"",((I=o.providerPriority)==null?void 0:I.join(","))??"",o.error??"",(((D=o.git)==null?void 0:D.submodules)??[]).map(L=>[L.path,L.commit,L.dirty?1:0,L.outOfSync?1:0,L.error??""].join("/")).join(",")].join("|")})].join("::")}function XA(e){return e.nodes.length===0?!1:e.nodes.every(t=>t.health==="unknown"&&(!t.connection||t.connection.state==="unknown"))}function ZA({scheduling:e}){const{t}=Ne("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:BA[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 eI({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:FA(t),tone:"warn",title:"Why this node cannot currently claim a new write task"},t))]}):null}function tI({node:e}){var u,m,f,g;const t=l.useContext(tn),n=((u=e.activeSessionDetails)==null?void 0:u.length)??((m=e.activeSessions)==null?void 0:m.length)??0,r=bi((f=e.git)==null?void 0:f.headCommit),a=e.isLocalWorktree===!0,o=e.worktreeBootstrap,i=e.staleDaemonBuild,c=e.providerVersions&&typeof e.providerVersions=="object"?e.providerVersions:void 0,d=c?Object.entries(c).filter(([,C])=>typeof C=="string"&&C):[],p=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:Um(e.health)}),a&&s.jsx(Ve,{label:"worktree",tone:"info",title:e.worktreeBranch?`Worktree branch ${e.worktreeBranch}`:"Local worktree node"}),(o==null?void 0:o.status)&&o.status!=="ready"&&s.jsx(Ve,{label:`bootstrap ${o.status}`,tone:"warn",title:"Worktree bootstrap is still in progress"}),((g=e.connection)==null?void 0:g.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"}),p&&s.jsx(Ve,{label:`build ${p}`,tone:"default",title:"Daemon build version reported by this node"}),s.jsx(eI,{scheduling:e.scheduling})]}),d.length>0&&s.jsx("div",{className:"mt-1.5 flex flex-wrap items-center gap-1.5",children:d.map(([C,h])=>s.jsx(Ve,{label:`${C}@${h}`,tone:"info",title:"Detected provider version on this node"},C))}),s.jsxs("div",{className:`mt-1.5 text-[11px] ${t.textSecondary}`,children:[HA(e),r?s.jsxs("span",{className:"ml-2 font-mono opacity-70",children:["@",r]}):null]})]})}function sI({status:e}){const{t}=Ne("common"),n=l.useContext(tn),r=e.meshProtocolMetrics,a=Array.isArray(e.providerVersionSkew)?e.providerVersionSkew:[];return!r&&a.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"}),a.length>0&&s.jsx(Ve,{label:`${a.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(([o,i])=>s.jsx(Ve,{label:`${o}: ${i}`,tone:"default",title:"v2 event scope breakdown"},o))}),a.length>0&&s.jsx("div",{className:"mt-2 flex flex-col gap-1.5",children:a.map(o=>s.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[s.jsx("span",{className:`text-[11px] font-semibold ${n.textPrimary}`,children:o.provider}),o.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))]},o.provider))}),e.providerVersionSkewWarning&&s.jsx("p",{className:`mt-2 text-[11px] ${n.textSecondary}`,children:e.providerVersionSkewWarning})]})}function nI({canonicalStatus:e}){const{t}=Ne("common"),n=l.useContext(tn);return s.jsxs("div",{className:"flex flex-col gap-3 p-1",children:[s.jsx(ZA,{scheduling:e.scheduling}),s.jsx(sI,{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(tI,{node:r},r.nodeId))]})]})}function rI({canonicalStatus:e,queueSummary:t,ledgerSummary:n,isBootstrapMode:r,meshTheme:a,sessionEntries:o,inlineMode:i=!1}){var v;const c=t&&(t.active>0||t.historical>0),d=n.recentFailures>0||n.taskFailed>0,p=(v=e.queue)!=null&&v.tasks?e.queue.tasks.filter(N=>N.status==="failed"||N.status==="cancelled").slice(0,5):[],u=e.asyncRefineJobs,m=(u==null?void 0:u.filter(N=>N.status==="running"||N.status==="accepted"))??[],f=(u==null?void 0:u.filter(N=>N.status==="failed"))??[],g=e.staleDirectWorkSummary,C=g&&g.count>0;if(!c&&!d&&e.nodes.length===0&&!r&&m.length===0&&f.length===0&&!C&&o.length===0)return null;const{t:h}=Ne("common"),x=a.isDark,y=`border-t ${x?"border-white/8":"border-slate-200"}`,b=`group w-full rounded-lg border text-xs ${x?"border-white/8 bg-white/[0.02]":"border-slate-200 bg-slate-50/60"}`,S=`flex cursor-pointer list-none items-center gap-1.5 px-2.5 py-1.5 [&::-webkit-details-marker]:hidden ${a.textSecondary}`;function k({label:N,value:j,tone:A}){const I=A==="rose"?x?"text-rose-300":"text-rose-600":A==="sky"?x?"text-sky-300":"text-sky-600":A==="amber"?x?"text-amber-300":"text-amber-600":A==="emerald"?x?"text-emerald-300":"text-emerald-600":A==="muted"?a.textMuted:a.textPrimary;return s.jsxs("div",{className:`flex flex-col items-center rounded-lg border px-2 py-1.5 ${x?"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 ${I}`,children:j}),s.jsx("span",{className:`mt-0.5 text-[9px] uppercase tracking-wide ${a.textMuted}`,children:N})]})}const w=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(k,{label:"Pending",value:t.pending}),s.jsx(k,{label:"Active",value:t.active,tone:t.active>0?"sky":void 0}),s.jsx(k,{label:"Done",value:t.completed,tone:"emerald"}),s.jsx(k,{label:"Failed",value:t.failed,tone:t.failed>0?"rose":void 0})]}):s.jsxs(s.Fragment,{children:[s.jsx(k,{label:"Done",value:n.taskCompleted,tone:"emerald"}),s.jsx(k,{label:"Failed",value:n.taskFailed,tone:n.taskFailed>0?"rose":void 0}),s.jsx(k,{label:"Sessions",value:n.sessionLaunched}),s.jsx(k,{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(k,{label:"Ledger done",value:n.taskCompleted,tone:"emerald"}),s.jsx(k,{label:"Sessions",value:n.sessionLaunched}),s.jsx(k,{label:"Recent↯",value:n.recentFailures,tone:n.recentFailures>0?"amber":"muted"})]}),n.lastActivityAt&&s.jsxs("div",{className:`flex items-center justify-between ${a.textMuted}`,children:[s.jsx("span",{children:h("meshGraph.health.lastActivity")}),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(N=>{var P;const j=((P=N.connection)==null?void 0:P.state)??"unknown",A=j==="unknown"||j==="connecting",L=A?"bg-amber-400":j==="failed"||j==="closed"||j==="disconnected"?x?"bg-rose-400":"bg-rose-500":j==="connected"||j==="self"?x?"bg-emerald-400":"bg-emerald-500":x?"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 ${L}`}),s.jsx("span",{className:`min-w-0 flex-1 truncate ${a.textSecondary}`,title:N.workspace,children:N.machineLabel}),s.jsx("span",{className:`shrink-0 font-mono text-[10px] ${a.textMuted}`,children:A?"…":j})]},N.nodeId)})})}),u&&u.length>0&&s.jsx("div",{className:`pt-2.5 ${y}`,children:s.jsxs("details",{className:b,children:[s.jsxs("summary",{className:S,children:[s.jsx("span",{className:"flex-1",children:h("meshGraph.health.refineJobs")}),s.jsx("span",{className:`tabular-nums ${x?"text-slate-400":"text-slate-500"}`,children:u.length}),f.length>0&&s.jsxs("span",{className:x?"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:u.slice(0,8).map(N=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${a.textMuted}`,children:[N.branch??N.jobId.slice(0,14),N.into?` → ${N.into}`:""]}),s.jsx("span",{className:`shrink-0 text-[9px] font-semibold ${N.status==="failed"?x?"text-rose-300":"text-rose-600":N.status==="running"||N.status==="accepted"?x?"text-sky-300":"text-sky-600":x?"text-emerald-300":"text-emerald-600"}`,children:N.status})]},N.jobId))})]})}),p.length>0&&s.jsx("div",{className:u&&u.length>0?"":`pt-2.5 ${y}`,children:s.jsxs("details",{className:b,children:[s.jsxs("summary",{className:S,children:[s.jsx("span",{className:`flex-1 ${x?"text-rose-300":"text-rose-600"}`,children:h("meshGraph.health.failedTasks")}),s.jsx("span",{className:`tabular-nums ${x?"text-rose-400":"text-rose-500"}`,children:p.length})]}),s.jsx("div",{className:"flex flex-col gap-1 px-2.5 pb-2",children:p.map(N=>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] ${a.textMuted}`,children:N.id.slice(0,10)}),N.message&&s.jsx("span",{className:`flex-1 truncate ${x?"text-slate-300":"text-slate-700"}`,children:N.message.slice(0,55)})]}),N.cancelReason&&s.jsx("div",{className:`truncate text-[10px] ${a.textMuted}`,children:N.cancelReason.slice(0,55)})]},N.id))})]})}),C&&s.jsxs("div",{className:`flex items-center justify-between pt-2.5 ${y}`,children:[s.jsx("span",{className:a.textMuted,children:h("meshGraph.health.staleWork")}),s.jsx("span",{className:`tabular-nums ${x?"text-amber-300":"text-amber-600"}`,children:g.count})]}),o.length>0&&s.jsx("div",{className:`pt-2.5 ${y}`,children:s.jsxs("details",{className:b,children:[s.jsxs("summary",{className:S,children:[s.jsx("span",{className:"flex-1",children:h("meshGraph.health.sessions")}),s.jsx("span",{className:`tabular-nums ${x?"text-slate-400":"text-slate-500"}`,children:o.length})]}),s.jsx("div",{className:"flex flex-col gap-0.5 px-2.5 pb-2",children:o.map(N=>s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("span",{className:`min-w-0 flex-1 truncate font-mono text-[10px] ${a.textMuted}`,title:N.session.sessionId,children:Gm(N.session.sessionId)}),s.jsx("span",{className:`shrink-0 ${a.textMuted}`,children:N.session.providerType||"?"}),s.jsx("span",{className:`shrink-0 text-[9px] font-semibold ${a.textMuted}`,children:Xr(N.session)})]},N.session.sessionId))})]})})]});return i?w:s.jsxs("details",{className:`rounded-2xl border text-xs ${a.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 ${a.textSecondary}`,children:[s.jsx("span",{className:"flex-1",children:h("meshGraph.health.panelTitle")}),m.length>0&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${a.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] ${a.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"]}),d&&s.jsxs("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${a.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] ${a.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"})]}),w]})}function qm({meshTheme:e,activeTab:t,onActiveTabChange:n,helpOpen:r,onHelpOpenChange:a}){const{t:o}=Ne("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:o("meshGraph.obs.tabOverview")}),s.jsx("button",{type:"button",role:"tab","aria-selected":t==="status",className:i(t==="status"),onClick:()=>n("status"),children:o("meshGraph.obs.tabStatus")}),s.jsx("button",{type:"button",role:"tab","aria-selected":t==="graph",className:i(t==="graph"),onClick:()=>n("graph"),children:o("meshGraph.obs.tabGraph")})]}),s.jsx(MA,{meshTheme:e,open:r,onToggle:()=>a(!r)})]})}function aI({status:e,emptyMessage:t,daemonId:n=null,sendDaemonCommand:r=null,bootstrapFallback:a,activeTab:o,onActiveTabChange:i,helpOpen:c,onHelpOpenChange:d,hideControls:p=!1}){var Xe,dt,it;const{t:u}=Ne("common"),{theme:m}=Ls(),f=l.useMemo(()=>Rs(m),[m]),g=l.useMemo(()=>({merged_to_main:u("meshGraph.obs.convergenceMergedToMain"),pushed_feature_branch_needs_merge:u("meshGraph.obs.convergenceNeedsMerge"),blocked_review:u("meshGraph.obs.convergenceBlockedReview"),cleanup_candidate:u("meshGraph.obs.convergenceCleanup"),not_mergeable:u("meshGraph.obs.convergenceNotMergeable")}),[u]),C=t??u("meshGraph.obs.emptyGraph"),h=l.useMemo(()=>Du(e),[e]),x=a??XA(h),y=l.useMemo(()=>QA(h),[h]),b=l.useMemo(()=>Dm(h),[y]),[S,k]=l.useState("overview"),[w,v]=l.useState(!1),N=o??S,j=c??w,A=l.useCallback(he=>{i?i(he):k(he)},[i]),I=l.useCallback(he=>{d?d(he):v(he)},[d]),[D,L]=l.useState(!1);l.useEffect(()=>{N==="graph"&&L(!0)},[N]);const[P,_]=l.useState(null),[q,B]=l.useState(null),[E,K]=l.useState(null),[R,T]=l.useState({}),[H,M]=l.useState(null),[W,J]=l.useState(null),re=l.useMemo(()=>new Map(h.nodes.map(he=>[he.nodeId,he])),[h.nodes]),V=l.useMemo(()=>new Map(b.nodes.map(he=>[he.id,he])),[b.nodes]),X=((Xe=h.queue)==null?void 0:Xe.summary)??null,de=((dt=h.ledger)==null?void 0:dt.summary)??PA,ne=l.useMemo(()=>OA(h),[h]),O=l.useMemo(()=>{const he=new Map;for(const $e of ne){const Be=Xr($e.session);he.set(Be,(he.get(Be)??0)+1)}return[...he.entries()].sort(($e,Be)=>Be[1]-$e[1])},[ne]);l.useEffect(()=>{P&&(V.has(P)||(_(null),K(he=>!he||"nodeId"in he&&he.nodeId===P?null:he)))},[V,P]);const ie=P?re.get(P)??null:null,z=JA(b,P),ae=(E==null?void 0:E.kind)==="edge"&&q?b.edges.find(he=>he.id===q)??null:null,Ce=ae?b.nodes.find(he=>he.id===ae.source)??null:null,ye=ae?b.nodes.find(he=>he.id===ae.target)??null:null;l.useEffect(()=>{var he,$e,Be;if(P)try{console.info("[RepoMeshGraphDebug]",{event:"selected_canonical_node",meshId:h.meshId,selectedNodeId:P,canonicalNode:Ew(ie),graphNode:z?{id:z.id,branch:z.branch,upstream:z.upstream,headCommit:z.submoduleCommit,submoduleCount:(($e=(he=ie==null?void 0:ie.git)==null?void 0:he.submodules)==null?void 0:$e.length)??0,snapshotCompleteness:z.snapshotCompleteness,snapshotWarnings:z.snapshotWarnings,branchConvergence:((Be=z.branchConvergence)==null?void 0:Be.status)??null}:null})}catch{}},[h.meshId,z,P,ie]);const ke=(E==null?void 0:E.kind)==="session"?ne.find(he=>he.nodeId===E.nodeId&&he.session.sessionId===E.sessionId)??null:null,me=l.useMemo(()=>ne.filter(he=>he.nodeId===P),[P,ne]),G=zA({coordinatorDaemonId:n,selectedNodeStatus:ie,selectedSessionEntry:ke}),U=(G==null?void 0:G.workspace)??null,Z=U?R[U]??null:null,Y=GA(ie,(Z==null?void 0:Z.entries)??[]),fe=(z==null?void 0:z.daemonId)??(ie==null?void 0:ie.daemonId)??n??null,Te=!!(z&&r&&fe&&z.type!=="submoduleNode"&&z.behind>0&&z.ahead===0&&z.dirtyFiles===0&&!z.dirty&&!z.hasConflicts&&z.upstreamStatus==="fresh"),ce=l.useCallback(()=>{_(null),B(null),K(null),M(null)},[]);l.useEffect(()=>{M(null)},[P]);const $=l.useCallback(async()=>{if(!z||!fe||!r||!Te)return;J(z.id),M(null);const he=(ie==null?void 0:ie.workspace)??z.workspace??"";try{const $e=await r(fe,"fast_forward_mesh_node",{meshId:h.meshId,nodeId:z.id,workspace:he,updateSubmodules:!0,dryRun:!0,execute:!1}),Be=($e==null?void 0:$e.result)??$e;if(M({phase:"dry_run",code:typeof(Be==null?void 0:Be.code)=="string"?Be.code:void 0,error:typeof(Be==null?void 0:Be.operationError)=="string"?Be.operationError:null,executed:(Be==null?void 0:Be.executed)===!0}),!(Be!=null&&Be.success)||Be.code!=="fast_forward_available"||!window.confirm(`Apply fast-forward for ${z.label}?`))return;const ve=await r(fe,"fast_forward_mesh_node",{meshId:h.meshId,nodeId:z.id,workspace:he,updateSubmodules:!0,dryRun:!1,execute:!0}),We=(ve==null?void 0:ve.result)??ve;M({phase:"execute",code:typeof(We==null?void 0:We.code)=="string"?We.code:void 0,error:typeof(We==null?void 0:We.operationError)=="string"?We.operationError:null,executed:(We==null?void 0:We.executed)===!0})}catch($e){M({phase:"dry_run",error:$e instanceof Error?$e.message:"fast-forward failed"})}finally{J(null)}},[Te,h.meshId,z,fe,r]);l.useEffect(()=>{if(!z&&!ae)return;const he=$e=>{$e.key==="Escape"&&ce()};return window.addEventListener("keydown",he),()=>window.removeEventListener("keydown",he)},[ce,ae,z]),l.useEffect(()=>{if(!G||!r)return;const{daemonId:he,workspace:$e}=G,Be=R[$e];if(Be!=null&&Be.loading||Be&&(Be.entries.length>0||Be.error))return;let Me=!1;return T(ve=>{var We;return{...ve,[$e]:{loading:!0,error:null,entries:((We=ve[$e])==null?void 0:We.entries)??[]}}}),r(he,"git_log",{workspace:$e,limit:5}).then(ve=>{Me||T(We=>({...We,[$e]:{loading:!1,error:null,entries:qA(ve)}}))}).catch(ve=>{Me||T(We=>({...We,[$e]:{loading:!1,error:ve instanceof Error?ve.message:"git_log failed",entries:[]}}))}),()=>{Me=!0}},[R,G,r]);const pe=[...b.warnings??[],...h.nodes.filter(he=>he.machineStatus&&he.machineStatus!=="online").map(he=>`${he.machineLabel}: ${he.machineStatus}`)],le=b.stats.incompleteSnapshotNodes>0,F=b.stats.followUpNodes>0?`${b.stats.followUpNodes} need follow-up`:le?"mesh visibility incomplete":"mesh converged",be=b.stats.followUpNodes>0?"danger":le?"warn":"good",[je,Se]=l.useState("LR"),He=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:[!p&&s.jsx("div",{className:"shrink-0 flex items-center justify-end",children:s.jsx(qm,{meshTheme:f,activeTab:N,onActiveTabChange:A,helpOpen:j,onHelpOpenChange:I})}),j&&s.jsx(DA,{meshTheme:f,onClose:()=>I(!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(mA,{status:h,daemonId:n,meshId:h.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(nI,{canonicalStatus:h})}),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:F,tone:be,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:()=>Se("auto"),className:He(je==="auto"),title:"Auto-detect direction",children:"Auto"}),s.jsx("button",{type:"button",onClick:()=>Se("LR"),className:He(je==="LR"),title:"Left to right",children:"LR"}),s.jsx("button",{type:"button",onClick:()=>Se("TB"),className:He(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 Be;const he=((Be=h.asyncRefineJobs)==null?void 0:Be.filter(Me=>Me.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"]}):u("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(rI,{canonicalStatus:h,queueSummary:X,ledgerSummary:de,isBootstrapMode:x,meshTheme:f,sessionEntries:ne,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:u("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"}),O.length===0?s.jsx(Ve,{label:"no session metadata"}):O.slice(0,2).map(([he,$e])=>s.jsx(Ve,{label:`${$e} ${he}`,tone:No(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"})]}),pe.length>0&&s.jsx("div",{className:"flex flex-wrap gap-2",children:pe.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."})]})})]})})]})]}),x&&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:u("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:D?b.nodes.length>0?s.jsx(sA,{data:b,selectedNodeId:P,directionPref:je,onNodeClick:he=>{if((E==null?void 0:E.kind)==="node"&&P===he.id){ce();return}B(null),_(he.id),K({kind:"node",nodeId:he.id})},onEdgeClick:he=>{if((E==null?void 0:E.kind)==="edge"&&q===he.id){ce();return}_(null),B(he.id),K({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:C}):s.jsx("div",{className:"flex h-full min-h-[320px] items-center justify-center px-6 text-center text-sm text-slate-400",children:u("meshGraph.obs.loadingGraph")})}),z&&(E==null?void 0:E.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:u("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:z.label}),s.jsx("div",{className:`mt-0.5 font-mono text-[11px] ${f.textMuted}`,children:z.id.slice(0,16)})]}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1.5",children:[z.behind>0&&s.jsx("button",{type:"button",onClick:()=>{$()},disabled:!Te||W===z.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:W===z.id?u("meshGraph.obs.checking"):u("meshGraph.obs.heal")}),s.jsx("button",{type:"button",onClick:ce,"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=(ie==null?void 0:ie.health)??z.health;return he==="unknown"?s.jsx(Ve,{label:u("meshGraph.obs.connecting"),tone:"default"}):s.jsx(Ve,{label:he,tone:Um(he)})})(),z.branch&&s.jsx(Ve,{label:z.branch,tone:"default"}),z.ahead>0&&s.jsx(Ve,{label:`ahead ${z.ahead}`,tone:"warn"}),z.behind>0&&s.jsx(Ve,{label:`behind ${z.behind}`,tone:"warn"}),z.dirtyFiles>0&&s.jsx(Ve,{label:`${z.dirtyFiles} dirty`,tone:"warn"}),(ie==null?void 0:ie.connection)&&ie.connection.state!=="unknown"&&s.jsx(Ve,{label:KA(ie),tone:_A(ie.connection)}),((it=ie==null?void 0:ie.connection)==null?void 0:it.state)==="unknown"&&s.jsx(Ve,{label:u("meshGraph.obs.meshConnecting"),tone:"warn"}),me.length>0&&s.jsx(Ve,{label:`${me.length} sessions`,tone:"info"})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[z.machineLabel&&s.jsx(Pt,{label:u("meshGraph.obs.fieldMachine"),value:z.machineLabel}),z.locality&&z.locality!=="unknown"&&s.jsx(Pt,{label:u("meshGraph.obs.fieldLocality"),value:z.locality}),s.jsx(Pt,{label:u("meshGraph.obs.fieldWorkspace"),value:(ie==null?void 0:ie.workspace)??z.workspace}),Y&&s.jsx(Pt,{label:u("meshGraph.obs.fieldHead"),value:Y}),(z.dirtyFiles>0||z.ahead>0||z.behind>0)&&s.jsx(Pt,{label:u("meshGraph.obs.fieldDirtyAheadBehind"),value:`${z.dirtyFiles}/${z.ahead}/${z.behind}`}),me.length>0&&s.jsx(Pt,{label:u("meshGraph.obs.fieldSessions"),value:String(me.length)}),z.upstream&&s.jsx(Pt,{label:u("meshGraph.obs.fieldUpstream"),value:z.upstream}),(()=>{var $e;const he=(($e=ie==null?void 0:ie.connection)==null?void 0:$e.source)??VA(z);return he&&he!=="unknown"?s.jsx(Pt,{label:u("meshGraph.obs.fieldSource"),value:String(he)}):null})(),(()=>{var $e;const he=($e=ie==null?void 0:ie.connection)==null?void 0:$e.transport;return he&&he!=="unknown"?s.jsx(Pt,{label:u("meshGraph.obs.fieldTransport"),value:he}):null})(),(()=>{const he=z.machineId??(ie==null?void 0:ie.machineId);return he?s.jsx(Pt,{label:u("meshGraph.obs.fieldMachineId"),value:he}):null})(),(()=>{const he=z.daemonId??(ie==null?void 0:ie.daemonId);return he?s.jsx(Pt,{label:u("meshGraph.obs.fieldDaemonId"),value:he}):null})()]}),me.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:`mb-1.5 text-[10px] uppercase tracking-wide ${f.textMuted}`,children:u("meshGraph.obs.activeSessions")}),s.jsx("div",{className:"flex flex-col gap-1.5",children:me.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:Gm(he.session.sessionId)}),s.jsx(Ve,{label:Xr(he.session),tone:No(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||u("meshGraph.obs.providerUnknown")}),s.jsx("span",{children:LA(he.session)}),s.jsx("span",{children:EA(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:u("meshGraph.obs.ledger")}),s.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[s.jsx(Pt,{label:u("meshGraph.obs.fieldCompleted"),value:String(de.taskCompleted)}),s.jsx(Pt,{label:u("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:u("meshGraph.obs.fieldLaunched"),value:String(de.sessionLaunched)}),s.jsx(Pt,{label:u("meshGraph.obs.fieldRecentFailures"),value:s.jsx("span",{className:de.recentFailures>0?f.isDark?"text-amber-300":"text-amber-600":"",children:de.recentFailures})})]})]}),(()=>{var Be,Me;const he=((Be=h.queue)==null?void 0:Be.tasks)??((Me=h.queue)==null?void 0:Me.items)??null;if(!Array.isArray(he)||he.length===0)return null;const $e=he.filter(ve=>WA(ve)===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:u("meshGraph.obs.queueTasks")}),s.jsx("div",{className:"flex flex-col gap-1.5",children:$e.map(ve=>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:ve.id.slice(0,12)}),s.jsx(Ve,{label:ve.status??"unknown",tone:No(ve.status)})]}),ve.message&&s.jsx("div",{className:`mt-0.5 truncate ${f.textMuted}`,children:ve.message.slice(0,48)})]},ve.id))})]})})(),z.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:u("meshGraph.obs.keyWarning")}),s.jsx("div",{className:"mt-1",children:z.snapshotWarnings[0]})]}),z.branchConvergence&&(z.branchConvergence.reason||z.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:u("meshGraph.obs.followUpLabel",{status:g[z.branchConvergence.status]??z.branchConvergence.status})}),z.branchConvergence.reason&&s.jsx("div",{className:"mt-1",children:z.branchConvergence.reason}),z.branchConvergence.nextStep&&s.jsx("div",{className:`${z.branchConvergence.reason?"mt-1.5 pt-1.5 border-t border-sky-400/20":"mt-1"}`,children:z.branchConvergence.nextStep})]}),H&&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:H.phase==="execute"?u("meshGraph.obs.healResult"):u("meshGraph.obs.healPreview")}),s.jsx("div",{className:"mt-1",children:H.code??H.error??u("meshGraph.obs.noResultCode")})]})]}),ae&&(E==null?void 0:E.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:u("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:ae.label||pd(ae)}),s.jsx("div",{className:`mt-0.5 break-all font-mono text-[11px] ${f.textMuted}`,children:ae.id})]}),s.jsx("button",{type:"button",onClick:ce,"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:pd(ae),tone:"default"}),s.jsx(Ve,{label:YA(ae),tone:"info"})]}),s.jsxs("div",{className:"grid gap-1.5 text-xs",children:[s.jsx(Pt,{label:u("meshGraph.obs.fieldFrom"),value:(Ce==null?void 0:Ce.label)??ae.source}),s.jsx(Pt,{label:u("meshGraph.obs.fieldTo"),value:(ye==null?void 0:ye.label)??ae.target}),s.jsx(Pt,{label:u("meshGraph.obs.fieldLabel"),value:ae.label??"none"})]})]})]})]})})]})})}function Nt(e){return typeof e=="string"?e.trim():""}function gi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function ml(...e){const t=new Set;for(const n of e){const r=Nt(n);r&&t.add(r)}return[...t]}function oI(e,t){var m,f;const n=gi(e==null?void 0:e.settings),r=Nt((m=e==null?void 0:e.coordinator)==null?void 0:m.meshId)||Nt(n.meshCoordinatorFor),a=Nt(n.meshNodeFor),o=!!r||!!a,i=r===t||a===t;if(o&&!i)return null;const c=gi(e==null?void 0:e.activeChat),d=ml(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),p=d[0]||"";if(!p)return null;const u=r===t?Nt((f=e==null?void 0:e.coordinator)==null?void 0:f.role)||"coordinator":a===t?Nt(n.meshNodeRole)||"worker":Nt(e==null?void 0:e.role)||Nt(n.meshNodeRole)||void 0;return{sessionId:p,aliases:d,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,...u?{role:u}:{},...i?{isSelfCoordinator:r===t}:{},workspace:Nt(e==null?void 0:e.workspace)||null}}function zm(e,t){var r;return t?(Array.isArray((r=e.status)==null?void 0:r.sessions)?e.status.sessions:[]).map(a=>oI(a,t)).filter(a=>a!==null):[]}function va(e){return e.aliases&&e.aliases.length>0?e.aliases:[e.sessionId]}function iI(e,t){const n=new Set(va(t));return va(e).some(r=>n.has(r))}function lI(e,t){const n=t.filter(a=>!!a);return n.length===0?e:[...e.filter(a=>!n.some(o=>iI(a,o))),...n]}function cI(e,t){if(t.length===0)return e;const n=new Map;for(const i of t)for(const c of va(i))n.set(c,i);let r=!1;const o=(e.nodes??[]).map((i,c)=>{const d=Array.isArray(i.activeSessionDetails)?i.activeSessionDetails:Array.isArray(i.sessions)?i.sessions:[],p=new Map;for(const f of d){const g=ml(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),C=g[0]||"";if(!C)continue;const h=g.map(x=>n.get(x)).find(Boolean);h&&(r=!0),p.set(C,h?{...f,sessionId:C,providerType:h.providerType||f.providerType,state:h.state||f.state,chatStatus:h.chatStatus||f.chatStatus,lifecycle:h.lifecycle||f.lifecycle,surfaceKind:h.surfaceKind||f.surfaceKind,recoveryState:h.recoveryState||f.recoveryState,role:h.role||f.role,isSelfCoordinator:h.isSelfCoordinator??f.isSelfCoordinator,workspace:h.workspace||f.workspace}:{...f,sessionId:C})}for(const f of i.activeSessions??[])p.has(f)||p.set(f,{sessionId:f,workspace:i.workspace,isCached:!0});const u=c===0;for(const f of t){if(va(f).some(x=>p.has(x)))continue;const C=f.nodeId!=null&&f.nodeId===i.nodeId,h=f.isSelfCoordinator&&!f.nodeId&&u;!C&&!h||(r=!0,p.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=[...p.values()];return m.length===0?i:{...i,activeSessionDetails:m,activeSessions:m.map(f=>f.sessionId)}});return r?{...e,nodes:o}:e}function dI(e,t){const r=zm(e,t).map(a=>{var d;const o=(Array.isArray((d=e.status)==null?void 0:d.sessions)?e.status.sessions:[]).find(p=>Nt(p==null?void 0:p.id)===a.sessionId),i=gi(o==null?void 0:o.activeInteractivePrompt),c=o!=null&&o.meshQueueStats&&typeof o.meshQueueStats=="object"?JSON.stringify(o.meshQueueStats):"";return[a.sessionId,a.providerType??"",a.state??"",a.chatStatus??"",a.lifecycle??"",a.surfaceKind??"",a.recoveryState??"",Nt(i.status)||Nt(i.kind)||Nt(i.type),a.nodeId??"",a.isSelfCoordinator?"coordinator":"worker",c].join("|")}).filter(a=>!!a).sort();return r.length>0?r.join(`
89
+ `):null}function Km({status:e,daemonId:t,extraDaemonIds:n,meshId:r,sendData:a,extraLiveSessions:o=[]}){const[i,c]=l.useState(new Map),d=l.useRef(new Map),p=l.useMemo(()=>{const g=new Set;if(t&&g.add(t),n)for(const C of n)C&&g.add(C);return[...g].sort()},[t,n]),u=p.join(",");l.useEffect(()=>{d.current=new Map,c(new Map)},[t,r]),l.useEffect(()=>{if(!r||!a||p.length===0)return;const g=p.map(C=>ls.subscribe({sendData:a},C,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${C}`,params:{includeSessions:!0}},h=>{if(h.topic!=="daemon.metadata")return;const x=dI(h,r);if(x===(d.current.get(C)??null))return;d.current.set(C,x);const y=zm(h,r);c(b=>{const S=new Map(b);return S.set(C,y),S})}));return()=>{for(const C of g)C()}},[u,r,a]);const m=l.useMemo(()=>{const g=[];for(const C of i.values())g.push(...C);return g},[i]),f=l.useMemo(()=>lI(m,o),[o,m]);return l.useMemo(()=>e?cI(e,f):null,[f,e])}const md=[1500,4e3,9e3];function uI(e){var t,n,r,a,o,i;return!!(((t=e.git)==null?void 0:t.isGitRepo)===!0||(n=e.git)!=null&&n.branch||(r=e.git)!=null&&r.upstream||(a=e.git)!=null&&a.headCommit||(o=e.git)!=null&&o.workspace||(i=e.git)!=null&&i.repoRoot)}function pI(e){return!Array.isArray(e)||e.length===0?!1:e.some(t=>{var n;return uI(t)?!1:t.gitProbePending||((n=t.connection)==null?void 0:n.state)==="connecting"?!0:t.machineStatus==="online"||t.launchReady===!0})}function mI(e){return!Number.isInteger(e)||e<0?md[0]:md[e]??null}const Ao=new Map;function hI(e,t){return!e||!t?null:`${e}::${t}`}function fI(e,t){var o,i,c,d;if(!t||!e.sessionId)return null;const n=((o=e.coordinator)==null?void 0:o.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 a=typeof((d=e.settings)==null?void 0:d.meshNodeId)=="string"?e.settings.meshNodeId:null;return{sessionId:e.sessionId,aliases:ml(e.sessionId,e.providerSessionId,e.historySessionId,e.nativeSessionId),meshId:t,nodeId:a,providerType:e.agentType,state:e.status,chatStatus:e.status,role:n===t?"coordinator":"worker",isSelfCoordinator:n===t,workspace:e.workspacePath??null}}function Vm({activeConv:e,sendDaemonCommand:t,onClose:n}){var V,X,de,ne,O,ie;const r=((V=e.coordinator)==null?void 0:V.meshId)??(typeof((X=e.settings)==null?void 0:X.meshCoordinatorFor)=="string"?e.settings.meshCoordinatorFor:null),a=e.daemonId??null,o=hI(a,r),i=o?Ao.get(o)??null:null,{t:c}=Ne("common"),d=Bi(),{sendData:p}=vt(),{theme:u}=Ls(),m=l.useMemo(()=>Rs(u),[u]),[f,g]=l.useState("overview"),[C,h]=l.useState(!1),x=l.useMemo(()=>fI(e,r),[e.agentType,(de=e.coordinator)==null?void 0:de.meshId,e.sessionId,(ne=e.settings)==null?void 0:ne.meshCoordinatorFor,(O=e.settings)==null?void 0:O.meshNodeFor,(ie=e.settings)==null?void 0:ie.meshNodeId,e.status,e.workspacePath,r]),[y,b]=l.useState(i),[S,k]=l.useState(!1),[w,v]=l.useState(!1),[N,j]=l.useState(!1),[A,I]=l.useState(null),[D,L]=l.useState((i==null?void 0:i.refreshedAt)??null),P=l.useRef(i!==null),_=l.useRef(!1),q=l.useRef(!1),B=l.useRef(!0),E=l.useRef(0),K=l.useRef(null);l.useEffect(()=>{P.current=y!==null},[y]);const R=l.useCallback(()=>{K.current!==null&&(clearTimeout(K.current),K.current=null)},[]);l.useEffect(()=>{R(),E.current=0;const z=o?Ao.get(o)??null:null;b(z),L((z==null?void 0:z.refreshedAt)??null),P.current=z!==null,q.current=!1,v(!1),I(null)},[o,R]);const T=l.useCallback(async(z=!1,ae=!1)=>{if(!a||!r){I(c("meshGraph.dialog.errorNoMeshId")),b(null);return}if(_.current){z&&(q.current=!0);return}ae||(R(),E.current=0),_.current=!0;const Ce=!P.current;k(Ce),v(z&&P.current),I(null);try{const ye=d!=null&&d.loadMeshStatus?await d.loadMeshStatus(a,r,{refresh:z,retryProfile:ae?"interactive":"settled"}):await t(a,"mesh_status",{meshId:r,refresh:z}),ke=Oi(ye);if(!ke){I(c("meshGraph.dialog.errorUnexpectedPayload"));return}if(o&&Ao.set(o,ke),b(ke),P.current=!0,L(ke.refreshedAt||new Date().toISOString()),pI(ke.nodes)){const me=mI(E.current);me!==null&&B.current&&(E.current+=1,K.current=setTimeout(()=>{B.current&&T(!0,!0)},me))}else E.current=0}catch(ye){I(ye instanceof Error?ye.message:"Failed to load live mesh status")}finally{_.current=!1,k(!1),v(!1),q.current&&B.current&&(q.current=!1,window.setTimeout(()=>{B.current&&T(!0)},0))}},[o,R,a,r,d,t]);l.useEffect(()=>(B.current=!0,E.current=0,(async()=>(await T(!1,!0),B.current&&K.current===null&&!_.current&&T(!0,!0)))(),()=>{B.current=!1,R()}),[T,R]),l.useEffect(()=>{const z=ae=>{ae.key==="Escape"&&n()};return window.addEventListener("keydown",z),()=>window.removeEventListener("keydown",z)},[n]);const H=(y==null?void 0:y.meshName)||r||"Repo Mesh",M=l.useMemo(()=>x?[x]:[],[x]),W=Km({status:y,daemonId:a,meshId:r,sendData:p,extraLiveSessions:M}),J=D?new Date(D).toLocaleTimeString():null,re=l.useMemo(()=>c(S?"meshGraph.dialog.loadingStatus":"meshGraph.dialog.noGraph"),[S,c]);return s.jsx("div",{className:m.dialogOverlayClass,onClick:n,children:s.jsxs("div",{role:"dialog","aria-modal":"true",className:m.dialogShellClass,onClick:z=>z.stopPropagation(),children:[s.jsxs("div",{className:`relative ${m.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 ${m.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:m.dialogTitleClass,children:H}),s.jsx("span",{className:m.dialogKickerClass,children:c("meshGraph.dialog.kicker")}),s.jsx("button",{type:"button",onClick:()=>j(z=>!z),"aria-expanded":N,"aria-label":c(N?"meshGraph.dialog.hideDetails":"meshGraph.dialog.showDetails"),className:"btn btn-secondary btn-sm rounded-lg px-1.5 py-1 md:hidden",title:c(N?"meshGraph.dialog.hideDetails":"meshGraph.dialog.showDetails"),children:s.jsx(Ai,{size:14})})]}),s.jsxs("p",{className:`${m.dialogSubtitleClass} ${N?"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(qm,{meshTheme:m,activeTab:f,onActiveTabChange:g,helpOpen:C,onHelpOpenChange:h}),J&&s.jsx("span",{className:`${m.dialogRefreshedChipClass} ${N?"inline-flex":"hidden"} md:inline-flex`,children:c("meshGraph.dialog.refreshedAt",{time:J})}),!w&&y&&s.jsx("span",{className:`${m.dialogRefreshedChipClass} ${N?"inline-flex":"hidden"} md:inline-flex`,children:c(p&&!A?"meshGraph.dialog.liveMetadata":"meshGraph.dialog.metadataUnavailable")}),s.jsx("button",{type:"button",onClick:()=>{T(!0)},disabled:S||w,className:"btn btn-secondary btn-sm rounded-xl px-3.5",title:c("meshGraph.dialog.refreshTitle"),children:c(S||w?"meshGraph.dialog.refreshing":"meshGraph.dialog.refresh")})]})]}),A&&s.jsx("div",{className:m.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:A}),s.jsx("div",{className:m.dialogBodyClass,children:W?s.jsx(aI,{status:W,emptyMessage:re,daemonId:a,sendDaemonCommand:t,activeTab:f,onActiveTabChange:g,helpOpen:C,onHelpOpenChange:h,hideControls:!0}):s.jsx("div",{className:m.dialogEmptyClass,children:re})})]})})}function bI(e,t){const{sendCommand:n}=vt(),[r,a]=l.useState(null),[o,i]=l.useState(!1);l.useEffect(()=>{if(!e||!t){a(null);return}i(!0),n(e,"git_remote_url",{workspace:t}).then(d=>{const p=(d==null?void 0:d.result)??d;a(typeof(p==null?void 0:p.remoteUrl)=="string"?p.remoteUrl:null)}).catch(()=>{a(null)}).finally(()=>i(!1))},[e,t,n]);const c=gI(r);return{remoteUrl:r,githubUrl:c,loading:o}}function gI(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 Ym=5e3;function xI(e){return`git:${e}`}function vI({workspace:e,includeDiffSummary:t=!1,intervalMs:n=Ym}){return{type:"subscribe",topic:"workspace.git",key:xI(e),params:{workspace:e,includeDiffSummary:t,intervalMs:n}}}function hl(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 yI(e){const t=hl(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 wI(e){const t=hl(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 Io(e){return e===void 0||typeof e=="boolean"}function kI(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.path=="string"&&typeof t.diff=="string"&&Io(t.binary)&&Io(t.truncated)&&Io(t.staged)}function SI(e){const t=hl(e);return(t==null?void 0:t.success)===!1?{diff:null,error:Xs(t,"Git file diff request failed")}:kI(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 CI({daemonId:e,workspace:t,enabled:n=!0,includeDiffSummary:r=!1,intervalMs:a=Ym}){const{sendCommand:o,sendData:i}=vt(),c=typeof t=="string"?t.trim():"",d=!!(n&&e&&c),[p,u]=l.useState(null),[m,f]=l.useState(null),[g,C]=l.useState(!1),[h,x]=l.useState(null),y=l.useCallback(async()=>{if(!(!d||!e||!c)){C(!0),x(null);try{const S=yI(await o(e,"git_status",{workspace:c}));if(S.error){u(null),f(null),x(S.error);return}if(u(S.status),!r){f(null);return}const k=wI(await o(e,"git_diff_summary",{workspace:c}));if(k.error){f(null),x(k.error);return}f(k.diffSummary)}catch(S){x(Xs(S,"Git status request failed"))}finally{C(!1)}}},[d,e,r,o,c]),b=l.useMemo(()=>c?vI({workspace:c,includeDiffSummary:r,intervalMs:a}):null,[r,a,c]);return l.useEffect(()=>{if(!d||!e||!c||!b){u(null),f(null),C(!1),x(null);return}const S=i?ls.subscribe({sendData:i},e,b,k=>{var w,v;k.workspace===c&&(u(k.status),f(k.diffSummary??null),x(((w=k.status)==null?void 0:w.error)||((v=k.diffSummary)==null?void 0:v.error)||null),C(!1))},{retryIntervalMs:1e3}):null;return y(),()=>{S==null||S()}},[d,e,y,b,i,c]),{status:p,diffSummary:m,loading:g,error:h,refresh:y}}const jI={added:"A",modified:"M",deleted:"D",renamed:"R",copied:"C",untracked:"?",conflict:"!"},NI={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 hd(e){return e.split("/").pop()??e}function AI(e){const t=e.lastIndexOf("/");return t>0?e.slice(0,t):""}function II({files:e,truncated:t,onFileClick:n,selectedPath:r,className:a=""}){const{t:o}=Ne("common");return e.length===0?s.jsx("p",{className:"px-3 py-2 text-xs text-text-secondary",children:"No changed files."}):s.jsxs("div",{className:`flex flex-col ${a}`,children:[s.jsx("ul",{className:"min-w-0 divide-y divide-border/30",children:e.map(i=>{const c=r===i.path,d=jI[i.status]??"?",p=NI[i.status]??"text-text-muted",u=AI(i.path),m=hd(i.path),f=i.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 ${c?"bg-surface-elevated":""}`,onClick:()=>n==null?void 0:n(i),children:[s.jsx("span",{className:`w-3 shrink-0 font-mono font-bold ${p}`,title:i.status,children:d}),s.jsxs("span",{className:"min-w-0 flex-1 truncate",children:[u&&s.jsxs("span",{className:"text-text-secondary",children:[u,"/"]}),s.jsx("span",{className:"text-text-primary",children:m}),i.oldPath&&s.jsxs("span",{className:"ml-1 text-text-secondary",children:["← ",hd(i.oldPath)]}),f]}),!i.binary&&(i.insertions>0||i.deletions>0)&&s.jsxs("span",{className:"shrink-0 font-mono text-[10px]",children:[i.insertions>0&&s.jsxs("span",{className:"text-status-online",children:["+",i.insertions]}),i.insertions>0&&i.deletions>0&&s.jsx("span",{className:"text-text-secondary",children:" "}),i.deletions>0&&s.jsxs("span",{className:"text-status-error",children:["-",i.deletions]})]}),i.binary&&s.jsx("span",{className:"shrink-0 text-[10px] text-text-secondary",children:o("git.changeList.binaryBadge")})]},`${i.path}-${i.staged?"S":"U"}`)})}),t&&s.jsx("p",{className:"px-3 py-1.5 text-[10px] text-text-secondary",children:s.jsx(Bo,{i18nKey:"git.changeList.truncatedNote",ns:"common",components:{code:s.jsx("code",{className:"font-mono"})}})})]})}function TI(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 MI({diff:e,binary:t,truncated:n,loading:r,error:a,className:o=""}){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 ${o}`,children:"Loading diff…"});if(a)return s.jsx("div",{className:`px-3 py-4 text-xs text-status-error ${o}`,children:a});if(t)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"Binary file — diff not available."});if(!e)return s.jsx("div",{className:`px-3 py-4 text-xs text-text-secondary ${o}`,children:"No diff available."});const c=e.split(`
90
+ `);return s.jsxs("div",{ref:i,className:`overflow-auto ${o}`,children:[s.jsx("div",{className:"py-1",children:c.map((d,p)=>TI(d,p))}),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 DI(e,t){const n=[`Branch: ${e||"unknown"}`];n.push(`Changed: ${t.files.length} file(s) +${t.totalInsertions}/-${t.totalDeletions}`);const r={};for(const a of t.files)r[a.status]||(r[a.status]=[]),r[a.status].push(a.path);for(const[a,o]of Object.entries(r))n.push(`${a}: ${o.slice(0,5).join(", ")}${o.length>5?` (+${o.length-5} more)`:""}`);return n.join(`
91
+ `)}function Jm({daemonId:e,workspace:t,onClose:n}){const{t:r}=Ne("common"),{sendCommand:a}=vt(),{status:o,diffSummary:i,loading:c,error:d,refresh:p}=CI({daemonId:e,workspace:t,includeDiffSummary:!0}),[u,m]=l.useState(null),[f,g]=l.useState(null),[C,h]=l.useState(""),[x,y]=l.useState(!1),[b,S]=l.useState(!1),[k,w]=l.useState(null),[v,N]=l.useState(null),{githubUrl:j}=bI(e,t),A=l.useCallback(async q=>{if(!((u==null?void 0:u.path)===q.path&&!u.loading)){m({path:q.path,diff:"",binary:!1,truncated:!1,loading:!0,error:null});try{const B=await a(e,"git_diff_file",{workspace:t,path:q.path,staged:q.staged}),E=SI(B);if(E.error||!E.diff){m({path:q.path,diff:"",binary:!1,truncated:!1,loading:!1,error:E.error??"Failed to load diff"});return}m({path:q.path,diff:E.diff.diff,binary:E.diff.binary??!1,truncated:E.diff.truncated??!1,loading:!1,error:null})}catch(B){const E=B instanceof Error?B.message:"Failed to load diff";m({path:q.path,diff:"",binary:!1,truncated:!1,loading:!1,error:E})}}},[e,a,u,t]),I=l.useCallback(q=>{h(""),y(!1),w(null),N(null),g(q)},[]),D=l.useCallback(()=>{g(null),w(null),S(!1)},[]),L=l.useCallback(async()=>{var q,B,E;if(f){S(!0),w(null);try{let K;f==="checkpoint"?K=await a(e,"git_checkpoint",{workspace:t,message:C,includeUntracked:x}):f==="stash"?K=await a(e,"git_stash_push",{workspace:t,message:C,includeUntracked:x}):f==="stash_pop"?K=await a(e,"git_stash_pop",{workspace:t}):f==="checkout_files"&&u&&(K=await a(e,"git_checkout_files",{workspace:t,paths:[u.path]}));const R=(K==null?void 0:K.result)??K;if((R==null?void 0:R.success)===!1||R!=null&&R.error){w((R==null?void 0:R.error)??"Action failed"),S(!1);return}f==="checkpoint"?N(`Checkpoint created: ${((B=(q=R==null?void 0:R.checkpoint)==null?void 0:q.commit)==null?void 0:B.slice(0,7))??"done"}`):f==="stash"?N(`Stashed as ${((E=R==null?void 0:R.stash)==null?void 0:E.stashRef)??"stash@{0}"}`):f==="stash_pop"?N("Stash restored"):(N("File reverted"),m(null)),g(null),await p()}catch(K){w(K instanceof Error?K.message:"Action failed")}finally{S(!1)}}},[f,a,e,t,C,x,u,p]),P=!!(o!=null&&o.hasConflicts),_=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:q=>{q.target===q.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}),j&&s.jsx("a",{href:`${j}/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:p,disabled:c,className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40",title:"Refresh",children:"↺"}),s.jsx("button",{onClick: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:r("git.statusDialog.conflicts")}),_===0&&!o.error&&s.jsx("span",{className:"text-status-online",children:r("git.statusDialog.clean")}),i&&i.files.length>0&&s.jsxs("span",{className:"text-text-secondary",children:[i.files.length," file",i.files.length!==1?"s":"",i.totalInsertions>0&&s.jsxs("span",{className:"text-status-online",children:[" +",i.totalInsertions]}),i.totalDeletions>0&&s.jsxs("span",{className:"text-status-error",children:[" -",i.totalDeletions]})]})]}),d&&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:d}),s.jsxs("div",{className:"flex min-h-0 flex-1",children:[s.jsxs("div",{className:"flex w-56 shrink-0 flex-col overflow-y-auto border-r border-border/50",children:[c&&!i&&s.jsx("p",{className:"px-3 py-4 text-xs text-text-secondary",children:"Loading…"}),i&&s.jsx(II,{files:i.files,truncated:i.truncated,selectedPath:(u==null?void 0:u.path)??null,onFileClick:A}),!c&&!i&&!d&&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:u?s.jsx(MI,{diff:u.diff,binary:u.binary,truncated:u.truncated,loading:u.loading,error:u.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:()=>N(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:()=>I("checkpoint"),disabled:P,title:P?"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:()=>I("stash"),disabled:P,title:P?"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:()=>I("stash_pop"),disabled:P||!(o!=null&&o.stashCount),title:P?"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:()=>I("checkout_files"),disabled:!u,title:u?`Revert changes to ${u.path}`:"Select a file to revert",className:"rounded px-2 py-1 text-xs text-text-secondary hover:text-text-primary disabled:opacity-40 disabled:cursor-not-allowed border border-border/50 hover:border-border",children:"Checkout selected"}),i&&i.files.length>0&&s.jsx("button",{onClick:()=>{const q=DI((o==null?void 0:o.branch)??null,i);navigator.clipboard.writeText(q),N("Copied to clipboard"),setTimeout(()=>N(null),2e3)},className:"rounded border border-border px-2.5 py-1 text-xs text-text-secondary hover:text-text-primary",children:"Copy summary"})]}),f&&s.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-black/60",children:s.jsxs("div",{className:"flex w-80 flex-col gap-3 rounded-xl border border-border bg-surface p-4 shadow-xl",children:[s.jsxs("p",{className:"text-sm font-semibold text-text-primary",children:[f==="checkpoint"&&"Create checkpoint commit",f==="stash"&&"Stash changes",f==="stash_pop"&&"Restore latest stash?",f==="checkout_files"&&`Revert changes to ${(u==null?void 0:u.path)??"file"}?`]}),(f==="checkpoint"||f==="stash")&&s.jsxs(s.Fragment,{children:[s.jsx("input",{type:"text",value:C,onChange:q=>h(q.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:x,onChange:q=>y(q.target.checked)}),"Include untracked files"]})]}),k&&s.jsx("p",{className:"text-xs text-status-error",children:k}),s.jsxs("div",{className:"flex justify-end gap-2",children:[s.jsx("button",{onClick:D,disabled:b,className:"rounded px-3 py-1 text-xs text-text-secondary hover:text-text-primary border border-border/50 disabled:opacity-40",children:"Cancel"}),s.jsx("button",{onClick:L,disabled:b||(f==="checkpoint"||f==="stash")&&!C.trim(),className:"rounded px-3 py-1 text-xs text-text-primary bg-border hover:bg-border/80 disabled:opacity-40",children:b?"Working…":"Confirm"})]})]})})]})})}function PI({isMobile:e,showMobileChatMode:t,visibleConversationCount:n}){const[r,a]=l.useState(!1),[o,i]=l.useState(!1),[c,d]=l.useState(!1),[p,u]=l.useState(!1),[m,f]=l.useState(!1),[g,C]=l.useState("quickstart"),[h,x]=l.useState("workspace"),y=l.useMemo(()=>!t&&!e,[t,e]),b=l.useCallback(j=>{a(j),j&&i(!1)},[]),S=l.useCallback(j=>{i(j),j&&a(!1)},[]),k=l.useCallback(()=>{C(n===0?"quickstart":"shortcuts"),x("workspace"),d(!0),a(!1),i(!1)},[n]),w=l.useCallback(()=>{d(!1)},[]),v=l.useCallback(()=>{u(!0)},[]),N=l.useCallback(()=>{u(!1)},[]);return l.useEffect(()=>{if(!y){f(!1);return}f(!0);const j=window.setTimeout(()=>{f(!1)},1e4);return()=>window.clearTimeout(j)},[y]),{inboxOpen:r,hiddenOpen:o,shortcutHelpOpen:c,newSessionOpen:p,guideNudgeVisible:m,guideTab:g,shortcutSection:h,isDesktopDashboard:y,setGuideTab:C,setShortcutSection:x,handleInboxOpenChange:b,handleHiddenOpenChange:S,handleOpenShortcutHelp:k,closeShortcutHelp:w,openNewSession:v,closeNewSession:N}}function LI(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 RI(e){return e instanceof Error?e.message:String(e||"")}function EI(e){const t=RI(e).toLowerCase();return t.includes("button not found")||t.includes("not in approval state")||t.includes("command failed")}function _I({showMobileChatMode:e,isMobile:t,activeConv:n,wsStatus:r,isConnected:a,onOpenHistory:o,onOpenRemote:i,onStopCli:c,activeCliViewMode:d,onSetActiveCliViewMode:p,mobileChatConversations:u,hiddenConversations:m,ides:f,actionLogs:g,sendDaemonCommand:C,setActionLogs:h,setCliViewModeOverrides:x,isStandalone:y,initialDataLoaded:b,userName:S,requestedMobileTabKey:k,onRequestedMobileTabConsumed:w,requestedMachineId:v,onRequestedMachineConsumed:N,requestedMobileSection:j,onRequestedMobileSectionConsumed:A,containerRef:I,isSplitMode:D,numGroups:L,groupSizes:P,groupedConvs:_,clearedTabs:q,focusedGroup:B,focusGroup:E,moveTabToGroup:K,splitTabRelative:R,closeGroup:T,handleResizeStart:H,groupActiveTabIds:M,setGroupActiveTab:W,groupTabOrders:J,setGroupTabOrder:re,toggleHiddenTab:V,visibleConversations:X,requestedDesktopTabKey:de,onRequestedDesktopTabConsumed:ne,onDesktopActiveTabChange:O,onRequestScrollToBottom:ie,onHideConversation:z,onShowHiddenConversation:ae,onShowAllHiddenConversations:Ce,scrollToBottomRequest:ye,machineEntries:ke,layoutProfile:me,onBrowseMachineDirectory:G,onSaveMachineWorkspace:U,onLaunchMachineIde:Z,onLaunchMachineProvider:Y,onListMachineMeshes:fe,onLaunchMeshCoordinator:Te,onListMachineSavedSessions:ce,notifications:$,notificationUnreadCount:pe,liveSessionInboxState:le,onMarkNotificationRead:F,onMarkNotificationUnread:be,onDeleteNotification:je}){const Se=Rt.useRef(null),{inboxOpen:He,hiddenOpen:Xe,shortcutHelpOpen:dt,newSessionOpen:it,guideNudgeVisible:he,guideTab:$e,shortcutSection:Be,isDesktopDashboard:Me,setGuideTab:ve,setShortcutSection:We,handleInboxOpenChange:ut,handleHiddenOpenChange:ot,handleOpenShortcutHelp:pt,closeShortcutHelp:Q,openNewSession:ee,closeNewSession:oe}=PI({isMobile:t,showMobileChatMode:e,visibleConversationCount:X.length}),[ue,xe]=Rt.useState(null),[Ie,Le]=Rt.useState(null),Ae=Rt.useCallback((De,Qe)=>{xe({daemonId:De,workspace:Qe})},[]),Fe=Rt.useCallback(De=>{Le(De)},[]),qe=Rt.useCallback(De=>{var Qe;fn.flushSync(()=>{ae(De)}),(Qe=Se.current)==null||Qe.restoreHiddenTabToSavedLocation(De.tabKey)},[ae]),Ze=Rt.useCallback(De=>{var Dt;const Qe=u.find(Tt=>Qo(Tt,De))||m.find(Tt=>Qo(Tt,De));Qe&&(m.some(Tt=>Tt.tabKey===Qe.tabKey)&&qe(Qe),O(Qe.tabKey),(Dt=Se.current)==null||Dt.activateConversationTab(Qe.tabKey),ie(Qe.tabKey,"notification-open")),F(De.id),ut(!1)},[qe,m,u,O,F,ie]),_e=Rt.useCallback(()=>{var Qe;window.confirm("Move every floating or popout panel back into the main dashboard grid?")&&((Qe=Se.current)==null||Qe.resetAllPanelsToMain(),ot(!1))},[ot]),Ue=Rt.useCallback(async De=>{var Vt;if(!n)return;const Qe=(Vt=n.modalButtons)==null?void 0:Vt[De];if(!Qe)return;const Dt=Us(n);if(!Dt)return;const Tt=Qe.replace(/[⌥⏎⇧⌫⌘⌃↵]/g,"").trim().toLowerCase(),Kt=/^(run|approve|accept|yes|allow|always|proceed|save)/.test(Tt);try{await C(Dt,"resolve_action",{button:Qe,action:Kt?"approve":"reject",buttonIndex:De,...Ws(n)})}catch(Yt){EI(Yt)||console.error("[Shortcut approval] Failed:",Yt)}},[n,C]),{isMac:et,actionDefinitions:te,actionShortcuts:ge,shortcutListening:we,shortcutListeningDraft:ze,setShortcutListening:Oe,setShortcutListeningDraft:tt,saveShortcuts:Ke}=p1({enabled:Me&&!dt,onTrigger:De=>{var Qe,Dt,Tt,Kt,Vt,Yt,xs,Re,rt,jt,Wt,se,Ge,Ee,yt,Jt;if(De==="openShortcutHelp"){pt();return}if(De==="openNewSession"){ee();return}if(De==="hideCurrentTab"){n&&z(n);return}if(De==="toggleHiddenTabs"){ot(!Xe);return}if(De==="openHistoryForActiveTab"){n&&!lt(n)&&o(n);return}if(De==="openRemoteForActiveTab"){n&&!ct(n)&&!lt(n)&&i(n);return}if(De==="splitActiveTabRight"){(Qe=Se.current)==null||Qe.splitActiveTabRight();return}if(De==="splitActiveTabDown"){(Dt=Se.current)==null||Dt.splitActiveTabDown();return}if(De==="floatActiveTab"){(Tt=Se.current)==null||Tt.floatActiveTab();return}if(De==="popoutActiveTab"){(Kt=Se.current)==null||Kt.popoutActiveTab();return}if(De==="dockActiveTab"){(Vt=Se.current)==null||Vt.dockActiveTab();return}if(De==="focusLeftPane"){(Yt=Se.current)==null||Yt.focusLeftPane();return}if(De==="focusRightPane"){(xs=Se.current)==null||xs.focusRightPane();return}if(De==="focusUpPane"){(Re=Se.current)==null||Re.focusUpPane();return}if(De==="focusDownPane"){(rt=Se.current)==null||rt.focusDownPane();return}if(De==="moveActiveTabToLeftPane"){(jt=Se.current)==null||jt.moveActiveTabToLeftPane();return}if(De==="moveActiveTabToRightPane"){(Wt=Se.current)==null||Wt.moveActiveTabToRightPane();return}if(De==="moveActiveTabToUpPane"){(se=Se.current)==null||se.moveActiveTabToUpPane();return}if(De==="moveActiveTabToDownPane"){(Ge=Se.current)==null||Ge.moveActiveTabToDownPane();return}if(De==="triggerPrimaryApprovalAction"){Ue(0);return}if(De==="triggerSecondaryApprovalAction"){Ue(1);return}if(De==="triggerTertiaryApprovalAction"){Ue(2);return}if(De==="setActiveTabShortcut"){(Ee=Se.current)==null||Ee.setShortcutForActiveTab();return}if(De==="selectPreviousGroupTab"){(yt=Se.current)==null||yt.activatePreviousTabInGroup();return}if(De==="selectNextGroupTab"){(Jt=Se.current)==null||Jt.activateNextTabInGroup();return}!n||!ct(n)||lt(n)||De==="toggleCliView"&&p(d==="chat"?"terminal":"chat")}}),Ye=Rt.useCallback(()=>{Q(),Oe(null),tt([])},[Q,Oe,tt]),It=Rt.useMemo(()=>Be==="all"?te:te.filter(De=>LI(De)===Be),[te,Be]),Ot=Rt.useCallback(()=>{const De=Object.fromEntries(te.map(Qe=>[Qe.id,""]));Ke(De)},[te,Ke]),ss=Rt.useCallback(()=>{if(typeof window<"u"&&!window.confirm("Reset all dashboard shortcuts back to their default values?"))return;const De=Object.fromEntries(te.map(Qe=>[Qe.id,Qe.defaultShortcut]));Ke(De)},[te,Ke]);return Rt.useEffect(()=>{const De=Qe=>{(navigator.platform.toUpperCase().indexOf("MAC")>=0?Qe.metaKey&&Qe.key.toLowerCase()==="w":Qe.ctrlKey&&Qe.key.toLowerCase()==="w")&&(Qe.preventDefault(),n&&z&&z(n))};return window.addEventListener("keydown",De),()=>window.removeEventListener("keydown",De)},[n,z]),Rt.useEffect(()=>{if(!dt||we)return;const De=Qe=>{Qe.key==="Escape"&&(Qe.preventDefault(),Ye())};return window.addEventListener("keydown",De,!0),()=>window.removeEventListener("keydown",De,!0)},[Ye,dt,we]),s.jsxs(s.Fragment,{children:[!e&&s.jsx(Vk,{activeConv:n,wsStatus:r,isConnected:a,conversations:X,hiddenConversations:m,onOpenHistory:o,onHideConversation:z,onShowConversation:qe,onShowAllHidden:Ce,onResetPanelsToMain:_e,notifications:$,notificationUnreadCount:pe,onOpenNotification:Ze,onMarkNotificationRead:F,onMarkNotificationUnread:be,onDeleteNotification:je,inboxOpen:He,onInboxOpenChange:ut,hiddenOpen:Xe,onHiddenOpenChange:ot,onOpenNewSession:t?void 0:ee,onOpenDashboardGuide:pt,guideNudgeVisible:he,actionShortcuts:ge,onOpenRemote:()=>{!n||ct(n)||lt(n)||i(n)},onStopCli:c,activeCliViewMode:d,onSetCliViewMode:p,onOpenGitDialog:Ae,onOpenMeshGraph:Fe}),e?s.jsx(e1,{conversations:u,hiddenConversations:m,ides:f,actionLogs:g,sendDaemonCommand:C,setActionLogs:h,setCliViewModeOverrides:x,isStandalone:y,userName:S,requestedActiveTabKey:k,onRequestedActiveTabConsumed:w,requestedMachineId:v,onRequestedMachineConsumed:N,requestedMobileSection:j,onRequestedMobileSectionConsumed:A,onOpenHistory:o,onOpenRemote:i,onStopCli:c,wsStatus:r,isConnected:a,onShowAllHiddenConversations:Ce,onHideConversation:z,onOpenMeshGraph:Fe,onOpenNewSession:ee,liveSessionInboxState:le}):t?s.jsx(l1,{containerRef:I,isSplitMode:D,numGroups:L,groupSizes:P,groupedConvs:_,clearedTabs:q,ides:f,actionLogs:g,sendDaemonCommand:C,setActionLogs:h,isStandalone:y,hasRegisteredMachines:ke.length>0,userName:S,focusedGroup:B,focusGroup:E,moveTabToGroup:K,splitTabRelative:R,closeGroup:T,handleResizeStart:H,groupActiveTabIds:M,setGroupActiveTab:W,groupTabOrders:J,setGroupTabOrder:re,toggleHiddenTab:V,onOpenNewSession:ee,allowTabShortcuts:!1,liveSessionInboxState:le}):s.jsx(N1,{visibleConversations:X,clearedTabs:q,ides:f,actionLogs:g,sendDaemonCommand:C,setActionLogs:h,isStandalone:y,hasRegisteredMachines:ke.length>0,initialDataLoaded:b,userName:S,toggleHiddenTab:V,actionShortcuts:ge,registerActionHandlers:De=>{Se.current=De},onActiveTabChange:O,requestedActiveTabKey:de,onRequestedActiveTabConsumed:ne,onRequestScrollToBottom:ie,scrollToBottomRequest:ye,onOpenNewSession:ee,liveSessionInboxState:le,layoutProfile:me}),it&&s.jsx(_1,{machines:ke,ides:f,onClose:oe,onBrowseDirectory:G,onSaveWorkspace:U,onLaunchIde:Z,onLaunchProvider:Y,onListMeshes:fe,onLaunchMeshCoordinator:Te,onListSavedSessions:ce}),Ie&&s.jsx(Vm,{activeConv:Ie,sendDaemonCommand:C,onClose:()=>Le(null)}),ue&&s.jsx(Jm,{daemonId:ue.daemonId,workspace:ue.workspace,onClose:()=>xe(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:De=>De.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(De=>s.jsx("button",{type:"button",className:`btn btn-sm ${$e===De.id?"btn-primary":"btn-secondary"}`,onClick:()=>ve(De.id),children:De.label},De.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(De=>s.jsx("button",{type:"button",className:`btn btn-sm ${Be===De.id?"btn-primary":"btn-secondary"}`,onClick:()=>We(De.id),children:De.label},De.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ot,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:It.map(De=>s.jsx("div",{className:`rounded-xl border px-4 py-3 ${we===De.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:De.label}),s.jsx("div",{className:"text-xs text-text-secondary mt-1",children:De.description}),s.jsxs("div",{className:"text-[11px] text-text-muted mt-2",children:["Default: ",s.jsx("span",{className:"font-mono",children:De.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===De.id?ze.length>0?`${ze.join(" ")} ...`:"Listening...":ge[De.id]||"Off"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{Oe(De.id),tt([])},children:we===De.id?"Listening":"Set"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>{const Qe={...ge};Qe[De.id]="",Ke(Qe)},children:"Disable"})]})]})},De.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 $I=[{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:"🕸️"}],HI={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"},BI={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 FI({onClose:e,standalone:t=!1}){const[n,r]=l.useState(0),a=[...$I,t?BI:HI],o=a[n],i=n===a.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:a.map((c,d)=>s.jsx("div",{style:{width:d===n?24:8,height:8,borderRadius:4,background:d===n?"var(--accent, #7c3aed)":"var(--border-subtle, #444)",transition:"all 0.3s ease"}},d))}),s.jsx("div",{style:{textAlign:"center",fontSize:"3rem",marginBottom:"1rem"},children:o.visual||o.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:o.icon})," ",o.title]}),s.jsx("p",{style:{fontSize:"0.9rem",color:"var(--text-secondary)",lineHeight:1.6,marginBottom:"1.25rem"},children:o.desc}),o.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:"$"}),o.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 OI({hasExtensions:e,ideName:t,activeChatTab:n,extensionTabs:r,onSelectTab:a}){return e?s.jsxs("div",{className:"flex border-b border-border-subtle bg-surface-primary shrink-0",children:[s.jsx("button",{className:`flex-1 py-2.5 px-4 border-b-2 text-[11px] font-bold tracking-wide cursor-pointer transition-all font-[var(--font)] ${n==="native"?"text-text-primary border-accent-primary bg-bg-primary":"text-text-muted border-transparent bg-transparent hover:text-text-secondary"}`,onClick:()=>a("native"),children:t}),r.map(o=>{const i=n===o.tabKey,c=o.status==="waiting_approval",d=o.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:()=>a(o.tabKey),children:[s.jsx("span",{className:"shrink-0",style:{display:"inline-block",width:6,height:6,borderRadius:"50%",background:c?"var(--status-warning)":d?"var(--accent-primary)":"var(--text-muted)",boxShadow:d?"0 0 6px var(--accent-primary)":"none"}}),o.title,c&&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:"!"})]},o.tabKey)})]}):null}function WI({ideData:e,allIdes:t,connectionStates:n,ideName:r,preferredTabKey:a}){const[o,i]=l.useState(()=>a||"native"),c=l.useMemo(()=>yp(t),[t]),d=l.useMemo(()=>e?Vi(e,{machineNames:c,connectionStates:n,defaultConnectionState:"new"}):[],[e,c,n]),p=l.useMemo(()=>d.find(h=>h.streamSource==="native"),[d]),u=l.useMemo(()=>d.filter(h=>h.streamSource==="agent-stream"),[d]),m=l.useMemo(()=>e?cs(d,e.id):null,[d,e]);l.useEffect(()=>{a&&i(a)},[a]),l.useEffect(()=>{if(a||!m)return;const h=m.streamSource==="native"?"native":m.tabKey;!h||o===h||o==="native"&&i(h)},[o,m,a]),l.useEffect(()=>{var h;o!=="native"&&(u.some(x=>x.tabKey===o)||i(((h=u[0])==null?void 0:h.tabKey)||"native"))},[o,u]),l.useEffect(()=>{o==="native"&&(p||u[0]&&i(u[0].tabKey))},[o,p,u]);const f=l.useMemo(()=>o==="native"&&p?p:u.find(h=>h.tabKey===o)||m||p||u[0],[o,p,m,u]),g=l.useMemo(()=>u.map(h=>({tabKey:h.tabKey,title:cp(h)||r,status:h.status})),[u,r]),C=l.useCallback(h=>{if(h)return d.find(x=>Qo(x,{sessionId:h,routeId:h,tabKey:h,providerSessionId:h}))},[d]);return{activeChatTab:o,setActiveChatTab:i,activeConv:f,conversations:d,extensionTabs:g,hasExtensions:g.length>0,resolveConversationByTarget:C}}function UI({activeConv:e,ideEntry:t,ides:n,connectionStates:r,actionLogs:a,sendDaemonCommand:o,setActionLogs:i,isStandalone:c,userName:d,onOpenHistory:p,onConversationChange:u,onClose:m}){const{t:f}=Ne("common"),[g,C]=l.useState("split"),[h,x]=l.useState(()=>Ms(e)?"native":e.tabKey),y=l.useRef(null),b=l.useMemo(()=>t||n.find(K=>K.id===e.routeId),[e.routeId,t,n]),S=l.useMemo(()=>$t((b==null?void 0:b.type)||""),[b==null?void 0:b.type]),{conversations:k,extensionTabs:w,hasExtensions:v}=WI({ideData:b,allIdes:n,connectionStates:r,ideName:S||"IDE",preferredTabKey:Ms(e)?void 0:e.tabKey}),N=l.useMemo(()=>b?cs(k,b.id):null,[b,k]);l.useEffect(()=>{const K=y.current,R={routeId:e.routeId,tabKey:e.tabKey,streamSource:e.streamSource};if(y.current=R,!(K&&K.routeId===R.routeId&&K.tabKey===R.tabKey&&K.streamSource===R.streamSource)){if(Ms(e)){x("native");return}x(e.tabKey)}},[e.routeId,e.streamSource,e.tabKey]),l.useEffect(()=>{if(h==="native"){if(k.some(K=>K.streamSource==="native"))return;(N==null?void 0:N.streamSource)==="agent-stream"&&x(N.tabKey);return}if(!k.some(K=>K.tabKey===h)){if((N==null?void 0:N.streamSource)==="agent-stream"){x(N.tabKey);return}x("native")}},[k,h,N]);const j=l.useMemo(()=>h==="native"?k.find(K=>K.streamSource==="native")||e:k.find(K=>K.tabKey===h)||e,[e,k,h]),A=Lp(j),I=l.useMemo(()=>A.status||A.modalMessage||A.modalButtons?{...j,...A.status?{status:A.status}:{},...A.modalMessage!==void 0?{modalMessage:A.modalMessage}:{},...A.modalButtons!==void 0?{modalButtons:A.modalButtons}:{}}:j,[j,A]),D=en(I),L=Da({sendDaemonCommand:o,activeConv:I,setActionLogs:i,isStandalone:c}),{connScreenshot:P,screenshotUsage:_,handleRemoteAction:q}=um({doId:D,targetSessionId:Fu(I),connState:I.connectionState||"new",viewMode:g}),B=l.useMemo(()=>a.filter(K=>K.routeId===I.tabKey),[a,I.tabKey]);l.useEffect(()=>{u==null||u(I)},[I,u]),l.useEffect(()=>{const K=R=>{R.key==="Escape"&&m()};return window.addEventListener("keydown",K),()=>window.removeEventListener("keydown",K)},[m]);const E=l.useCallback(K=>{K.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:E,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(j)||"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(K=>{const R=g===K;return s.jsx("button",{className:`w-9 h-9 rounded-lg flex items-center justify-center transition-all ${R?"bg-accent-primary/12 border border-accent-primary/35 text-accent-primary shadow-glow":"bg-bg-secondary border border-border-subtle text-text-secondary hover:bg-bg-glass hover:text-text-primary"}`,onClick:()=>C(K),title:K==="split"?"Split view":"Remote only",children:K==="split"?s.jsx($f,{size:15}):s.jsx(us,{size:15})},K)})}),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:()=>p(j),title:"Chat History",children:[s.jsx(Ii,{size:14,className:"md:mr-1.5"}),s.jsx("span",{className:"hidden md:inline",children:f("dashboard.remoteDialog.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 ${g==="split"?"grid-cols-1 grid-rows-[1fr_minmax(320px,42vh)] md:grid-cols-[minmax(360px,0.92fr)_minmax(420px,1.08fr)] md:grid-rows-1":"grid-cols-1 grid-rows-1"}`,children:[g!=="remote"&&s.jsxs("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${g==="split"?"order-2 md:order-1 border-b md:border-b-0 md:border-r border-border-subtle":""}`,children:[s.jsx(OI,{hasExtensions:v,ideName:S||"IDE",activeChatTab:h,extensionTabs:w,onSelectTab:x}),s.jsx(mu,{activeConv:I,onModalButton:L.handleModalButton}),s.jsx(ai,{activeConv:I,ideEntry:b,showMetaChips:!1,handleSendChat:L.handleSendChat,handleForceSendChat:L.handleForceSendChat,isSendingChat:L.isSendingChat,sendFeedbackMessage:L.sendFeedbackMessage,handleFocusAgent:L.handleFocusAgent,isFocusingAgent:L.isFocusingAgent,actionLogs:B,userName:d})]}),s.jsx("div",{className:`flex flex-col min-w-0 min-h-0 bg-bg-primary ${g==="split"?"order-1 md:order-2":""}`,children:s.jsx(lu,{addLog:()=>{},connState:I.connectionState||"new",connScreenshot:P,screenshotUsage:_,transportType:I.transport,onAction:q})})]})]})})}function GI({activeConv:e,canSaveAndStop:t=!1,onCancel:n,onStopNow:r,onSaveAndStop:a}){const{t:o}=Ne(),i=Ak(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:o("cliStop.title",{agent:i})}),s.jsx("div",{className:"mt-1 text-[13px] md:text-sm text-text-muted leading-relaxed",children:o(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:a,className:"btn btn-primary w-full justify-center min-h-[42px]",children:o("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:o("cliStop.forceStop")}),s.jsx("button",{onClick:n,className:"btn btn-secondary w-full justify-center min-h-[42px]",children:o("common.cancel")})]})]})]})}function qI({historyModal:e,remoteDialog:t,cliStopDialog:n,connectionBanner:r,toastOverlay:a,onboarding:o,interactivePrompt:i}){var c;return s.jsxs(s.Fragment,{children:[s.jsx(Wk,{wsStatus:r.wsStatus,showReconnected:r.showReconnected,loginUrl:r.loginUrl,onReconnect:r.onReconnect}),e.open&&e.targetConv&&s.jsx(gp,{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(UI,{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(GI,{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(xp,{toasts:a.toasts,onDismiss:a.onDismiss,onClickToast:a.onClick}),s.jsx(du,{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)??(()=>{})}),o.open&&s.jsx(FI,{onClose:o.onClose,standalone:o.standalone})]})}function zI({daemons:e,targetVersion:t,required:n=!1,upgradingDaemons:r,onUpgrade:a,onDismiss:o}){const{t:i}=Ne("common");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(Sa,{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(c=>{const d=ts(c,{fallbackId:c.id}),p=r[c.id],u=c.version||c.daemonVersion||"unknown",m=c.versionUpdateRequired===!0,g=Up(c)==="preview"?"Update to preview":m?"Update now":"Upgrade";return s.jsxs("span",{className:"inline-flex items-center gap-1.5 px-2 py-0.5 rounded-md",style:{background:m?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 8%, transparent)",border:`1px solid ${m?"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:d}),s.jsxs("span",{className:"text-[10px] text-text-muted",children:["v",u]}),m&&s.jsx("span",{className:"text-[10px]",style:{color:"var(--status-danger)"},children:i("dashboard.versionBanner.required")}),p==="upgrading"?s.jsx("span",{className:"text-[10px] animate-pulse",style:{color:m?"var(--status-danger)":"var(--status-warning)"},children:"upgrading…"}):p==="done"?s.jsx("span",{className:"text-[10px] text-green-400",children:"✓ restarting"}):p==="error"?s.jsx("button",{className:"text-[10px] text-red-400 hover:text-red-300 underline cursor-pointer",onClick:()=>a(c.id),children:i("dashboard.versionBanner.retry")}):s.jsx("button",{className:"text-[10px] font-semibold cursor-pointer px-1.5 py-px rounded transition-colors",style:{color:m?"var(--status-danger)":"var(--status-warning)",background:m?"color-mix(in srgb, var(--status-danger) 10%, transparent)":"color-mix(in srgb, var(--status-warning) 10%, transparent)",border:`1px solid ${m?"color-mix(in srgb, var(--status-danger) 20%, transparent)":"color-mix(in srgb, var(--status-warning) 20%, transparent)"}`},onClick:()=>a(c.id),children:g})]},c.id)})]}),!n&&s.jsx("button",{className:"text-text-muted hover:text-text-primary transition-colors shrink-0",onClick:o,title:"Dismiss",children:s.jsx(At,{size:16})})]})}function KI(e){return e.isMobile&&e.mobileViewMode==="chat"?{recentActivityMs:0}:void 0}function VI(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 YI(e){return{metadataDaemonIds:e.map(t=>t.id),runtimeDaemonIds:e.filter(t=>VI(t)).map(t=>t.id)}}function JI(){var yl,wl,kl,Sl;const{sendCommand:e}=vt(),t=Tn(),n=Pp(),r=Si(),a=mr(),[o,i]=Oh(),c=o.get("activeTab"),d=((yl=r.state)==null?void 0:yl.openRemoteForTabKey)||null,p=((wl=r.state)==null?void 0:wl.openMachineId)||null,u=((kl=r.state)==null?void 0:kl.mobileSection)||null,m=rp(),f=m.ides||[],g=m.initialLoaded??!0,{updateRouteChats:C,setToasts:h}=m,[x,y]=l.useState(()=>{try{return!localStorage.getItem("adhdev_onboarding_v1")}catch{return!1}}),b=m.toasts||[],S=m.wsStatus||"connected",k=m.isConnected??!0,w=m.connectionStates||{},v=m.showReconnected||!1,{layoutProfile:N,groupAssignments:j,updateGroupAssignments:A,focusedGroup:I,updateFocusedGroup:D,focusGroup:L,groupActiveTabIds:P,updateGroupActiveTabIds:_,setGroupActiveTab:q,groupTabOrders:B,updateGroupTabOrders:E,setGroupTabOrder:K,groupSizes:R,updateGroupSizes:T,isMobile:H,hasHydratedStoredLayout:M,hydrateStoredLayout:W,focusConversationTab:J}=YC(),[re,V]=l.useState(()=>Xi());l.useEffect(()=>nC(V),[]);const X=l.useMemo(()=>KI({isMobile:H,mobileViewMode:re}),[H,re]),[de,ne]=l.useState([]),[O,ie]=l.useState({}),[z,ae]=l.useState({});hr("Dashboard",{ideCount:f.length,toastCount:b.length,focusedGroup:I,groupCount:Object.keys(j).length,actionLogCount:de.length});const Ce=l.useMemo(()=>f.filter(at=>at.type==="adhdev-daemon").sort(_i),[f]),ke=!!Ce[0];l.useEffect(()=>{const{metadataDaemonIds:at,runtimeDaemonIds:Ut}=YI(Ce);for(const Dn of at)t(Dn,{minFreshMs:3e4}).catch(()=>{});for(const Dn of Ut)n(Dn,{minFreshMs:3e4}).catch(()=>{})},[t,n,Ce]);const me=l.useMemo(()=>wC(f,O),[f,O]),{conversations:G,visibleConversations:U,visibleTabKeys:Z,resolveConversationBySessionId:Y,resolveConversationByTarget:fe}=RC({ides:me,connectionStates:w,clearedTabs:z}),Te=l.useMemo(()=>new Map(G.map(at=>[at.tabKey,at])),[G]);Z0(U,X);const ce=l.useMemo(()=>pu(f),[f]),$=sm(ce,e,l.useCallback(at=>on(h,`⚠️ ${at}`),[h])),{notifications:pe,unreadCount:le}=uj({conversations:G,liveSessionInboxState:ce}),{handleMarkDashboardNotificationRead:F,handleMarkDashboardNotificationUnread:be,handleDeleteDashboardNotification:je}=pj({notifications:pe,sendDaemonCommand:e}),{containerRef:Se,normalizedGroupAssignments:He,numGroups:Xe,isSplitMode:dt,groupedConvs:it,moveTabToGroup:he,closeGroup:$e,handleResizeStart:Be,splitTabRelative:Me}=sj({groupAssignments:j,updateGroupAssignments:A,updateFocusedGroup:D,updateGroupActiveTabIds:_,updateGroupTabOrders:E,groupSizes:R,updateGroupSizes:T,isMobile:H,visibleConversations:U,visibleTabKeys:Z}),{activeConv:ve,openDesktopConversation:We,requestScrollToBottom:ut,scrollToBottomRequest:ot,setDesktopActiveTab:pt}=Cj({isMobile:H,conversations:G,visibleConversations:U,groupActiveTabIds:P,focusedGroup:I,groupedConvs:it,setSearchParams:i});Aj({activeConv:ve,isMobile:H,liveSessionInboxState:ce,sendDaemonCommand:e});const{requestedDesktopTabKey:Q,requestedMobileTabKey:ee,consumeRequestedActiveTab:oe}=EC({isMobile:H,urlActiveTab:c,resolveConversationBySessionId:Y,setSearchParams:i}),{remoteDialogConv:ue,remoteDialogIdeEntry:xe,remoteDialogActiveConv:Ie,setRemoteDialogActiveConv:Le,openRemoteDialog:Ae,closeRemoteDialog:Fe,cliStopDialogOpen:qe,cliStopTargetConv:Ze,requestCliStop:_e,cancelCliStop:Ue,confirmCliStop:et}=Mj({isMobile:H,location:r,navigate:a,requestedRemoteTabTarget:d,requestedDesktopTabKey:Q,conversations:G,ides:f,resolveConversationByTarget:fe,activeConv:ve,sendDaemonCommand:e}),{historyModalOpen:te,openHistoryModal:ge,closeHistoryModal:we,historyTargetConv:ze,isSavedSessionHistoryTarget:Oe,isHistoryCreatingChat:tt,isHistoryRefreshingHistory:Ke,handleHistorySwitchSession:Ye,handleHistoryNewChat:It,handleHistoryRefresh:Ot,savedHistorySessions:ss,savedHistoryFilters:De,setSavedHistoryFilters:Qe,missingWorkspaceResumePath:Dt,isSavedHistoryLoading:Tt,resumingSavedHistorySessionId:Kt,handleRefreshSavedHistory:Vt,handleResumeSavedHistorySession:Yt}=Ij({activeConv:ve,remoteDialogConv:ue,remoteDialogActiveConv:Ie,ides:f,sendDaemonCommand:e,updateRouteChats:C,setToasts:h,setClearedTabs:ae,setSearchParams:i}),xs=l.useMemo(()=>U,[U]),Re=H&&re==="chat",rt=l.useMemo(()=>G.filter(at=>Ds(at,ce).surfaceHidden),[G,ce]),jt=l.useCallback(at=>{const Ut=new URLSearchParams(o);Ut.set("activeTab",at),i(Ut,{replace:!0})},[o,i]),{trackPendingLaunch:Wt}=yj({ides:f,conversations:G,onOpenSession:jt}),{handleBrowseMachineDirectory:se,handleSaveMachineWorkspace:Ge,handleLaunchMachineIde:Ee,handleLaunchMachineProvider:yt,handleListMachineMeshes:Jt,handleLaunchMeshCoordinator:Mn,handleListMachineSavedSessions:Oa,setActiveCliViewMode:vs}=wj({sendDaemonCommand:e,trackPendingLaunch:Wt,onOpenSession:jt,activeConv:ve,ides:f,setCliViewModeOverrides:ie});SC({visibleConversations:U,clearedTabs:z,setClearedTabs:ae,setActionLogs:ne,isConversationMuted:$.isMuted}),_C({ides:f,sendDaemonCommand:e,setToasts:h,resolveConversationByTarget:fe});const ah=Rp(),{isRefreshingHistory:oh,handleRefreshHistory:ih}=Wp({sendDaemonCommand:e,activeConv:ve,chats:(Sl=f.find(at=>at.id===(ve==null?void 0:ve.routeId)))==null?void 0:Sl.chats,updateRouteChats:C,setToasts:h,setClearedTabs:ae});QC({urlActiveTab:H&&!Re?c:null,conversations:G,resolveConversationBySessionId:Y,normalizedGroupAssignments:He,hasHydratedStoredLayout:H&&!Re?M:!0,hydrateStoredLayout:H&&!Re?W:()=>{},focusConversationTab:J,setSearchParams:i,historyModalOpen:te,activeConv:ve,isRefreshingHistory:oh,ides:f,handleRefreshHistory:ih});const lh=l.useMemo(()=>!ve||!ct(ve)||lt(ve)?null:In(ve),[ve]),{versionMismatchDaemons:ch,hasRequiredVersionDaemons:xl,targetVersion:dh,versionBannerDismissed:uh,setVersionBannerDismissed:ph,upgradingDaemons:mh,handleBannerUpgrade:hh}=rj({ides:f,sendDaemonCommand:e}),vl=l.useCallback(at=>{$.setHidden(at,!1),We(at)},[We,$]),fh=l.useCallback(()=>{for(const at of rt)$.setHidden(at,!1)},[rt,$]),bh=l.useCallback(at=>{$.setHidden(at,!0)},[$]),gh=l.useCallback(at=>{$.toggleHidden(at)},[$]);return s.jsxs("div",{className:"page-dashboard flex-1 min-h-0 bg-bg-primary text-text-primary flex flex-col overflow-hidden",children:[(!uh||xl)&&s.jsx(zI,{daemons:ch,targetVersion:dh,required:xl,upgradingDaemons:mh,onUpgrade:hh,onDismiss:()=>ph(!0)}),s.jsx(_I,{showMobileChatMode:Re,isMobile:H,activeConv:ve,wsStatus:S,isConnected:k,onOpenHistory:at=>{at&&Le(at),ge()},onOpenRemote:Ae,onStopCli:_e,activeCliViewMode:lh,onSetActiveCliViewMode:vs,mobileChatConversations:xs,ides:f,actionLogs:de,sendDaemonCommand:e,setActionLogs:ne,setCliViewModeOverrides:ie,isStandalone:ke,initialDataLoaded:g,userName:m.userName,requestedMobileTabKey:ee,onRequestedMobileTabConsumed:oe,requestedMachineId:p,onRequestedMachineConsumed:()=>{a(r.pathname+r.search,{replace:!0,state:null})},requestedMobileSection:u,onRequestedMobileSectionConsumed:()=>{a(r.pathname+r.search,{replace:!0,state:null})},containerRef:Se,isSplitMode:dt,numGroups:Xe,groupSizes:R,groupedConvs:it,clearedTabs:z,focusedGroup:I,focusGroup:L,moveTabToGroup:he,splitTabRelative:Me,closeGroup:$e,handleResizeStart:Be,groupActiveTabIds:P,setGroupActiveTab:q,groupTabOrders:B,setGroupTabOrder:K,toggleHiddenTab:at=>{const Ut=Te.get(at);Ut&&gh(Ut)},visibleConversations:U,hiddenConversations:rt,requestedDesktopTabKey:Q,onRequestedDesktopTabConsumed:oe,onDesktopActiveTabChange:pt,onRequestScrollToBottom:ut,onHideConversation:bh,onShowHiddenConversation:vl,onShowAllHiddenConversations:fh,scrollToBottomRequest:ot,machineEntries:Ce,layoutProfile:N,onBrowseMachineDirectory:se,onSaveMachineWorkspace:Ge,onLaunchMachineIde:Ee,onLaunchMachineProvider:yt,onListMachineMeshes:Jt,onLaunchMeshCoordinator:Mn,onListMachineSavedSessions:Oa,notifications:pe,notificationUnreadCount:le,liveSessionInboxState:ce,onMarkNotificationRead:F,onMarkNotificationUnread:be,onDeleteNotification:je}),s.jsx("style",{children:`
95
+ body { overflow: hidden; overscroll-behavior: none; }
96
+ `}),s.jsx(qI,{historyModal:{open:te,targetConv:ze,ides:f,isCreatingChat:tt,isRefreshingHistory:Oe?!1:Ke,savedSessions:ss,savedHistoryFilters:De,missingWorkspaceResumePath:Dt||null,onSavedHistoryFiltersChange:Qe,isSavedSessionsLoading:Tt,isResumingSavedSessionId:Kt,onClose:we,onNewChat:It,onSwitchSession:Ye,onRefreshHistory:Oe?Vt:Ot,onResumeSavedSession:Yt},remoteDialog:{conversation:ue,ideEntry:xe,ides:f,connectionStates:w,actionLogs:de,sendDaemonCommand:e,setActionLogs:ne,isStandalone:ke,userName:m.userName,onOpenHistory:at=>{at&&Le(at),ge()},onConversationChange:Le,onClose:Fe},cliStopDialog:{open:qe,targetConv:Ze,onCancel:Ue,onStopNow:async()=>{await et("hard")},onSaveAndStop:async()=>{await et("save")}},connectionBanner:{wsStatus:S,showReconnected:v,loginUrl:m.connectionLoginUrl,onReconnect:m.retryServerConnection},toastOverlay:{toasts:b,onDismiss:at=>h(Ut=>Ut.filter(Dn=>Dn.id!==at)),onClick:at=>{if(at.targetKey){const Ut=fe(at.targetKey);Ut&&(J(Ut.tabKey,He),vl(Ut),ut(Ut.tabKey,"toast-open"))}}},onboarding:{open:x,standalone:ke,onClose:()=>{try{localStorage.setItem("adhdev_onboarding_v1","done")}catch{}y(!1)}},interactivePrompt:ah})]})}function QI({machineId:e,registeredMachineId:t,sendDaemonCommand:n,onNicknameSynced:r,logsEndRef:a}){const{launchCli:o}=wa(),[i,c]=l.useState([]),[d,p]=l.useState(null),[u,m]=l.useState(null),[f,g]=l.useState(!1),[C,h]=l.useState(null),[x,y]=l.useState(!1),[b,S]=l.useState(""),k=l.useRef(null),w=l.useCallback(T=>{k.current=T},[]),v=l.useCallback((T,H,M=!1)=>{c(W=>[...W.slice(-100),{timestamp:Date.now(),level:T,message:H}]),setTimeout(()=>{var W;return(W=a.current)==null?void 0:W.scrollIntoView({behavior:"smooth"})},100),M&&mt.showToast(H,T==="error"||T==="warn"?"warning":"success")},[a]),N=l.useCallback(T=>{const H=T instanceof Error?T.message:String(T||"");return H.includes("P2P command timeout")||H.includes("P2P not connected")||H.includes("P2P not available")},[]),j=l.useCallback(async(T,H)=>{var M;if(!e||d)return!1;p(T),v("info",`Launching ${$t(T)}${H!=null&&H.workspace?` in ${H.workspace}`:""}...`);try{const W={ideType:T,enableCdp:!0};(M=H==null?void 0:H.workspace)!=null&&M.trim()?W.workspace=H.workspace.trim():H!=null&&H.useDefaultWorkspace&&(W.useDefaultWorkspace=!0);const J=await n(e,"launch_ide",W);return v(J!=null&&J.success?"info":"error",J!=null&&J.success?`${$t(T)} launched`:`Failed: ${J==null?void 0:J.error}`,!0),!!(J!=null&&J.success)}catch(W){return v("error",`Launch error: ${W.message}`,!0),!1}finally{p(null)}},[e,d,v,n]),A=l.useCallback(async T=>{if(!e)return{success:!1};const{cliType:H,dir:M,workspaceId:W,useDefaultWorkspace:J,useHome:re,argsStr:V,model:X,resumeSessionId:de}=T;if(!H)return v("warn","Select a CLI or ACP provider first",!0),{success:!1};const ne=V?V.split(/\s+/).filter(Boolean):void 0,O=(M==null?void 0:M.trim())||(W?"(saved id)":J?"(default workspace)":re?"(home)":"");v("info",`Launching ${H}${O?` in ${O}`:""}${X?` (model: ${X})`:""}...`),m(H);try{const ie={cliType:H,cliArgs:ne,initialModel:X||void 0};M!=null&&M.trim()?ie.dir=M.trim():W?ie.workspaceId=W:J?ie.useDefaultWorkspace=!0:re&&(ie.useHome=!0),de&&(ie.resumeSessionId=de);const z=await o(e,ie),ae=(z==null?void 0:z.result)||z;return z!=null&&z.success?(v("info",`${H} launched`,!0),(ae==null?void 0:ae.launchSource)==="home"?v("info","📂 Running in home directory (explicit choice)"):(ae==null?void 0:ae.launchSource)==="defaultWorkspace"&&v("info","📂 Using default workspace (explicit choice)"),{success:!0,sessionId:ae==null?void 0:ae.sessionId}):(v("error",`Failed: ${(z==null?void 0:z.error)||(ae==null?void 0:ae.error)}`,!0),(z==null?void 0:z.code)==="WORKSPACE_LAUNCH_CONTEXT_REQUIRED"&&h({cliType:H,argsStr:V,model:X}),{success:!1,sessionId:ae==null?void 0:ae.sessionId})}catch(ie){return N(ie)?(v("warn",`${H} launch requested — waiting for session to appear...`,!0),{success:!1,pending:!0}):(v("error",`Launch error: ${ie.message}`,!0),{success:!1})}finally{m(null)}},[e,v,N,n]),I=l.useCallback(async(T,H,M,W)=>e?T?H.trim()?A({cliType:T,dir:H,argsStr:M,model:W}):(h({cliType:T,argsStr:M,model:W}),{success:!1}):(v("warn","Select a provider",!0),{success:!1}):{success:!1},[e,v,A]),D=l.useCallback(async(T,H,M)=>{if(e&&window.confirm(`Stop ${T}?
97
+ This will terminate the process.`))try{const W=await n(e,"stop_cli",{cliType:T,dir:H,targetSessionId:M});W!=null&&W.success?v("info",`${T} stopped`,!0):v("error",`Stop failed: ${(W==null?void 0:W.error)||"Unknown error"}`,!0)}catch(W){v("error",`Stop failed: ${W.message}`,!0)}},[e,v,n]),L=l.useCallback(async T=>{try{await n(T.daemonId,"restart_ide",{ideType:T.type}),v("info",`${$t(T.type)} restart initiated`,!0)}catch(H){v("error",`Restart failed: ${H.message}`,!0)}},[v,n]),P=l.useCallback(async T=>{if(window.confirm(`Stop ${$t(T.type)}?
98
+ This will disconnect CDP and optionally kill the process.`))try{const H=await n(T.daemonId,"stop_ide",{ideType:T.type,killProcess:!0});H!=null&&H.success?v("info",`${$t(T.type)} stopped`,!0):v("error",`Stop failed: ${(H==null?void 0:H.error)||"Unknown error"}`,!0)}catch(H){v("error",`Stop failed: ${H.message}`,!0)}},[v,n]),_=l.useCallback(async()=>{if(e)try{const T=await n(e,"detect_ides",{});v("info",`Found ${((T==null?void 0:T.result)||[]).length} IDE(s)`,!0)}catch(T){v("error",`Detection failed: ${T.message}`,!0)}},[e,v,n]),q=l.useCallback(async T=>{if(!e||!T.trim())return!1;g(!0);try{const H=await n(e,"workspace_add",{path:T.trim()});return H!=null&&H.success?(v("info",`Workspace added: ${T.trim()}`),!0):(v("error",(H==null?void 0:H.error)||"workspace_add failed"),!1)}catch(H){return v("error",H.message),!1}finally{g(!1)}},[e,v,n]),B=l.useCallback(async T=>{if(!(!e||!window.confirm("Remove this workspace from the list?"))){g(!0);try{const H=await n(e,"workspace_remove",{id:T});H!=null&&H.success?v("info","Workspace removed",!0):v("error",(H==null?void 0:H.error)||"workspace_remove failed",!0)}catch(H){v("error",H.message,!0)}finally{g(!1)}}},[e,v,n]),E=l.useCallback(async T=>{var H;if(e){g(!0);try{const M=await n(e,"workspace_set_default",T===null?{clear:!0}:{id:T});if(M!=null&&M.success){v("info",T?"Default workspace updated":"Default workspace cleared",!0);const W=typeof M.defaultWorkspacePath=="string"?M.defaultWorkspacePath:"";W&&((H=k.current)==null||H.call(k,W))}else v("error",(M==null?void 0:M.error)||"workspace_set_default failed",!0)}catch(M){v("error",M.message,!0)}finally{g(!1)}}},[e,v,n]),K=l.useCallback(async T=>{var M;if(!e||!T.trim())return;const H=T.trim();g(!0);try{const W=await n(e,"workspace_set_default",{path:H});W!=null&&W.success?(v("info","Default workspace set from history"),(M=k.current)==null||M.call(k,H)):v("error",(W==null?void 0:W.error)||"Could not set default (path missing on disk?)")}catch(W){v("error",W.message)}finally{g(!1)}},[e,v,n]),R=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(T){v("warn",`Live nickname updated, but account sync failed: ${T.message}`)}v("info",`Nickname set to "${b||"(cleared)"}"`),y(!1)}catch(T){v("error",`Failed: ${T.message}`)}},[e,b,t,v,r,n]);return{logs:i,launchingIde:d,launchingAgentType:u,workspaceBusy:f,launchPick:C,setLaunchPick:h,editingNickname:x,setEditingNickname:y,nicknameInput:b,setNicknameInput:S,addLog:v,handleLaunchIde:j,runLaunchCliCore:A,handleLaunchCli:I,handleStopCli:D,handleRestartIde:L,handleStopIde:P,handleDetectIdes:_,handleWorkspaceAdd:q,handleWorkspaceRemove:B,handleWorkspaceSetDefault:E,handleWorkspaceResumePath:K,handleSaveNickname:R,setOnDefaultWorkspaceChanged:w}}function XI({machine:e,ideSessions:t,cliSessions:n,acpSessions:r}){var d;const a=typeof e.uptime=="number"||typeof e.freeMem=="number"||typeof e.availableMem=="number"||Array.isArray(e.loadavg)&&e.loadavg.length>0,o=e.availableMem??e.freeMem??e.totalMem,i=a&&e.totalMem>0?Math.min(100,Math.max(0,Math.round((e.totalMem-o)/e.totalMem*100))):0,c=((d=e.loadavg)==null?void 0:d[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(Qd,{size:16}),label:"Uptime",value:typeof e.uptime=="number"?My(e.uptime):"Waiting…"}),s.jsx(kr,{icon:s.jsx(us,{size:16}),label:"IDEs",value:`${t.length}`}),s.jsx(kr,{icon:s.jsx(Mi,{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(Hl,{value:a?Math.min(Math.round(c/e.cpus*100),100):0,max:100,label:"CPU Load",color:"#8b5cf6",detail:a?`${c.toFixed(2)} avg / ${e.cpus} cores`:"Polled from machine page"}),s.jsx(Hl,{value:i,max:100,label:"Memory",color:"#3b82f6",detail:a?`${Qa(e.totalMem-o)} / ${Qa(e.totalMem)}${e.platform==="darwin"?" (approx.)":""}`:`Polled from machine page · ${Qa(e.totalMem)} total`})]})]})]})}function ZI(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 eT(e,t,n){const r=[];for(const[a,o]of Object.entries(e.settings)){const i=n!=null&&n.filterSchema?n.filterSchema(o):o;if(i.length===0)continue;const c=t.find(d=>d.type===a);r.push({type:a,displayName:(c==null?void 0:c.displayName)||a,icon:(c==null?void 0:c.icon)||"",category:(c==null?void 0:c.category)||"unknown",schema:i,values:e.values[a]||{}})}return r}function To(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 fd(e){if(!e||typeof e!="object")return null;if(To(e))return e;const t=e,n=t.result;return To(n)?n:To(t.sourceConfig)?t.sourceConfig:null}function tT(e){const t=e.trim();return t||null}function sT({machineId:e,providers:t,sendDaemonCommand:n,onClose:r,onCreated:a}){var v;const{t:o}=Ne("common"),i=t.filter(N=>N.category==="ide"),[c,d]=l.useState(((v=i[0])==null?void 0:v.type)||""),[p,u]=l.useState(""),[m,f]=l.useState(""),[g,C]=l.useState(!1),[h,x]=l.useState(""),[y,b]=l.useState(!1),S=N=>{const j=N.toLowerCase().replace(/[^a-z0-9-]/g,"");u(j),(!m||m===k(p))&&f(k(j))},k=N=>N.split("-").map(j=>j.charAt(0).toUpperCase()+j.slice(1)).join(" "),w=async()=>{if(!(!p||!m||!c)){C(!0),x("");try{const N=await n(e,"provider_clone",{type:p,name:m,category:"ide",location:"user",cloneFrom:c});N!=null&&N.success||N!=null&&N.created?(b(!0),a==null||a(p)):x((N==null?void 0:N.error)||"Failed to create provider")}catch(N){x((N==null?void 0:N.message)||"Connection failed")}C(!1)}};return s.jsx("div",{className:"fixed inset-0 z-50 flex items-end justify-center overflow-y-auto bg-black/60 backdrop-blur-sm px-2 pt-[calc(8px+env(safe-area-inset-top,0px))] pb-[calc(8px+env(safe-area-inset-bottom,0px))] sm:items-center sm:p-4",onClick: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:o("machine.providerClone.title")}),s.jsx("p",{className:"text-[11px] text-text-muted mt-0.5",children:o("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:y?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:o("machine.providerClone.createdTitle")}),s.jsxs("p",{className:"text-[11px] text-text-muted mt-1",children:[o("machine.providerClone.createdDesc",{type:p})," ",s.jsxs("code",{className:"text-green-400",children:["~/.adhdev/providers/",p,"/"]})]}),s.jsx("p",{className:"text-[11px] text-text-muted mt-2",children:o("machine.providerClone.createdRunHint",{type:p})})]}):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:o("machine.providerClone.baseProvider")}),s.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:i.map(N=>s.jsxs("button",{onClick:()=>d(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:o("machine.providerClone.providerTypeId")}),s.jsx("input",{value:p,onChange:N=>S(N.target.value),placeholder:o("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:[o("machine.providerClone.typeIdHint")," ",s.jsxs("code",{className:"text-violet-400",children:["~/.adhdev/providers/",p||"...","/"]})]})]}),s.jsxs("div",{children:[s.jsx("label",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mb-1.5 block",children:o("machine.providerClone.displayName")}),s.jsx("input",{value:m,onChange:N=>f(N.target.value),placeholder:o("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"})]}),h&&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:h})]})}),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:y?s.jsx("button",{onClick:r,className:"machine-btn",children:o("machine.providerClone.close")}):s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:r,className:"machine-btn",children:o("machine.providerClone.cancel")}),s.jsx("button",{onClick:w,disabled:!p||!m||g,className:"machine-btn",style:{background:p&&m?"rgba(34,197,94,0.12)":void 0,borderColor:p&&m?"rgba(34,197,94,0.3)":void 0,color:p&&m?"#86efac":void 0,opacity:!p||!m||g?.4:1},children:o(g?"machine.providerClone.creating":"machine.providerClone.createProvider")})]})})]})})}const bd={"user-custom":"Custom",trusted:"Official","trusted-with-scripts":"Official · runs JS","external-safe":"External · spec-only","external-untrusted":"⚠ External · untrusted JS"},nT={"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 rT({trust:e,sourceName:t,description:n}){const r=t&&(e==="external-safe"||e==="external-untrusted")?`${bd[e]} · ${t}`:bd[e];return s.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded border whitespace-nowrap ${nT[e]}`,title:n,children:r})}function aT(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 gd={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"},oT={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 xd(e){if(!e)return"—";const t=e.ok?"OK":"Failed",n=e.message||e.path||e.command||"";return n?`${t} — ${n}`:t}function iT(e){return e==="cli"||e==="acp"}function lT({prov:e,providerInfo:t,savingKey:n,onSetSetting:r,onEnableToggle:a,onDetect:o,onResetCommand:i}){const{t:c}=Ne("common"),d={detected:c("machine.providerRow.statusDetected"),not_detected:c("machine.providerRow.statusNotDetected"),enabled_unchecked:c("machine.providerRow.statusEnabledUnchecked"),disabled:c("machine.providerRow.statusDisabled")},[p,u]=l.useState(!1),m=(t==null?void 0:t.enabled)===!0||e.values.enabled===!0,f=t==null?void 0:t.machineStatus,g=m&&f==="disabled"?"enabled_unchecked":f||(m?"enabled_unchecked":"disabled"),C=iT(e.category);return s.jsxs(Ss,{padding:"none",children:[s.jsxs("button",{onClick:()=>u(h=>!h),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 ${oT[e.category]??"border-border-subtle text-text-muted"}`,children:e.category.toUpperCase()}),(t==null?void 0:t.trust)&&s.jsx(rT,{trust:t.trust,sourceName:t.sourceName??null,description:t.trustDescription}),C&&s.jsx("span",{className:`text-[9px] font-semibold px-1.5 py-px rounded border ${gd[g]??gd.disabled}`,children:d[g]??g}),s.jsxs("div",{className:"ml-auto flex items-center gap-1.5",children:[C&&s.jsx("button",{onClick:h=>{h.stopPropagation(),a(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:p?"▾":"▸"})]})]}),p&&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 h=t==null?void 0:t.links;if(!h)return null;const x=Object.entries(h).map(([y,b])=>({k:y,href:aT(b)})).filter(y=>y.href!==null);return x.length===0?null:s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:c("machine.providerRow.labelLinks")})," ",x.map(({k:y,href:b})=>s.jsx("a",{href:b,target:"_blank",rel:"noopener noreferrer",className:"text-violet-400 hover:underline mr-2",children:y},y))]})})()]}),C&&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")})," ",xd(t==null?void 0:t.lastDetection)]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary font-medium",children:c("machine.providerRow.labelVerification")})," ",xd(t==null?void 0:t.lastVerification)]})]}),e.schema.length>0&&s.jsx("div",{className:"flex flex-col gap-1.5",children:e.schema.map(h=>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:[h.label||h.key,n===`${e.type}.${h.key}`&&s.jsx("span",{className:"ml-1.5 text-[9px] text-violet-500",children:c("machine.providerRow.saving")})]}),h.description&&s.jsx("div",{className:"text-[10px] text-text-muted mt-px",children:h.description})]}),s.jsx("div",{className:"shrink-0",children:h.type==="boolean"?s.jsx("button",{onClick:()=>void r(e.type,h.key,!(e.values[h.key]??h.default)),className:"w-10 h-[22px] rounded-[11px] border-none relative cursor-pointer transition-colors duration-200",style:{background:e.values[h.key]??h.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[h.key]??h.default?21:3}})}):h.type==="number"?s.jsx("input",{type:"number",value:Number(e.values[h.key]??h.default??0)||0,min:h.min,max:h.max,onChange:x=>{const y=parseInt(x.target.value)||0;h.min!==void 0&&y<h.min||h.max!==void 0&&y>h.max||r(e.type,h.key,y)},className:"machine-input w-20 text-center text-[11px]"}):h.type==="select"&&h.options?s.jsx("select",{value:String(e.values[h.key]??h.default??""),onChange:x=>void r(e.type,h.key,x.target.value),className:"machine-input text-[11px]",children:h.options.map(x=>s.jsx("option",{value:x,children:x},x))}):s.jsx("input",{type:"text",defaultValue:String(e.values[h.key]??h.default??""),onBlur:x=>void r(e.type,h.key,x.target.value),className:"machine-input w-[180px] text-[11px]"})})]},h.key))}),s.jsx("div",{className:"flex gap-1.5 flex-wrap pt-1 border-t border-border-subtle",children:C&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:()=>void o(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 Br(e){return e&&typeof e=="object"&&e.result&&typeof e.result=="object"?e.result:e}function cT({machineId:e,sendDaemonCommand:t,onChange:n}){const[r,a]=l.useState([]),[o,i]=l.useState([]),[c,d]=l.useState(!1),[p,u]=l.useState(null),[m,f]=l.useState(!1),[g,C]=l.useState(""),[h,x]=l.useState("main"),[y,b]=l.useState(""),[S,k]=l.useState(!1),[w,v]=l.useState(null),[N,j]=l.useState(null),A=l.useCallback(async()=>{if(e){d(!0),u(null);try{const P=Br(await t(e,"list_provider_sources",{}));if(!(P!=null&&P.success)){u((P==null?void 0:P.error)||"Failed to load sources");return}a(P.sources||[]),i(P.conflicts||[])}catch(P){u((P==null?void 0:P.message)||String(P))}finally{d(!1)}}},[e,t]);l.useEffect(()=>{A()},[A]);const I=async()=>{if(g.trim()){k(!0),u(null);try{const P=Br(await t(e,"add_provider_source",{url:g.trim(),ref:h.trim()||"main",...y.trim()?{name:y.trim()}:{}}));P!=null&&P.success?(f(!1),C(""),x("main"),b(""),await A(),n==null||n()):u((P==null?void 0:P.error)||"Failed to add source")}catch(P){u((P==null?void 0:P.message)||String(P))}finally{k(!1)}}},D=async P=>{if(confirm(`Remove provider source ${P}? This deletes the cloned manifests and clears any active-source entries that pointed here.`)){v(P),u(null);try{const _=Br(await t(e,"remove_provider_source",{name:P}));_!=null&&_.success?(await A(),n==null||n()):u((_==null?void 0:_.error)||"Failed to remove source")}catch(_){u((_==null?void 0:_.message)||String(_))}finally{v(null)}}},L=async(P,_)=>{j(`${P}:${_}`),u(null);try{const q=Br(await t(e,"set_active_provider_source",{type:P,sourceName:_}));q!=null&&q.success?(await A(),n==null||n()):u((q==null?void 0:q.error)||"Failed to set active source")}catch(q){u((q==null?void 0:q.message)||String(q))}finally{j(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"})]})]}),p&&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:p}),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 D(P.name),disabled:w===P.name,className:"machine-btn text-[10px] text-red-400 hover:bg-red-500/[0.10]",children:w===P.name?"…":"Remove"})]}),s.jsx("div",{className:"mt-1.5 text-[10px] text-text-muted",children:Object.entries(P.providers).map(([_,q])=>s.jsxs("span",{className:"mr-3",children:[s.jsxs("span",{className:"text-text-secondary",children:[_,":"]})," ",q.length]},_))})]},P.name))}),o.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:o.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(_=>s.jsxs("button",{type:"button",onClick:()=>void L(P.type,_),disabled:N===`${P.type}:${_}`,className:`text-[10px] px-2 py-0.5 rounded border ${P.active===_?"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===_?"Active":`Switch active to ${_}`,children:[P.active===_?"● ":"",_]},_))})]},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:g,onChange:P=>C(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:h,onChange:P=>x(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:y,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 I(),disabled:S||!g.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:S?"Cloning…":"Clone + register"})]})]})]})}function dT({machineId:e,providers:t,sendDaemonCommand:n}){var K;const{t:r}=Ne("common"),[a,o]=l.useState([]),[i,c]=l.useState(!1),[d,p]=l.useState(null),[u,m]=l.useState("all"),[f,g]=l.useState(!1),[C,h]=l.useState(!1),[x,y]=l.useState(!1),[b,S]=l.useState(null),[k,w]=l.useState("normal"),[v,N]=l.useState(""),[j,A]=l.useState(!1),I=l.useCallback(async()=>{if(e)try{const R=await n(e,"get_provider_source_config",{}),T=fd(R);T&&(S(T),w(T.sourceMode),N(T.explicitProviderDir||""))}catch{}},[e,n]),D=l.useCallback(async()=>{if(e){c(!0);try{const R=await n(e,"get_provider_settings",{}),T=ZI(R);if(T){const H=eT(T,t,{filterSchema:M=>M.filter(W=>W.key!=="enabled")});H.sort((M,W)=>M.category.localeCompare(W.category)||M.displayName.localeCompare(W.displayName)),o(H)}}catch{}c(!1)}},[e,t,n]);l.useEffect(()=>{a.length===0&&D(),b||I()},[]);const L=async(R,T,H)=>{p(`${R}.${T}`),o(M=>M.map(W=>W.type===R?{...W,values:{...W.values,[T]:H}}:W));try{const M=await n(e,"set_provider_setting",{providerType:R,key:T,value:H});M!=null&&M.success||D()}catch{D()}p(null)},P=async(R,T)=>{await L(R,"enabled",T),await D()},_=async R=>{p(`${R}.detect`);try{await n(e,"detect_provider",{providerType:R})}finally{await D(),p(null)}},q=async R=>{await L(R,"executablePath",""),await L(R,"executableArgs",""),await D()},B=async()=>{A(!0);try{const R=await n(e,"set_provider_source_config",{providerSourceMode:k,providerDir:tT(v)}),T=fd(R);T?(S(T),w(T.sourceMode),N(T.explicitProviderDir||"")):await I(),await D()}catch{await I()}A(!1)},E=a.filter(R=>u==="all"||R.category===u);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(R=>s.jsx("button",{onClick:()=>m(R),className:`machine-btn text-[10px] px-2 py-0.5 ${u===R?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:R.toUpperCase()},R))]}),s.jsxs("div",{className:"flex gap-1.5",children:[s.jsx("button",{onClick:()=>h(R=>!R),className:`machine-btn text-[10px] ${C?"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:()=>g(!0),className:"machine-btn text-[10px]",title:"Create a new provider from an existing one",children:r("machine.providers.create")}),s.jsxs("button",{onClick:D,disabled:i,className:"machine-btn text-[10px]",children:[i?"⏳":"↻"," ",r("machine.providers.refresh")]}),s.jsx("button",{onClick:()=>y(R=>!R),className:"machine-btn text-[10px]",title:"Show source configuration (advanced)",children:r("machine.providers.advanced")})]})]}),C&&s.jsx(cT,{machineId:e,sendDaemonCommand:n,onChange:()=>{D()}}),x&&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:I,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:k,onChange:R=>w(R.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:v,onChange:R=>N(R.target.value),placeholder:r("machine.providers.providerDirPlaceholder"),className:"machine-input text-[11px]"})]}),s.jsx("button",{onClick:()=>void B(),disabled:j,className:"machine-btn text-[10px] bg-violet-500/[0.08] border-violet-500/20 text-violet-300 hover:bg-violet-500/[0.14]",children:r(j?"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")})," ",((K=b==null?void 0:b.providerRoots)==null?void 0:K.join(" → "))||"—"]})]})]}),i&&a.length===0?s.jsx("div",{className:"p-10 text-center text-text-muted",children:r("machine.providers.loadingSettings")}):E.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:u==="all"?r("machine.providers.noProviders"):r("machine.providers.noFilteredProviders",{filter:u.toUpperCase()})})}):s.jsx("div",{className:"flex flex-col gap-1.5",children:E.map(R=>s.jsx(lT,{prov:R,providerInfo:t.find(T=>T.type===R.type),savingKey:d,onSetSetting:L,onEnableToggle:P,onDetect:_,onResetCommand:q},R.type))}),f&&s.jsx(sT,{machineId:e,providers:t,sendDaemonCommand:n,onClose:()=>g(!1),onCreated:()=>{g(!1),D()}})]})}const uT=[{value:"all",label:"All trace"},{value:"session_host",label:"Session host"}];function pT({count:e,since:t,category:n}){return{count:e,since:t,...n==="all"?{}:{category:n}}}function mT(e,t){return t==="all"?e:e.filter(n=>n.category===t)}function hT(e){return e.trim().toLowerCase()}function Ba(e,t){const n=hT(t);return n?e.some(r=>String(r??"").toLowerCase().includes(n)):!0}function fl(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=fl(e);return n?n.length>t?`${n.slice(0,t)}…`:n:""}function fT(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 bT(e,t){return e.filter(n=>Ba([n.level,n.message],t))}function vd(e){return`${e.timestamp}:${e.level}:${e.message}`}function gT(e,t,n=300){if(t.entries.length>0){const r=new Map;for(const i of e.entries)r.set(vd(i),i);for(const i of t.entries)r.set(vd(i),i);const a=Array.from(r.values()).sort((i,c)=>i.timestamp-c.timestamp).slice(-n),o=a.reduce((i,c)=>Math.max(i,Number(c.timestamp||0)),e.lastTs);return{entries:a,kind:"structured",rawText:"",lastTs:o}}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 xT(e,t,n=120){if(t.length===0)return e;const r=new Map;for(const a of e)r.set(a.id,a);for(const a of t)r.set(a.id,a);return Array.from(r.values()).sort((a,o)=>a.ts-o.ts).slice(-n)}function vT(e,t){return e.split(`
99
+ `).map(n=>n.trimEnd()).filter(Boolean).filter(n=>Ba([n],t))}function yT(e,t){return e.filter(n=>Ba([n.level,n.category,n.stage,n.interactionId,fl(n.payload)],t))}function wT(e,t){return e.filter(n=>Ba([n.kind,n.topic,n.interactionId,fl(n.payload)],t))}function yd(e){return e==="warn"||e==="error"}function kT({daemonLogs:e,daemonRawLines:t,trace:n,webEvents:r}){return{all:e.length+t.length+n.length+r.length,info:e.filter(a=>a.level!=="debug").length+n.filter(a=>a.level!=="debug").length+r.length,issues:e.filter(a=>yd(a.level)).length+n.filter(a=>yd(a.level)).length}}function ST({daemonLogs:e,daemonRawLines:t,trace:n,webEvents:r}){const a=[];return e.length>0?a.push(["[daemon logs]",...e.map(o=>`${new Date(o.timestamp).toISOString()} ${o.level.toUpperCase()} ${o.message}`)].join(`
100
+ `)):t.length>0&&a.push(["[daemon logs]",...t].join(`
101
+ `)),n.length>0&&a.push(["[trace]",...n.map(o=>`${new Date(o.ts).toISOString()} ${o.level.toUpperCase()} ${o.category}.${o.stage} ${jn(o.payload,500)}`.trim())].join(`
102
+ `)),r.length>0&&a.push(["[browser events]",...r.map(o=>`${new Date(o.ts).toISOString()} ${o.kind}${o.topic?` topic=${o.topic}`:""} ${jn(o.payload,500)}`.trim())].join(`
103
+ `)),a.join(`
104
+
105
+ `)}function CT({machineId:e,sendDaemonCommand:t}){const[n,r]=l.useState([]),[a,o]=l.useState("empty"),[i,c]=l.useState(""),[d,p]=l.useState([]),[u,m]=l.useState([]),[f,g]=l.useState(null),[C,h]=l.useState(!0),[x,y]=l.useState("info"),[b,S]=l.useState("all"),[k,w]=l.useState(!0),[v,N]=l.useState(!0),[j,A]=l.useState(""),[I,D]=l.useState(""),[L,P]=l.useState(0),_=l.useRef(0),q=l.useRef(0),B=l.useRef({entries:[],kind:"empty",rawText:"",lastTs:0}),E=l.useRef([]),K=l.useCallback(()=>{const re={entries:[],kind:"empty",rawText:"",lastTs:0};B.current=re,_.current=0,r([]),c(""),o("empty"),w(!0)},[]),R=l.useCallback(()=>{E.current=[],q.current=0,p([]),N(!0)},[]),T=l.useCallback(re=>{re!==x&&(K(),y(re))},[x,K]),H=l.useCallback(re=>{S(V=>V===re?V:re)},[]),M=l.useCallback(()=>{K(),R(),m([]),g(null),A(""),D(""),bn.clear()},[K,R]),W=l.useCallback(()=>{P(re=>re+1)},[]),J=l.useCallback(async()=>{if(!e)return;const re=_.current,V=q.current,[X,de]=await Promise.allSettled([t(e,"get_logs",{count:200,minLevel:x,since:re}),t(e,"get_debug_trace",pT({count:120,since:V,category:b}))]);if(X.status==="fulfilled"){const ne=X.value,O=(ne==null?void 0:ne.result)||ne,ie=fT(O),z=gT(B.current,ie,300);B.current=z,_.current=z.lastTs,w(!1),A((ne==null?void 0:ne.success)===!1?String((ne==null?void 0:ne.error)||"Could not load daemon logs"):""),o(z.kind),c(z.rawText),r(z.entries)}else w(!1),A(X.reason instanceof Error?X.reason.message:"Could not load daemon logs");if(de.status==="fulfilled"){const ne=de.value,O=(ne==null?void 0:ne.result)||ne;if((ne==null?void 0:ne.success)===!1)D(String((ne==null?void 0:ne.error)||"Could not load daemon trace"));else if(Array.isArray(O==null?void 0:O.trace)){const ie=O.trace,z=xT(E.current,ie,120),ae=ie.reduce((Ce,ye)=>Math.max(Ce,Number(ye.ts||0)),V);E.current=z,ae>V&&(q.current=ae),D(""),p(z)}else D("");N(!1)}else N(!1),D(de.reason instanceof Error?de.reason.message:"Could not load daemon trace");m(bn.list({limit:120})),g(Date.now())},[x,e,t,b]);return l.useEffect(()=>{R()},[R,b]),l.useEffect(()=>{if(!e||(J(),!C))return;const re=setInterval(()=>{J()},3e3);return()=>clearInterval(re)},[C,J,e,L]),{daemonLogs:n,daemonLogKind:a,daemonRawText:i,debugTrace:d,webEvents:u,lastUpdatedAt:f,autoRefresh:C,logLevel:x,traceCategory:b,daemonLoading:k,traceLoading:v,daemonFetchError:j,traceFetchError:I,setAutoRefresh:h,setLogLevel:T,setTraceCategory:H,refresh:W,clear:M}}function jT({daemonLoading:e,traceLoading:t,daemonFetchError:n,traceFetchError:r,daemonLogKind:a,daemonLogsCount:o,daemonRawLineCount:i,traceCount:c,webEventCount:d}){return[{id:"daemon_logs",label:"Daemon logs",status:n?"error":e?"loading":o>0||i>0?"ok":"empty",detail:n||(a==="text"?`${i} raw file-fallback line(s)`:`${o} 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:d>0?"ok":"empty",detail:d>0?`${d} local browser event(s)`:"No browser events captured"}]}function wd(e){return e==="warn"||e==="error"}function NT(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 AT(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 kd(e){return e==="daemon_log"?0:e==="browser_event"?1:e==="daemon_trace"?2:3}function IT(e){const t=jn(e.payload,320);return t?`${e.category}.${e.stage} ${t}`:`${e.category}.${e.stage}`}function TT(e){const t=jn(e.payload,320),n=e.topic?` topic=${e.topic}`:"";return t?`${e.kind}${n} ${t}`:`${e.kind}${n}`}function MT({daemonLogs:e,daemonRawLines:t,trace:n,webEvents:r}){const a=[];return e.forEach((o,i)=>{a.push({id:`daemon-log-${o.timestamp}-${i}`,source:"daemon_log",ts:Number(o.timestamp||0),severity:o.level,message:o.message,raw:o.message})}),r.forEach(o=>{a.push({id:`browser-event-${o.id}`,source:"browser_event",ts:Number(o.ts||0),severity:"info",message:TT(o),topic:o.topic,interactionId:o.interactionId,payload:o.payload})}),n.forEach(o=>{a.push({id:`daemon-trace-${o.id}`,source:"daemon_trace",ts:Number(o.ts||0),severity:o.level,message:IT(o),category:o.category,stage:o.stage,interactionId:o.interactionId,payload:o.payload})}),t.forEach((o,i)=>{a.push({id:`raw-file-${i}`,source:"raw_file",ts:AT(o,i),severity:NT(o),message:o,raw:o})}),a.sort((o,i)=>o.ts!==i.ts?o.ts-i.ts:kd(o.source)-kd(i.source))}function DT(e){return`${e.source}:${e.severity}:${e.message}`}function PT(e){const t=e.filter(r=>wd(r.severity)).sort((r,a)=>a.ts-r.ts),n=new Map;for(const r of e){if(!wd(r.severity))continue;const a=DT(r),o=n.get(a);o?(o.count+=1,o.firstTs=Math.min(o.firstTs,r.ts),o.lastTs=Math.max(o.lastTs,r.ts)):n.set(a,{key:a,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,a)=>a.count!==r.count?a.count-r.count:a.lastTs-r.lastTs).slice(0,5)}}function LT(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"unknown-time":new Date(e).toISOString()}function Sd(e){const t=e.category&&e.stage?` ${e.category}.${e.stage}`:e.topic?` topic=${e.topic}`:"",n=e.interactionId?` ix=${e.interactionId}`:"";return`${LT(e.ts)} ${e.severity.toUpperCase()} ${e.source}${t}${n} ${e.message}`.trim()}function RT({events:e,summary:t,sources:n,maxTimelineEvents:r=80}){const a=[];a.push(["[diagnostic summary]",`total_events: ${t.totalCount}`,`issue_events: ${t.issueCount}`].join(`
106
+ `)),a.push(["[source status]",...n.map(i=>`${i.label}: ${i.status} - ${i.detail}`)].join(`
107
+ `)),t.latestIssue&&a.push(["[latest issue]",Sd(t.latestIssue)].join(`
108
+ `)),t.repeatedPatterns.length>0&&a.push(["[top repeated patterns]",...t.repeatedPatterns.map(i=>`${i.count}x ${i.severity.toUpperCase()} ${i.source} ${i.message}`)].join(`
109
+ `));const o=e.slice(-r);return a.push(["[timeline]",...o.length>0?o.map(Sd):["No diagnostic events captured."]].join(`
110
+ `)),a.join(`
111
+
112
+ `)}function ET(e,t){return t==="issues"?e.filter(n=>n.level==="warn"||n.level==="error"):t==="info"?e.filter(n=>n.level!=="debug"):e}function _T(e,t){return t==="issues"?e.filter(n=>n.level==="warn"||n.level==="error"):t==="info"?e.filter(n=>n.level!=="debug"):e}function $T({daemonLogs:e,daemonRawText:t,daemonLogKind:n,debugTrace:r,webEvents:a,traceCategory:o,quickFilter:i,searchQuery:c,daemonLoading:d,traceLoading:p,daemonFetchError:u,traceFetchError:m}){const f=mT(r,o),g=bT(e,c),C=vT(t,c),h=yT(f,c),x=wT(a,c),y=ET(g,i),b=i==="all"?C:[],S=_T(h,i),k=i==="issues"?[]:x,w=kT({daemonLogs:g,daemonRawLines:C,trace:h,webEvents:x}),v=MT({daemonLogs:y,daemonRawLines:b,trace:S,webEvents:k}),N=PT(v),j=jT({daemonLoading:d,traceLoading:p,daemonFetchError:u,traceFetchError:m,daemonLogKind:n,daemonLogsCount:g.length,daemonRawLineCount:C.length,traceCount:h.length,webEventCount:x.length});return{filteredDaemonLogs:g,filteredDaemonRawLines:C,filteredTraceEntries:h,filteredWebEvents:x,visibleDaemonLogs:y,visibleDaemonRawLines:b,visibleTraceEntries:S,visibleWebEvents:k,quickFilterCounts:w,diagnosticEvents:v,diagnosticsSummary:N,sourceStates:j}}function HT(e){return e?new Date(e).toLocaleTimeString():"Not yet loaded"}function Qm(e){return!Number.isFinite(e)||e<=0||e>Date.now()+365*24*60*60*1e3?"raw file":new Date(e).toLocaleTimeString()}function xi(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 Mo(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 bl(e){return e==="daemon_log"?"daemon":e==="daemon_trace"?"trace":e==="browser_event"?"browser":"raw file"}function BT({event:e}){return s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${xi(e.severity)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:Qm(e.ts)}),s.jsx("span",{children:e.severity.toUpperCase()}),s.jsx("span",{children:bl(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 FT({quickFilter:e,quickFilterCounts:t,searchQuery:n,autoRefresh:r,onQuickFilterChange:a,onSearchQueryChange:o,onCopyDiagnostics:i,onCopyVisible:c,onToggleAutoRefresh:d,onRefresh:p,onClear:u}){return s.jsxs("div",{className:"flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider mr-1",children:"View"}),s.jsx("div",{className:"flex items-center gap-1 rounded-lg border border-border-subtle bg-bg-secondary p-1",children:[{id:"info",label:`Info+ (${t.info})`},{id:"issues",label:`Issues (${t.issues})`},{id:"all",label:`All (${t.all})`}].map(m=>s.jsx("button",{type:"button",onClick:()=>a(m.id),className:`rounded-md px-2.5 py-1 text-[11px] transition-colors ${e===m.id?"bg-violet-500/15 text-violet-300 border border-violet-500/30":"text-text-secondary hover:text-text-primary"}`,children:m.label},m.id))}),s.jsx("input",{value:n,onChange:m=>o(m.target.value),placeholder:"Search diagnostics…",className:"min-w-[220px] flex-1 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-primary placeholder:text-text-muted"})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("button",{onClick:i,className:"machine-btn",children:"Copy diagnostics"}),s.jsx("button",{onClick:c,className:"machine-btn",children:"Copy visible"}),s.jsx("button",{onClick:d,className:`machine-btn ${r?"text-green-500 border-green-500/30":""}`,children:r?"⏸ Pause":"▶ Resume"}),s.jsx("button",{onClick:p,className:"machine-btn",children:"↻ Refresh"}),s.jsx("button",{onClick:u,className:"machine-btn",children:"Clear"})]})]})}function OT({logLevel:e,traceCategory:t,onLogLevelChange:n,onTraceCategoryChange:r}){return s.jsx(Ss,{padding:"sm",children:s.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between",children:[s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wider text-text-muted font-semibold",children:"Advanced source scope"}),["debug","info","warn","error"].map(a=>s.jsxs("button",{onClick:()=>n(a),className:`machine-btn text-[10px] px-2 py-0.5 ${e===a?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:["Daemon ",a.toUpperCase(),"+"]},a))]}),s.jsx("div",{className:"flex flex-wrap gap-2 items-center",children:uT.map(a=>s.jsx("button",{onClick:()=>r(a.value),className:`machine-btn text-[10px] px-2 py-0.5 ${t===a.value?"bg-violet-500/15 border-violet-500/40 text-violet-400":""}`,children:a.label},a.value))})]})})}function WT({diagnosticsSummary:e,diagnosticEventsCount:t,sourceStates:n,searchQuery:r,lastUpdatedAt:a,autoRefresh:o,daemonFetchError:i,traceFetchError:c}){var u,m;const d=((u=e.latestIssue)==null?void 0:u.severity)==="error"?"danger":((m=e.latestIssue)==null?void 0:m.severity)==="warn"?"warning":"good",p=i||c?"danger":o?"good":"neutral";return s.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[s.jsxs("div",{className:`rounded-xl border p-3 ${Mo(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 ${Mo(d)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Latest issue"}),e.latestIssue?s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"text-[13px] text-text-primary font-medium",children:[bl(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:Qm(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 ${Mo(p)}`,children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted mb-2",children:"Source status"}),s.jsx("div",{className:"text-[13px] text-text-primary font-medium",children:i||c?"Needs attention":o?"Live polling every 3s":"Paused"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:["Last update: ",HT(a)]}),s.jsx("div",{className:"text-[10px] text-text-muted mt-2 space-y-1",children:n.map(f=>s.jsxs("div",{children:[f.label,": ",f.status]},f.id))})]})]})}function UT({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()," · ",bl(t.source)]}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1 line-clamp-2",children:t.message})]},t.key))})]})}function GT({streams:e,sectionsOpen:t,setSectionsOpen:n,diagnosticEvents:r,visibleDaemonLogs:a,visibleDaemonRawLines:o,visibleTraceEntries:i,visibleWebEvents:c,quickFilter:d,searchQuery:p}){return s.jsxs("div",{className:"grid gap-3",children:[s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(u=>({...u,timeline:!u.timeline})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Unified timeline"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[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(u=>s.jsx(BT,{event:u},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(u=>({...u,daemon:!u.daemon})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · daemon logs"}),s.jsx("div",{className:"text-[11px] text-text-secondary mt-1",children:e.daemonLogKind==="text"?`${o.length} visible raw line(s) from file fallback`:`${a.length} visible structured line(s)`})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.daemon?"Hide":"Show"})]}),t.daemon&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[360px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.daemonLoading&&a.length===0&&o.length===0&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon logs…"}),!e.daemonLoading&&e.daemonFetchError&&e.daemonLogKind==="empty"&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.daemonFetchError}),!e.daemonLoading&&e.daemonLogKind==="empty"&&!e.daemonFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No daemon logs captured yet for this machine."}),e.daemonLogKind==="text"&&o.length===0&&e.daemonRawText&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:d==="all"?"No raw daemon log lines match the current search.":"Raw file-fallback logs are available only in All view."}),e.daemonLogKind==="structured"&&a.length===0&&e.daemonLogs.length>0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"No structured daemon logs match the current view."}),e.daemonLogKind==="text"&&o.map((u,m)=>s.jsx("div",{className:"py-0.5 text-text-secondary whitespace-pre-wrap break-words",children:u},`raw-${m}`)),e.daemonLogKind!=="text"&&a.map((u,m)=>s.jsxs("div",{className:`flex gap-2 py-1 px-2 mb-1 rounded-lg border ${xi(u.level)}`,children:[s.jsx("span",{className:"text-text-muted min-w-[75px] shrink-0",children:new Date(u.timestamp).toLocaleTimeString()}),s.jsx("span",{className:"font-semibold min-w-[32px] shrink-0 text-[9px]",children:u.level==="error"?"ERR":u.level==="warn"?"WRN":u.level==="debug"?"DBG":"INF"}),s.jsx("span",{className:"break-words",children:u.message})]},`log-${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(u=>({...u,trace:!u.trace})),children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:["Raw source · daemon trace",e.traceCategory==="session_host"?" · session_host only":""]}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[i.length," visible trace event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.trace?"Hide":"Show"})]}),t.trace&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[160px] max-h-[320px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[e.traceLoading&&i.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:"Loading daemon trace…"}),!e.traceLoading&&e.traceFetchError&&i.length===0&&s.jsx("div",{className:"p-6 text-center text-red-300",children:e.traceFetchError}),!e.traceLoading&&i.length===0&&!e.traceFetchError&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:p.trim()?"No trace entries match the current search.":e.traceCategory==="session_host"?"No session_host trace entries yet. This filter uses get_debug_trace(category=session_host).":"No trace entries yet. Run daemon with --dev or --trace."}),i.map(u=>s.jsxs("div",{className:`py-2 px-2 mb-2 rounded-lg border ${xi(u.level)}`,children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.level.toUpperCase()}),s.jsxs("span",{children:[u.category,".",u.stage]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:jn(u.payload,360)||"No payload"})]},u.id))]})]}),s.jsxs("div",{className:"bg-bg-secondary border border-border-subtle rounded-xl overflow-hidden",children:[s.jsxs("button",{type:"button",className:"w-full flex items-center justify-between gap-3 px-3 py-3 text-left",onClick:()=>n(u=>({...u,web:!u.web})),children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-muted",children:"Raw source · browser debug events"}),s.jsxs("div",{className:"text-[11px] text-text-secondary mt-1",children:[c.length," visible browser event(s)"]})]}),s.jsx("div",{className:"text-[11px] text-text-muted",children:t.web?"Hide":"Show"})]}),t.web&&s.jsxs("div",{className:"border-t border-border-subtle p-3 min-h-[140px] max-h-[260px] overflow-y-auto font-mono text-[11px] leading-relaxed",children:[c.length===0&&s.jsx("div",{className:"p-6 text-center text-text-muted",children:p.trim()?"No browser debug events match the current search.":"No browser debug events captured yet."}),c.map(u=>s.jsxs("div",{className:"py-2 px-2 mb-2 rounded-lg border border-border-subtle bg-bg-primary",children:[s.jsxs("div",{className:"flex gap-2 text-[10px] text-text-muted flex-wrap",children:[s.jsx("span",{children:new Date(u.ts).toLocaleTimeString()}),s.jsx("span",{children:u.kind}),u.topic&&s.jsxs("span",{children:["topic=",u.topic]}),u.interactionId&&s.jsxs("span",{children:["ix=",u.interactionId]})]}),s.jsx("div",{className:"mt-1 break-words text-text-primary/90",children:jn(u.payload,360)||"No payload"})]},u.id))]})]})]})}function qT({machineId:e,sendDaemonCommand:t}){const n=CT({machineId:e,sendDaemonCommand:t}),[r,a]=l.useState("info"),[o,i]=l.useState(""),[c,d]=l.useState({timeline:!0,daemon:!1,trace:!1,web:!1}),p=l.useRef(null),u=l.useRef(!1),m=l.useMemo(()=>$T({daemonLogs:n.daemonLogs,daemonRawText:n.daemonRawText,daemonLogKind:n.daemonLogKind,debugTrace:n.debugTrace,webEvents:n.webEvents,traceCategory:n.traceCategory,quickFilter:r,searchQuery:o,daemonLoading:n.daemonLoading,traceLoading:n.traceLoading,daemonFetchError:n.daemonFetchError,traceFetchError:n.traceFetchError}),[r,o,n.daemonFetchError,n.daemonLoading,n.daemonLogKind,n.daemonLogs,n.daemonRawText,n.debugTrace,n.traceCategory,n.traceFetchError,n.traceLoading,n.webEvents]);l.useEffect(()=>{if(n.autoRefresh&&m.diagnosticEvents.length>0){const C=u.current?"smooth":"instant";setTimeout(()=>{var h;(h=p.current)==null||h.scrollIntoView({behavior:C}),u.current=!0},50)}},[m.diagnosticEvents.length,n.autoRefresh]);const f=l.useCallback(async()=>{var h;const C=ST({daemonLogs:m.visibleDaemonLogs,daemonRawLines:m.visibleDaemonRawLines,trace:m.visibleTraceEntries,webEvents:m.visibleWebEvents});if(!C.trim()){mt.showToast("No visible logs to copy.","info");return}try{await((h=navigator.clipboard)==null?void 0:h.writeText(C)),mt.showToast("Copied visible logs to clipboard.","success")}catch(x){mt.showToast(x instanceof Error?x.message:"Could not copy visible logs","warning")}},[m.visibleDaemonLogs,m.visibleDaemonRawLines,m.visibleTraceEntries,m.visibleWebEvents]),g=l.useCallback(async()=>{var h;const C=RT({events:m.diagnosticEvents,summary:m.diagnosticsSummary,sources:m.sourceStates});try{await((h=navigator.clipboard)==null?void 0:h.writeText(C)),mt.showToast("Copied diagnostic bundle to clipboard.","success")}catch(x){mt.showToast(x instanceof Error?x.message:"Could not copy diagnostic bundle","warning")}},[m.diagnosticEvents,m.diagnosticsSummary,m.sourceStates]);return s.jsxs("div",{className:"space-y-4",children:[s.jsx(FT,{quickFilter:r,quickFilterCounts:m.quickFilterCounts,searchQuery:o,autoRefresh:n.autoRefresh,onQuickFilterChange:a,onSearchQueryChange:i,onCopyDiagnostics:()=>{g()},onCopyVisible:()=>{f()},onToggleAutoRefresh:()=>n.setAutoRefresh(C=>!C),onRefresh:n.refresh,onClear:n.clear}),s.jsx(OT,{logLevel:n.logLevel,traceCategory:n.traceCategory,onLogLevelChange:n.setLogLevel,onTraceCategoryChange:n.setTraceCategory}),s.jsx(WT,{diagnosticsSummary:m.diagnosticsSummary,diagnosticEventsCount:m.diagnosticEvents.length,sourceStates:m.sourceStates,searchQuery:o,lastUpdatedAt:n.lastUpdatedAt,autoRefresh:n.autoRefresh,daemonFetchError:n.daemonFetchError,traceFetchError:n.traceFetchError}),s.jsx(UT,{patterns:m.diagnosticsSummary.repeatedPatterns}),s.jsx(GT,{streams:n,sectionsOpen:c,setSectionsOpen:d,diagnosticEvents:m.diagnosticEvents,visibleDaemonLogs:m.visibleDaemonLogs,visibleDaemonRawLines:m.visibleDaemonRawLines,visibleTraceEntries:m.visibleTraceEntries,visibleWebEvents:m.visibleWebEvents,quickFilter:r,searchQuery:o}),s.jsx("div",{ref:p})]})}function zT(e){return e.diagnostics?{label:"Managed",toneClass:"bg-green-500/[0.08] text-green-500"}:e.loading||e.refreshing?{label:"Checking…",toneClass:"bg-sky-500/[0.08] text-sky-400"}:e.error?{label:"Diagnostics issue",toneClass:"bg-amber-500/[0.08] text-amber-400"}:{label:"Unavailable",toneClass:"bg-red-500/[0.08] text-red-400"}}function Xm(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 KT(e){var a;const t=[],n=[],r=[];for(const o of e||[]){const i=String((o==null?void 0:o.lifecycle)||"").trim(),c=Xm((o==null?void 0:o.meta)||void 0),d=((a=o==null?void 0:o.meta)==null?void 0:a.restoredFromStorage)===!0;["starting","running","stopping","interrupted"].includes(i)?t.push(o):(i==="stopped"||i==="failed")&&(d||c)?n.push(o):r.push(o)}return{liveRuntimes:t,recoverySnapshots:n,inactiveRecords:r}}function VT(e){return e==="live"?"Attach":e==="recovery"?"Recover":"Restart"}function Do(e){return e==="live"?"These runtimes are live now and are the only attachable targets.":e==="recovery"?"These records were restored from session-host state and are not live attach targets until you explicitly recover or restart them.":"These inactive records are shown for reference and usually need restart before they are useful again."}function Po(e){return e!=null&&e.result&&typeof e.result=="object"&&"success"in e.result?e.result:e}function Lo(e){return e?new Date(e).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}):"unknown"}function Cd(e){if(!e)return"unknown";const t=Date.now()-e,n=Math.max(0,Math.round(t/1e3));if(n<60)return`${n}s ago`;const r=Math.round(n/60);if(r<60)return`${r}m ago`;const a=Math.round(r/60);return a<48?`${a}h ago`:`${Math.round(a/24)}d ago`}function YT(e){return e?e.ownerType==="user"?`user control · ${e.clientId}`:`agent control · ${e.clientId}`:"view only"}function JT(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 QT(e){var n;const t=new Map;for(const r of e){if(!["starting","running","stopping","interrupted"].includes(r.lifecycle))continue;const a=typeof((n=r.meta)==null?void 0:n.providerSessionId)=="string"?String(r.meta.providerSessionId).trim():"";if(!a)continue;const o=`${r.providerType}::${r.workspace}::${a}`;t.set(o,(t.get(o)||0)+1)}return Array.from(t.values()).filter(r=>r>1).length}function XT({machineId:e,cliSessions:t,sendDaemonCommand:n}){const[r,a]=l.useState(""),[o,i]=l.useState(null),[c,d]=l.useState(!1),p=mC(e,{enabled:!!e,includeSessions:!0,limit:ic,intervalMs:N0}),u=p.diagnostics,m=p.loading,f=p.applyDiagnostics,g=l.useMemo(()=>zT({diagnostics:u,loading:m,refreshing:c,error:r}),[u,m,c,r]),C=l.useMemo(()=>new Map(t.map(D=>[D.sessionId||D.id,D])),[t]),h=l.useCallback(async()=>{if(e){d(!0);try{const D=await n(e,"session_host_get_diagnostics",{includeSessions:!0,limit:ic}),L=Po(D);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),a("")}catch(D){const L=D instanceof Error?D.message:"Could not load hosted runtime diagnostics";a(L)}finally{d(!1)}}},[f,e,n]);l.useEffect(()=>{!e||u||m||c||h()},[u,m,e,h,c]);const x=l.useCallback(async(D,L)=>{const P=`${D}:${L.sessionId}`;if(!(D==="session_host_stop_session"&&!window.confirm(`Stop ${L.displayName}?
113
+ This will terminate the hosted runtime.`))){i(P);try{const _=await n(e,D,{sessionId:L.sessionId}),q=Po(_);if(!(q!=null&&q.success))throw new Error((q==null?void 0:q.error)||"Session host action failed");const B=D==="session_host_resume_session"?"resumed":D==="session_host_restart_session"?"restarted":"stopped";mt.showToast(`Session host ${B}: ${L.displayName}`,"success"),await h()}catch(_){const q=_ instanceof Error?_.message:"Session host action failed";mt.showToast(q,"warning"),a(q)}finally{i(_=>_===P?null:_)}}},[e,h,n]),y=l.useCallback(async()=>{if(window.confirm(`Prune duplicate hosted runtimes?
114
+ The newest runtime for each provider session will be kept and older duplicates will be stopped and removed.`)){i("session_host_prune_duplicate_sessions");try{const L=await n(e,"session_host_prune_duplicate_sessions",{}),P=Po(L);if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Duplicate prune failed");const _=P.result||{},q=Array.isArray(_.prunedSessionIds)?_.prunedSessionIds.length:0,B=typeof _.duplicateGroupCount=="number"?_.duplicateGroupCount:0;mt.showToast(`Pruned ${q} duplicate runtime(s) across ${B} group(s)`,"success"),await h()}catch(L){const P=L instanceof Error?L.message:"Duplicate prune failed";mt.showToast(P,"warning"),a(P)}finally{i(L=>L==="session_host_prune_duplicate_sessions"?null:L)}}},[e,h,n]),b=l.useMemo(()=>[...(u==null?void 0:u.sessions)||[]].sort((D,L)=>(L.lastActivityAt||0)-(D.lastActivityAt||0)),[u==null?void 0:u.sessions]),S=l.useMemo(()=>u!=null&&u.liveRuntimes||u!=null&&u.recoverySnapshots||u!=null&&u.inactiveRecords?{liveRuntimes:(u==null?void 0:u.liveRuntimes)||[],recoverySnapshots:(u==null?void 0:u.recoverySnapshots)||[],inactiveRecords:(u==null?void 0:u.inactiveRecords)||[]}:KT(b),[u==null?void 0:u.inactiveRecords,u==null?void 0:u.liveRuntimes,u==null?void 0:u.recoverySnapshots,b]),k=S.liveRuntimes,w=S.recoverySnapshots,v=S.inactiveRecords,N=l.useMemo(()=>QT(k),[k]),j=l.useMemo(()=>[...(u==null?void 0:u.recentTransitions)||[]].slice(-6).reverse(),[u==null?void 0:u.recentTransitions]),A=l.useMemo(()=>[...(u==null?void 0:u.recentLogs)||[]].reverse().find(D=>D.level==="warn"||D.level==="error")||null,[u==null?void 0:u.recentLogs]),I=(D,L)=>{var H;const P=o===`session_host_resume_session:${D.sessionId}`,_=o===`session_host_restart_session:${D.sessionId}`,q=o===`session_host_stop_session:${D.sessionId}`,B=Xm(D.meta),E=C.get(D.sessionId),K=D.attachedClients.length===1?"1 client":`${D.attachedClients.length} clients`,R=L==="recovery"?"Recover":"Resume",T=VT(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:D.displayName||(E==null?void 0:E.cliName)||D.providerType}),s.jsx("span",{className:`px-2 py-0.5 rounded-md text-[10px] font-semibold ${JT(D.lifecycle)}`,children:D.lifecycle}),B&&s.jsx("span",{className:"px-2 py-0.5 rounded-md text-[10px] font-semibold bg-sky-500/[0.08] text-sky-300",children:B})]}),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:D.workspaceLabel||(E==null?void 0:E.runtimeWorkspaceLabel)||D.workspace||"No workspace"}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsx("span",{className:"font-mono text-text-primary",children:D.runtimeKey}),D.osPid?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/90",children:["pid ",D.osPid]})]}):null]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-1 flex flex-wrap gap-2",children:[s.jsx("span",{className:((H=D.writeOwner)==null?void 0:H.ownerType)==="user"?"text-amber-200":"text-text-primary/85",children:YT(D.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(Kd,{size:11})," ",K]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-text-primary/85",children:["active ",Cd(D.lastActivityAt)]}),s.jsx("span",{className:"text-text-muted",children:"·"}),s.jsxs("span",{className:"text-sky-200",children:["Next: ",T]})]})]}),s.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[L==="recovery"&&(D.lifecycle==="interrupted"||D.lifecycle==="failed"||D.lifecycle==="stopped")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{x("session_host_resume_session",D)},children:P?`${R}ing…`:R}),s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1",disabled:!!o,onClick:()=>{x("session_host_restart_session",D)},children:_?"Restarting…":"Restart"}),L==="live"&&(D.lifecycle==="running"||D.lifecycle==="starting"||D.lifecycle==="interrupted")&&s.jsx("button",{type:"button",className:"machine-btn text-[10px] px-2 py-1 border-red-500/20 text-red-300 hover:text-red-200",disabled:!!o,onClick:()=>{x("session_host_stop_session",D)},children:q?"Stopping…":"Stop"})]})]})},D.sessionId)};return s.jsxs(Ss,{padding:"lg",className:"mb-5",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(Ts,{size:14})," Hosted Runtime Recovery"]}),s.jsx("div",{className:"text-[12px] text-text-secondary mt-1",children:Zk()})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[N>0&&s.jsx("button",{type:"button",className:"machine-btn",onClick:()=>{y()},disabled:o==="session_host_prune_duplicate_sessions",children:o==="session_host_prune_duplicate_sessions"?"Pruning…":`Prune duplicates (${N})`}),s.jsx("span",{className:`px-2 py-1 rounded-md text-[10px] font-semibold ${g.toneClass}`,children:g.label}),s.jsxs("button",{type:"button",className:"machine-btn flex items-center gap-1",onClick:()=>{h()},disabled:m||c,children:[s.jsx(Sa,{size:13}),m||c?"Refreshing…":"Refresh"]})]})]}),r&&!u&&s.jsx("div",{className:"rounded-xl border border-amber-500/[0.22] bg-amber-500/[0.08] px-3.5 py-3 text-[12px] text-amber-200 mb-3",children:s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(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})]})]})}),u&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2.5 mb-4",children:[s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Live runtimes"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.runtimeCount})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Recovery"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:w.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Requests"}),s.jsx("div",{className:"text-[18px] font-semibold text-text-primary mt-1",children:u.recentRequests.length})]}),s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3 py-2.5",children:[s.jsx("div",{className:"text-[10px] uppercase tracking-wider text-text-secondary",children:"Started"}),s.jsx("div",{className:"text-[12px] font-medium text-text-primary mt-1",children:Cd(u.hostStartedAt)}),s.jsx("div",{className:"text-[10px] text-text-secondary mt-0.5",children:Lo(u.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:[Lo(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(Mi,{size:14})," Live Hosted Runtimes"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Do("live")}),k.length===0?s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-primary px-3.5 py-4 text-[12px] text-text-secondary",children:"No live hosted runtimes on this machine right now."}):s.jsx("div",{className:"space-y-2",children:k.map(D=>I(D,"live"))})]}),s.jsxs("div",{children:[s.jsxs("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider flex items-center gap-1.5 mb-2.5",children:[s.jsx(Ts,{size:14})," Recovery Snapshots"]}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Do("recovery")}),w.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:w.map(D=>I(D,"recovery"))})]}),v.length>0&&s.jsxs("div",{children:[s.jsx("div",{className:"text-[11px] text-text-secondary font-semibold uppercase tracking-wider mb-2.5",children:"Inactive Records"}),s.jsx("div",{className:"text-[11px] text-text-secondary mb-2.5",children:Do("inactive")}),s.jsx("div",{className:"space-y-2 opacity-85",children:v.map(D=>I(D,"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"}),j.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:j.map(D=>{var P;const L=b.find(_=>_.sessionId===D.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=C.get(D.sessionId))==null?void 0:P.cliName)||D.sessionId}),s.jsxs("div",{className:"text-text-secondary mt-0.5 leading-relaxed",children:[D.action,D.lifecycle?` · ${D.lifecycle}`:"",D.detail?` · ${D.detail}`:"",D.error?` · ${D.error}`:""]})]}),s.jsx("div",{className:`shrink-0 text-[10px] ${D.success===!1?"text-red-300":"text-text-secondary"}`,children:Lo(D.timestamp)})]},`${D.sessionId}:${D.timestamp}:${D.action}`)})})]}),s.jsxs("div",{className:"text-[10px] text-text-secondary mt-3",children:["Endpoint: ",s.jsx("span",{className:"font-mono text-text-primary",children:u.endpoint||"unknown"}),r?s.jsxs("span",{className:"text-amber-200",children:[" · last error: ",r]}):null]})]})]})}function ZT({machine:e,launchPick:t,actions:n}){const{runLaunchCliCore:r,setLaunchPick:a}=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(o=>s.jsxs("button",{type:"button",className:"text-left text-xs px-3 py-2 rounded-lg border border-border-subtle bg-bg-primary hover:bg-violet-500/10 transition-colors",onClick:()=>{a(null),r({cliType:t.cliType,workspaceId:o.id,argsStr:t.argsStr,model:t.model})},children:[s.jsx("span",{className:"font-medium text-text-primary block truncate",children:o.label||o.path}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:o.path})]},o.id))}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx("button",{type:"button",className:"machine-btn text-[11px] flex-1 min-w-[120px]",disabled:!e.defaultWorkspacePath,onClick:()=>{a(null),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:()=>{a(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:()=>a(null),children:"Cancel"})]})]})})}function eM(e,t){const n=Up(e),r=dn(e,t),a=Yi(e,r),o=tr(e,r),i=n==="preview"?"Update to preview":"Update daemon";return a?{visible:!0,showButton:!0,title:o?"Daemon update required":"Version mismatch detected",description:o?"This machine is on an incompatible daemon version. Update it before starting more sessions.":n==="preview"?"This machine can be upgraded to the current preview daemon without opening a remote shell.":"This machine is running a different daemon version than the current app. Update it before starting more sessions.",buttonLabel:i,targetVersion:r,channel:n,required:o,tone:"warn"}:n==="preview"?{visible:!0,showButton:!1,title:r?"Preview daemon is up to date":"Preview update status unknown",description:r?"This machine is already on the current preview daemon target.":"The app is connected to preview, but the server did not report a preview target version yet.",buttonLabel:i,targetVersion:r,channel:n,required:!1,tone:r?"good":"info"}:{visible:!1,showButton:!1,title:"",description:"",buttonLabel:i,targetVersion:r,channel:n,required:!1,tone:"info"}}function Ro({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 Eo({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 tM({machineEntry:e,providers:t,recentLaunches:n,currentConversations:r,onUpgradeDaemon:a,onOpenRecent:o,onOpenConversation:i}){const{t:c}=Ne("common"),d=r.slice(0,6),p=n.slice(0,4),m=eM(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:[d.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ro,{icon:s.jsx(Zs,{size:13}),children:c("machine.commandCenter.currentChats")}),s.jsx(Eo,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:d.map(f=>{const g=mi(f);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>i(f),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:xt(f)}),g>0&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:Ca(g)})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:yn(f)})]},f.tabKey)})})})]}),p.length>0&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ro,{icon:s.jsx(Qd,{size:13}),children:c("machine.commandCenter.recentLaunches")}),s.jsx(Eo,{children:s.jsx("div",{className:"flex flex-col gap-1.5",children:p.map(f=>{const{metaText:g,updatedLabel:C}=tm(f);return s.jsxs("button",{type:"button",className:"flex flex-col gap-1 items-start text-left p-3 rounded-xl bg-bg-glass border border-transparent hover:border-border-default hover:bg-bg-glass transition-colors cursor-pointer group",onClick:()=>o(f),children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 w-full",children:[s.jsx("span",{className:"text-sm font-semibold text-text-primary truncate group-hover:text-accent-primary transition-colors",children:f.label}),C&&s.jsx("span",{className:"text-[11px] text-text-muted shrink-0",children:C})]}),s.jsx("span",{className:"text-xs text-text-secondary truncate w-full opacity-80",children:g})]},f.id)})})})]}),m.visible&&s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(Ro,{icon:s.jsx(Ys,{size:13}),children:c("machine.commandCenter.daemonUpdate")}),s.jsx(Eo,{className:m.tone==="good"?"border-emerald-500/20 bg-emerald-500/5":m.tone==="info"?"border-sky-500/20 bg-sky-500/5":"border-amber-500/20 bg-amber-500/5",children:s.jsxs("div",{className:"flex flex-col gap-3",children:[s.jsx("div",{className:"text-sm font-semibold text-text-primary",children:m.title}),s.jsxs("div",{className:"text-xs text-text-secondary leading-relaxed",children:[m.description,m.targetVersion&&s.jsxs("span",{className:"block mt-1 text-text-muted",children:["Target: v",m.targetVersion,m.channel?` (${m.channel})`:""]})]}),m.showButton?s.jsxs("button",{type:"button",className:"inline-flex items-center justify-center gap-2 px-3 py-2 rounded-xl bg-amber-500/12 border border-amber-500/20 text-amber-300 hover:bg-amber-500/18 transition-colors",onClick:a,children:[s.jsx(Sa,{size:13}),s.jsx("span",{className:"text-sm font-medium",children:m.buttonLabel})]}):s.jsx("div",{className:m.tone==="good"?"text-xs font-medium text-emerald-300":"text-xs font-medium text-sky-300",children:"No preview update action is needed."})]})})]})]})}function sM({machineId:e,machine:t,ideSessions:n,cliSessions:r,acpSessions:a,actions:o,sendDaemonCommand:i}){const{workspaceBusy:c,handleWorkspaceAdd:d,handleWorkspaceRemove:p,handleWorkspaceSetDefault:u}=o,{t:m}=Ne("common"),[f,g]=l.useState(!1),[C,h]=l.useState(""),[x,y]=l.useState([]),[b,S]=l.useState(!1),[k,w]=l.useState(""),v=l.useCallback(async j=>{S(!0),w("");try{const A=await nl(i,e,j);h(A.path),y(A.directories)}catch(A){w(A instanceof Error?A.message:"Could not load folder")}finally{S(!1)}},[e,i]),N=l.useCallback(()=>{g(!0);const j=[...n.map(I=>I.workspace),...r.map(I=>I.workspace),...a.map(I=>I.workspace)],A=sl(t.platform,tl(j,t.defaultWorkspacePath,(t.workspaces||[]).map(I=>I.path)));v(A)},[a,r,n,v,t.defaultWorkspacePath,t.platform,t.workspaces]);return s.jsxs(s.Fragment,{children:[s.jsxs(Ss,{padding:"lg",className:"mb-4",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3 mb-3",children:[s.jsxs("div",{className:"text-[11px] text-text-muted font-semibold uppercase tracking-wider flex items-center gap-1.5",children:[s.jsx(xn,{size:14})," Workspaces"]}),s.jsx("button",{type:"button",className:"btn bg-bg-glass hover:bg-bg-glass-hover text-text-muted hover:text-text-primary px-3 py-1 rounded transition-colors text-xs",disabled:c,onClick:N,children:"+ Add workspace"})]}),(t.workspaces||[]).length===0?s.jsxs("div",{className:"text-[11px] text-text-muted py-4 text-center",children:["No saved workspaces yet. Click ",s.jsx("span",{className:"text-text-secondary",children:"+ Add workspace"})," to pick a folder."]}):s.jsx("ul",{className:"space-y-1.5 max-h-72 overflow-y-auto",children:(t.workspaces||[]).map(j=>{const A=j.id===t.defaultWorkspaceId;return s.jsxs("li",{className:`flex items-start gap-2 text-[11px] rounded-lg border px-2.5 py-2 transition-colors ${A?"border-yellow-500/30 bg-yellow-500/[0.05]":"border-border-subtle bg-bg-primary"}`,children:[s.jsx("button",{type:"button",title:A?"Default workspace — click to unset":"Set as default workspace",disabled:c,onClick:()=>void u(A?null:j.id),className:`text-base leading-none shrink-0 transition-colors ${A?"text-yellow-400 hover:text-yellow-300":"text-text-muted/40 hover:text-yellow-400"}`,children:"★"}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("div",{className:"font-medium text-text-primary truncate",children:vu(j.path,j.label)}),s.jsx("div",{className:"font-mono text-text-muted truncate text-[10px]",title:j.path,children:j.path})]}),s.jsx("button",{type:"button",className:"text-[10px] text-red-400/90 hover:underline shrink-0",disabled:c,onClick:()=>void p(j.id),children:m("machine.managedWorkspaces.remove")})]},j.id)})})]}),f&&s.jsx(al,{title:"Add workspace",description:"Browse the machine like a normal explorer, then add the current folder as a saved workspace.",currentPath:C,directories:x,busy:b,error:k,confirmLabel:"Add workspace",onClose:()=>g(!1),onNavigate:j=>{v(j)},onConfirm:j=>{(async()=>{if(!j)return;await d(j)&&g(!1)})()}})]})}function nM({machine:e,machineId:t,ideSessions:n,cliSessions:r,acpSessions:a,actions:o,sendDaemonCommand:i}){return s.jsxs("div",{className:"flex flex-col flex-1 min-w-0 h-full",children:[s.jsxs("div",{className:"flex flex-col gap-1 pb-4 border-b border-border-subtle mb-4",children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:"Workspaces"}),s.jsx("div",{className:"text-sm text-text-secondary",children:'Save folders as workspaces on this machine. Use the dashboard "+" button to launch a session.'})]}),i&&s.jsx(sM,{machineId:t,machine:e,ideSessions:n,cliSessions:r,acpSessions:a,actions:o,sendDaemonCommand:i})]})}function rM({onNicknameSynced:e}={}){var ye,ke,me,G,U,Z,Y,fe,Te,ce;const{t}=Ne("common"),{id:n}=Wh(),r=mr(),a=Si(),{sendCommand:o}=vt(),i=Tn(),c=Pp(),d=rp(),p=d.ides||[],u=d.initialLoaded??!0,m=p.find($=>$.id===n&&$.type==="adhdev-daemon"),f=p.some($=>$.type==="adhdev-daemon"),g=n?(ye=d.connectionRetryStatuses)==null?void 0:ye[n]:void 0,C=!!(g!=null&&g.blocked),[h,x]=l.useState("workspace"),[y,b]=l.useState(null);l.useCallback(($,pe)=>{b({daemonId:$,workspace:pe})},[]);const[,S]=l.useState("ide"),k=l.useRef(null),[w,v]=l.useState(null),N=l.useRef("__home__"),[j,A]=l.useState("__home__"),[I,D]=l.useState(!1),L=l.useRef(null);l.useEffect(()=>{!n||!m||!(!m.workspaces||!m.availableProviders||!m.detectedIdes||!m.recentLaunches)||i(n,{minFreshMs:3e4}).catch(()=>{})},[i,m,n]),l.useEffect(()=>{if(!n||!m||h!=="overview")return;const $=m.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")&&c(n,{minFreshMs:3e4}).catch(()=>{})},[h,c,m,n]),pC(n&&h==="overview"?[n]:[],{enabled:h==="overview",intervalMs:S0});const P=()=>{if(f){r("/dashboard",{state:{mobileSection:"machines"}});return}r("/machines")},_=QI({machineId:n,registeredMachineId:(m==null?void 0:m.machineId)||null,sendDaemonCommand:o,onNicknameSynced:e,logsEndRef:L});l.useEffect(()=>mt.onToast(pe=>{d.setToasts(F=>{if(F.some(Se=>Se.message===pe.message&&pe.timestamp-Se.timestamp<3e3))return F;const je={id:pe.id,message:pe.message,type:pe.type,timestamp:pe.timestamp,targetKey:pe.targetKey,actions:pe.actions};return[...F.slice(-4),je]});const le=pe.duration||5e3;setTimeout(()=>d.setToasts(F=>F.filter(be=>be.id!==pe.id)),le)}),[d]);const q=(m==null?void 0:m.availableProviders)||[],B={};for(const $ of q)B[$.type]=$.icon;const E=m?{id:m.id,hostname:yu(m,{fallbackId:m.id}),platform:((ke=m.machine)==null?void 0:ke.platform)||"unknown",arch:((me=m.machine)==null?void 0:me.arch)||"",cpus:((G=m.machine)==null?void 0:G.cpus)||0,totalMem:((U=m.machine)==null?void 0:U.totalMem)||0,freeMem:(Z=m.machine)==null?void 0:Z.freeMem,availableMem:(Y=m.machine)==null?void 0:Y.availableMem,loadavg:(fe=m.machine)==null?void 0:fe.loadavg,uptime:(Te=m.machine)==null?void 0:Te.uptime,release:((ce=m.machine)==null?void 0:ce.release)||"",cdpConnected:!!m.cdpConnected,machineNickname:m.machineNickname||null,p2p:m.p2p?{screenshotActive:!1,...m.p2p}:{available:!1,state:"unavailable",peers:0,screenshotActive:!1},detectedIdes:m.detectedIdes||[],workspaces:m.workspaces||[],defaultWorkspaceId:m.defaultWorkspaceId??m.activeWorkspaceId??null,defaultWorkspacePath:m.defaultWorkspacePath??m.activeWorkspacePath??null}:null,K=p.filter($=>$.daemonId===n&&$.type!=="adhdev-daemon").filter($=>!ir($)&&!mn($)).map($=>({id:$.id,sessionId:$.sessionId,type:$.type,version:$.version||"",instanceId:$.instanceId||"",status:$.status,workspace:$.workspace||null,terminals:$.terminals||0,aiAgents:Hy($.aiAgents||($.agents||[]).map(pe=>({id:pe.name,name:pe.name,status:pe.status,version:pe.version}))),activeChat:$.activeChat||null,chats:$.chats||[],childSessions:$.childSessions||[],cdpConnected:$.cdpConnected||!1,daemonId:n,lastMessageAt:$.lastMessageAt})),R=p.filter($=>$.daemonId===n&&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:n,lastMessageAt:$.lastMessageAt})),T=p.filter($=>$.daemonId===n&&mn($)).map($=>({id:$.id,sessionId:$.sessionId,type:$.type,acpName:$.cliName||$.type,status:$.status,workspace:$.workspace||"",activeChat:$.activeChat||null,providerSessionId:$.providerSessionId,daemonId:n,lastMessageAt:$.lastMessageAt})),H=m?ts(m,{fallbackId:n}):"",M="workspace",W=a.state,J=W==null?void 0:W.initialMachineTab,re=W==null?void 0:W.initialWorkspaceCategory;W==null||W.initialWorkspaceId,W==null||W.initialWorkspacePath;const V=J==="ides"||J==="clis"||J==="acps"?"workspace":J||M,X=J==="ides"?"ide":J==="clis"?"cli":J==="acps"?"acp":re,de=[...K.map($=>{var pe;return{id:`ide:${$.type}:${$.workspace||""}`,label:((pe=$.activeChat)==null?void 0:pe.title)||$.type,kind:"ide",providerType:$.type,subtitle:$.workspace||void 0,workspace:$.workspace||void 0,lastLaunchedAt:$.lastMessageAt||0}}),...R.map($=>{var pe;return{id:`cli:${$.type}:${$.workspace||""}`,label:((pe=$.activeChat)==null?void 0:pe.title)||$.cliName,kind:"cli",providerType:$.type,providerSessionId:$.providerSessionId,subtitle:$.workspace||void 0,workspace:$.workspace||void 0,lastLaunchedAt:$.lastMessageAt||0}}),...T.map($=>{var pe;return{id:`acp:${$.type}:${$.workspace||""}`,label:((pe=$.activeChat)==null?void 0:pe.title)||$.acpName,kind:"acp",providerType:$.type,providerSessionId:$.providerSessionId,subtitle:Js($.summaryMetadata)||$.workspace||void 0,workspace:$.workspace||void 0,lastLaunchedAt:$.lastMessageAt||0}})].sort(($,pe)=>(pe.lastLaunchedAt||0)-($.lastLaunchedAt||0)),ne=((m==null?void 0:m.recentLaunches)||[]).length>0?((m==null?void 0:m.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})):de,O=l.useMemo(()=>{var pe;const $=((pe=d.connectionStates)==null?void 0:pe[n||""])||void 0;return p.filter(le=>le.daemonId===n&&le.type!=="adhdev-daemon").flatMap(le=>Vi(le,{connectionStates:n&&$?{[n]:$}:void 0,defaultConnectionState:$})).filter(le=>!(le.transport==="pty"&&le.mode==="terminal")).sort((le,F)=>mi(F)-mi(le))},[p,d.connectionStates,n]),ie=l.useCallback($=>{const pe=Kp($);pe&&r(dr(pe))},[r]),z=l.useCallback(()=>{k.current&&(D(!0),k.current().finally(()=>{k.current=null,D(!1),v(null)}))},[]),ae=l.useCallback($=>{if(!E)return;const{options:pe,selectedKey:le}=em({machine:E,currentWorkspacePath:$.workspace}),F=async()=>{S($.kind),x("workspace")};k.current=async()=>{const be=pe.find(He=>He.key===N.current),je=(be==null?void 0:be.workspacePath)??null,Se=(be==null?void 0:be.workspaceId)??null;if($.kind==="ide"&&$.providerType){await _.handleLaunchIde($.providerType,je?{workspace:je}:void 0);return}if(($.kind==="cli"||$.kind==="acp")&&$.providerType){await _.runLaunchCliCore({cliType:$.providerType,dir:Se?void 0:je||"",workspaceId:Se||void 0,model:$.kind==="acp"&&ku($.summaryMetadata,"model",{preferShortValue:!0})||void 0,resumeSessionId:$.providerSessionId});return}await F()},N.current=le,A(le),v({title:$.kind==="ide"?da("restart-ide",$.label):$.providerSessionId?fp($.label):da("start-fresh",$.label),description:$.kind==="ide"?ua("restart-ide"):$.providerSessionId?bp():ua("start-fresh"),confirmLabel:$.kind==="ide"?pa("restart-ide"):$.providerSessionId?oi(!0):pa("start-fresh"),busyLabel:$.kind==="ide"?ma("restart-ide"):$.providerSessionId?hp(!0):ma("start-fresh"),workspaceOptions:pe,details:[{label:"Mode",value:$.kind.toUpperCase()},...$.providerType?[{label:"Provider",value:$.providerType}]:[]]})},[_,E]);if(l.useEffect(()=>{x(V)},[M,V,n]),l.useEffect(()=>{X&&S(X)},[X,n]),!E)return u?s.jsxs("div",{className:"p-10 text-center text-text-muted",children:[s.jsx("h2",{className:"text-text-primary",children:t("machine.detail.notFound")}),s.jsx("p",{className:"mt-3",children:t("machine.detail.offlineHint")}),s.jsx("button",{onClick:P,className:"machine-btn-back",children:t("machine.detail.back")})]}):s.jsx("div",{className:"p-10 text-center text-text-muted",children:s.jsx("p",{children:t("machine.detail.loading")})});const Ce=[{id:"workspace",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(us,{size:14})," ",t("machine.detail.tabWorkspace")]}),count:K.length+R.length+T.length},{id:"session-host",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Ts,{size:14})," ",t("machine.detail.tabHostedRuntimes")]})},{id:"providers",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(ka,{size:14})," ",t("machine.detail.tabProviders")]})},{id:"overview",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(_f,{size:14})," ",t("machine.detail.tabSystem")]})},{id:"logs",label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(Yd,{size:14})," ",t("machine.detail.tabLogs")]})}];return s.jsxs("div",{className:"flex flex-col h-full",children:[s.jsxs("div",{className:"flex flex-col w-full bg-bg-surface px-4 md:px-8 pt-6 pb-0 shrink-0 border-b border-[#ffffff0a]",children:[s.jsx("div",{className:"flex items-center justify-between w-full",children:s.jsxs("div",{className:"flex items-center gap-3 w-full min-w-0",children:[s.jsx("button",{onClick:P,className:"flex items-center justify-center w-8 h-8 rounded-full bg-[#ffffff0a] hover:bg-[#ffffff14] text-text-muted hover:text-text-primary transition-colors shrink-0",children:"←"}),s.jsxs("div",{className:"flex flex-col min-w-0",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[_.editingNickname?s.jsxs("div",{className:"flex gap-1.5 items-center",children:[s.jsx("input",{autoFocus:!0,value:_.nicknameInput,onChange:$=>_.setNicknameInput($.target.value),onKeyDown:$=>{$.key==="Enter"&&_.handleSaveNickname(),$.key==="Escape"&&_.setEditingNickname(!1)},placeholder:t("machine.detail.nicknamePlaceholder"),className:"px-2.5 py-1 rounded-md border border-violet-500/30 bg-bg-secondary text-text-primary text-sm font-semibold w-[140px] md:w-[200px]"}),s.jsx("button",{onClick:_.handleSaveNickname,className:"flex items-center justify-center px-3 py-1 rounded bg-green-500/20 text-green-400 hover:bg-green-500/30 text-sm font-medium transition-colors",children:t("machine.detail.save")}),s.jsx("button",{onClick:()=>_.setEditingNickname(!1),className:"flex items-center justify-center px-3 py-1 rounded bg-[#ffffff0a] text-text-muted hover:bg-[#ffffff14] hover:text-text-primary text-sm font-medium transition-colors",children:t("machine.detail.cancel")})]}):s.jsx("h1",{className:"text-xl md:text-2xl font-bold text-text-primary cursor-pointer truncate hover:text-accent-primary transition-colors",onClick:()=>{_.setEditingNickname(!0),_.setNicknameInput(E.machineNickname||"")},title:t("machine.detail.clickToSetNickname"),children:H}),C?s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-red-500 shrink-0"}),d.retryConnection&&n&&s.jsx("button",{onClick:()=>d.retryConnection(n),className:"px-2.5 py-0.5 rounded text-[11px] font-semibold bg-red-500/10 border border-red-500/20 text-red-400 hover:bg-red-500/20 transition-colors",children:t("machine.detail.reconnect")})]}):s.jsx("span",{className:"w-2.5 h-2.5 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.6)] shrink-0"})]}),s.jsxs("div",{className:"flex flex-wrap gap-x-3 gap-y-1 items-center mt-1.5 text-xs text-text-secondary opacity-80",children:[s.jsxs("span",{className:"font-mono bg-[#ffffff08] px-1.5 py-0.5 rounded",children:[E.platform," · ",E.arch]}),s.jsx("span",{children:t("machine.detail.coresCount",{count:E.cpus})}),(m==null?void 0:m.version)&&s.jsxs("span",{children:["v",m.version]}),E.p2p.available&&s.jsx("span",{children:t("machine.detail.p2pState",{state:E.p2p.state==="connected"?t("machine.detail.p2pConnected"):E.p2p.state})}),E.machineNickname&&s.jsx("span",{className:"text-text-muted opacity-60 shrink-0",children:E.hostname})]})]})]})}),s.jsx("div",{className:"flex overflow-x-auto overflow-y-hidden mt-4 gap-6 px-1 border-b border-[#ffffff0a]",children:Ce.map($=>s.jsxs("button",{onClick:()=>x($.id),className:`pb-3 text-sm font-medium border-b-2 transition-colors flex items-center gap-2 px-1 whitespace-nowrap ${h===$.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 ${h===$.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:[h==="workspace"&&s.jsxs("div",{className:"flex flex-col md:flex-row gap-6 md:gap-10 h-full",children:[s.jsx(tM,{machineEntry:m,providers:q,recentLaunches:ne,currentConversations:O,onUpgradeDaemon:async()=>{try{await o(n,"daemon_upgrade",Gp(m))}catch{}},onOpenRecent:ae,onOpenConversation:ie}),s.jsx(nM,{machine:E,machineId:n,ideSessions:K,cliSessions:R,acpSessions:T,actions:_,sendDaemonCommand:o})]}),h==="providers"&&s.jsx(dT,{machineId:n,providers:q,sendDaemonCommand:o}),h==="overview"&&s.jsx(XI,{machine:E,ideSessions:K,cliSessions:R,acpSessions:T}),h==="session-host"&&s.jsx(XT,{machineId:n,cliSessions:R,sendDaemonCommand:o}),h==="logs"&&s.jsx(qT,{machineId:n,sendDaemonCommand:o})]})})}),_.launchPick&&E&&s.jsx(ZT,{machine:E,launchPick:_.launchPick,actions:_}),w&&s.jsx(Zp,{title:w.title,description:w.description,details:w.details,workspaceOptions:w.workspaceOptions,selectedWorkspaceKey:j,onWorkspaceChange:$=>{N.current=$,A($)},confirmLabel:w.confirmLabel,busyLabel:w.busyLabel,busy:I,onConfirm:z,onCancel:()=>{k.current=null,v(null)}}),y&&s.jsx(Jm,{daemonId:y.daemonId,workspace:y.workspace,onClose:()=>b(null)}),s.jsx(xp,{toasts:d.toasts||[],onDismiss:$=>d.setToasts(pe=>pe.filter(le=>le.id!==$)),onClickToast:$=>{$.targetKey&&r(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 aM({daemonIds:e,meshId:t,sendData:n,onRevisionAdvance:r}){const a=l.useRef(new Map),o=l.useRef(r);o.current=r;const i=[...new Set(e.filter(Boolean))].sort().join(",");l.useEffect(()=>{a.current=new Map},[i,t]),l.useEffect(()=>{if(!t||!n)return;const c=[...new Set(e.filter(Boolean))];if(c.length===0)return;const d=c.map(p=>ls.subscribe({sendData:n},p,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${p}`,params:{includeSessions:!0}},u=>{if(u.topic!=="daemon.metadata")return;const m=u.meshStateRevisions;if(!m)return;const f=m[t]??m["*"];if(typeof f!="number")return;const g=a.current.get(p);a.current.set(p,f),g!==void 0&&f>g&&o.current()}));return()=>{for(const p of d)p()}},[i,t,n])}const oM={meshHostDaemonSection:!1,createDaemonPicker:!1,addNodeDaemonPicker:!1,queueSection:!0,coordinatorPrompt:!0,nodeInstruction:!0,hermesMcpConfig:!0,reviewInbox:!0},Zm=l.createContext(null);function iM(){const e=l.useContext(Zm);if(!e)throw new Error("useRepoMeshContext must be used inside RepoMeshProvider");return e}function lM({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 cM({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 dM({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 uM({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 pM({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 mM(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function hM({meshes:e,loading:t,error:n,onDismissError:r,daemons:a,features:o,showCreate:i,onToggleCreate:c,createName:d,onCreateNameChange:p,createRepoIdentity:u,onCreateRepoIdentityChange:m,createRepoRemoteUrl:f,onCreateRepoRemoteUrlChange:g,newMeshDaemonId:C,onNewMeshDaemonIdChange:h,newMeshWorkspace:x,onNewMeshWorkspaceChange:y,createPickerWorkspaces:b,onSelectMesh:S,onCreate:k,onCancelCreate:w}){const{t:v}=Ne("common");return s.jsxs(gr,{icon:s.jsx(es,{}),title:v("repoMesh.list.title"),subtitle:v("repoMesh.list.count",{count:e.length}),widthClassName:"max-w-5xl",actions:s.jsx("button",{className:"btn btn-primary btn-sm",onClick:c,children:v("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:v("repoMesh.list.createTitle")}),o.createDaemonPicker&&s.jsx(Ct,{label:v("repoMesh.list.createOnMachine"),hint:v("repoMesh.list.createOnMachineHint"),children:s.jsx("select",{className:"input w-full",value:C,onChange:N=>h(N.target.value),disabled:!a.length,children:a.length===0?s.jsx("option",{value:"",children:v("repoMesh.list.noConnectedDaemon")}):a.map(N=>s.jsx("option",{value:N.id,children:mM(N)},N.id))})}),o.createDaemonPicker&&s.jsx(Ct,{label:v("repoMesh.list.workspace"),hint:v("repoMesh.list.workspaceHint"),children:s.jsx("select",{className:"input w-full",value:x,onChange:N=>y(N.target.value),disabled:!C||!b.length,children:C?b.length===0?s.jsx("option",{value:"",children:v("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:v("repoMesh.list.selectMachineFirst")})})}),s.jsx(Ct,{label:v("repoMesh.list.name"),children:s.jsx(is,{value:d,onChange:N=>p(N.target.value),placeholder:"my-project-mesh",autoFocus:!0})}),s.jsx(Ct,{label:v("repoMesh.list.remoteUrl"),hint:v("repoMesh.list.remoteUrlHint"),children:s.jsx(is,{value:f,onChange:N=>g(N.target.value),placeholder:"https://github.com/user/repo"})}),s.jsx(Ct,{label:v("repoMesh.list.repoIdentity"),hint:v("repoMesh.list.remoteUrlHint"),children:s.jsx(is,{value:u,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:k,disabled:!d.trim()||!f.trim()&&!u.trim()||o.createDaemonPicker&&(!C||!x),children:v("repoMesh.list.create")}),s.jsx("button",{className:"btn btn-secondary btn-sm",onClick:w,children:v("repoMesh.list.cancel")})]})]}),t?s.jsx("div",{className:"text-sm text-text-muted p-4",children:v("repoMesh.list.loading")}):e.length===0?s.jsx(La,{icon:s.jsx(es,{}),title:v("repoMesh.list.emptyTitle"),description:a.length>0?v("repoMesh.list.emptyWithDaemons"):v("repoMesh.list.emptyNoDaemons"),action:s.jsx("button",{className:"btn btn-primary btn-sm",disabled:!a.length,onClick:c,children:v("repoMesh.list.createFirst")})}):s.jsx("div",{className:"flex flex-col gap-2.5",children:e.map(N=>{var j;return s.jsx("button",{type:"button",onClick:()=>S(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||v("repoMesh.list.noRepoIdentity")}),(N.defaultBranch||N.default_branch)&&s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(cM,{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:[((j=N.nodes)==null?void 0:j.length)??N.nodeCount??0," ",v("repoMesh.list.nodesSuffix")]})]})]})},N.id)})})]})}const fM=["claude-cli","codex-cli","gemini-cli","hermes-cli","antigravity-cli"],bM=[{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 gM(){return{nodeId:"",provider:"",model:"",n:""}}function jd(e){var t;return(t=e.providers)!=null&&t.length?e.providers.filter(Boolean):(e.providerPriority??[]).filter(Boolean)}function xM(e){return{nodeId:e.nodeId??"",provider:e.provider??"",model:e.model??"",n:e.n!=null?String(e.n):""}}function vM(e){const t=[];for(let n=0;n<e.length;n++){const r=e[n],a=r.provider.trim();if(!a)return{error:{code:"provider_required",slot:n+1}};const o=r.nodeId.trim(),i=r.model.trim(),c=r.n.trim();let d;if(c){const p=Number(c);if(!Number.isFinite(p)||p<1)return{error:{code:"replica_min",slot:n+1}};d=Math.floor(p)}t.push({provider:a,...o?{nodeId:o}:{},...i?{model:i}:{},...d!==void 0?{n:d}:{}})}return t.length===0?{error:{code:"no_slot"}}:{slots:t}}function yM({status:e,daemonId:t,sendDaemonCommand:n,availableProviders:r}){const{t:a}=Ne(),{theme:o}=Ls(),i=l.useMemo(()=>Rs(o),[o]),c=l.useMemo(()=>Sp(r),[r]),[d,p]=l.useState({}),[u,m]=l.useState(!1),[f,g]=l.useState(null),[C,h]=l.useState({}),[x,y]=l.useState(null),b=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(T=>({nodeId:T.nodeId,machineLabel:T.machineLabel,providers:T.providers,providerPriority:T.providerPriority})),[e==null?void 0:e.nodes]),S=l.useMemo(()=>((e==null?void 0:e.nodes)??[]).map(T=>T.nodeId),[e==null?void 0:e.nodes]),k=l.useMemo(()=>Object.fromEntries(((e==null?void 0:e.nodes)??[]).map(T=>[T.nodeId,T.machineLabel||T.nodeId])),[e==null?void 0:e.nodes]),w=l.useMemo(()=>{const T={};for(const H of b)T[H.nodeId]=jd(H);return T},[b]),v=l.useMemo(()=>{const T=[...new Set(b.flatMap(jd).filter(Boolean))];return[...new Set([...T,...fM])].sort()},[b]),N=!!t&&!!n,j=T=>T&&typeof T=="object"&&"result"in T?T.result:T,A=l.useCallback(async()=>{if(!(!t||!n)){m(!0),g(null);try{const T=await n(t,"magi_kind_panel_list",{}),H=j(T);if((H==null?void 0:H.success)===!1)throw new Error(H.error||a("meshGraph.magiKind.errorLoad"));p(H!=null&&H.kindPanels&&typeof H.kindPanels=="object"?H.kindPanels:{}),h({})}catch(T){g((T==null?void 0:T.message)||a("meshGraph.magiKind.errorLoad"))}finally{m(!1)}}},[t,n,a]);l.useEffect(()=>{A()},[A]);const I=l.useCallback(T=>{if(C[T])return C[T];const H=d[T];return H?H.map(xM):[]},[C,d]),D=(T,H)=>{h(M=>({...M,[T]:H}))},L=(T,H,M)=>{const W=I(T);D(T,W.map((J,re)=>re===H?{...J,...M}:J))},P=T=>{D(T,[...I(T),gM()])},_=(T,H)=>{D(T,I(T).filter((M,W)=>W!==H))},q=l.useCallback(async T=>{if(!t||!n)return;const H=vM(I(T));if("error"in H){const M=H.error,W=M.code==="provider_required"?a("meshGraph.magiKind.errorSlotProvider",{slot:M.slot}):M.code==="replica_min"?a("meshGraph.magiKind.errorSlotReplica",{slot:M.slot}):a("meshGraph.magiKind.errorNoSlot");g(`${T}: ${W}`);return}y(T),g(null);try{const M=await n(t,"magi_kind_panel_set",{kind:T,slots:H.slots}),W=j(M);if((W==null?void 0:W.success)===!1)throw new Error(W.error||a("meshGraph.magiKind.errorSave"));await A()}catch(M){g((M==null?void 0:M.message)||a("meshGraph.magiKind.errorSave"))}finally{y(null)}},[t,n,I,A,a]),B=l.useCallback(async T=>{if(!(!t||!n)&&confirm(a("meshGraph.magiKind.removeConfirm",{kind:T}))){y(T),g(null);try{const H=await n(t,"magi_kind_panel_remove",{kind:T}),M=j(H);if((M==null?void 0:M.success)===!1)throw new Error(M.error||a("meshGraph.magiKind.errorRemove"));await A()}catch(H){g((H==null?void 0:H.message)||a("meshGraph.magiKind.errorRemove"))}finally{y(null)}}},[t,n,A,a]),E=`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"}`,K="btn btn-primary btn-sm",R="btn btn-secondary btn-sm";return s.jsxs("div",{className:"flex flex-col gap-3 p-1",children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("p",{className:`text-[12px] ${i.textSecondary}`,children:a("meshGraph.magiKind.intro")}),s.jsx("div",{className:"ml-auto flex items-center gap-2",children:s.jsx("button",{type:"button",className:R,onClick:()=>void A(),disabled:u||!N,children:a(u?"meshGraph.magiKind.loading":"meshGraph.magiKind.refresh")})})]}),!N&&s.jsx("div",{className:`rounded-xl border p-3 text-[12px] ${i.textSecondary} ${i.isDark?"border-white/10":"border-slate-200"}`,children:a("meshGraph.magiKind.connectPrompt")}),f&&s.jsx("div",{className:"rounded-xl border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-[12px] text-rose-300",children:f}),s.jsx("div",{className:"flex flex-col gap-3",children:bM.map(({kind:T,labelKey:H,hint:M})=>{const W=I(T),J=!!d[T],re=x===T;return s.jsxs("div",{className:`${i.cardClass} rounded-2xl p-4 flex flex-col gap-3`,children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("span",{className:`text-[13px] font-semibold ${i.textPrimary}`,children:a(H)}),s.jsx("span",{className:`font-mono text-[10px] ${i.textMuted}`,children:M}),s.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.14em] ${J?"border-emerald-400/30 bg-emerald-500/10 text-emerald-300":"border-slate-400/20 bg-slate-500/10 text-slate-300"}`,children:J?a("meshGraph.magiKind.agentCount",{count:d[T].length}):a("meshGraph.magiKind.off")})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[W.length===0&&s.jsx("div",{className:`rounded-xl border p-2.5 text-[11px] ${i.textSecondary} ${i.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:a("meshGraph.magiKind.noAgents")}),W.map((V,X)=>{const de=V.nodeId?w[V.nodeId]??[]:[],ne=V.nodeId&&de.length?de:v;return s.jsxs("div",{className:`rounded-xl border p-2.5 grid grid-cols-1 sm:grid-cols-[1fr_1fr_1fr_auto_auto] gap-x-2 gap-y-1 items-start ${i.isDark?"border-white/10 bg-slate-950/30":"border-slate-200 bg-white"}`,children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:a("meshGraph.magiKind.machine")}),s.jsxs("select",{className:E,value:V.nodeId,onChange:O=>L(T,X,{nodeId:O.target.value}),title:a("meshGraph.magiKind.machineTitle"),children:[s.jsx("option",{value:"",children:a("meshGraph.magiKind.anyMachine")}),S.map(O=>s.jsx("option",{value:O,children:k[O]??O},O)),V.nodeId&&!S.includes(V.nodeId)&&s.jsx("option",{value:V.nodeId,children:a("meshGraph.magiKind.offlineSuffix",{label:k[V.nodeId]??V.nodeId})})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsxs("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:[a("meshGraph.magiKind.provider")," *"]}),s.jsxs("select",{className:E,value:V.provider,onChange:O=>L(T,X,{provider:O.target.value}),title:a("meshGraph.magiKind.providerTitle"),children:[s.jsx("option",{value:"",children:a("meshGraph.magiKind.selectProvider")}),ne.map(O=>s.jsx("option",{value:O,children:O},O)),V.provider&&!ne.includes(V.provider)&&s.jsx("option",{value:V.provider,children:V.provider})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:a("meshGraph.magiKind.model")}),(()=>{var z;const O=(V.provider?(z=c.get(V.provider))==null?void 0:z.models:void 0)??[],ie=!!V.model&&O.length>0&&!O.includes(V.model);return O.length>0&&!ie?s.jsxs("select",{className:E,value:O.includes(V.model)?V.model:"",title:a("meshGraph.magiKind.modelTitle"),onChange:ae=>L(T,X,{model:ae.target.value==="__custom__"?" ":ae.target.value}),children:[s.jsx("option",{value:"",children:a("meshGraph.magiKind.modelDefault")}),O.map(ae=>s.jsx("option",{value:ae,children:ae},ae)),s.jsx("option",{value:"__custom__",children:a("meshGraph.magiKind.modelCustom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:E,value:V.model.trim(),placeholder:a("meshGraph.magiKind.modelDefault"),title:a("meshGraph.magiKind.modelTitle"),onChange:ae=>L(T,X,{model:ae.target.value})}),O.length>0&&s.jsx("button",{type:"button",className:`self-start bg-transparent border-none cursor-pointer p-0 text-[10px] ${i.textSecondary} hover:underline`,onClick:()=>L(T,X,{model:""}),children:a("meshGraph.magiKind.backToModelList")})]})})()]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:`text-[9px] uppercase tracking-wide ${i.textSecondary}`,children:a("meshGraph.magiKind.copies")}),s.jsx("input",{className:`${E} sm:w-16`,value:V.n,placeholder:"1",inputMode:"numeric",title:a("meshGraph.magiKind.copiesTitle"),onChange:O=>L(T,X,{n:O.target.value})})]}),s.jsx("button",{type:"button",className:`${R} sm:mt-[18px] inline-flex h-8 w-8 items-center justify-center p-0`,onClick:()=>_(T,X),"aria-label":a("meshGraph.magiKind.removeAgent"),title:a("meshGraph.magiKind.removeAgent"),children:"✕"})]},X)}),s.jsx("div",{children:s.jsx("button",{type:"button",className:R,onClick:()=>P(T),disabled:!N,children:a("meshGraph.magiKind.addAgent")})})]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",className:K,onClick:()=>void q(T),disabled:re||!N,children:a(re?"meshGraph.magiKind.saving":"meshGraph.magiKind.save")}),s.jsx("button",{type:"button",className:R,onClick:()=>void B(T),disabled:re||!N||!J,title:a(J?"meshGraph.magiKind.removeBindingTitle":"meshGraph.magiKind.removeBindingDisabledTitle"),children:a("meshGraph.magiKind.removeBinding")})]})]},T)})})]})}function wM({daemonId:e,meshId:t,cliType:n,sendCommand:r}){const{t:a}=Ne(),[o,i]=l.useState(!1),[c,d]=l.useState(!1),[p,u]=l.useState(null),[m,f]=l.useState(null),[g,C]=l.useState(null),h=l.useCallback(async()=>{if(!e||!t){u(a("repoMesh.promptPreview.connectPrompt"));return}d(!0),u(null);try{const y=await r(e,"coordinator_prompt_preview",{meshId:t,cliType:n}),b=y!=null&&y.result&&typeof y.result=="object"?y.result:y;if(!(b!=null&&b.success)){u((b==null?void 0:b.error)||a("repoMesh.promptPreview.errorRender"));return}f(typeof b.prompt=="string"?b.prompt:""),C(typeof b.bytes=="number"?b.bytes:null)}catch(y){u((y==null?void 0:y.message)||String(y))}finally{d(!1)}},[e,t,n,r,a]),x=l.useCallback(()=>{const y=!o;i(y),y&&m===null&&!c&&h()},[o,m,c,h]);return s.jsxs("div",{className:"mt-2",children:[s.jsxs("button",{type:"button",onClick:x,className:"inline-flex items-center gap-1 text-[12px] text-accent-primary bg-transparent border-none cursor-pointer p-0",children:[s.jsx("span",{className:`transition-transform ${o?"rotate-90":""}`,"aria-hidden":!0,children:"▸"}),a(o?"repoMesh.promptPreview.hide":"repoMesh.promptPreview.view"),s.jsxs("span",{className:"text-text-muted",children:["(",n,")"]})]}),o&&s.jsxs("div",{className:"mt-2",children:[c&&s.jsx("div",{className:"text-[12px] text-text-muted",children:a("repoMesh.promptPreview.rendering")}),p&&s.jsxs("div",{className:"rounded-md border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-[12px] text-amber-300",children:[p,s.jsx("button",{type:"button",onClick:()=>void h(),className:"ml-2 underline bg-transparent border-none cursor-pointer text-amber-300",children:a("repoMesh.promptPreview.retry")})]}),!c&&!p&&m!==null&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"mb-1 flex items-center justify-between text-[11px] text-text-muted",children:[s.jsx("span",{children:a("repoMesh.promptPreview.info")}),g!==null&&s.jsxs("span",{children:[(g/1024).toFixed(1)," KB"]})]}),s.jsx("textarea",{readOnly:!0,value:m,rows:14,className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-secondary font-mono",onFocus:y=>y.currentTarget.select()})]})]})]})}const kM=e=>e&&typeof e=="object"&&"result"in e?e.result:e;function SM(e){const t=kM(e);return t&&typeof t=="object"&&t.status&&typeof t.status=="object"&&Array.isArray(t.status.missions)?t.status:t}function CM(e){const t=e==null?void 0:e.missions;return Array.isArray(t)?t:[]}function jM(e){return typeof e.goal=="string"&&e.goal?{text:e.goal,truncated:!1}:{text:e.goalPreview??"",truncated:e.goalTruncated===!0}}const NM=["active","paused","completed","abandoned"];function Nd(e){return(e.status||"active").toLowerCase()}const AM=8;function IM({status:e,daemonId:t,meshId:n,sendCommand:r}){const{t:a}=Ne("common"),o=l.useMemo(()=>CM(e),[e]),[i,c]=l.useState({}),[d,p]=l.useState({}),[u,m]=l.useState(!1),[f,g]=l.useState(null),[C,h]=l.useState("active"),[x,y]=l.useState(!1),b=l.useMemo(()=>{const A={};for(const I of o){const D=Nd(I);A[D]=(A[D]||0)+1}return A},[o]),S=l.useMemo(()=>C==="all"?o:o.filter(A=>Nd(A)===C),[o,C]),k=x?S:S.slice(0,AM),w=S.length-k.length,v=!!t&&o.length>0,N=l.useCallback(async()=>{if(t){m(!0),g(null);try{const A=await r(t,"mesh_status",{meshId:n,verbose:!0}),I=SM(A),D=Array.isArray(I==null?void 0:I.missions)?I.missions:[],L={};for(const P of D)P.id&&typeof P.goal=="string"&&P.goal&&(L[P.id]=P.goal);c(P=>({...P,...L}))}catch(A){g(A instanceof Error?A.message:a("repoMesh.missions.errorFetch"))}finally{m(!1)}}},[t,n,r,a]),j=l.useCallback(A=>{p(I=>({...I,[A]:!I[A]})),!d[A]&&!i[A]&&N()},[d,i,N]);return o.length===0?null:s.jsxs(bt,{title:a("repoMesh.missions.title"),description:a("repoMesh.missions.description"),children:[f&&s.jsx("div",{className:"mb-3 text-[12px] text-amber-400",children:f}),s.jsxs("div",{className:"mb-3 flex flex-wrap items-center gap-1.5",children:[NM.filter(A=>(b[A]||0)>0).map(A=>s.jsxs("button",{type:"button",onClick:()=>{h(A),y(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] capitalize transition-colors ${C===A?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:[A," ",b[A]]},A)),s.jsxs("button",{type:"button",onClick:()=>{h("all"),y(!1)},className:`rounded-full border px-2.5 py-0.5 text-[11px] transition-colors ${C==="all"?"border-accent-primary text-accent-primary":"border-border-subtle text-text-muted hover:text-text-secondary"}`,children:["All ",o.length]})]}),S.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:a("repoMesh.missions.empty",{status:C})}),s.jsx("div",{className:"flex flex-col gap-2",children:k.map(A=>{var B;const I=d[A.id]===!0,D=i[A.id],L=jM(A),P=I&&D?D:L.text,_=I&&!D&&L.truncated,q=((B=A.tasks)==null?void 0:B.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}),q>0&&s.jsx("span",{className:"shrink-0 text-[11px] text-text-muted",children:a("repoMesh.missions.taskCount",{count:q})})]}),P&&s.jsxs("div",{className:`mt-1.5 whitespace-pre-wrap text-[12px] leading-5 text-text-secondary ${I?"max-h-72 overflow-y-auto":"line-clamp-2"}`,children:[P,_&&s.jsx("span",{className:"text-text-muted",children:a("repoMesh.missions.goalUnavailable")})]}),(L.truncated||D)&&v&&s.jsx("button",{type:"button",className:"mt-1.5 text-[12px] text-accent-primary hover:underline disabled:opacity-50",onClick:()=>j(A.id),disabled:u,children:a(I?"repoMesh.missions.showLess":u&&!D?"repoMesh.missions.loading":"repoMesh.missions.showFullGoal")})]},A.id)})}),w>0&&s.jsx("button",{type:"button",className:"mt-2 text-[12px] text-accent-primary hover:underline",onClick:()=>y(!0),children:a("repoMesh.missions.showMore",{count:w})})]})}const TM=["","low","medium","high"],MM={easy:"Easy",medium:"Medium",difficult:"Difficult",freeform:"Freeform"};function Ad(e){return{provider:e.provider||"",model:e.model||"",thinkingLevel:e.thinkingLevel||"",difficulty:Array.isArray(e.difficulty)?e.difficulty:[],capability:Array.isArray(e.capability)?e.capability:[],maxParallel:e.maxParallel!=null?String(e.maxParallel):""}}function Id(e){const t=e.provider.trim();if(!t)return null;const n=e.model.trim(),r=e.thinkingLevel.trim()||void 0,a=Number(e.maxParallel),o=Number.isFinite(a)&&a>0?Math.floor(a):void 0;return{provider:t,...n?{model:n}:{},...r?{thinkingLevel:r}:{},...e.difficulty.length?{difficulty:e.difficulty}:{},...e.capability.length?{capability:e.capability}:{},...o!==void 0?{maxParallel:o}:{}}}function DM(){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 PM({slots:e,availableProviders:t,saving:n,onSave:r}){const{t:a}=Ne("common"),[o,i]=l.useState(()=>e.map(Ad)),c=l.useMemo(()=>JSON.stringify(e),[e]);l.useEffect(()=>{i(e.map(Ad))},[c]);const d=l.useMemo(()=>[...new Set(t.map(b=>b.type).filter(Boolean))],[t]),p=l.useMemo(()=>Sp(t),[t]),u=l.useMemo(()=>{const b=o.map(Id).filter(Boolean);return JSON.stringify(b)!==JSON.stringify(e)},[o,e]),m=(b,S)=>i(k=>k.map((w,v)=>v===b?{...w,...S}:w)),f=(b,S)=>i(k=>k.map((w,v)=>{var A;if(v!==b)return w;const N=((A=p.get(S))==null?void 0:A.models)??[],j=!w.model||N.length===0||N.includes(w.model);return{...w,provider:S,...j?{}:{model:""}}})),g=b=>i(S=>S.filter((k,w)=>w!==b)),C=()=>i(b=>[...b,DM()]),h=(b,S)=>i(k=>{const w=b+S;if(w<0||w>=k.length)return k;const v=[...k];return[v[b],v[w]]=[v[w],v[b]],v}),x=(b,S)=>i(k=>k.map((w,v)=>{if(v!==b)return w;const N=w.difficulty.includes(S);return{...w,difficulty:N?w.difficulty.filter(j=>j!==S):[...w.difficulty,S]}})),y=()=>r(o.map(Id).filter(Boolean));return s.jsxs("div",{className:"flex flex-col gap-2",onClick:b=>b.stopPropagation(),children:[o.length===0&&s.jsx("div",{className:"text-[12px] text-text-muted",children:a("repoMesh.slotEditor.empty")}),o.map((b,S)=>s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-secondary/40 p-2.5",children:[s.jsxs("div",{className:"flex items-center gap-1.5 mb-2",children:[s.jsxs("span",{className:"text-[11px] font-semibold text-text-muted",children:["#",S+1]}),s.jsxs("div",{className:"ml-auto flex items-center gap-1",children:[s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:S===0,onClick:()=>h(S,-1),title:a("repoMesh.slotEditor.moveUp"),children:"↑"}),s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-border-subtle text-text-muted hover:text-text-primary disabled:opacity-40",disabled:S===o.length-1,onClick:()=>h(S,1),title:a("repoMesh.slotEditor.moveDown"),children:"↓"}),s.jsx("button",{type:"button",className:"inline-flex h-6 w-6 items-center justify-center rounded-full border border-status-error/30 text-status-error hover:bg-status-error/10",onClick:()=>g(S),"aria-label":a("repoMesh.slotEditor.removeSlot"),children:s.jsx(At,{size:12})})]})]}),s.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:a("repoMesh.slotEditor.provider")}),d.length>0?s.jsxs("select",{className:_s,value:b.provider,onChange:k=>f(S,k.target.value),children:[s.jsx("option",{value:"",children:a("repoMesh.slotEditor.select")}),d.map(k=>s.jsx("option",{value:k,children:k},k)),b.provider&&!d.includes(b.provider)&&s.jsx("option",{value:b.provider,children:b.provider})]}):s.jsx("input",{className:_s,value:b.provider,placeholder:"claude-cli",onChange:k=>m(S,{provider:k.target.value})})]}),(()=>{var j;const k=p.get(b.provider),w=(k==null?void 0:k.models)??[],v=(j=k==null?void 0:k.thinking)!=null&&j.length?["",...k.thinking]:TM,N=!!b.model&&w.length>0&&!w.includes(b.model);return s.jsxs(s.Fragment,{children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:a("repoMesh.slotEditor.model")}),w.length>0&&!N?s.jsxs("select",{className:_s,value:w.includes(b.model)?b.model:"",onChange:A=>m(S,{model:A.target.value==="__custom__"?" ":A.target.value}),children:[s.jsx("option",{value:"",children:a("repoMesh.slotEditor.providerDefault")}),w.map(A=>s.jsx("option",{value:A,children:A},A)),s.jsx("option",{value:"__custom__",children:a("repoMesh.slotEditor.custom")})]}):s.jsxs(s.Fragment,{children:[s.jsx("input",{className:_s,value:b.model.trim(),placeholder:b.provider?`${b.provider} model`:a("repoMesh.slotEditor.modelPlaceholder"),onChange:A=>m(S,{model:A.target.value})}),w.length>0&&s.jsx("button",{type:"button",className:"self-start bg-transparent border-none cursor-pointer p-0 text-[10px] text-text-muted hover:underline",onClick:()=>m(S,{model:""}),children:a("repoMesh.slotEditor.backToModelList")})]})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:a("repoMesh.slotEditor.thinking")}),s.jsx("select",{className:_s,value:b.thinkingLevel,onChange:A=>m(S,{thinkingLevel:A.target.value}),children:v.map(A=>s.jsx("option",{value:A,children:A||a("repoMesh.slotEditor.thinkingDefault")},A||"_default"))})]})]})})()]}),s.jsxs("div",{className:"mt-2",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:a("repoMesh.slotEditor.difficulty")}),s.jsx("div",{className:"mt-1 flex flex-wrap gap-1.5",children:jy.map(k=>{const w=b.difficulty.includes(k);return s.jsx("button",{type:"button",className:`rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors ${w?"border-accent-primary/60 bg-accent-primary/15 text-accent-primary":"border-border-subtle bg-bg-primary/60 text-text-muted hover:text-text-primary"}`,onClick:()=>x(S,k),children:MM[k]},k)})})]}),s.jsxs("div",{className:"mt-2 grid grid-cols-1 sm:grid-cols-2 gap-2",children:[s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:a("repoMesh.slotEditor.capabilityTags")}),s.jsx("input",{className:_s,value:b.capability.join(", "),placeholder:"worktree, os=darwin",onChange:k=>m(S,{capability:k.target.value.split(",").map(w=>w.trim()).filter(Boolean)})})]}),s.jsxs("label",{className:"flex flex-col gap-1",children:[s.jsx("span",{className:"text-[11px] text-text-muted",children:a("repoMesh.slotEditor.maxParallel")}),s.jsx("input",{type:"number",inputMode:"numeric",min:1,className:_s,value:b.maxParallel,placeholder:a("repoMesh.slotEditor.maxParallelPlaceholder"),onChange:k=>m(S,{maxParallel:k.target.value})})]})]})]},S)),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm inline-flex items-center gap-1",onClick:C,children:[s.jsx(Di,{size:13})," ",a("repoMesh.slotEditor.addSlot")]}),s.jsx("button",{type:"button",className:"btn btn-primary btn-sm ml-auto",onClick:y,disabled:!!n||!u,children:a(n?"repoMesh.slotEditor.saving":"repoMesh.slotEditor.saveSlots")})]})]})}function LM(e){const t=new Map;for(const n of e)n!=null&&n.id&&t.set(n.id,wn(n.availableProviders||[]));return t}function RM(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 EM(e){var d,p,u;const t=e,n=[],r=Array.isArray(t.capabilities)?t.capabilities:[];for(const m of r){const f=typeof m=="string"?m.trim():"";f&&n.push({tag:f,custom:!0})}const a=(((d=t.userOverrides)==null?void 0:d.platform)||t.reportedPlatform||"").toString().trim(),o=(((p=t.userOverrides)==null?void 0:p.arch)||t.reportedArch||"").toString().trim();a&&n.push({tag:`os=${a}`,custom:!1}),o&&n.push({tag:`arch=${o}`,custom:!1});const i=Array.isArray((u=t.policy)==null?void 0:u.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 _M(e){const t=e.capabilities;return Array.isArray(t)?t.map(n=>typeof n=="string"?n.trim():"").filter(Boolean):[]}const $M=["os=","arch=","provider=","worktree=","converge="];function HM({node:e,saving:t,onSave:n}){const{t:r}=Ne("common"),a=l.useMemo(()=>EM(e).filter(h=>!h.custom),[e]),o=l.useMemo(()=>_M(e),[e]),[i,c]=l.useState(o),[d,p]=l.useState(""),u=JSON.stringify(i)!==JSON.stringify(o),f=(h=>{const x=h.trim();return x?/\s/.test(x)?r("repoMesh.tagEditor.noSpaces"):$M.some(y=>x.toLowerCase().startsWith(y))?r("repoMesh.tagEditor.reservedPrefix"):i.includes(x)?r("repoMesh.tagEditor.alreadyAdded"):null:null})(d);function g(){const h=d.trim();!h||f||(c(x=>[...x,h]),p(""))}function C(h){c(x=>x.filter(y=>y!==h))}return s.jsxs("div",{className:"mt-2",onClick:h=>h.stopPropagation(),children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[s.jsx("span",{className:"text-[10px] uppercase tracking-wide text-text-muted mr-1",children:r("repoMesh.tagEditor.routingTags")}),a.map(h=>s.jsx("span",{className:"rounded-full border border-border-subtle bg-bg-secondary px-1.5 py-0.5 font-mono text-[10px] text-text-muted",title:r("repoMesh.tagEditor.autoDerivedTitle"),children:h.tag},h.tag)),i.map(h=>s.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-accent-primary/40 bg-accent-primary/10 px-1.5 py-0.5 font-mono text-[10px] text-accent-primary",title:r("repoMesh.tagEditor.customTagTitle"),children:[h,s.jsx("button",{type:"button",className:"text-accent-primary/70 hover:text-accent-primary bg-transparent border-none cursor-pointer p-0 leading-none",onClick:()=>C(h),disabled:t,"aria-label":r("repoMesh.tagEditor.remove",{tag:h}),children:"×"})]},h))]}),s.jsxs("div",{className:"mt-1.5 flex flex-wrap items-center gap-2",children:[s.jsx("input",{type:"text",value:d,onChange:h=>p(h.target.value),onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),g())},placeholder:r("repoMesh.tagEditor.addPlaceholder"),disabled:t,className:"min-w-[12rem] flex-1 px-2 py-1 rounded-lg bg-bg-secondary border border-border-subtle text-[12px] text-text-primary"}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:g,disabled:t||!d.trim()||!!f,children:r("repoMesh.tagEditor.add")}),u&&s.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>n(i),disabled:t,children:r(t?"repoMesh.tagEditor.saving":"repoMesh.tagEditor.saveTags")})]}),f&&s.jsx("div",{className:"mt-1 text-[11px] text-amber-400",children:f}),i.length===0&&a.length===0&&s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:r("repoMesh.tagEditor.empty")})]})}function BM(e,t){return t.filter(n=>n.status!=="assigned"?!1:(n.assignedNodeId||n.nodeId)===e.id)}function FM(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 OM(e){var r;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>n.has(a)?!1:(n.add(a),!0))}function WM(e){const t=OM(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 UM(e){return e.isLocalWorktree===!0}function GM(e,t){const n=t;return[...Array.isArray(n==null?void 0:n.cliSessions)?n.cliSessions:[],...Array.isArray(n==null?void 0:n.acpSessions)?n.acpSessions:[],...Array.isArray(n==null?void 0:n.sessions)?n.sessions:[]].filter(a=>{var o;return((o=a==null?void 0:a.settings)==null?void 0:o.meshNodeId)===e.id||(a==null?void 0:a.workspace)===e.workspace}).map(a=>{var o;return{id:a.sessionId||a.id||a.instanceId||"unknown",provider:a.providerType||a.cliType||a.acpType||a.type||"unknown",status:a.status||((o=a.activeChat)==null?void 0:o.status)||"unknown"}})}function Td(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function qM(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 zM({nodes:e,meshQueue:t,activeDaemon:n,daemons:r,selectedMeshId:a,userName:o,features:i,coordinatorDaemonId:c,availableCliProviders:d,savingNodeSlotsId:p,onUpdateNodeSlots:u,savingNodeCapabilitiesId:m,onUpdateNodeCapabilities:f,nodeSystemPromptDrafts:g,onNodeSystemPromptDraftChange:C,savingNodeSystemPromptId:h,onSaveNodeSystemPrompt:x,selectedNodeId:y,onSelectNode:b,showAddNode:S,onShowAddNode:k,onCancelAddNode:w,nodeWorkspace:v,onNodeWorkspaceChange:N,nodeProviderPriority:j,onNodeProviderPriorityChange:A,nodeDaemonId:I,onNodeDaemonIdChange:D,nodeCustomPath:L,onNodeCustomPathChange:P,nodePickerWorkspaces:_,nodePickerProviders:q,attachableDaemons:B,onAddNode:E,onRemoveNode:K}){const{t:R}=Ne("common"),T=l.useMemo(()=>LM(r),[r]),H=l.useMemo(()=>e.filter(M=>!UM(M)),[e]);return s.jsxs(bt,{title:i.addNodeDaemonPicker?R("repoMesh.nodeList.title",{count:H.length}):R("repoMesh.nodeList.titleNoCount"),description:i.addNodeDaemonPicker?R("repoMesh.nodeList.descriptionCloud"):R("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:R("repoMesh.nodeList.daemonCandidates")}),s.jsx("div",{className:"text-[12px] text-text-muted",children:R("repoMesh.nodeList.daemonCandidatesHint")})]}),s.jsx("span",{className:"text-[11px] text-text-muted",children:R("repoMesh.nodeList.available",{count:B.length})})]}),r.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:R("repoMesh.nodeList.noDaemonsAvailable")}):B.length===0?s.jsx("div",{className:"text-[12px] text-text-muted",children:R("repoMesh.nodeList.allDaemonsAttached")}):s.jsx("div",{className:"grid gap-2 md:grid-cols-2",children:B.map(M=>s.jsxs("button",{type:"button",className:`text-left rounded-lg border px-3 py-2 transition-colors ${M.id===c?"border-accent-primary/50 bg-accent-primary/10":"border-border-subtle bg-bg-primary hover:border-border-default"}`,onClick:()=>{D(M.id),N(""),P(!1),A(cr(wn(M.availableProviders||[]))),k()},children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("span",{className:"text-sm font-medium truncate",children:Td(M)}),M.id===c&&s.jsx("span",{className:"text-[10px] text-accent-primary",children:R("repoMesh.nodeList.selectedHost")})]}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted font-mono truncate",children:M.id}),s.jsx("div",{className:"mt-1 text-[11px] text-text-muted",children:R("repoMesh.nodeList.workspacesDetected",{count:(M.workspaces||[]).length})})]},M.id))})]}),!S&&s.jsxs("button",{className:"btn btn-primary btn-sm mb-4 inline-flex items-center gap-1.5",onClick:k,children:[s.jsx(uM,{size:13})," ",i.addNodeDaemonPicker?R("repoMesh.nodeList.attachMachine"):R("repoMesh.nodeList.addNode")]}),S&&s.jsxs("div",{className:"mb-4 p-4 rounded-xl border border-accent-primary/30 bg-bg-glass animate-[fadeIn_0.3s_ease-out]",children:[s.jsxs("div",{className:"flex justify-between items-center mb-3",children:[s.jsx("h4",{className:"text-sm font-bold",children:i.addNodeDaemonPicker?R("repoMesh.nodeList.attachMachineTitle"):R("repoMesh.nodeList.addNodeTitle")}),s.jsx("button",{onClick:()=>{w(),D(""),P(!1)},className:"text-text-muted cursor-pointer bg-transparent border-none",children:s.jsx(At,{size:16})})]}),i.addNodeDaemonPicker&&s.jsx(Ct,{label:R("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:I,onChange:M=>{var W;D(M.target.value),N(""),P(!1),A(cr(wn(((W=r.find(J=>J.id===M.target.value))==null?void 0:W.availableProviders)||[])))},children:[s.jsx("option",{value:"",children:R("repoMesh.nodeList.selectMachine")}),r.map(M=>s.jsx("option",{value:M.id,children:Td(M)},M.id))]})}),(i.addNodeDaemonPicker?I:!0)&&s.jsx(Ct,{label:R("repoMesh.nodeList.workspacePath"),children:i.addNodeDaemonPicker&&!L&&_.length>0?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex flex-col gap-1.5 mb-2",children:_.map(M=>s.jsxs("button",{type:"button",className:`text-left text-xs px-3 py-2 rounded-lg border transition-colors ${v===M.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(M.path),children:[s.jsx("span",{className:"font-medium block truncate",children:M.label||M.path.split("/").pop()}),s.jsx("span",{className:"text-[10px] text-text-muted font-mono truncate block",children:M.path})]},M.id||M.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:R("repoMesh.nodeList.enterCustomPath")})]}):s.jsx(s.Fragment,{children:i.addNodeDaemonPicker?s.jsxs(s.Fragment,{children:[s.jsx(is,{value:v,onChange:M=>N(M.target.value),placeholder:"/Users/dev/projects/myapp",onKeyDown:M=>{M.key==="Enter"&&E()}}),_.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:R("repoMesh.nodeList.pickFromSaved")})]}):(()=>{var J;const M=Array.isArray(n==null?void 0:n.workspaces)?n.workspaces:[],W=`mesh-add-node-workspaces-${a||"new"}`;return s.jsxs(s.Fragment,{children:[s.jsx(is,{value:v,onChange:re=>N(re.target.value),placeholder:((J=M[0])==null?void 0:J.path)||"/Users/dev/projects/myapp",list:M.length>0?W:void 0,autoFocus:!0}),M.length>0&&s.jsxs(s.Fragment,{children:[s.jsx("datalist",{id:W,children:M.map(re=>s.jsx("option",{value:re.path,children:re.label||re.path},re.id||re.path))}),s.jsx("div",{className:"mt-2 flex flex-wrap gap-1.5",children:M.slice(0,6).map(re=>s.jsx("button",{type:"button",onClick:()=>N(re.path),className:"text-[11px] px-2 py-0.5 rounded-full border border-border-subtle hover:border-accent-primary/50 text-text-muted hover:text-text-primary transition-colors bg-transparent cursor-pointer",title:re.path,children:re.label||re.path.split("/").filter(Boolean).pop()||re.path},re.id||re.path))})]})]})})()})}),s.jsx(Ct,{label:R("repoMesh.nodeList.preferredTools"),hint:R("repoMesh.nodeList.preferredToolsHint"),children:s.jsx(gS,{value:j,availableProviders:i.addNodeDaemonPicker?q:d,onChange:A})}),s.jsxs("div",{className:"flex gap-2 mt-3",children:[s.jsx("button",{onClick:E,disabled:!v.trim()||i.addNodeDaemonPicker&&!I,className:"btn btn-primary btn-sm",children:R("repoMesh.nodeList.add")}),s.jsx("button",{onClick:()=>{w(),D(""),P(!1)},className:"btn btn-secondary btn-sm",children:R("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:R("repoMesh.nodeList.setupInventoryWarning")}),H.length===0?s.jsx(La,{icon:s.jsx(xn,{}),title:R("repoMesh.nodeList.emptyTitle"),description:R("repoMesh.nodeList.emptyDescription")}):s.jsx("div",{className:"flex flex-col gap-2",children:H.map(M=>{var de;const W=WM(M),J=BM(M,t),re=GM(M,n),V=y===M.id,X=M.status||M.machine_status||(J.length>0||re.length>0?"active":"enabled");return s.jsxs("div",{className:`p-3 rounded-lg border bg-bg-primary transition-colors ${i.addNodeDaemonPicker?"bg-bg-glass border-border-subtle rounded-xl px-5 py-4":`cursor-pointer ${V?"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(V?null:M.id),onKeyDown:i.addNodeDaemonPicker?void 0:ne=>{(ne.key==="Enter"||ne.key===" ")&&(ne.preventDefault(),b(V?null:M.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:M.machine_label||M.machine_nickname||M.hostname||M.workspace}):s.jsx("span",{className:"text-sm font-medium",children:M.workspace.split("/").pop()}),i.addNodeDaemonPicker&&s.jsx(pM,{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:R("repoMesh.nodeList.setupInventory")})]}),i.addNodeDaemonPicker&&s.jsx("div",{className:"text-[11px] text-text-muted",children:R("repoMesh.nodeList.ownerMachine",{owner:qM(r.find(ne=>ne.id===String(M.daemon_id||"")),o),machine:M.machine_label||M.daemon_id||M.workspace})}),s.jsx("div",{className:"text-[10px] text-text-muted font-mono",children:M.workspace}),s.jsx(HM,{node:M,saving:m===M.id,onSave:ne=>f(M,ne)}),i.addNodeDaemonPicker&&s.jsx("div",{className:"mt-2 text-[11px] text-amber-300",children:R("repoMesh.nodeList.liveDetailGraphOwned")}),s.jsxs("div",{className:"mt-3 max-w-2xl",onClick:ne=>ne.stopPropagation(),children:[s.jsx(Ct,{label:R("repoMesh.nodeList.slotsLabel"),hint:R("repoMesh.nodeList.slotsHint"),children:s.jsx(PM,{slots:Array.isArray((de=M.policy)==null?void 0:de.slots)?M.policy.slots:[],availableProviders:RM(M,T),saving:p===M.id,onSave:ne=>u(M,ne)})}),i.nodeInstruction&&s.jsxs(Ct,{label:R("repoMesh.nodeList.nodeInstruction"),hint:R("repoMesh.nodeList.nodeInstructionHint"),children:[s.jsx("textarea",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary font-mono",rows:3,value:g[M.id]??"",onChange:ne=>{const O=ne.target.value;C(M.id,O)},onClick:ne=>ne.stopPropagation(),disabled:h===M.id,placeholder:R("repoMesh.nodeList.nodeInstructionPlaceholder")}),s.jsx("div",{className:"mt-2 flex items-center gap-2",children:s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm shrink-0",onClick:ne=>{ne.stopPropagation(),x(M)},disabled:h===M.id,children:h===M.id?R("repoMesh.nodeList.saving"):R("repoMesh.nodeList.saveInstruction")})})]})]})]}),s.jsx("button",{className:`transition-colors bg-transparent border-none cursor-pointer ${i.addNodeDaemonPicker?"btn btn-sm text-text-muted hover:text-red-400":"text-text-muted hover:text-red-400"}`,onClick:ne=>{ne.stopPropagation(),K(M.id)},title:R("repoMesh.nodeList.removeNode"),children:s.jsx(dM,{size:14})})]}),s.jsxs("details",{className:"mt-3 group",onClick:ne=>ne.stopPropagation(),children:[s.jsxs("summary",{className:"cursor-pointer select-none text-[12px] text-text-muted hover:text-text-secondary inline-flex items-center gap-1",children:[s.jsx("span",{className:"transition-transform group-open:rotate-90","aria-hidden":!0,children:"▸"})," ",R("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:R("repoMesh.nodeList.nodeId")})," ",s.jsx("span",{className:"font-mono break-all",children:M.id})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:R("repoMesh.nodeList.launchReady")})," ",s.jsx("span",{className:W.configured?"text-green-400":"text-amber-400",children:W.configured?R("repoMesh.nodeList.launchReadyYes"):R("repoMesh.nodeList.launchReadyNo")})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:R("repoMesh.nodeList.repoRoot")})," ",s.jsx("span",{className:"font-mono break-all",children:M.repoRoot||M.workspace})]}),s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:R("repoMesh.nodeList.activeSessionsLabel")})," ",re.length]}),i.addNodeDaemonPicker&&s.jsxs("div",{children:[s.jsx("span",{className:"text-text-secondary",children:R("repoMesh.nodeList.added")})," ",new Date(M.created_at||M.createdAt||Date.now()).toLocaleDateString()]})]}),s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:R("repoMesh.nodeList.activeQueueAssignments")}),J.length===0?s.jsx("div",{children:R("repoMesh.nodeList.noActiveAssignment")}):s.jsx("ul",{className:"m-0 pl-4",children:J.map(ne=>s.jsx("li",{className:"font-mono",children:FM(ne)},ne.id))})]}),re.length>0&&s.jsxs("div",{className:"mt-3",children:[s.jsx("div",{className:"text-text-secondary mb-1",children:R("repoMesh.nodeList.activeSessions")}),s.jsx("ul",{className:"m-0 pl-4",children:re.map(ne=>s.jsxs("li",{className:"font-mono",children:[ne.provider," / ",ne.status," / ",ne.id]},ne.id))})]})]})]})]},M.id)})})]})}function Fr(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function KM({daemons:e,coordinatorDaemonId:t,onCoordinatorDaemonIdChange:n,coordinatorCliType:r,onCoordinatorCliTypeChange:a,launchingCoordinator:o,launchResult:i,isHostNodeAttached:c,selectedHostNode:d,hostPinned:p,hostLabel:u,hostOnline:m,hostRebindDaemonId:f,onHostRebindDaemonIdChange:g,onLaunchCoordinator:C}){const{t:h}=Ne("common"),x=s.jsx(Ct,{label:h("repoMesh.host.coordinatorProvider"),hint:h("repoMesh.host.coordinatorProviderHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:r,onChange:S=>a(S.target.value),children:[s.jsx("option",{value:"",children:h("repoMesh.host.useNodePriority")}),s.jsx("option",{value:"claude-cli",children:"Claude Code"}),s.jsx("option",{value:"codex-cli",children:"Codex"}),s.jsx("option",{value:"gemini-cli",children:"Gemini"}),s.jsx("option",{value:"hermes-cli",children:"Hermes"})]})}),y=i&&s.jsx("div",{className:"mt-3 text-[12px] text-green-400 bg-green-500/10 border border-green-500/20 rounded-lg px-3 py-2",children:i});if(p)return s.jsxs(bt,{title:h("repoMesh.host.title"),description:h("repoMesh.host.descriptionSet"),children:[s.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[s.jsxs("span",{className:`inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-[13px] text-text-primary ${m?"border-accent-primary/40 bg-accent-primary/10":"border-amber-500/40 bg-amber-500/10"}`,children:[s.jsx("span",{className:"text-text-muted",children:h("repoMesh.host.hostLabel")}),s.jsx("span",{className:"font-medium",children:u||h("repoMesh.host.unknown")}),s.jsxs("span",{className:m?"text-text-muted":"text-amber-400",children:["· ",h(m?"repoMesh.host.online":"repoMesh.host.offline")]})]}),(d==null?void 0:d.workspace)&&s.jsxs("span",{className:"text-[12px] text-text-muted",children:[h("repoMesh.host.hostNode")," ",s.jsx("span",{className:"font-mono text-text-secondary",children:d.workspace})]})]}),!m&&s.jsxs("div",{className:"mt-4",children:[s.jsxs(Gt,{variant:"warning",className:"mb-3",children:[s.jsx("strong",{children:h("repoMesh.host.hostOffline")})," ",h("repoMesh.host.hostOfflineText")]}),e.length>0?s.jsx(Ct,{label:h("repoMesh.host.reconnectToCommand"),hint:h("repoMesh.host.reconnectToCommandHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:f,onChange:S=>g(S.target.value),children:[s.jsx("option",{value:"",children:h("repoMesh.host.waitForHost")}),e.map(S=>s.jsx("option",{value:S.id,children:Fr(S)},S.id))]})}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:h("repoMesh.host.noDaemonsToRoute")})]}),s.jsxs("div",{className:"mt-3 grid gap-3 sm:grid-cols-[180px_auto] items-end",children:[x,s.jsx("button",{className:"btn btn-primary btn-sm",onClick:C,disabled:o||!t,title:t?void 0:h("repoMesh.host.noCommandTarget"),children:h(o?"repoMesh.host.launching":"repoMesh.host.launchHost")})]}),y]});const b=e.find(S=>S.id===t);return s.jsxs(bt,{title:h("repoMesh.host.title"),description:h("repoMesh.host.descriptionUnset"),children:[s.jsxs(Gt,{variant:"info",className:"mb-4",children:[s.jsx("strong",{children:h("repoMesh.host.setHostBanner")})," ",h("repoMesh.host.setHostBannerText")]}),e.length>0?s.jsxs(s.Fragment,{children:[t?s.jsx("div",{className:"mb-3 rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:c?s.jsxs(s.Fragment,{children:["Will host on ",s.jsx("span",{className:"font-medium text-text-primary",children:Fr(b)}),d!=null&&d.workspace?s.jsxs(s.Fragment,{children:[" · setup node ",s.jsx("span",{className:"font-mono text-text-secondary",children:d.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:Fr(b)}),". Attach one of its workspaces as a node first, then launch to set the host."]})}):s.jsx(Ct,{label:h("repoMesh.host.hostDaemon"),hint:h("repoMesh.host.hostDaemonHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:"",onChange:S=>n(S.target.value),children:[s.jsx("option",{value:"",children:h("repoMesh.host.resolvingHost")}),e.map(S=>s.jsx("option",{value:S.id,children:Fr(S)},S.id))]})}),s.jsxs("div",{className:"grid gap-3 sm:grid-cols-[180px_auto] items-end mt-3",children:[x,s.jsx("button",{className:"btn btn-primary btn-sm",onClick:C,disabled:!t||!c||o,title:t?c?void 0:h("repoMesh.host.attachNodeFirst"):h("repoMesh.host.pickHostFirst"),children:h(o?"repoMesh.host.launching":"repoMesh.host.launchHostSetsHost")})]})]}):s.jsx("div",{className:"rounded-lg border border-border-subtle bg-bg-secondary px-3 py-2 text-[12px] text-text-muted",children:h("repoMesh.host.noDaemonsToHost")}),y]})}function VM({meshId:e,availableCliAgents:t}){const{t:n}=Ne(),r=t.find(o=>{const i=o.id.toLowerCase();return i==="hermes-cli"||i.includes("hermes")||o.name.toLowerCase().includes("hermes")}),a=zp(r==null?void 0:r.meshCoordinator,{meshId:e});return a?s.jsx(bt,{title:n("repoMesh.hermesMcp.title"),description:n("repoMesh.hermesMcp.description"),children:s.jsx(bm,{setup:a,providerName:(r==null?void 0:r.name)||n("repoMesh.hermesMcp.fallbackProvider")})}):null}const _o=[{value:"preserve",label:"Preserve history and runtimes",description:"Keep completed chat history and leave live runtimes alone."},{value:"stop",label:"Stop live runtimes only",description:"Release running session processes, but keep chat records/transcripts."},{value:"delete_stopped",label:"Delete stopped sessions only",description:"Clean completed/stopped chat clutter without killing live runtimes."},{value:"stop_and_delete",label:"Stop and delete sessions",description:"Stop matching runtimes, then remove their session records/transcripts."}],YM=[{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 JM(e){return e==="smart"?"fitness":e==="spread"?"least_loaded":"first_eligible"}function QM(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 XM={requirePreTaskCheckpoint:!1,requirePostTaskCheckpoint:!0,requireApprovalForPush:!0,allowAutoPublishSubmoduleMainCommits:!1,requireApprovalForDestructiveGit:!0,dirtyWorkspaceBehavior:"warn",maxParallelTasks:2,schedulingStrategy:"first_eligible",sessionCleanupOnNodeRemove:"preserve"};function vi(e){return{...XM,...(e==null?void 0:e.policy)||{}}}function ZM(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 eD({selectedMesh:e,error:t,onDismissError:n,onBack:r,onDelete:a,displayedMeshStatus:o,graphLoading:i,graphError:c,onRefreshGraph:d,savingPolicy:p,onUpdatePolicy:u,coordinatorPromptDraft:m,onCoordinatorPromptDraftChange:f,savingCoordinatorPrompt:g,onSaveCoordinatorPrompt:C,daemons:h,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:y,coordinatorCliType:b,onCoordinatorCliTypeChange:S,launchingCoordinator:k,launchResult:w,isHostNodeAttached:v,selectedHostNode:N,hostPinned:j,hostLabel:A,hostOnline:I,hostRebindDaemonId:D,onHostRebindDaemonIdChange:L,onLaunchCoordinator:P,activeDaemon:_,activeDaemonId:q,meshQueue:B,userName:E,availableCliProviders:K,savingNodeSlotsId:R,onUpdateNodeSlots:T,savingNodeCapabilitiesId:H,onUpdateNodeCapabilities:M,nodeSystemPromptDrafts:W,onNodeSystemPromptDraftChange:J,savingNodeSystemPromptId:re,onSaveNodeSystemPrompt:V,selectedNodeId:X,onSelectNode:de,showAddNode:ne,onShowAddNode:O,onCancelAddNode:ie,nodeWorkspace:z,onNodeWorkspaceChange:ae,nodeProviderPriority:Ce,onNodeProviderPriorityChange:ye,nodeDaemonId:ke,onNodeDaemonIdChange:me,nodeCustomPath:G,onNodeCustomPathChange:U,nodePickerWorkspaces:Z,nodePickerProviders:Y,attachableDaemons:fe,onAddNode:Te,onRemoveNode:ce,availableCliAgents:$,features:pe,sendCommand:le}){var Be;const{t:F}=Ne("common"),be=vi(e),je=e.nodes||[],Se=je.some(Me=>{var We;const ve=Number((We=Me.policy)==null?void 0:We.schedulingPriority);return Number.isFinite(ve)&&ve!==0}),He=!be.schedulingStrategy,Xe=l.useMemo(()=>je.some(Me=>{var ve;return Array.isArray((ve=Me.policy)==null?void 0:ve.slots)&&Me.policy.slots.length>0}),[je]),dt=He?Xe?"smart":je.length>=2?"spread":null:null,[it,he]=l.useState(!1),$e=!!q&&!!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:F("repoMesh.detail.back")}),s.jsxs("button",{className:"btn btn-secondary btn-sm inline-flex items-center gap-1.5",onClick:()=>d(!0),disabled:i,children:[s.jsx(lM,{size:13}),F(i?"repoMesh.detail.probing":"repoMesh.detail.refresh")]}),s.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>a(e.id),children:F("repoMesh.detail.delete")})]}),children:[t&&s.jsx(Gt,{variant:"error",onDismiss:n,className:"mb-4",children:t}),pe.meshHostDaemonSection&&s.jsx(KM,{daemons:h,coordinatorDaemonId:x,onCoordinatorDaemonIdChange:y,coordinatorCliType:b,onCoordinatorCliTypeChange:S,launchingCoordinator:k,launchResult:w,isHostNodeAttached:v,selectedHostNode:N,hostPinned:j,hostLabel:A,hostOnline:I,hostRebindDaemonId:D,onHostRebindDaemonIdChange:Me=>{L(Me),d()},onLaunchCoordinator:P}),s.jsxs(bt,{title:F("repoMesh.detail.observabilityTitle"),description:F("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:F($e?"repoMesh.detail.observabilityOpenTitle":"repoMesh.detail.observabilityDisabledTitle"),children:[s.jsx(es,{size:14}),F("repoMesh.detail.observabilityOpen")]}),s.jsx("span",{className:"text-[12px] text-text-muted",children:F("repoMesh.detail.observabilityHint")})]})]}),s.jsx(zM,{nodes:je,meshQueue:B,activeDaemon:_,daemons:h,selectedMeshId:e.id,userName:E,features:{addNodeDaemonPicker:pe.addNodeDaemonPicker,nodeInstruction:pe.nodeInstruction},coordinatorDaemonId:x,availableCliProviders:K,savingNodeSlotsId:R,onUpdateNodeSlots:T,savingNodeCapabilitiesId:H,onUpdateNodeCapabilities:M,nodeSystemPromptDrafts:W,onNodeSystemPromptDraftChange:J,savingNodeSystemPromptId:re,onSaveNodeSystemPrompt:V,selectedNodeId:X,onSelectNode:de,showAddNode:ne,onShowAddNode:O,onCancelAddNode:ie,nodeWorkspace:z,onNodeWorkspaceChange:ae,nodeProviderPriority:Ce,onNodeProviderPriorityChange:ye,nodeDaemonId:ke,onNodeDaemonIdChange:me,nodeCustomPath:G,onNodeCustomPathChange:U,nodePickerWorkspaces:Z,nodePickerProviders:Y,attachableDaemons:fe,onAddNode:Te,onRemoveNode:ce}),s.jsxs(bt,{title:F("repoMesh.detail.schedulingTitle"),description:F("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:F("repoMesh.detail.distribution")}),s.jsx("div",{className:"flex flex-col gap-2",children:YM.map(Me=>{const We=QM(be.schedulingStrategy,{priorityConfigured:Se})===Me.value;return s.jsxs("label",{className:`flex items-start gap-3 rounded-lg border px-3 py-2.5 cursor-pointer transition-colors ${We?"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:Me.value,checked:We,disabled:p,onChange:()=>u({schedulingStrategy:JM(Me.value)})}),s.jsxs("span",{className:"min-w-0",children:[s.jsxs("span",{className:"flex items-center gap-2 text-sm text-text-primary",children:[Me.label,dt===Me.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:F("repoMesh.detail.recommended")})]}),s.jsx("span",{className:"block text-[12px] text-text-muted",children:Me.description})]})]},Me.value)})})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:F("repoMesh.detail.saving")})]}),s.jsx(bt,{title:F("repoMesh.detail.visibilityTitle"),description:F("repoMesh.detail.visibilityDescription"),children:s.jsx(Ct,{label:F("repoMesh.detail.visibilityLabel"),hint:F("repoMesh.detail.visibilityHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:be.spawnedSessionVisibility==="visible"?"visible":"hidden",onChange:Me=>u({spawnedSessionVisibility:Me.target.value==="visible"?"visible":"hidden"}),disabled:p,children:[s.jsx("option",{value:"hidden",children:F("repoMesh.detail.visibilityHidden")}),s.jsx("option",{value:"visible",children:F("repoMesh.detail.visibilityVisible")})]})})}),o&&s.jsx(bt,{title:F("repoMesh.detail.magiTitle"),description:F("repoMesh.detail.magiDescription"),children:s.jsx(yM,{status:o,daemonId:q,sendDaemonCommand:le,availableProviders:K})}),s.jsx(IM,{status:o,daemonId:q,meshId:e.id,sendCommand:le}),pe.coordinatorPrompt&&s.jsxs(bt,{title:F("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:F("repoMesh.detail.advanced")}),description:F("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:F("repoMesh.detail.thisMesh")}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:F("repoMesh.detail.thisMeshHint",{name:e.name})}),s.jsxs(Ct,{label:F("repoMesh.detail.overrideLabel"),hint:F("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:Me=>f({...m,override:Me.target.value}),disabled:g,placeholder:F("repoMesh.detail.overridePlaceholder")}),s.jsx(wM,{daemonId:q,meshId:e.id,cliType:b,sendCommand:le})]}),s.jsx(Ct,{label:F("repoMesh.detail.appendLabel"),hint:F("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:Me=>f({...m,append:Me.target.value}),disabled:g,placeholder:F("repoMesh.detail.appendPlaceholder")})}),s.jsxs("details",{className:"mt-2 text-[12px] text-text-muted",children:[s.jsx("summary",{className:"cursor-pointer select-none",children:F("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:C,disabled:g,children:F(g?"repoMesh.detail.saving":"repoMesh.detail.saveCoordinatorPrompt")}),s.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>f({override:"",append:""}),disabled:g,title:F("repoMesh.detail.clearTitle"),children:F("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:F("repoMesh.detail.userLevel")}),s.jsx("p",{className:"text-[12px] text-text-muted mb-3",children:F("repoMesh.detail.userLevelDescription")}),s.jsx(zS,{daemonId:q||void 0})]})]}),s.jsxs(bt,{title:F("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:F("repoMesh.detail.advanced")}),description:F("repoMesh.detail.safetyDescription"),children:[s.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:[{label:F("repoMesh.detail.checkpointBefore"),key:"requirePreTaskCheckpoint",opts:[["no","No"],["yes","Yes"]],val:Me=>Me?"yes":"no",parse:Me=>Me==="yes"},{label:F("repoMesh.detail.checkpointAfter"),key:"requirePostTaskCheckpoint",opts:[["yes","Yes"],["no","No"]],val:Me=>Me?"yes":"no",parse:Me=>Me==="yes"},{label:F("repoMesh.detail.pushApproval"),key:"requireApprovalForPush",opts:[["required",F("repoMesh.detail.requireApprovalBeforePush")],["not_required",F("repoMesh.detail.doNotRequireApproval")]],val:Me=>Me?"required":"not_required",parse:Me=>Me==="required"},{label:F("repoMesh.detail.destructiveGitApproval"),key:"requireApprovalForDestructiveGit",opts:[["required",F("repoMesh.detail.requireApproval")],["not_required",F("repoMesh.detail.doNotRequireApproval")]],val:Me=>Me?"required":"not_required",parse:Me=>Me==="required"},{label:F("repoMesh.detail.uncommittedChanges"),key:"dirtyWorkspaceBehavior",opts:[["warn",F("repoMesh.detail.warnAndContinue")],["block",F("repoMesh.detail.blockTask")],["checkpoint_then_continue",F("repoMesh.detail.checkpointThenContinue")]],val:Me=>Me||"warn",parse:Me=>Me},{label:F("repoMesh.detail.autoPublishSubmodule"),key:"allowAutoPublishSubmoduleMainCommits",opts:[["disabled",F("repoMesh.detail.requireExplicitApproval")],["enabled",F("repoMesh.detail.allowRefineryPublish")]],val:Me=>Me?"enabled":"disabled",parse:Me=>Me==="enabled"}].map(({label:Me,key:ve,opts:We,val:ut,parse:ot})=>s.jsx(Ct,{label:Me,children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ut(be[ve]),onChange:pt=>u({[ve]:ot(pt.target.value)}),disabled:p,children:We.map(([pt,Q])=>s.jsx("option",{value:pt,children:Q},pt))})},ve))}),(()=>{const Me=be.autoFastForward&&typeof be.autoFastForward=="object"?be.autoFastForward:{},ve=Me.enabled!==!1,We=Me.remoteNodes===!0,ut=Me.mode==="continuous"?"continuous":"idle",ot=pt=>u({autoFastForward:{...Me,...pt}});return s.jsxs("div",{className:"mt-4 grid gap-4 sm:grid-cols-2",children:[s.jsx(Ct,{label:F("repoMesh.detail.autoFastForward"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ve?"enabled":"disabled",onChange:pt=>ot({enabled:pt.target.value==="enabled"}),disabled:p,children:[s.jsx("option",{value:"enabled",children:F("repoMesh.detail.ffEnabled")}),s.jsx("option",{value:"disabled",children:F("repoMesh.detail.ffDisabled")})]})}),s.jsx(Ct,{label:F("repoMesh.detail.includeRemoteNodes"),hint:F("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:We?"yes":"no",onChange:pt=>ot({remoteNodes:pt.target.value==="yes"}),disabled:p||!ve,children:[s.jsx("option",{value:"no",children:F("repoMesh.detail.remoteNo")}),s.jsx("option",{value:"yes",children:F("repoMesh.detail.remoteYes")})]})}),s.jsx(Ct,{label:F("repoMesh.detail.detectionMode"),hint:F("repoMesh.detail.detectionModeHint"),children:s.jsxs("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:ut,onChange:pt=>ot({mode:pt.target.value==="continuous"?"continuous":"idle"}),disabled:p||!ve||!We,children:[s.jsx("option",{value:"idle",children:F("repoMesh.detail.idleEdgeOnly")}),s.jsx("option",{value:"continuous",children:F("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:F("repoMesh.detail.sessionCleanupLabel"),hint:F("repoMesh.detail.sessionCleanupHint"),children:s.jsx("select",{className:"w-full px-3 py-2 rounded-lg bg-bg-secondary border border-border-subtle text-sm text-text-primary",value:be.sessionCleanupOnNodeRemove||"preserve",onChange:Me=>u({sessionCleanupOnNodeRemove:Me.target.value}),disabled:p,children:_o.map(Me=>s.jsx("option",{value:Me.value,children:Me.label},Me.value))})}),s.jsx("div",{className:"mt-2 text-[12px] text-text-muted",children:((Be=_o.find(Me=>Me.value===be.sessionCleanupOnNodeRemove))==null?void 0:Be.description)||_o[0].description})]}),p&&s.jsx("div",{className:"mt-3 text-[12px] text-text-muted",children:F("repoMesh.detail.saving")})]}),pe.hermesMcpConfig&&s.jsx(VM,{meshId:e.id,availableCliAgents:$}),pe.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(Vm,{activeConv:ZM({meshId:e.id,daemonId:q,meshName:e.name}),sendDaemonCommand:le,onClose:()=>he(!1)})]})}const Un=new Map;function tD({daemons:e,primaryDaemonId:t,sendCommand:n,unwrapResult:r,normalizeMesh:a,features:o,loadDaemonMetadata:i}){const c=e.map(T=>T.id).filter(Boolean).sort().join(","),[d,p]=l.useState(()=>Un.get(c)??[]),[u,m]=l.useState(null),[f,g]=l.useState(()=>!Un.has(c)),[C,h]=l.useState(null),[x,y]=l.useState(!1),[b,S]=l.useState(""),[k,w]=l.useState(""),[v,N]=l.useState(""),[j,A]=l.useState(""),[I,D]=l.useState(""),L=l.useMemo(()=>e.find(T=>T.id===j),[e,j]),P=(L==null?void 0:L.workspaces)||[],_=l.useMemo(()=>wn((L==null?void 0:L.availableProviders)||[]),[L]);l.useEffect(()=>{!o.createDaemonPicker||!i||!j||!L||!(!L.workspaces||!L.availableProviders)||Promise.resolve(i(j,{minFreshMs:3e4})).catch(()=>{})},[o.createDaemonPicker,i,j,L]);const q=l.useMemo(()=>e.map(T=>T.id).filter(Boolean).sort().join(","),[e]),B=l.useCallback(async(T=!1)=>{const H=T||Un.has(q);g(M=>H?M:!0);try{if(o.createDaemonPicker){const M=await Promise.allSettled(e.map(async re=>{if(!re.id)return[];const V=await n(re.id,"list_meshes",{}),X=r(V);if((X==null?void 0:X.success)===!1)throw new Error(X.error||"Failed to load meshes");return(Array.isArray(X==null?void 0:X.meshes)?X.meshes:[]).map(de=>a(de,re.id)).filter(de=>de.id)})),W=new Map;for(const re of M)if(re.status==="fulfilled")for(const V of re.value)W.has(V.id)||W.set(V.id,V);const J=Array.from(W.values());p(J),Un.set(q,J),h(null)}else{if(!t)return;const M=await n(t,"list_meshes");if(M!=null&&M.success){const W=(M.meshes||[]).map(J=>a(J,t));p(W),Un.set(q,W),h(null)}else h((M==null?void 0:M.error)||"Failed to load meshes")}}catch(M){h((M==null?void 0:M.message)||"Failed to load meshes")}finally{g(!1)}},[q,t,n,r,a,o.createDaemonPicker]);async function E(){var W,J;const T=o.createDaemonPicker?j:t;if(!T||!b.trim())return;const H=v.trim(),M=k.trim();if(!(!H&&!M))try{const re={name:b.trim()};H&&(re.repoRemoteUrl=H),M&&(re.repoIdentity=M);const V=await n(T,"create_mesh",re),X=r(V);if((X==null?void 0:X.success)===!1)throw new Error(X.error||"Create failed");const de=typeof((W=X==null?void 0:X.mesh)==null?void 0:W.id)=="string"?X.mesh.id:"";if(de&&o.createDaemonPicker&&I){const ne=await n(T,"add_mesh_node",{meshId:de,daemonId:T,machineId:L==null?void 0:L.machineId,workspace:I,role:"host",providerPriority:cr(_)}),O=r(ne);if((O==null?void 0:O.success)===!1)throw new Error(O.error||"Mesh created but failed to attach workspace")}y(!1),S(""),w(""),N(""),D(""),await B(),(J=X==null?void 0:X.mesh)!=null&&J.id&&m(X.mesh.id)}catch(re){h((re==null?void 0:re.message)||"Create failed")}}async function K(T){var M;if(!confirm("Delete this mesh? This cannot be undone."))return;const H=((M=d.find(W=>W.id===T))==null?void 0:M.__sourceDaemonId)||t;try{const W=await n(H,"delete_mesh",{meshId:T}),J=r(W);if((J==null?void 0:J.success)===!1)throw new Error(J.error||"Failed to delete");u===T&&m(null),await B()}catch(W){h((W==null?void 0:W.message)||"Delete failed")}}function R(){y(!1),S(""),w(""),N("")}return{meshes:d,setMeshes:p,selectedMeshId:u,setSelectedMeshId:m,loading:f,error:C,setError:h,showCreate:x,setShowCreate:y,createName:b,setCreateName:S,createRepoIdentity:k,setCreateRepoIdentity:w,createRepoRemoteUrl:v,setCreateRepoRemoteUrl:N,newMeshDaemonId:j,setNewMeshDaemonId:A,newMeshWorkspace:I,setNewMeshWorkspace:D,createPickerWorkspaces:P,createPickerProviders:_,loadMeshes:B,handleCreate:E,handleDelete:K,cancelCreate:R}}function sD({selectedMesh:e,selectedMeshId:t,primaryDaemonId:n,activeDaemonId:r,daemons:a,sendCommand:o,unwrapResult:i,loadLiveMesh:c,resolveCommandTarget:d,launchCoordinator:p,features:u,loadMeshes:m,loadQueue:f,queueSection:g,setError:C}){const[h,x]=l.useState({}),[y,b]=l.useState(null),[S,k]=l.useState(null),[w,v]=l.useState(!1),[N,j]=l.useState(""),[A,I]=l.useState([]),[D,L]=l.useState(""),[P,_]=l.useState(!1),[q,B]=l.useState(""),[E,K]=l.useState(!1),[R,T]=l.useState(null),[H,M]=l.useState(!1),[W,J]=l.useState({override:"",append:""}),[re,V]=l.useState(!1),[X,de]=l.useState({}),[ne,O]=l.useState(null),ie=l.useMemo(()=>a.find(le=>le.id===D),[a,D]),z=(ie==null?void 0:ie.workspaces)||[],ae=l.useMemo(()=>wn((ie==null?void 0:ie.availableProviders)||[]),[ie]);async function Ce(){const le=(e==null?void 0:e.__sourceDaemonId)||n;if(!t||!le)return;const F=N.trim();if(F)try{const be={meshId:t,workspace:F};u.addNodeDaemonPicker&&D&&(be.daemonId=D,be.machineId=ie==null?void 0:ie.machineId),be.providerPriority=kn(A);const je=await o(le,"add_mesh_node",be),Se=i(je);if((Se==null?void 0:Se.success)===!1)throw new Error(Se.error||"Add node failed");v(!1),j(""),I([]),L(""),_(!1),await m(),g||await f(t)}catch(be){C((be==null?void 0:be.message)||"Add node failed")}}async function ye(le){var Se;if(!e)return;const F=vi(e),be=((Se=[{value:"preserve",label:"Preserve history and runtimes"},{value:"stop",label:"Stop live runtimes only"},{value:"delete_stopped",label:"Delete stopped sessions only"},{value:"stop_and_delete",label:"Stop and delete sessions"}].find(He=>He.value===F.sessionCleanupOnNodeRemove))==null?void 0:Se.label)||"Preserve history and runtimes";if(!confirm(`Remove this node?
120
+
121
+ Node removal cleanup policy: ${be}`))return;const je=e.__sourceDaemonId||n;try{const He=await o(je,"remove_mesh_node",{meshId:e.id,nodeId:le}),Xe=i(He);if((Xe==null?void 0:Xe.success)===!1)throw new Error(Xe.error||"Remove failed");S===le&&k(null),await m(),g||await f(t)}catch(He){C((He==null?void 0:He.message)||"Remove node failed")}}async function ke(le){if(!e)return;const F={...vi(e),...le},be=e.__sourceDaemonId||n;try{M(!0),C(null);const je=await o(be,"update_mesh",{meshId:e.id,policy:F}),Se=i(je);if((Se==null?void 0:Se.success)===!1)throw new Error(Se.error||"Policy update failed");await m()}catch(je){C((je==null?void 0:je.message)||"Policy update failed")}finally{M(!1)}}async function me(le){if(!t)return;const F=(e==null?void 0:e.__sourceDaemonId)||n,be=h[le.id]||nD(le),je=kn(be),Se={...le.policy||{}};delete Se.provider_priority,je.length?Se.providerPriority=je:delete Se.providerPriority;try{b(le.id),C(null);const He=await o(F,"update_mesh_node",{meshId:t,nodeId:le.id,policy:Se,providerPriority:je}),Xe=i(He);if((Xe==null?void 0:Xe.success)===!1){C(Xe.error||"Node policy update failed");return}await m()}catch(He){C((He==null?void 0:He.message)||"Node policy update failed")}finally{b(null)}}const[G,U]=l.useState(null);async function Z(le,F){if(!t)return;const be=(e==null?void 0:e.__sourceDaemonId)||n;try{U(le.id),C(null);const je=await o(be,"update_mesh_node",{meshId:t,nodeId:le.id,policy:{slots:F}}),Se=i(je);if((Se==null?void 0:Se.success)===!1){C(Se.error||"Node slots update failed");return}await m()}catch(je){C((je==null?void 0:je.message)||"Node slots update failed")}finally{U(null)}}const[Y,fe]=l.useState(null);async function Te(le,F){if(!t)return;const be=(e==null?void 0:e.__sourceDaemonId)||n,je=F.map(Se=>Se.trim()).filter(Boolean);try{fe(le.id),C(null);const Se=await o(be,"update_mesh_node",{meshId:t,nodeId:le.id,capabilities:je}),He=i(Se);if((He==null?void 0:He.success)===!1){C(He.error||"Node tag update failed");return}await m()}catch(Se){C((Se==null?void 0:Se.message)||"Node tag update failed")}finally{fe(null)}}async function ce(){if(!n||!t)return;const F={...(e==null?void 0:e.coordinator)||{}};W.override.trim()?F.systemPromptOverride=W.override:delete F.systemPromptOverride,W.append.trim()?F.systemPromptAppend=W.append:delete F.systemPromptAppend,delete F.systemPromptSuffix;try{V(!0),C(null);const be=await o(n,"update_mesh",{meshId:t,coordinator:F}),je=i(be);if((je==null?void 0:je.success)===!1){C(je.error||"Coordinator prompt save failed");return}await m()}catch(be){C((be==null?void 0:be.message)||"Coordinator prompt save failed")}finally{V(!1)}}async function $(le){if(!n||!t)return;const F=(X[le.id]||"").trim();try{O(le.id),C(null);const be=await o(n,"update_mesh_node",{meshId:t,nodeId:le.id,systemPrompt:F}),je=i(be);if((je==null?void 0:je.success)===!1){C(je.error||"Node instruction save failed");return}await m()}catch(be){C((be==null?void 0:be.message)||"Node instruction save failed")}finally{O(null)}}async function pe(){if(e){C(null),T(null);try{K(!0);const le=c?await c(r,e.id,e):null,F=d(r,e.id,e,e.nodes||[],le);if("error"in F)throw new Error(F.error);const be=await p(F.targetDaemonId,{meshId:e.id,inlineMesh:F.inlineMesh,coordinatorNodeId:F.coordinatorNodeId,cliType:q.trim()||void 0});T(be.message)}catch(le){C((le==null?void 0:le.message)||"Coordinator launch failed")}finally{K(!1)}}}return{nodeProviderPriorityDrafts:h,setNodeProviderPriorityDrafts:x,savingNodePolicyId:y,selectedNodeId:S,setSelectedNodeId:k,showAddNode:w,setShowAddNode:v,nodeWorkspace:N,setNodeWorkspace:j,nodeProviderPriority:A,setNodeProviderPriority:I,nodeDaemonId:D,setNodeDaemonId:L,nodeCustomPath:P,setNodeCustomPath:_,nodePickerWorkspaces:z,nodePickerProviders:ae,coordinatorCliType:q,setCoordinatorCliType:B,launchingCoordinator:E,launchResult:R,savingPolicy:H,coordinatorPromptDraft:W,setCoordinatorPromptDraft:J,savingCoordinatorPrompt:re,nodeSystemPromptDrafts:X,setNodeSystemPromptDrafts:de,savingNodeSystemPromptId:ne,savingNodeSlotsId:G,savingNodeCapabilitiesId:Y,handleAddNode:Ce,handleRemoveNode:ye,handleUpdatePolicy:ke,handleUpdateNodeProviderPriority:me,handleUpdateNodeSlots:Z,handleUpdateNodeCapabilities:Te,handleSaveCoordinatorPrompt:ce,handleSaveNodeSystemPrompt:$,handleLaunchCoordinator:pe}}function nD(e){var r;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>n.has(a)?!1:(n.add(a),!0))}function rD(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 aD({primaryDaemonId:e,activeDaemonId:t,sendCommand:n,unwrapResult:r,loadLiveMesh:a,resolveCommandTarget:o}){const[i,c]=l.useState([]),[d,p]=l.useState(null),[u,m]=l.useState(!1),[f,g]=l.useState(null),C=l.useCallback(async x=>{if(!e||!x){c([]);return}try{const y=await n(e,"get_mesh_queue",{meshId:x});c(y!=null&&y.success?Array.isArray(y.queue)?y.queue:[]:[])}catch{c([])}},[e,n]);async function h(x){var y,b;if(x){m(!0),g(null);try{const S=a?await a(t,x.id,x):null,k=o(t,x.id,x,x.nodes||[],S);if("error"in k)throw new Error(k.error);const w=await n(k.targetDaemonId,"get_mesh_queue",{meshId:x.id}),v=r(w);if((v==null?void 0:v.success)===!1)throw new Error(v.error||"Queue load failed");const N=Array.isArray(((y=v==null?void 0:v.result)==null?void 0:y.rows)??(v==null?void 0:v.rows)??(v==null?void 0:v.queue))?((b=v==null?void 0:v.result)==null?void 0:b.rows)??(v==null?void 0:v.rows)??(v==null?void 0:v.queue):[];p(rD(N))}catch(S){g((S==null?void 0:S.message)||"Queue load failed")}finally{m(!1)}}}return{meshQueue:i,setMeshQueue:c,queueSummary:d,queueLoading:u,queueError:f,loadQueue:C,handleLoadQueue:h}}function oD(e){return!e||typeof e!="object"?!1:e._bootstrapFallback===!0}const eh=new Map;function th(e){return e?eh.get(e)??null:null}function iD(e,t){!e||!t||eh.set(e,t)}function lD({selectedMeshId:e,loadMeshStatus:t,extractStatus:n,normalizeNode:r,gateIncompleteGraph:a}){const[o,i]=l.useState(()=>th(e)),[c,d]=l.useState(!1),[p,u]=l.useState(null),[m,f]=l.useState("idle"),[g,C]=l.useState(!1),h=l.useRef(!1);async function x(y,b=e,S=!1){if(!(!y||!b))try{d(!S&&o===null),f(S?"settling":"first_paint"),u(null);const k=await t(y,b,{refresh:S,retryProfile:S?"settled":"interactive"});C(oD(k));const w=n(k),v=r&&w?{...w,nodes:(w.nodes??[]).map(N=>r(N,w.meshId??b,""))}:w;if(v){if(a&&!S&&o!==null&&!AN(Dm(v))){f("settling"),h.current||(h.current=!0,Promise.resolve().then(()=>x(y,b,!0)).finally(()=>{h.current=!1}));return}i(v),iD(b,v),f("settled")}else i(null),u("mesh_status returned an unexpected payload."),f("idle")}catch(k){o||i(null),u((k==null?void 0:k.message)||"Failed to load mesh graph"),f("idle")}finally{d(!1)}}return{meshGraphStatus:o,setMeshGraphStatus:i,graphLoading:c,graphError:p,setGraphError:u,graphProvenance:m,graphBootstrapFallback:g,loadGraph:x}}function cD(e,t,n,r,a){if(!e.length)return"";const o=String(a||"");if(o){const d=e.find(p=>Os(p.id,o));return d?d.id:o}const i=t.find(d=>d.role==="host"),c=String((i==null?void 0:i.daemon_id)||(i==null?void 0:i.daemonId)||"");if(c){const d=e.find(p=>Os(p.id,c));if(d)return d.id}return""}const dD=7e3,uD=45e3;function pD(){const e=iM(),{sendCommand:t,sendData:n,daemons:r,userName:a,loadMeshStatus:o,launchCoordinator:i,loadLiveMesh:c,extractStatus:d,unwrapResult:p,normalizeMesh:u,normalizeNode:m,resolveCommandTarget:f,features:g,gateIncompleteGraph:C}=e,h=Tn(),x=r[0],y=(x==null?void 0:x.id)||"",b=l.useMemo(()=>((x==null?void 0:x.availableProviders)||[]).filter(rt=>rt.category==="cli").map(rt=>({id:rt.type||rt.id,name:rt.displayName||rt.name||rt.type,meshCoordinator:rt.meshCoordinator})),[x]),S=l.useMemo(()=>wn((x==null?void 0:x.availableProviders)||[]),[x]),{meshes:k,selectedMeshId:w,setSelectedMeshId:v,loading:N,error:j,setError:A,showCreate:I,setShowCreate:D,createName:L,setCreateName:P,createRepoIdentity:_,setCreateRepoIdentity:q,createRepoRemoteUrl:B,setCreateRepoRemoteUrl:E,newMeshDaemonId:K,setNewMeshDaemonId:R,newMeshWorkspace:T,setNewMeshWorkspace:H,createPickerWorkspaces:M,loadMeshes:W,handleCreate:J,handleDelete:re,cancelCreate:V}=tD({daemons:r,primaryDaemonId:y,sendCommand:t,unwrapResult:p,normalizeMesh:u,features:g,loadDaemonMetadata:h}),X=k.find(Re=>Re.id===w)||null,{meshGraphStatus:de,setMeshGraphStatus:ne,graphLoading:O,graphError:ie,setGraphError:z,loadGraph:ae}=lD({selectedMeshId:w,loadMeshStatus:o,extractStatus:d,normalizeNode:m,gateIncompleteGraph:C}),[Ce,ye]=l.useState(""),[ke,me]=l.useState(""),G=g.meshHostDaemonSection&&Ce||y,{meshQueue:U,loadQueue:Z}=aD({primaryDaemonId:y,activeDaemonId:G,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f}),{setNodeProviderPriorityDrafts:Y,selectedNodeId:fe,setSelectedNodeId:Te,showAddNode:ce,setShowAddNode:$,nodeWorkspace:pe,setNodeWorkspace:le,nodeProviderPriority:F,setNodeProviderPriority:be,nodeDaemonId:je,setNodeDaemonId:Se,nodeCustomPath:He,setNodeCustomPath:Xe,nodePickerWorkspaces:dt,nodePickerProviders:it,coordinatorCliType:he,setCoordinatorCliType:$e,launchingCoordinator:Be,launchResult:Me,savingPolicy:ve,coordinatorPromptDraft:We,setCoordinatorPromptDraft:ut,savingCoordinatorPrompt:ot,nodeSystemPromptDrafts:pt,setNodeSystemPromptDrafts:Q,savingNodeSystemPromptId:ee,savingNodeSlotsId:oe,savingNodeCapabilitiesId:ue,handleAddNode:xe,handleRemoveNode:Ie,handleUpdatePolicy:Le,handleUpdateNodeSlots:Ae,handleUpdateNodeCapabilities:Fe,handleSaveCoordinatorPrompt:qe,handleSaveNodeSystemPrompt:Ze,handleLaunchCoordinator:_e}=sD({selectedMesh:X,selectedMeshId:w,primaryDaemonId:y,activeDaemonId:G,daemons:r,availableCliProviders:S,sendCommand:t,unwrapResult:p,loadLiveMesh:c,resolveCommandTarget:f,launchCoordinator:i,features:{addNodeDaemonPicker:g.addNodeDaemonPicker},loadMeshes:W,loadQueue:Z,queueSection:g.queueSection,setError:A}),Ue=l.useMemo(()=>r.find(Re=>Re.id===G)||x,[r,G,x]),et=l.useMemo(()=>new Set(((X==null?void 0:X.nodes)||[]).map(Re=>String(Re.daemon_id||Re.daemonId||""))),[X]),te=l.useMemo(()=>r.filter(Re=>Re.id&&!et.has(Re.id)),[r,et]),ge=(X==null?void 0:X.nodes)||[],we=l.useMemo(()=>ge.find(Re=>Os(String(Re.daemon_id||Re.daemonId||""),Ce)),[ge,Ce]),ze=g.meshHostDaemonSection?!!we:!0,Oe=l.useMemo(()=>{if(!g.meshHostDaemonSection||!X)return{pinned:!1,daemonId:"",label:"",online:!1};const Re=X.meshHost,rt=de!=null&&de.meshId&&String(de.meshId)===String(X.id??"")?de.meshHost:void 0,jt=rt!=null&&rt.hostDaemonId?rt:Re??rt,Wt=String((jt==null?void 0:jt.hostDaemonId)||""),se=ge.find(vs=>vs.role==="host"),Ge=String((jt==null?void 0:jt.hostNodeId)||(se==null?void 0:se.id)||""),Ee=Ge?ge.find(vs=>String(vs.id)===Ge):void 0,yt=String((Ee==null?void 0:Ee.daemon_id)||(Ee==null?void 0:Ee.daemonId)||""),Jt=Wt||yt;if(!Jt)return{pinned:!1,daemonId:"",label:"",online:!1};const Mn=r.find(vs=>Wt&&Os(vs.id,Wt))||(yt?r.find(vs=>Os(vs.id,yt)):void 0);if(Mn)return{pinned:!0,daemonId:Mn.id,label:mD(Mn),online:!0};const Oa=String((Ee==null?void 0:Ee.machineLabel)||"")||String((Ee==null?void 0:Ee.workspace)||"")||Jt;return{pinned:!0,daemonId:Jt,label:Oa,online:!1}},[X,ge,r,de,g.meshHostDaemonSection]),tt=Oe.daemonId,Ke=Oe.online,Ye=l.useMemo(()=>!g.meshHostDaemonSection||!Oe.pinned?"":!Ke&&ke&&r.some(Re=>Re.id===ke)?ke:tt,[g.meshHostDaemonSection,Oe.pinned,Ke,ke,r,tt]),It=l.useMemo(()=>de?[...new Set((de.nodes??[]).map(Re=>String(Re.daemonId||Re.daemon_id||"")).filter(Boolean))]:[],[de]),Ot=Km({status:de,daemonId:G||null,extraDaemonIds:It,meshId:w,sendData:n});l.useEffect(()=>{Y(Object.fromEntries(((X==null?void 0:X.nodes)||[]).map(Re=>[Re.id,hD(Re)])))},[X]),l.useEffect(()=>{const Re=(X==null?void 0:X.coordinator)||{};ut({override:typeof Re.systemPromptOverride=="string"?Re.systemPromptOverride:"",append:typeof Re.systemPromptAppend=="string"?Re.systemPromptAppend:typeof Re.systemPromptSuffix=="string"?Re.systemPromptSuffix:""}),Q(Object.fromEntries(((X==null?void 0:X.nodes)||[]).map(rt=>[rt.id,typeof rt.systemPrompt=="string"?rt.systemPrompt:""])))},[X]),l.useEffect(()=>{const Re=g.addNodeDaemonPicker?cr(it):cr(S);ce&&F.length===0&&Re.length>0&&be(Re)},[ce,S,it,F.length,g.addNodeDaemonPicker]),l.useEffect(()=>{const Re=new Set(((X==null?void 0:X.nodes)||[]).map(rt=>rt.id));fe&&!Re.has(fe)&&Te(null)},[X,fe]);const ss=l.useMemo(()=>{var Re;if(!(!(de!=null&&de.meshId)||String(de.meshId)!==String((X==null?void 0:X.id)??"")))return(Re=de.meshHost)==null?void 0:Re.hostDaemonId},[de,X]),De=l.useMemo(()=>cD(r,ge,G,y,ss),[r,ge,G,y,ss]);l.useEffect(()=>{if(!g.meshHostDaemonSection)return;if(!r.length&&!Oe.pinned){ye("");return}const Re=Oe.pinned?Ye:De;Re&&!Os(Re,Ce)&&ye(Re)},[r,Ce,Oe.pinned,Ye,De,g.meshHostDaemonSection]),l.useEffect(()=>{ke&&(Ke||!r.some(Re=>Re.id===ke))&&me("")},[Ke,ke,r]),l.useEffect(()=>{if(g.createDaemonPicker){if(!r.length){R("");return}(!K||!r.some(Re=>Re.id===K))&&R(r[0].id)}},[r,K,g.createDaemonPicker]),l.useEffect(()=>{var Re;if(!g.createDaemonPicker||!K){H("");return}if(!M.length){H("");return}M.some(rt=>rt.path===T)||H(((Re=M[0])==null?void 0:Re.path)||"")},[K,T,M,g.createDaemonPicker]);const Qe=l.useRef(null);l.useEffect(()=>{if(!w)return;const Re=Qe.current!==w;if(Qe.current=w,Re){const rt=th(w);ne(rt),z(null),ae(G,w,rt!==null)}else z(null),ae(G,w,!0)},[w,G]);const Dt=l.useRef(ae);Dt.current=ae;const Tt=l.useRef(!1),Kt=l.useRef(()=>{});Kt.current=()=>{Tt.current||!w||!G||(Tt.current=!0,Promise.resolve(Dt.current(G,w,!0)).finally(()=>{Tt.current=!1}))};const Vt=g.meshStatePushRefresh?uD:dD;aM({daemonIds:l.useMemo(()=>[G,...It].filter(Boolean),[G,It]),meshId:w,sendData:n,onRevisionAdvance:()=>{typeof document<"u"&&document.visibilityState!=="visible"||Kt.current()}}),l.useEffect(()=>{if(!w||!G||typeof document>"u")return;let Re=null;const rt=()=>{document.visibilityState==="visible"&&Kt.current()},jt=()=>{Re===null&&(Re=setInterval(rt,Vt))},Wt=()=>{Re!==null&&(clearInterval(Re),Re=null)},se=()=>{document.visibilityState==="visible"?jt():Wt()};return document.visibilityState==="visible"&&jt(),document.addEventListener("visibilitychange",se),()=>{Wt(),document.removeEventListener("visibilitychange",se)}},[w,G,Vt]),l.useEffect(()=>{g.queueSection||Z(w)},[w,g.queueSection]);const Yt=l.useMemo(()=>r.map(Re=>Re.id).filter(Boolean).sort().join(","),[r]),xs=l.useRef(!1);return l.useEffect(()=>{W(xs.current),xs.current=!0},[Yt]),y?X?s.jsx(eD,{selectedMesh:X,error:j,onDismissError:()=>A(null),onBack:()=>{v(null),ne(null)},onDelete:re,displayedMeshStatus:Ot,graphLoading:O,graphError:ie,onRefreshGraph:()=>ae(G,w,!0),savingPolicy:ve,onUpdatePolicy:Le,coordinatorPromptDraft:We,onCoordinatorPromptDraftChange:ut,savingCoordinatorPrompt:ot,onSaveCoordinatorPrompt:qe,daemons:r,coordinatorDaemonId:Ce,onCoordinatorDaemonIdChange:ye,coordinatorCliType:he,onCoordinatorCliTypeChange:$e,launchingCoordinator:Be,launchResult:Me,isHostNodeAttached:ze,selectedHostNode:we,hostPinned:Oe.pinned,hostLabel:Oe.label,hostOnline:Ke,hostRebindDaemonId:ke,onHostRebindDaemonIdChange:Re=>me(Re),onLaunchCoordinator:_e,activeDaemon:Ue,activeDaemonId:G,meshQueue:U,userName:a,availableCliProviders:S,savingNodeSlotsId:oe,onUpdateNodeSlots:Ae,savingNodeCapabilitiesId:ue,onUpdateNodeCapabilities:Fe,nodeSystemPromptDrafts:pt,onNodeSystemPromptDraftChange:(Re,rt)=>Q(jt=>({...jt,[Re]:rt})),savingNodeSystemPromptId:ee,onSaveNodeSystemPrompt:Ze,selectedNodeId:fe,onSelectNode:Te,showAddNode:ce,onShowAddNode:()=>$(!0),onCancelAddNode:()=>$(!1),nodeWorkspace:pe,onNodeWorkspaceChange:le,nodeProviderPriority:F,onNodeProviderPriorityChange:be,nodeDaemonId:je,onNodeDaemonIdChange:Se,nodeCustomPath:He,onNodeCustomPathChange:Xe,nodePickerWorkspaces:dt,nodePickerProviders:it,attachableDaemons:te,onAddNode:xe,onRemoveNode:Ie,availableCliAgents:b,features:{coordinatorPrompt:g.coordinatorPrompt,meshHostDaemonSection:g.meshHostDaemonSection,hermesMcpConfig:g.hermesMcpConfig,addNodeDaemonPicker:g.addNodeDaemonPicker,nodeInstruction:g.nodeInstruction},sendCommand:t}):s.jsx(hM,{meshes:k,loading:N,error:j,onDismissError:()=>A(null),daemons:r,features:{createDaemonPicker:g.createDaemonPicker},showCreate:I,onToggleCreate:()=>D(!I),createName:L,onCreateNameChange:P,createRepoIdentity:_,onCreateRepoIdentityChange:q,createRepoRemoteUrl:B,onCreateRepoRemoteUrlChange:E,newMeshDaemonId:K,onNewMeshDaemonIdChange:R,newMeshWorkspace:T,onNewMeshWorkspaceChange:H,createPickerWorkspaces:M,onSelectMesh:v,onCreate:J,onCancelCreate:V}):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 mD(e){return e&&(e.machineNickname||e.nickname||e.hostname||e.id)||"Unknown"}function hD(e){var r;const t=Array.isArray(e.providerPriority)?e.providerPriority:Array.isArray((r=e.policy)==null?void 0:r.providerPriority)?e.policy.providerPriority:[],n=new Set;return t.map(a=>typeof a=="string"?a.trim():"").filter(Boolean).filter(a=>n.has(a)?!1:(n.add(a),!0))}function fD({children:e}){const{sendCommand:t,sendData:n}=vt(),{ides:r}=gs(),a=l.useMemo(()=>r.filter(i=>i.daemonMode||i.type==="adhdev-daemon").map(i=>i),[r]),o=l.useMemo(()=>({sendCommand:t,sendData:n,daemons:a,userName:void 0,loadMeshStatus:async(i,c)=>t(i,"mesh_status",{meshId:c}),launchCoordinator:async(i,c)=>{var f;const d={meshId:c.meshId};c.cliType&&(d.cliType=c.cliType);const p=await t(i,"launch_mesh_coordinator",d),u=(p==null?void 0:p.result)??p;if((u==null?void 0:u.success)===!1)throw new Error(u.error||"Coordinator launch failed");const m=(u==null?void 0:u.sessionId)||((f=u==null?void 0:u.session)==null?void 0:f.id)||(u==null?void 0:u.targetSessionId);return{sessionId:m,message:m?`Coordinator launched (${m})`:"Coordinator launch command sent"}},loadLiveMesh:void 0,extractStatus:Oi,unwrapResult:i=>i,normalizeMesh:(i,c)=>i,normalizeNode:(i,c,d)=>i,resolveCommandTarget:i=>({targetDaemonId:i}),features:oM}),[t,n,a]);return s.jsx(Zm.Provider,{value:o,children:e})}function gl(){return typeof window>"u"?null:new URLSearchParams(window.location.search).get("token")}function bD(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=gl();return n&&!t.searchParams.has("token")&&t.searchParams.set("token",n),e.startsWith("http://")||e.startsWith("https://")?t.toString():`${t.pathname}${t.search}${t.hash}`}async function hs(e,t){return await fetch(bD(e),{credentials:"same-origin",...t})}function sh(){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 gD{constructor(){st(this,"adapters",new Map);st(this,"states",new Map);st(this,"runtimeListeners",new Map);st(this,"screenshotCallbacks",new Map);st(this,"statusCallbacks",new Set);st(this,"stateChangeCallbacks",new Set);st(this,"ptyInputSender",null)}resolveDaemonId(t){if(this.adapters.has(t))return t;if(t.startsWith("standalone")){for(const n of this.adapters.keys())if(n.startsWith("standalone"))return n}return null}register(t,n){this.adapters.set(t,n),this.states.set(t,n.connectionState)}unregister(t){this.adapters.delete(t),this.states.delete(t)}setState(t,n){this.states.set(t,n);const r=this.resolveDaemonId(t)||t;this.stateChangeCallbacks.forEach(a=>a(r,n))}onStateChange(t){return this.stateChangeCallbacks.add(t),()=>{this.stateChangeCallbacks.delete(t)}}retryConnection(t){}get(t){const n=this.resolveDaemonId(t);return n?this.adapters.get(n):void 0}getState(t){const n=this.resolveDaemonId(t);return n&&this.states.get(n)||"disconnected"}registerPtyInputSender(t){this.ptyInputSender=t}sendData(t,n){return!1}sendPtyInput(t,n,r){return this.ptyInputSender?this.ptyInputSender(t,n,r):!1}onScreenshot(t,n){return this.screenshotCallbacks.set(t,n),()=>{this.screenshotCallbacks.delete(t)}}emitScreenshot(t,n){this.screenshotCallbacks.forEach(r=>r(t,n))}onStatus(t){return this.statusCallbacks.add(t),()=>{this.statusCallbacks.delete(t)}}emitStatus(t,n){this.statusCallbacks.forEach(r=>r(t,n))}emitRuntimeSnapshot(t,n,r=0,a=!1,o,i){this.emitRuntimeEvent(t,{type:"runtime_snapshot",sessionId:t,seq:r,text:n,truncated:a,cols:o,rows:i})}emitSessionOutput(t,n,r){!t||typeof n!="string"||!n||this.emitRuntimeEvent(t,{type:"session_output",sessionId:t,...typeof r=="number"?{seq:r}:{},data:n})}onRuntimeEvent(t,n){const r=this.runtimeListeners.get(t)||new Set;return r.add(n),this.runtimeListeners.set(t,r),()=>{const a=this.runtimeListeners.get(t);a&&(a.delete(n),a.size===0&&this.runtimeListeners.delete(t))}}async requestRuntimeSnapshot(t,n,r){if(!n)return{success:!1,error:"sessionId is required"};const a=new URL(`/api/v1/runtime/${encodeURIComponent(n)}/snapshot`,window.location.origin);typeof(r==null?void 0:r.sinceSeq)=="number"&&a.searchParams.set("sinceSeq",String(r.sinceSeq));const o=await hs(`${a.pathname}${a.search}`);if(!o.ok){let c=`Runtime snapshot unavailable (${o.status})`;try{const d=await o.json();d!=null&&d.error&&(c=d.error)}catch{}return{success:!1,error:c}}const i=await o.json();return this.emitRuntimeEvent(n,{type:"runtime_snapshot",sessionId:n,seq:typeof i.seq=="number"?i.seq:0,text:typeof i.text=="string"?i.text:"",truncated:!!i.truncated,cols:typeof i.cols=="number"?i.cols:void 0,rows:typeof i.rows=="number"?i.rows:void 0,force:!!(r!=null&&r.force)}),{success:!0}}emitRuntimeEvent(t,n){var r;(r=this.runtimeListeners.get(t))==null||r.forEach(a=>a(n))}}const ms=new gD;function xD(){if(typeof window>"u")return"ws://localhost:3847/ws";const t=`${window.location.protocol==="https:"?"wss":"ws"}://${window.location.host}/ws`,n=gl();return n?`${t}?token=${encodeURIComponent(n)}`:t}const Or=xD(),Md=3e3,vD=3e4;let as=null,yD=0;const ya=new Map;let $s=null,nr=null;function Dd(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 wD(e){return e==="connected"?"connected":e}async function rr(e,t,n){const r=Cp(e,n||{}),a=as;if(a&&a.readyState===WebSocket.OPEN){const o=`req_${++yD}_${Date.now()}`;return new Promise((i,c)=>{const d=setTimeout(()=>{ya.delete(o),c(new Error(`WS command timeout: ${t}`))},3e4);ya.set(o,{resolve:p=>{clearTimeout(d),i(p)},reject:p=>{clearTimeout(d),c(p)}}),a.send(JSON.stringify({type:"command",requestId:o,data:{type:t,payload:r.payload}}))})}throw new Error(`WS command channel unavailable: ${t}`)}function yi(e,t){const n=as;if(!n||n.readyState!==WebSocket.OPEN||!t||t.type!=="subscribe"&&t.type!=="unsubscribe")return!1;try{return n.send(JSON.stringify(t)),!0}catch{return!1}}function nh(e,t,n){const r=as;if(!r||r.readyState!==WebSocket.OPEN)return!1;const a=Cp(e,{sessionId:t,targetSessionId:t,data:n});try{return r.send(JSON.stringify({type:"command",data:{type:"pty_input",payload:a.payload}})),!0}catch{return!1}}ms.registerPtyInputSender(nh);class kD{constructor(t){st(this,"daemonId");st(this,"screenshotIdeType",null);this.daemonId=t}get hasCommandChannel(){return(as==null?void 0:as.readyState)===WebSocket.OPEN}get connectionState(){return(as==null?void 0:as.readyState)===WebSocket.OPEN?"connected":"disconnected"}async sendCommand(t,n){return rr(this.daemonId,t,n)}async sendInput(t,n){return rr(this.daemonId,"cdp_remote_action",{action:t,params:n,...this.screenshotIdeType&&{targetSessionId:this.screenshotIdeType}})}startScreenshots(t){this.screenshotIdeType=t||null,$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 a=await fetch(`data:image/jpeg;base64,${r.base64}`).then(o=>o.blob());ms.emitScreenshot(this.daemonId,a)}}catch{}};n(),$s=setInterval(n,2e3)}stopScreenshots(t){$s&&(clearInterval($s),$s=null)}}let Xt=null;function SD(e){return(!Xt||Xt.daemonId!==e)&&(Xt=new kD(e)),Xt}function CD({children:e}){const t=l.useRef(ar()),n=ar();t.current=n;const{setUserName:r}=gs(),a=l.useRef(r);a.current=r;const o=l.useRef(null),i=l.useRef(null),[,c]=l.useState("disconnected"),d=l.useCallback((h,x)=>{c(h),nr==null||nr(h,x)},[]),p=l.useRef(null),u=l.useRef(),m=l.useRef(Md),f=l.useRef(!0),g=l.useRef(!1),C=l.useRef("initial_connect");return l.useEffect(()=>{f.current=!0,g.current=!1;function h(){var b,S;if(!f.current||((b=p.current)==null?void 0:b.readyState)===WebSocket.OPEN||((S=p.current)==null?void 0:S.readyState)===WebSocket.CONNECTING)return;d("connecting"),console.log(`[Standalone WS] Connecting to ${Or}...`),Gn("connect_attempt",{url:Or,reason:C.current,delayMs:m.current});let y;try{y=new WebSocket(Or)}catch(k){console.error("[Standalone WS] Failed to create WebSocket:",k),x();return}p.current=y,y.onopen=()=>{if(!f.current){y.close();return}d("connected"),m.current=Md,Gn("open",{url:Or,reason:C.current}),ls.resubscribeAll({sendData:yi}),console.log("[Standalone WS] Connected")},as=y,y.onmessage=k=>{var w,v;try{const N=JSON.parse(k.data);if((N.type==="command_result"||N.type==="error")&&N.requestId){const j=ya.get(N.requestId);j&&(ya.delete(N.requestId),N.type==="error"?j.reject(new Error(((w=N.data)==null?void 0:w.message)||"Command failed")):j.resolve(N.data));return}if(N.type==="session_output"){const j=N.sessionId||N.cliId||N.cliType;j&&ms.emitSessionOutput(j,typeof N.data=="string"?N.data:"",typeof N.seq=="number"?N.seq:void 0);return}if(N.type==="runtime_snapshot"){ms.emitRuntimeSnapshot(N.sessionId,typeof N.text=="string"?N.text:"",typeof N.seq=="number"?N.seq:0,!!N.truncated,typeof N.cols=="number"?N.cols:void 0,typeof N.rows=="number"?N.rows:void 0);return}if(N.type==="topic_update"){const j=N.update;j&&ls.publish(j);return}if(N.type==="status"||N.type==="initial_state"){const j=N.data;if(!j)return;const{injectEntries:A,markLoaded:I,getIdes:D}=t.current,L=j.instanceId||"standalone",P=D().find(B=>B.id===L),_=SD(L);ms.register(L,_),ms.setState(L,"connected"),d("connected",L),ms.emitStatus(L,j);const q=oa(j,{daemonId:L,existingDaemon:P,existingEntries:D()});Dd("ws_status",{type:N.type,daemonId:L,sessions:(j.sessions||[]).map(B=>({id:B.id,parentId:B.parentId,providerType:B.providerType,kind:B.kind,transport:B.transport,unread:B.unread,inboxBucket:B.inboxBucket,lastSeenAt:B.lastSeenAt,lastUpdated:B.lastUpdated,title:B.title})),recentLaunches:(j.recentLaunches||[]).map(B=>({id:B.id,providerType:B.providerType,kind:B.kind,workspace:B.workspace,lastLaunchedAt:B.lastLaunchedAt}))}),Dd("entries",{daemonId:L,entries:q.filter(B=>B.type!=="adhdev-daemon").map(B=>({id:B.id,type:B.type,unread:B.unread,inboxBucket:B.inboxBucket,lastSeenAt:B.lastSeenAt,lastUpdated:B.lastUpdated,sessionId:B.sessionId}))}),q.length>0&&A(q,{authoritativeDaemonIds:[L]}),I(),i.current!==L&&((v=o.current)==null||v.call(o),i.current=L,o.current=ls.subscribe({sendData:yi},L,{type:"subscribe",topic:"daemon.metadata",key:`daemon:metadata:${L}`,params:{includeSessions:!0}},B=>{if(B.topic!=="daemon.metadata")return;const E=t.current.getIdes(),K=E.find(T=>T.id===L),R=oa(B.status,{daemonId:L,existingDaemon:K,existingEntries:E,timestamp:B.timestamp});R.length>0&&t.current.injectEntries(R,{authoritativeDaemonIds:[L]}),B.userName&&a.current&&a.current(B.userName)}))}}catch(N){console.error("[Standalone WS] Parse error:",N)}},y.onclose=k=>{f.current&&(Xt==null||Xt.stopScreenshots(),Xt&&ms.setState(Xt.daemonId,"disconnected"),d("disconnected"),p.current=null,C.current=`close:${k.code}${k.wasClean?":clean":":unclean"}`,Gn("close",{code:k.code,reason:k.reason||"",wasClean:k.wasClean}),x())},y.onerror=k=>{g.current||!f.current||(C.current="error",Gn("error",{message:k instanceof Event?"event":String(k),readyState:y.readyState}),console.warn("[Standalone WS] Error, will reconnect:",k))}}function x(){if(!f.current)return;clearTimeout(u.current);const y=m.current;console.log(`[Standalone WS] Reconnecting in ${y}ms...`),Gn("schedule_reconnect",{reason:C.current,delayMs:y}),u.current=setTimeout(()=>{m.current=Math.min(m.current*1.5,vD),h()},y)}return h(),()=>{var y;f.current=!1,g.current=!0,(y=o.current)==null||y.call(o),o.current=null,i.current=null,clearTimeout(u.current),p.current&&(p.current.onerror=null,p.current.onclose=null,p.current.close(),p.current=null,as=null),Xt&&(Xt.stopScreenshots(),ms.unregister(Xt.daemonId))}},[]),s.jsx(s.Fragment,{children:e})}function jD({children:e}){const[t,n]=l.useState("disconnected"),[r,a]=l.useState(null);l.useEffect(()=>(nr=(i,c)=>{n(i),c&&a(c)},()=>{nr=null}),[]);const o=l.useMemo(()=>{const i=t==="connected",c=wD(t),d={};return r&&(d[r]=c),d.standalone=c,{wsStatus:t,isConnected:i,connectionStates:d}},[t,r]);return s.jsx(of,{connectionOverrides:o,children:s.jsx(CD,{children:e})})}const rh="adhdev_standalone_font_preferences",Vs={chat:{preset:"default"},code:{preset:"default"},terminal:{preset:"default"}},Fa=[{id:"default",label:"Default",family:"var(--font-sans)",description:"Current dashboard sans stack"},{id:"system-ui",label:"System UI",family:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Use the browser/OS default UI font"},{id:"inter",label:"Inter",family:'"Inter", system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',description:"Match the current product default explicitly"},{id:"pretendard",label:"Pretendard",family:'"Pretendard", "Noto Sans KR", system-ui, sans-serif',description:"Crisp Korean-first sans fallback stack"},{id:"noto-sans-kr",label:"Noto Sans KR",family:'"Noto Sans KR", "Apple SD Gothic Neo", "Malgun Gothic", "Segoe UI", sans-serif',description:"Wide CJK coverage with neutral metrics"},{id:"serif",label:"Serif",family:'"Iowan Old Style", "Apple Garamond", "Times New Roman", serif',description:"Reading-focused serif stack for long replies"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS font-family stack"}],pr=[{id:"default",label:"Default mono",family:'ui-monospace, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace',description:"Current monospace stack"},{id:"jetbrains-mono",label:"JetBrains Mono",family:'"JetBrains Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Readable coding font with strong punctuation"},{id:"fira-code",label:"Fira Code",family:'"Fira Code", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Popular ligature-friendly code font"},{id:"cascadia-code",label:"Cascadia Code",family:'"Cascadia Code", "Cascadia Mono", ui-monospace, "SF Mono", Menlo, Consolas, monospace',description:"Windows-friendly modern coding font"},{id:"berkeley-mono",label:"Berkeley Mono",family:'"Berkeley Mono", "SF Mono", ui-monospace, Menlo, Consolas, monospace',description:"Editorial-feeling mono stack if installed"},{id:"custom",label:"Custom…",family:"",description:"Enter any CSS monospace stack"}],ND=new Set(Fa.map(e=>e.id)),AD=new Set(pr.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:{},a=typeof r.preset=="string"?r.preset.trim():"",o=typeof r.customFamily=="string"?r.customFamily.trim():"";return(e==="chat"?ND:AD).has(a)?a==="custom"?o?{preset:"custom",customFamily:o}:n:{preset:a}:n}function ea(e,t){var a;const n=Zr(e,t);if(n.preset==="custom"&&n.customFamily)return n.customFamily;const r=e==="chat"?Fa:pr;return((a=r.find(o=>o.id===n.preset))==null?void 0:a.family)||r[0].family}function ID(e){const t=fs(e),n=ea("chat",t.chat),r=ea("code",t.code),a=ea("terminal",t.terminal);return{"--chat-font-family":n,"--chat-code-font-family":r,"--chat-terminal-font-family":a,"--chat-tool-font-family":a}}function Fs(e,t=document.documentElement){const n=fs(e),r=ID(n);t.setAttribute("data-standalone-fonts","custom");for(const[a,o]of Object.entries(r))t.style.setProperty(a,o);return n}function wi(e){const t=fs(e);try{localStorage.setItem(rh,JSON.stringify(t))}catch{}return t}function TD(){try{const e=localStorage.getItem(rh);if(e)return fs(JSON.parse(e))}catch{}return Vs}function MD(){return Fs(TD())}function qn(e,t){var r;const n=e==="chat"?Fa:pr;return((r=n.find(a=>a.id===t))==null?void 0:r.label)||n[0].label}function DD({children:e}){const t=mr(),n=Si(),{t:r}=Ne("common"),a=l.useMemo(()=>[{id:"dashboard",path:"/dashboard",icon:s.jsx(zd,{}),label:r("standalone.nav.dashboard"),active:n.pathname.startsWith("/dashboard"),onSelect:()=>t("/dashboard")},{id:"machine",path:"/machines",icon:s.jsx(Ts,{}),label:"Burrow",active:n.pathname.startsWith("/machines"),onSelect:()=>t("/machines")},{id:"mesh",path:"/mesh",icon:s.jsx(es,{}),label:"Mesh",active:n.pathname.startsWith("/mesh"),onSelect:()=>t("/mesh")},{id:"settings",path:"/settings",icon:s.jsx(ka,{}),label:r("standalone.nav.settings"),active:n.pathname.startsWith("/settings"),onSelect:()=>t("/settings")}],[n.pathname,t,r]),o=l.useMemo(()=>[{id:"docs",label:s.jsxs(s.Fragment,{children:[s.jsx("span",{children:r("standalone.nav.docs")}),s.jsx("span",{className:"ml-auto text-[9px] text-text-muted",children:"↗"})]}),icon:s.jsx(Vd,{}),onSelect:()=>window.open("https://docs.adhf.dev","_blank"),title:r("standalone.nav.docs")},{id:"about",label:r("standalone.nav.about"),icon:s.jsx(Ai,{}),active:n.pathname==="/about",onSelect:()=>t("/about"),title:r("standalone.nav.about")}],[n.pathname,t,r]);return s.jsx(MS,{brand:({collapsed:i})=>s.jsxs(s.Fragment,{children:[s.jsx("img",{src:"/otter-logo.png",alt:"ADHDev",className:"w-7 h-7"}),!i&&s.jsx("span",{children:"ADHDev"})]}),navItems:a,footerItems:o,footerInfo:({collapsed:i})=>i?null:s.jsxs("div",{className:"px-3 py-2 text-xs text-text-muted",children:["Selfhost v","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 PD=[{icon:s.jsx(Ts,{size:16}),title:"Local-first runtime",desc:"Everything stays on your machine and the browser only connects over localhost."},{icon:s.jsx(Zs,{size:16}),title:"Agent chat relay",desc:"Read and respond to AI conversations in real time across connected IDEs."},{icon:s.jsx(Jd,{size:16}),title:"Live screenshots",desc:"View your IDE directly in the browser through the local screenshot stream."},{icon:s.jsx(us,{size:16}),title:"Remote control",desc:"Click, type, and steer your IDE sessions without switching windows."},{icon:s.jsx(or,{size:16}),title:"Multi-IDE support",desc:"Monitor VS Code, Cursor, Windsurf, and extension-based agents in one place."},{icon:s.jsx(Vd,{size:16}),title:"CLI and ACP coverage",desc:"Track standalone CLI agents and ACP-backed workflows alongside IDE sessions."}],LD=[{icon:s.jsx(Hf,{size:16}),title:"Access from anywhere",desc:"Reach your burrows from another laptop or phone without opening local ports."},{icon:s.jsx(zd,{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(Df,{size:16}),title:"REST API access",desc:"Integrate with Slack, CI, or internal tools using API keys and service routes."},{icon:s.jsx(Kd,{size:16}),title:"Team workspace",desc:"Share burrows, activity views, and policies across a team workspace."},{icon:s.jsx(Rf,{size:16}),title:"Enterprise controls",desc:"SSO, RBAC, audit logs, and managed policy features for production teams."}],RD=[{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 ED(){const{t:e}=Ne("common");return s.jsxs(gr,{icon:s.jsx(Ai,{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:PD.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:jp.map(t=>`${t.icon} ${t.name}`)},{label:"Extensions",items:Ap.map(t=>`${t.icon} ${t.name}`)},{label:"CLI agents",items:Np.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:LD.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:RD.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(La,{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(Kf,{size:14,className:"mr-1"}),e("standalone.about.discord")]})]})})]})}function $o(e,t,n){return{...e,[t]:n}}function Ho({surface:e,title:t,description:n,value:r,options:a,onChange:o}){const{t:i}=Ne("common");return s.jsxs("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 flex flex-col gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:t}),s.jsx("div",{className:"text-xs text-text-muted mt-1",children:n})]}),s.jsxs("div",{className:"flex flex-col gap-2",children:[s.jsx(RS,{value:r.preset,onChange:c=>{const d=c.target.value;o(d==="custom"?{preset:"custom",customFamily:r.customFamily||""}:{preset:d})},children:a.map(c=>s.jsx("option",{value:c.id,children:c.label},c.id))}),r.preset==="custom"&&s.jsx(is,{type:"text",className:"font-mono",placeholder:'e.g. "Pretendard", "Noto Sans KR", sans-serif',value:r.customFamily||"",onChange:c=>o({preset:"custom",customFamily:c.target.value})}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[s.jsx("span",{className:"font-medium text-text-secondary",children:i("standalone.fonts.resolvedStack")})," ",s.jsx("span",{className:"font-mono break-all",children:ea(e,r)})]})]})]})}function _D({value:e,savedValue:t,saving:n=!1,error:r,notice:a,onChange:o,onSave:i,onResetToSaved:c,onResetToDefaults:d}){const{t:p}=Ne("common"),u=JSON.stringify(e)!==JSON.stringify(t);return s.jsxs("div",{className:"flex flex-col gap-4",children:[s.jsx("div",{className:"rounded-xl border border-border-subtle bg-bg-glass px-4 py-3 text-sm text-text-muted",children:p("standalone.fonts.fontOverridesNotice")}),r&&s.jsx(Gt,{variant:"error",children:r}),a&&s.jsx(Gt,{variant:"success",children:a}),s.jsxs("div",{className:"grid gap-3 lg:grid-cols-3",children:[s.jsx(Ho,{surface:"chat",title:p("standalone.fonts.chat"),description:p("standalone.fonts.chatDescription"),value:e.chat,options:Fa,onChange:m=>o($o(e,"chat",m))}),s.jsx(Ho,{surface:"code",title:p("standalone.fonts.code"),description:p("standalone.fonts.codeDescription"),value:e.code,options:pr,onChange:m=>o($o(e,"code",m))}),s.jsx(Ho,{surface:"terminal",title:p("standalone.fonts.terminal"),description:p("standalone.fonts.terminalDescription"),value:e.terminal,options:pr,onChange:m=>o($o(e,"terminal",m))})]}),s.jsxs("div",{className:"rounded-2xl border border-border-subtle bg-bg-primary/70 p-4 flex flex-col gap-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-sm font-medium text-text-primary",children:p("standalone.fonts.livePreview")}),s.jsxs("div",{className:"text-xs text-text-muted mt-1",children:["Chat: ",qn("chat",e.chat.preset)," · Code: ",qn("code",e.code.preset)," · Terminal: ",qn("terminal",e.terminal.preset)]})]}),s.jsxs("div",{className:"text-[11px] text-text-muted",children:[p("standalone.fonts.defaults")," ",qn("chat",Vs.chat.preset)," / ",qn("code",Vs.code.preset)]})]}),s.jsx("div",{className:"chat-container rounded-xl border border-border-subtle min-h-0 !p-4",children:s.jsxs("div",{className:"chat-container-content",children:[s.jsx("div",{className:"self-start max-w-[88%] min-w-0 flex flex-col gap-1",children:s.jsxs("div",{className:"chat-bubble chat-bubble-assistant",children:[s.jsxs("div",{className:"chat-bubble-header mb-1.5",children:[s.jsx("span",{className:"chat-sender",children:"Hermes"}),s.jsx("span",{className:"chat-time",children:"now"})]}),s.jsxs("div",{className:"chat-markdown",children:[s.jsxs("p",{children:["Readable prose, ",s.jsx("strong",{children:"bold text"}),", and ",s.jsx("code",{children:"inline code"})," should all follow your standalone font choices."]}),s.jsx("pre",{children:s.jsx("code",{children:"const message = 'standalone custom fonts'"})})]})]})}),s.jsxs("div",{className:"chat-msg-tool",children:[s.jsx("span",{className:"tool-icon",children:"▸"}),s.jsx("span",{className:"tool-text",children:"tool_call --scope standalone --font preview"})]}),s.jsxs("div",{className:"chat-msg-terminal",children:[s.jsx("div",{className:"chat-msg-header",children:"Terminal"}),s.jsx("pre",{className:"chat-msg-body",children:"$ npm run dev:standalone\\nready on http://localhost:3847"})]})]})})]}),s.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[s.jsx(ks,{type:"button",variant:"primary",size:"sm",onClick:i,disabled:n||!u,children:p(n?"standalone.fonts.saving":"standalone.fonts.saveFontSettings")}),s.jsx(ks,{type:"button",variant:"secondary",size:"sm",onClick:c,disabled:n||!u,children:p("standalone.fonts.revertToSaved")}),s.jsx(ks,{type:"button",variant:"secondary",size:"sm",onClick:d,disabled:n,children:p("standalone.fonts.resetToDefaults")})]})]})}function $D(){const{t:e}=Ne("common"),{ides:t}=gs(),n=t.find(O=>O.type==="adhdev-daemon"),r=(n==null?void 0:n.detectedIdes)||[],{sendCommand:a}=vt(),{userName:o}=gs(),[i,c]=l.useState(o||""),[d,p]=l.useState(null),[u,m]=l.useState(null),[f,g]=l.useState(Vs),[C,h]=l.useState(!1),[x,y]=l.useState(""),[b,S]=l.useState(""),[k,w]=l.useState("127.0.0.1"),[v,N]=l.useState(""),[j,A]=l.useState(""),[I,D]=l.useState(""),[L,P]=l.useState(""),[_,q]=l.useState(""),[B,E]=l.useState(!1),K=async()=>{const ie=await(await hs("/auth/session")).json();p(ie)},R=async()=>{const ie=await(await hs("/api/v1/standalone/preferences")).json();m(ie),w(ie.standaloneBindHost);const z=fs(ie.standaloneFontPreferences);g(z),Fs(z),wi(z)};l.useEffect(()=>{o!==void 0&&c(o)},[o]),l.useEffect(()=>{Promise.all([K(),R()]).catch(O=>{P(O instanceof Error?O.message:String(O))})},[]),l.useEffect(()=>{Fs(f)},[f]);const T=O=>{const ie=O.target.value.trim();n!=null&&n.id&&ie!==o&&a(n.id,"set_user_name",{userName:ie}).catch(console.error)},[H,M]=l.useState(()=>{try{return localStorage.getItem("adhdev_sound")!=="0"}catch{return!0}}),W=O=>{M(O);try{localStorage.setItem("adhdev_sound",O?"1":"0")}catch{}},J=async()=>{y(""),S(""),h(!0);try{const O=fs(f),ie=await hs("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneFontPreferences:O})}),z=await ie.json();if(!ie.ok)throw new Error((z==null?void 0:z.error)||"Failed to save standalone font preferences");const ae=fs(z.standaloneFontPreferences);m(z),g(ae),Fs(ae),wi(ae),S(e("standalone.settings.fontsSaved"))}catch(O){y(O instanceof Error?O.message:String(O))}finally{h(!1)}},re=()=>{const O=fs(u==null?void 0:u.standaloneFontPreferences);y(""),S(""),g(O),Fs(O)},V=()=>{y(""),S(""),g(Vs),Fs(Vs)},X=async()=>{P(""),q(""),E(!0);try{const O=await hs("/api/v1/standalone/preferences",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({standaloneBindHost:k})}),ie=await O.json();if(!O.ok)throw new Error((ie==null?void 0:ie.error)||"Failed to save standalone network preference");m(ie),w(ie.standaloneBindHost),q(ie.standaloneBindHost==="0.0.0.0"?e("standalone.settings.networkSavedAll"):e("standalone.settings.networkSavedLocal"))}catch(O){P(O instanceof Error?O.message:String(O))}finally{E(!1)}},de=async()=>{if(P(""),q(""),j.trim().length<4){P(e("standalone.settings.passwordTooShort"));return}if(j!==I){P(e("standalone.settings.passwordMismatch"));return}E(!0);try{const O=await hs("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,newPassword:j})}),ie=await O.json();if(!O.ok)throw new Error((ie==null?void 0:ie.error)||"Failed to save password");p(ie),await R(),N(""),A(""),D(""),q(d!=null&&d.hasPasswordAuth?e("standalone.settings.passwordUpdated"):e("standalone.settings.passwordEnabled")),sh()}catch(O){P(O instanceof Error?O.message:String(O))}finally{E(!1)}},ne=async()=>{P(""),q(""),E(!0);try{const O=await hs("/auth/password",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({currentPassword:v,clear:!0})}),ie=await O.json();if(!O.ok)throw new Error((ie==null?void 0:ie.error)||"Failed to clear password");p(ie),await R(),N(""),A(""),D(""),q(e("standalone.settings.passwordDisabled"))}catch(O){P(O instanceof Error?O.message:String(O))}finally{E(!1)}};return s.jsxs(gr,{icon:s.jsx(ka,{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")}),(d==null?void 0:d.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:(u==null?void 0:u.currentBindHost)||(d==null?void 0:d.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:(u==null?void 0:u.standaloneBindHost)||"127.0.0.1"}),s.jsx("span",{className:"text-text-muted",children:e("standalone.settings.authLabel")}),s.jsx("span",{className:"text-xs",children:d!=null&&d.hasPasswordAuth?e("standalone.settings.authPassword"):d!=null&&d.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:k==="127.0.0.1",onChange:()=>w("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:k==="0.0.0.0",onChange:()=>w("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:B,children:e(B?"standalone.settings.saving":"standalone.settings.saveNetworkMode")}),s.jsx("span",{className:"text-xs text-text-muted",children:e("standalone.settings.networkRestartHint",{host:(u==null?void 0:u.currentBindHost)||(d==null?void 0:d.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:d!=null&&d.hasPasswordAuth?e("standalone.settings.passwordSet"):e("standalone.settings.passwordNotSet")}),L&&s.jsx(Gt,{variant:"error",children:L}),_&&s.jsx(Gt,{variant:"success",children:_}),s.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[s.jsx(is,{type:"password",placeholder:d!=null&&d.hasPasswordAuth?e("standalone.settings.currentPasswordPlaceholder"):e("standalone.settings.currentPasswordFirstTimePlaceholder"),value:v,onChange:O=>N(O.target.value)}),s.jsx(is,{type:"password",placeholder:d!=null&&d.hasPasswordAuth?e("standalone.settings.newPasswordPlaceholder"):e("standalone.settings.newPasswordFirstTimePlaceholder"),value:j,onChange:O=>A(O.target.value)}),s.jsx(is,{type:"password",className:"md:col-span-2",placeholder:e("standalone.settings.confirmPasswordPlaceholder"),value:I,onChange:O=>D(O.target.value)})]}),s.jsxs("div",{className:"flex flex-wrap gap-2",children:[s.jsx(ks,{type:"button",variant:"primary",size:"sm",onClick:()=>{de()},disabled:B,children:B?e("standalone.settings.saving"):d!=null&&d.hasPasswordAuth?e("standalone.settings.updatePassword"):e("standalone.settings.enablePassword")}),(d==null?void 0:d.hasPasswordAuth)&&s.jsx(ks,{type:"button",variant:"danger",size:"sm",onClick:()=>{ne()},disabled:B,children:e("standalone.settings.disablePassword")})]})]})}),s.jsx(bt,{title:e("standalone.settings.detectedIdesSection"),description:e("standalone.settings.detectedIdesDescription"),children:r.length===0?s.jsx("p",{className:"text-sm text-text-muted",children:e("standalone.settings.noIdesDetected")}):s.jsx("div",{className:"flex flex-col gap-1.5",children:r.map(O=>s.jsxs("div",{className:"flex justify-between items-center bg-bg-glass rounded-lg px-3.5 py-2.5",children:[s.jsxs("div",{className:"flex items-center gap-2.5",children:[s.jsx("span",{className:`w-2 h-2 rounded-full ${O.running?"bg-green-400":"bg-text-muted/30"}`}),s.jsx("span",{className:"text-sm font-medium",children:O.name})]}),s.jsx("span",{className:"text-[11px] text-text-muted font-mono",children:O.type})]},O.type))})}),s.jsx(bt,{title:e("standalone.settings.machineSection"),description:e("standalone.settings.machineDescription"),children:s.jsx(WS,{ides:t,emptyMessage:e("standalone.settings.daemonNotConnected")})}),s.jsx(bt,{title:e("standalone.settings.appearanceSection"),description:e("standalone.settings.appearanceDescription"),children:s.jsx(lC,{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(_D,{value:f,savedValue:fs(u==null?void 0:u.standaloneFontPreferences),saving:C,error:x,notice:b,onChange:g,onSave:()=>{J()},onResetToSaved:re,onResetToDefaults:V})]})})}),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(HS,{}),s.jsx(Bs,{label:s.jsxs("span",{className:"flex items-center gap-1.5",children:[s.jsx(zf,{size:15})," ",e("standalone.settings.soundEffectsLabel")]}),description:e("standalone.settings.soundEffectsDescription"),checked:H,onChange:W})]})}),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(Mf,{size:16,className:"text-text-secondary"})," ",e("standalone.settings.displayNameLabel")]}),s.jsx("span",{className:"text-[12px] text-text-muted leading-relaxed",children:e("standalone.settings.displayNameHint")})]}),s.jsx(is,{type:"text",className:"w-48 text-right",placeholder:e("standalone.settings.displayNamePlaceholder"),value:i,onChange:O=>c(O.target.value),onBlur:T,onKeyDown:O=>{O.key==="Enter"&&O.currentTarget.blur()}})]})})})]})}const HD=["claude-cli","codex-cli","antigravity-cli","hermes-cli"],Yn="adhdev_onboarding_done",BD=[{key:"all",label:"All"},{key:"cli",label:"CLI"},{key:"ide",label:"IDE"},{key:"extension",label:"Extension"},{key:"acp",label:"ACP"}],FD={cli:"CLI providers",ide:"IDE providers",extension:"Editor extensions",acp:"ACP providers"};function OD({onDone:e}){const{t}=Ne("common"),[n,r]=l.useState([]),[a,o]=l.useState(new Set(HD)),[i,c]=l.useState(!0),[d,p]=l.useState(null),[u,m]=l.useState(!1),[f,g]=l.useState(null),[C,h]=l.useState("all");l.useEffect(()=>{let v=!1;const N=window.location.hostname==="localhost"?"/registry":"https://api.adhf.dev/api/v1/registry";return fetch(`${N}/providers?sort=popular&limit=100`).then(j=>{if(!j.ok)throw new Error(`HTTP ${j.status}`);return j.json()}).then(j=>{v||r(j.providers??[])}).catch(j=>{v||p(j instanceof Error?j.message:String(j))}).finally(()=>{v||c(!1)}),()=>{v=!0}},[]);const x=n.filter(v=>C==="all"||v.category===C),y=["cli","ide","extension","acp"].map(v=>({category:v,items:x.filter(N=>N.category===v)})).filter(v=>v.items.length>0),b=l.useCallback(v=>{o(N=>{const j=new Set(N);return j.has(v)?j.delete(v):j.add(v),j})},[]),S=l.useCallback(async()=>{if(a.size===0){localStorage.setItem(Yn,"1"),e();return}m(!0);const v=[];for(const N of a)try{const A=await(await fetch("/api/v1/providers/install",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({type:N})})).json().catch(()=>({}));v.push({type:N,ok:!!A.success,error:A.error})}catch(j){v.push({type:N,ok:!1,error:j instanceof Error?j.message:String(j)})}g(v),m(!1),v.every(N=>N.ok)&&localStorage.setItem(Yn,"1")},[a,e]),k=l.useCallback(()=>{localStorage.setItem(Yn,"1"),e()},[e]),w=l.useCallback(()=>{f&&f.every(v=>v.ok)?e():u||k()},[f,u,e,k]);return s.jsx(Pu,{open:!0,onClose:w,size:"lg",contentClassName:"max-w-2xl",title:t("standalone.onboarding.title"),footer:s.jsxs("div",{className:"flex w-full items-center gap-2",children:[s.jsx("div",{className:"text-[11px] text-text-muted",children:t(a.size!==1?"standalone.onboarding.selectedCount_other":"standalone.onboarding.selectedCount_one",{count:a.size})}),s.jsxs("div",{className:"ml-auto flex gap-2",children:[s.jsx(ks,{variant:"secondary",size:"sm",onClick:k,disabled:u,children:t("standalone.onboarding.skip")}),s.jsx(ks,{variant:"primary",size:"sm",onClick:()=>{f?(localStorage.setItem(Yn,"1"),e()):S()},disabled:u||!f&&a.size===0,children:u?t("standalone.onboarding.installing"):f?t("standalone.onboarding.done"):t("standalone.onboarding.installCount",{count:a.size})})]})]}),children:s.jsxs("div",{className:"flex flex-col gap-5",children:[s.jsx("div",{className:"text-[12px] text-text-muted",children:t("standalone.onboarding.intro")}),!i&&!d&&n.length>0&&s.jsx("div",{className:"flex gap-1 flex-wrap border-b border-border-subtle pb-2",children:BD.map(v=>{const N=v.key==="all"?n.length:n.filter(j=>j.category===v.key).length;return N===0&&v.key!=="all"?null:s.jsxs("button",{onClick:()=>h(v.key),className:`machine-btn text-[10px] px-2 py-0.5 ${C===v.key?"bg-accent-primary/12 border-accent-primary/40 text-accent-primary":""}`,children:[v.label," ",s.jsxs("span",{className:"opacity-60",children:["(",N,")"]})]},v.key)})}),i&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.loadingRegistry")}),!i&&d&&s.jsx(Gt,{variant:"error",children:t("standalone.onboarding.loadError",{error:d})}),!i&&!d&&x.length===0&&s.jsx("div",{className:"text-text-muted text-[12px] py-8 text-center",children:t("standalone.onboarding.noProviders")}),!i&&!d&&x.length>0&&s.jsx("div",{className:"flex flex-col gap-4",children:y.map(v=>s.jsxs("div",{children:[s.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-text-muted mb-1.5",children:FD[v.category]??v.category}),s.jsx("div",{className:"grid gap-1.5",children:v.items.map(N=>{var L,P;const j=a.has(N.type),A=f==null?void 0:f.find(_=>_.type===N.type),I=((L=N.manifest)==null?void 0:L.icon)??"📦",D=((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 ${j?"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:j,onChange:()=>b(N.type),disabled:u,className:"shrink-0"}),s.jsx("span",{className:"text-base shrink-0",children:I}),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}),D&&s.jsx("div",{className:"text-[10px] text-text-muted truncate",children:D})]}),A&&s.jsx("span",{className:`text-[10px] font-semibold ${A.ok?"text-status-online":"text-status-error"}`,children:A.ok?t("standalone.onboarding.installed"):t("standalone.onboarding.installFailed",{error:A.error??"failed"})})]},N.type)})})]},v.category))})]})})}function WD(){try{return localStorage.getItem(Yn)==="1"}catch{return!1}}CS();eC();my();MD();const UD=Bd({baseUrl:"",getToken:gl});function GD({children:e}){const{t}=Ne("common"),[n,r]=l.useState(null),[a,o]=l.useState(!0),[i,c]=l.useState(""),[d,p]=l.useState(""),[u,m]=l.useState(!1),f=async()=>{o(!0),p("");try{const h=await(await hs("/auth/session")).json();r(h)}catch(C){p(C instanceof Error?C.message:String(C))}finally{o(!1)}};l.useEffect(()=>{f()},[]),l.useEffect(()=>{if(!n||n.required&&!n.authenticated)return;let C=!1;return(async()=>{try{const h=await hs("/api/v1/standalone/preferences");if(!h.ok)return;const x=await h.json();if(C)return;const y=fs(x.standaloneFontPreferences);Fs(y),wi(y)}catch{}})(),()=>{C=!0}},[n==null?void 0:n.authenticated,n==null?void 0:n.required]);const g=async C=>{C.preventDefault(),m(!0),p("");try{const h=await hs("/auth/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:i})}),x=await h.json();if(!h.ok)throw new Error((x==null?void 0:x.error)||"Login failed");r(x),c(""),sh()}catch(h){p(h instanceof Error?h.message:String(h))}finally{m(!1)}};return a?s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-text-muted",children:t("standalone.auth.loading")}):n?!n.required||n.authenticated?s.jsx(s.Fragment,{children:e}):s.jsx("div",{className:"min-h-screen bg-bg-base flex items-center justify-center px-4",children:s.jsxs("div",{className:"w-full max-w-md rounded-2xl border border-border-subtle bg-bg-panel p-6 shadow-2xl flex flex-col gap-4",children:[s.jsxs("div",{children:[s.jsx("div",{className:"text-lg font-semibold text-text-primary",children:t("standalone.auth.signInTitle")}),s.jsx("p",{className:"text-sm text-text-muted mt-1",children:n.hasPasswordAuth?t("standalone.auth.passwordProtected"):t("standalone.auth.tokenProtected")})]}),n.hasPasswordAuth?s.jsxs("form",{className:"flex flex-col gap-3",onSubmit:g,children:[s.jsx(is,{type:"password",value:i,onChange:C=>c(C.target.value),placeholder:t("standalone.auth.passwordPlaceholder"),autoFocus:!0}),s.jsx(ks,{type:"submit",variant:"primary",disabled:u||!i,className:"justify-center",children:t(u?"standalone.auth.signingIn":"standalone.auth.unlock")})]}):s.jsx(Gt,{variant:"warning",children:t("standalone.auth.noPasswordEnabled")}),d&&s.jsx(Gt,{variant:"error",children:d})]})}):s.jsx("div",{className:"min-h-screen flex items-center justify-center text-sm text-red-400",children:t("standalone.auth.loadError",{error:d||"unknown error"})})}function Pd(){const{t:e}=Ne("common"),{ides:t,initialLoaded:n}=gs();if(!n)return s.jsx("div",{className:"p-10 text-center text-text-muted",children:e("standalone.machine.loading")});const r=t.find(a=>a.daemonMode||a.type==="adhdev-daemon");return r?s.jsx(Wo,{to:`/machines/${r.id}`,replace:!0}):s.jsx(Wo,{to:"/dashboard",replace:!0})}function qD(){const[e,t]=l.useState(!1);return l.useEffect(()=>{let n=!1;if(!WD())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(OD,{onDone:()=>t(!1)}):null}function zD(){const{t:e}=Ne("common"),{ides:t}=gs(),n=l.useMemo(()=>{for(const u of t)if(u.activeInteractivePrompt)return u.instanceId??u.id;return null},[t]),{promptSession:r,hasActivePrompt:a,responseError:o,isSubmitting:i,submit:c,cancel:d,reopen:p}=Rp(n);return a?s.jsxs("div",{className:"relative",children:[!r&&s.jsx("button",{type:"button",onClick:p,className:"fixed bottom-4 right-4 z-[79] btn btn-primary btn-sm shadow-lg",children:e("standalone.machine.awaitingInput")}),s.jsx(du,{promptSession:r,isSubmitting:i,error:o,onSubmit:c,onCancel:d})]}):null}function KD(){const e=l.useMemo(()=>({sendCommand:rr,sendData:yi,sendPtyInput:nh}),[]);return s.jsx(Uh,{future:{v7_startTransition:!0,v7_relativeSplatPath:!0},children:s.jsx(df,{client:UD,children:s.jsx(GD,{children:s.jsx(jD,{children:s.jsx(pf,{value:e,children:s.jsxs(bf,{sendDaemonCommand:rr,children:[s.jsx(zD,{}),s.jsxs(DD,{children:[s.jsx(qD,{}),s.jsxs(Gh,{children:[s.jsx(js,{path:"/dashboard",element:s.jsx(JI,{})}),s.jsx(js,{path:"/machine",element:s.jsx(Pd,{})}),s.jsx(js,{path:"/machines/:id",element:s.jsx(rM,{})}),s.jsx(js,{path:"/machines",element:s.jsx(Pd,{})}),s.jsx(js,{path:"/about",element:s.jsx(ED,{})}),s.jsx(js,{path:"/settings",element:s.jsx($D,{})}),s.jsx(js,{path:"/mesh",element:s.jsx(fD,{children:s.jsx(pD,{})})}),s.jsx(js,{path:"*",element:s.jsx(Wo,{to:"/dashboard",replace:!0})})]})]})]})})})})})})}gk({connectionManager:ms});qh(document.getElementById("root")).render(s.jsx(KD,{}));