remote-codex 0.11.13 → 0.11.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/apps/supervisor-api/dist/{chunk-ZTQPMDTP.js → chunk-B3T3GIKQ.js} +51 -19
- package/apps/supervisor-api/dist/index.js +1 -1
- package/apps/supervisor-api/dist/worker-index.js +1 -1
- package/apps/supervisor-web/dist/assets/{index-Z5yu-xV3.js → index-C5VKPUvg.js} +5 -5
- package/apps/supervisor-web/dist/index.html +1 -1
- package/package.json +1 -1
- package/packages/shared/src/index.ts +1 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{j as e,u as es,d as
|
|
1
|
+
import{j as e,u as es,d as at,r,L as It,N as Os,e as ur,f as mr,b as mo,B as ho,h as hr,i as qe,O as po,k as fo,c as xo}from"./react-vendor-CgLzZcV4.js";import{u as Jt,a as ca,C as wn,f as ps,T as pr,A as go,b as bo,t as fr,E as vo,c as jo,d as yo,e as wo,g as No,L as So,P as ko,h as Co}from"./thread-ui-q6mjcjXn.js";import{l as nt}from"./ui-vendor-CeKGesq3.js";import"./graph-vendor-DVPtkh3h.js";import"./terminal-vendor-B365Go3Z.js";import"./markdown-vendor-BQJfKm05.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const d of document.querySelectorAll('link[rel="modulepreload"]'))n(d);new MutationObserver(d=>{for(const o of d)if(o.type==="childList")for(const m of o.addedNodes)m.tagName==="LINK"&&m.rel==="modulepreload"&&n(m)}).observe(document,{childList:!0,subtree:!0});function a(d){const o={};return d.integrity&&(o.integrity=d.integrity),d.referrerPolicy&&(o.referrerPolicy=d.referrerPolicy),d.crossOrigin==="use-credentials"?o.credentials="include":d.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(d){if(d.ep)return;d.ep=!0;const o=a(d);fetch(d.href,o)}})();var To=["codex","claude","opencode"],Tt="codex",Pa={codex:{displayName:"Codex",description:"Local Codex app-server runtime.",defaultTransport:"stdio",homeEnvVar:"CODEX_HOME",commandEnvVar:"CODEX_COMMAND",defaultHomeDir:".codex",defaultCommand:"codex"},claude:{displayName:"Claude Code",description:"Local Claude Code Agent SDK runtime.",defaultTransport:"sdk",homeEnvVar:"CLAUDE_HOME",commandEnvVar:"CLAUDE_COMMAND",defaultHomeDir:".claude",defaultCommand:"claude"},opencode:{displayName:"OpenCode",description:"Local OpenCode runtime.",defaultTransport:"sdk",homeEnvVar:"OPENCODE_HOME",commandEnvVar:"OPENCODE_COMMAND",defaultHomeDir:".opencode",defaultCommand:"opencode"}};function Io(t){return typeof t=="string"&&To.includes(t)}function Eo(t){return Io(t)?t:null}var Aa=15;function Ro(t){return t.replace(/\s+/g," ").trim()}function Po(t){const s=Ro(t);if(!s)return"";const a=Array.from(s);return a.length<=Aa?s:`${a.slice(0,Aa).join("")}...`}const Ao=["codex","claude","opencode"],xr="codex",gr={codex:{displayName:"Codex",description:"Local Codex app-server runtime.",defaultTransport:"stdio",homeEnvVar:"CODEX_HOME",commandEnvVar:"CODEX_COMMAND",defaultHomeDir:".codex",defaultCommand:"codex"},claude:{displayName:"Claude Code",description:"Local Claude Code Agent SDK runtime.",defaultTransport:"sdk",homeEnvVar:"CLAUDE_HOME",commandEnvVar:"CLAUDE_COMMAND",defaultHomeDir:".claude",defaultCommand:"claude"},opencode:{displayName:"OpenCode",description:"Local OpenCode runtime.",defaultTransport:"sdk",homeEnvVar:"OPENCODE_HOME",commandEnvVar:"OPENCODE_COMMAND",defaultHomeDir:".opencode",defaultCommand:"opencode"}},Ua=15;function Uo(t){return t.replace(/\s+/g," ").trim()}function Oo(t){const s=Uo(t);if(!s)return"";const a=Array.from(s);return a.length<=Ua?s:`${a.slice(0,Ua).join("")}...`}class re extends Error{constructor(s,a){super(a.message),this.statusCode=s,this.payload=a}}const Qn="remote-codex-auth-token",ea="remote-codex-relay-token",br="remote-codex-relay-mode",ta="remote-codex-relay-device-id",sa="remote-codex-relay-thread-id";function vr(){return typeof window>"u"?null:window.localStorage.getItem(Qn)}function $o(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(Qn,t);return}window.localStorage.removeItem(Qn)}}function jr(){return typeof window>"u"?null:window.localStorage.getItem(ea)}function ua(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(ea,t);return}window.localStorage.removeItem(ea)}}function fs(){var t;return typeof window>"u"?!1:((t=window.__REMOTE_CODEX_BOOTSTRAP__)==null?void 0:t.mode)==="relay"||window.location.pathname.startsWith("/relay-portal")||window.location.pathname.startsWith("/relay-admin")||window.location.search.includes("relay=1")||window.localStorage.getItem(br)==="true"}function xs(){typeof window>"u"||window.localStorage.setItem(br,"true")}function na(){return fs()}function yr(){return typeof window>"u"?null:window.localStorage.getItem(ta)}function bn(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(ta,t);return}window.localStorage.removeItem(ta)}}function Mo(){return typeof window>"u"?null:window.localStorage.getItem(sa)}function vn(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(sa,t);return}window.localStorage.removeItem(sa)}}function wr(t){if(!fs())return t;if(t.startsWith("/api/")){const s=yr();return s?`/relay/devices/${encodeURIComponent(s)}${t}`:`/relay${t}`}return t}function Lo(t){return t===400?"bad_request":t===401?"unauthorized":t===403?"forbidden":t===404?"not_found":t===409?"conflict":t===429||t===503?"service_unavailable":"internal_error"}function Do(t,s){const a=s==null?void 0:s.trim(),n=a?`${t} ${a}`:`${t}`;return t===429?`Too many requests (${n}).`:t===503?`Upstream service unavailable (${n}).`:`Request failed (${n}).`}function cs(t,s,a){const n=typeof(s==null?void 0:s.message)=="string"&&s.message.trim()?s.message.trim():a,d=s!=null&&s.details&&typeof s.details=="object"?s.details:void 0;return{code:(s==null?void 0:s.code)??Lo(t.status),message:n,...d?{details:d}:{}}}async function Nr(t){var d,o;const s=Do(t.status,t.statusText),a=((o=(d=t.headers)==null?void 0:d.get)==null?void 0:o.call(d,"content-type"))??"",n=async()=>cs(t,await t.json(),s);if(a.includes("application/json"))try{return await n()}catch{return cs(t,null,s)}try{if(typeof t.text!="function")try{return await n()}catch{return cs(t,null,s)}const m=(await t.text()).trim();if(m.startsWith("{"))try{return cs(t,JSON.parse(m),s)}catch{}return cs(t,m?{message:`${s}
|
|
2
2
|
${m}`}:null,s)}catch{try{return await n()}catch{return cs(t,null,s)}}}async function U(t,s){const a=new Headers(s==null?void 0:s.headers);(s==null?void 0:s.body)!==void 0&&!(s.body instanceof FormData)&&!a.has("Content-Type")&&a.set("Content-Type","application/json");const n=await fetch(wr(String(t)),kr({...s,headers:a}));if(!n.ok){const d=await Nr(n);throw new re(n.status,d)}return await n.json()}function Ho(t){const s=String(t);return s.includes("/exports/pdf")?s.includes("format=html")?"remote-codex-transcript.html":"remote-codex-transcript.pdf":"download"}function _o(t){var d;if(!t)return null;const s=t.match(/filename\*=UTF-8''([^;]+)/i);if(s!=null&&s[1])try{return decodeURIComponent(s[1].trim())}catch{return s[1].trim()}const a=t.match(/filename="([^"]+)"/i);if(a!=null&&a[1])return a[1].trim();const n=t.match(/filename=([^;]+)/i);return((d=n==null?void 0:n[1])==null?void 0:d.trim())??null}async function Sr(t,s){const a=await fetch(wr(String(t)),kr(s));if(!a.ok){const d=await Nr(a);throw new re(a.status,d)}const n=_o(a.headers.get("content-disposition"))??Ho(t);return{blob:await a.blob(),filename:n}}function kr(t={}){const s=new Headers(t.headers),a=jr(),n=vr();return fs()&&a&&!s.has("Authorization")?s.set("Authorization",`Bearer ${a}`):n&&!s.has("Authorization")&&s.set("Authorization",`Bearer ${n}`),{...t,credentials:t.credentials??"same-origin",headers:s}}function Bo(t,s){return`${t.baseUrl.replace(/\/+$/,"")}${s}`}function Fo(t,s){const a=new Headers(s==null?void 0:s.headers);return a.set("Authorization",`Bearer ${t.token}`),a}async function Se(t,s,a){return U(Bo(t,s),{...a,headers:Fo(t,a)})}function ma(t,s){return`${t.replace(/\/+$/,"")}${s}`}function Wo(t,s,a=typeof window>"u"?void 0:window.location.href){const n=new URL(ma(t,`/api/auth/oauth/${s}/start`));return a&&n.searchParams.set("returnTo",a),n.toString()}function qo(t,s){return U(ma(t,"/api/auth/password/register"),{method:"POST",body:JSON.stringify(s)})}function zo(t,s){return U(ma(t,"/api/auth/password/login"),{method:"POST",body:JSON.stringify(s)})}function ha(t){return Se(t,"/api/me",{cache:"no-store"})}function Vo(t,s=10){const a=new URLSearchParams({limit:String(s)});return Se(t,`/api/usage/events?${a.toString()}`,{cache:"no-store"})}function Jo(t){return Se(t,"/api/usage/harness/summary",{cache:"no-store"})}function Go(t,s=10){const a=new URLSearchParams({limit:String(s)});return Se(t,`/api/usage/harness/events?${a.toString()}`,{cache:"no-store"})}function Ko(t,s){return Se(t,"/api/me",{method:"PATCH",body:JSON.stringify(s)})}function Cr(t){return Se(t,"/api/projects",{cache:"no-store"})}function Yo(t,s){return Se(t,"/api/projects",{method:"POST",body:JSON.stringify(s)})}function Zo(t,s,a){return Se(t,`/api/projects/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(a)})}function Xo(t,s){return Se(t,`/api/projects/${encodeURIComponent(s)}`,{method:"DELETE"})}function aa(t,s){const a=s?`?projectId=${encodeURIComponent(s)}`:"";return Se(t,`/api/workspaces${a}`,{cache:"no-store"})}function Qo(t,s){const a=s.projectId?`/api/projects/${encodeURIComponent(s.projectId)}/workspaces`:"/api/workspaces",n=s.projectId?{name:s.name,slug:s.slug}:s;return Se(t,a,{method:"POST",body:JSON.stringify(n)})}function Oa(t,s,a){return Se(t,`/api/workspaces/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(a)})}function ra(t,s){return Se(t,`/api/workspaces/${encodeURIComponent(s)}/sessions`,{cache:"no-store"})}function el(t,s,a){return Se(t,`/api/workspaces/${encodeURIComponent(s)}/sessions`,{method:"POST",body:JSON.stringify(a)})}function $a(t,s,a){return Se(t,`/api/sessions/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(a)})}function tl(t,s){return Se(t,`/api/sessions/${encodeURIComponent(s)}/close`,{method:"POST"})}function Tr(t,s){return Se(t,`/api/sessions/${encodeURIComponent(s)}/resume`,{method:"POST"})}function sl(t){return Se(t,"/api/sandbox/start",{method:"POST"})}function nl(t){return Se(t,"/api/sandbox/stop",{method:"POST"})}function al(t){return Se(t,"/api/sandbox/restart",{method:"POST"})}function Ma(t){return Se(t,"/api/sandbox/health",{cache:"no-store"})}function rl(t){return Se(t,"/api/sandbox/harness/status",{cache:"no-store"})}function La(t,s){return Se(t,`/api/sandbox/harness/modules/${encodeURIComponent(s)}/tools`,{cache:"no-store"})}function Da(t,s){return Se(t,`/api/sandbox/harness/modules/${encodeURIComponent(s)}/runs`,{cache:"no-store"})}function ol(t,s){return Se(t,`/api/admin/sandboxes/${encodeURIComponent(s)}`,{cache:"no-store"})}function Ir(t,s,a){return Se(t,`/api/sandboxes/${encodeURIComponent(s)}/route-token`,{method:"POST",body:JSON.stringify(a)})}function Nn(t,s,a){const n=s.replace(/^\/+/,""),d=new URL(`/api/sandboxes/${encodeURIComponent(t.sandboxId)}/${n}`,t.routerBaseUrl);for(const[o,m]of Object.entries(a??{}))m!=null&&d.searchParams.set(o,String(m));return d.toString()}function Sn(t,s){const a=new Headers(s==null?void 0:s.headers);return a.set("Authorization",`Bearer ${t.token}`),a}function us(t,s,a={}){return U(Nn(t,`/api/threads/${encodeURIComponent(s)}`,a),{cache:"no-store",headers:Sn(t)})}function ll(t,s,a){return U(Nn(t,`/api/threads/${encodeURIComponent(s)}/items/${encodeURIComponent(a)}/detail`),{cache:"no-store",headers:Sn(t)})}function $n(t,s,a){return U(Nn(t,`/api/threads/${encodeURIComponent(s)}/prompt`),{method:"POST",body:JSON.stringify(a),headers:Sn(t)})}function Ha(t,s,a={}){return U(Nn(t,`/api/threads/${encodeURIComponent(s)}/interrupt`),{method:"POST",body:JSON.stringify(a),headers:Sn(t)})}function _a(t,s){const a=t.originalName.trim();if(a)return a;const n=t.file.name.trim();return n||(t.kind==="photo"?`photo-${s+1}.jpg`:`file-${s+1}`)}function il(){return U("/api/config/runtime")}function dl(){return U("/api/auth/session",{cache:"no-store"})}async function cl(t){const s=await U("/api/auth/login",{method:"POST",body:JSON.stringify(t)});return $o(s.token??null),s}function $s(){return U("/relay/auth/session",{credentials:"same-origin"})}async function ul(t){xs();const s=await U("/relay/auth/login",{method:"POST",body:JSON.stringify(t)});return ua(s.token),s}async function ml(t){xs();const s=await U("/relay/auth/register",{method:"POST",body:JSON.stringify(t)});return ua(s.token),s}async function Er(){const t=await U("/relay/auth/logout",{method:"POST"});return ua(null),bn(null),vn(null),t}function Rr(){return U("/relay/portal")}function Pr(t){return U("/relay/devices",{method:"POST",body:JSON.stringify(t)})}function Ar(t){return U(`/relay/devices/${encodeURIComponent(t)}`,{method:"DELETE"})}function hl(t){return U("/relay/account",{method:"PATCH",body:JSON.stringify(t)})}function pl(t){return U("/relay/account/password",{method:"PATCH",body:JSON.stringify(t)})}function fl(t){return U("/relay/shares",{method:"POST",body:JSON.stringify(t)})}function xl(t){return U(`/relay/shares/${encodeURIComponent(t)}`,{method:"DELETE"})}function gl(){return U("/relay/admin")}function bl(t){return U("/relay/admin/settings/registration",{method:"PATCH",body:JSON.stringify({enabled:t})})}function vl(t,s){return U(`/relay/admin/users/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({enabled:s})})}function jl(){return U("/api/config/workspace-settings",{cache:"no-store"})}function yl(t){return U("/api/config/workspace-settings",{method:"PATCH",body:JSON.stringify(t)})}function pa(){return U("/api/agent-runtimes",{cache:"no-store"})}function Ur(t){return U(`/api/agent-runtimes/${encodeURIComponent(t)}/status`,{cache:"no-store"})}function wl(t){return U(`/api/agent-runtimes/${encodeURIComponent(t)}/restart`,{method:"POST"})}function Nl(t,s){return U(`/api/agent-runtimes/${encodeURIComponent(t)}/install`,{method:"POST",body:JSON.stringify({action:s})})}function oa(t){return U(`/api/agent-runtimes/${encodeURIComponent(t)}/models`,{cache:"no-store"})}function Or(t,s){return U(`/api/config/providers/${encodeURIComponent(t)}/files/${encodeURIComponent(s)}`,{cache:"no-store"})}function $r(t,s,a){return U(`/api/config/providers/${encodeURIComponent(t)}/files/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(a)})}function Sl(t){return U(`/api/config/providers/${encodeURIComponent(t)}/archives`,{cache:"no-store"})}function kl(t,s={}){return U(`/api/config/providers/${encodeURIComponent(t)}/archives`,{method:"POST",body:JSON.stringify(s)})}function Cl(t,s,a){return U(`/api/config/providers/${encodeURIComponent(t)}/archives/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(a)})}function Tl(t,s){return U(`/api/config/providers/${encodeURIComponent(t)}/archives/${encodeURIComponent(s)}/apply`,{method:"POST"})}function Il(){return U("/api/service/build-restart",{method:"POST"})}function El(){return U("/healthz",{cache:"no-store"})}function fa(){return U("/api/workspaces")}function Rl(t){return U(`/api/workspaces/${encodeURIComponent(t)}/files/tree`,{cache:"no-store"})}function Pl(t,s){const a=new URLSearchParams({path:s.path});return s.offset!==void 0&&a.set("offset",String(s.offset)),s.limit!==void 0&&a.set("limit",String(s.limit)),U(`/api/workspaces/${encodeURIComponent(t)}/files/preview?${a.toString()}`,{cache:"no-store"})}function Al(t,s){const a=new URLSearchParams({path:s.path});return`/api/workspaces/${encodeURIComponent(t)}/files/raw?${a.toString()}`}function Ul(t,s){const a=new URLSearchParams({path:s.path});return Sr(`/api/workspaces/${encodeURIComponent(t)}/files/download?${a.toString()}`,{cache:"no-store"})}function Ol(t,s){const a=new FormData;return a.append("file",s.file,s.file.name),U(`/api/workspaces/${encodeURIComponent(t)}/files/upload`,{method:"POST",body:a})}function $l(t,s){return U(`/api/workspaces/${encodeURIComponent(t)}/files`,{method:"PUT",body:JSON.stringify(s)})}function Mr(){return U("/api/threads")}function Ba(t,s={}){const a=new URLSearchParams;return s.limit!==void 0&&a.set("limit",String(s.limit)),s.beforeTurnId&&a.set("beforeTurnId",s.beforeTurnId),U(`/api/threads/${t}${a.size>0?`?${a.toString()}`:""}`)}function Ml(t,s){return U(`/api/threads/${t}/items/${encodeURIComponent(s)}/detail`)}function Ll(){return U("/api/plugins",{cache:"no-store"})}function Dl(t){return U("/api/plugins/import",{method:"POST",body:JSON.stringify(t)})}function Hl(t,s){return U(`/api/plugins/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(s)})}function _l(t){return U(`/api/plugins/${encodeURIComponent(t)}`,{method:"DELETE"})}function Bl(t){return U(`/api/threads/${t}/export-turns`,{cache:"no-store"})}function Fl(t,s){var n,d,o;const a=new URLSearchParams;return s.format!==void 0&&a.set("format",s.format),a.set("mode",s.mode),s.limit!==void 0&&a.set("limit",String(s.limit)),s.turnIds!==void 0&&a.set("turnIds",s.turnIds.join(",")),s.profile!==void 0&&a.set("profile",s.profile),((n=s.options)==null?void 0:n.includeTokenAndPrice)!==void 0&&a.set("includeTokenAndPrice",String(s.options.includeTokenAndPrice)),((d=s.options)==null?void 0:d.includeCommandOutput)!==void 0&&a.set("includeCommandOutput",String(s.options.includeCommandOutput)),((o=s.options)==null?void 0:o.includeAbsolutePaths)!==void 0&&a.set("includeAbsolutePaths",String(s.options.includeAbsolutePaths)),`/api/threads/${encodeURIComponent(t)}/exports/pdf?${a.toString()}`}function Wl(t,s){return Sr(Fl(t,s),{cache:"no-store"})}function ql(t){return U(`/api/threads/${t}/shell`)}function zl(t){return U("/api/threads/start",{method:"POST",body:JSON.stringify(t)})}function Vl(t){return U("/api/threads/import",{method:"POST",body:JSON.stringify(typeof t=="string"?{sessionId:t}:t)})}function Jl(t,s={}){return U(`/api/threads/${t}/shell`,{method:"POST",...Object.keys(s).length>0?{body:JSON.stringify(s)}:{}})}function Gl(t){return U(`/api/shells/${t}/terminate`,{method:"POST"})}function Kl(t,s){return U(`/api/shells/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Fa(t,s={}){return U(`/api/threads/${t}/resume`,{method:"POST",...Object.keys(s).length>0?{body:JSON.stringify(s)}:{}})}function Yl(t){return U(`/api/threads/${t}/disconnect`,{method:"POST"})}function Zl(t,s){const a=s.attachments??[];if(a.length===0)return U(`/api/threads/${t}/prompt`,{method:"POST",body:JSON.stringify(s)});const n=new FormData;n.append("prompt",s.prompt),s.clientRequestId!==void 0&&n.append("clientRequestId",s.clientRequestId),s.model!==void 0&&n.append("model",s.model),s.reasoningEffort!==void 0&&s.reasoningEffort!==null&&n.append("reasoningEffort",s.reasoningEffort),s.collaborationMode!==void 0&&n.append("collaborationMode",s.collaborationMode),s.sandboxMode!==void 0&&s.sandboxMode!==null&&n.append("sandboxMode",s.sandboxMode);const d=a.map((o,m)=>({clientId:o.clientId,kind:o.kind,originalName:_a(o,m),placeholder:o.placeholder}));n.append("attachmentManifest",JSON.stringify(d));for(const[o,m]of a.entries())n.append("attachments",m.file,_a(m,o));return U(`/api/threads/${t}/prompt`,{method:"POST",body:n})}function Wa(t,s={}){return U(`/api/threads/${t}/interrupt`,{method:"POST",body:JSON.stringify(s)})}function Lr(t,s){return U(`/api/threads/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Dr(t){return U(`/api/threads/${t}`,{method:"DELETE"})}function Xl(t,s){return U(`/api/threads/${t}/settings`,{method:"PATCH",body:JSON.stringify(s)})}function Ql(t){return U(`/api/threads/${t}/compact`,{method:"POST"})}function ei(t){return U(`/api/threads/${t}/goal`,{cache:"no-store"})}function ti(t,s){return U(`/api/threads/${t}/goal`,{method:"PATCH",body:JSON.stringify(s)})}function si(t){return U(`/api/threads/${t}/goal`,{method:"DELETE"})}function ni(t){return U(`/api/threads/${t}/fork-turns`,{cache:"no-store"})}function qa(t,s){return U(`/api/threads/${t}/fork`,{method:"POST",body:JSON.stringify(s)})}function ai(t){return U(`/api/threads/${t}/skills`,{cache:"no-store"})}function ri(t){return U(`/api/threads/${t}/mcp-servers`,{cache:"no-store"})}function oi(t){return U(`/api/threads/${t}/hooks`,{cache:"no-store"})}function li(t,s){return U(`/api/threads/${t}/hooks`,{method:"POST",body:JSON.stringify(s)})}function ii(t,s){return U(`/api/threads/${t}/hooks`,{method:"PUT",body:JSON.stringify(s)})}function di(t,s){return U(`/api/threads/${t}/hooks/trust`,{method:"POST",body:JSON.stringify(s)})}function ci(t,s){return U(`/api/threads/${t}/hooks/untrust`,{method:"POST",body:JSON.stringify(s)})}function ui(t,s,a){return U(`/api/threads/${t}/requests/${encodeURIComponent(s)}/respond`,{method:"POST",body:JSON.stringify(a)})}function mi(t){return U("/api/workspaces",{method:"POST",body:JSON.stringify(t)})}function hi(t,s){return U(`/api/workspaces/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function pi(t){return U(`/api/workspaces/${t}`,{method:"DELETE"})}function fi(t,s){return U(`/api/workspaces/${t}/favorite`,{method:"POST",body:JSON.stringify(s)})}function Hr(t){const s=window.location.protocol==="https:"?"wss:":"ws:",a=new WebSocket(_r(s));return a.addEventListener("message",n=>{try{const d=JSON.parse(n.data);gi(d)&&t(d)}catch{}}),a}function xi(t={}){const s=window.location.protocol==="https:"?"wss:":"ws:",a=new WebSocket(_r(s));return a.addEventListener("message",n=>{var d,o;try{const m=JSON.parse(n.data);if(m.type==="supervisor.connected"){(d=t.onConnected)==null||d.call(t,m);return}bi(m)&&((o=t.onShellEvent)==null||o.call(t,m))}catch{}}),{socket:a,send(n){a.send(JSON.stringify(n))}}}function _r(t){const s=new URL(`${t}//${window.location.host}/ws`);if(fs()){const o=yr();s.pathname=o?`/relay/devices/${encodeURIComponent(o)}/ws`:"/relay/ws"}const a=vr(),n=jr(),d=Mo();return fs()&&n&&s.searchParams.set("relaySession",n),fs()&&d&&s.searchParams.set("threadId",d),a&&s.searchParams.set("token",a),s.toString()}function gi(t){return"threadId"in t&&t.type.startsWith("thread.")&&typeof t.payload=="object"&&t.payload!==null}function bi(t){return"shellId"in t&&t.type.startsWith("shell.")&&typeof t.payload=="object"&&t.payload!==null}function vi(){return e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-4 w-4 fill-current",children:e.jsx("path",{d:"M2 3.25h12v1.5H2Zm0 4h12v1.5H2Zm0 4h12v1.5H2Z"})})}function fn(){return e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-4 w-4 fill-current",children:e.jsx("path",{d:"M3.22 2.47 8 7.25l4.78-4.78 1.06 1.06L9.06 8.31l4.78 4.78-1.06 1.06L8 9.37l-4.78 4.78-1.06-1.06 4.78-4.78-4.78-4.78 1.06-1.06Z"})})}function Mn(t=!1){return`flex w-full items-center rounded-[0.95rem] px-3 py-2 text-left text-sm transition ${t?"cursor-not-allowed bg-[var(--theme-muted)] text-[var(--theme-fg-muted)]":"text-[var(--theme-fg)] hover:bg-[var(--theme-hover)]"}`}const ji=[{value:"light",label:"Light",description:"Always use the bright theme."},{value:"dark",label:"Dark",description:"Always use the dark theme."},{value:"system",label:"System",description:"Follow the operating system appearance."}],Br={hostConfigFiles:[],toolboxItems:[],hookCommandTemplates:[],providerConfigFormat:"none",mcpConfigFormat:"none",configArchives:!1,buildRestart:!1},yi={codex:{packageName:"@openai/codex",installCommand:null,updateCommand:"npm install -g @openai/codex@latest"},claude:{packageName:"@anthropic-ai/claude-agent-sdk",installCommand:"npm install -g @anthropic-ai/claude-code @anthropic-ai/claude-agent-sdk",updateCommand:"npm install -g @anthropic-ai/claude-code@latest @anthropic-ai/claude-agent-sdk@latest"},opencode:{packageName:"opencode-ai",installCommand:"npm install -g opencode-ai @opencode-ai/sdk",updateCommand:"npm install -g opencode-ai@latest @opencode-ai/sdk@latest"}};function la(t){const s=yi[t];return{packageName:s.packageName,installed:t==="codex",installedVersion:null,latestVersion:null,installCommand:s.installCommand,updateCommand:s.updateCommand,busy:!1,lastError:null}}function wi(t,s){return{provider:t,displayName:s,description:`${s} backend descriptor is not available.`,enabled:!1,isDefault:t===xr,status:{state:"stopped",transport:gr[t].defaultTransport,lastStartedAt:null,lastError:"Backend descriptor is not available.",restartCount:0},capabilities:{sessions:{list:!1,read:!1,resume:!1,importLocal:!1},turns:{start:!1,streamInput:!1,steer:!1,interrupt:!1,compact:!1},branching:{fork:!1,hardRollback:!1,resumeAt:!1,rewindFiles:!1},controls:{planMode:!1,permissionRequests:!1,sandboxMode:!1,performanceMode:!1,goals:!1},management:{models:!1,mcpStatus:!1,skills:!1,hooks:!1,hookTrust:!1,hostConfigFiles:!1,providerSettings:!1},usage:{contextWindow:!1,tokenUsage:!1,costUsd:!1}},managementSchema:Br,installation:la(t)}}function Ln(t){const s=t.installation??la(t.provider);return{...t,installation:{...la(t.provider),...s}}}const hs=[...Ao.map(t=>wi(t,gr[t].displayName))];function Ni(t){var s;return((s=hs.find(a=>a.provider===t))==null?void 0:s.managementSchema)??Br}function Si(t){const s=new Date(t);return Number.isNaN(s.getTime())?t:s.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function ki(t){const s=t.payload.details,a=typeof(s==null?void 0:s.stderr)=="string"&&s.stderr.trim()?s.stderr.trim():typeof(s==null?void 0:s.stdout)=="string"&&s.stdout.trim()?s.stdout.trim():null;return a?`${t.message}
|
|
3
|
-
${a}`:t.message}function Es(t){return{path:t,exists:!1,originalContent:"",draftContent:"",loading:!1,saving:!1,error:null,saveMessage:null}}function Fr({className:t=""}){const s=Jt();return s?e.jsx("button",{type:"button","aria-label":s.navOpen?"Close Navigation":"Open Navigation","aria-expanded":s.navOpen,"aria-controls":"app-shell-navigation-menu",onClick:s.toggleNav,className:`inline-flex h-10 w-10 shrink-0 items-center justify-center text-[var(--theme-fg)] transition hover:text-[var(--theme-fg-soft)] ${t}`.trim(),children:s.navOpen?e.jsx(fn,{}):e.jsx(vi,{})}):null}function Wr({className:t=""}){const s=Jt(),a=es(),n=
|
|
4
|
-
${ge.installation.lastError}`:`${ge.displayName} ${j==="install"?"installed":"updated"}.`,error:null}))}catch(Q){X(ge=>({...ge,saving:!1,operatingProvider:null,operatingAction:null,message:null,error:Q instanceof re?ki(Q):`Unable to ${j} ${(M==null?void 0:M.displayName)??b}.`}))}}async function ct(){if(!(C.busy||R.saving)){E({busy:!0,message:null,error:null});try{await Il(),E({busy:!1,message:"Build and restart launched. The page may disconnect briefly.",error:null})}catch(b){E({busy:!1,message:null,error:b instanceof re?b.message:"Unable to launch build and restart."})}}}async function Ye(){const b=Y.devHomeDraft.trim();if(!(!b||Y.saving)){I(j=>({...j,saving:!0,message:null,error:null}));try{const j=await yl({devHome:b});D(j),I(M=>({...M,devHomeDraft:j.devHome,saving:!1,message:"Workspace defaults saved."}))}catch(j){I(M=>({...M,saving:!1,error:j instanceof re?j.message:"Unable to save workspace settings."}))}}}async function wt(b){const j=x[b];if(!(!j||j.saving)){f(M=>({...M,[b]:{...Es(b),...M[b],saving:!0,error:null,saveMessage:null}}));try{const M=await $r(F.provider,b,{content:j.draftContent});f(Q=>({...Q,[b]:{path:M.path,exists:M.exists,originalContent:M.content,draftContent:M.content,loading:!1,saving:!1,error:null,saveMessage:"Saved"}}))}catch(M){f(Q=>({...Q,[b]:{...Es(b),...Q[b],saving:!1,error:M instanceof re?M.message:"Unable to save the file.",saveMessage:null}}))}}}async function ze(){if(!q.creating){B(b=>({...b,creating:!0,message:null,error:null}));try{const b=await kl(F.provider);J(j=>[b,...j]),B(j=>({...j,creating:!1,message:"Backup created."}))}catch(b){B(j=>({...j,creating:!1,error:b instanceof re?b.message:"Unable to create a config backup."}))}}}async function ut(b){if(!q.applyingId){B(j=>({...j,applyingId:b.id,message:null,error:null}));try{const j=await Tl(F.provider,b.id);B(M=>({...M,applyingId:null,message:j.status.state==="ready"?`Applied "${j.archive.label}" and restarted ${F.displayName}.`:`Applied "${j.archive.label}". ${F.displayName} state: ${j.status.state}.`}))}catch(j){B(M=>({...M,applyingId:null,error:j instanceof re?j.message:"Unable to apply the config archive."}))}}}async function _e(b){const j=q.renameDraft.trim();if(!(!j||q.renamingId!==b.id)){B(M=>({...M,message:null,error:null}));try{const M=await Cl(F.provider,b.id,{label:j});J(Q=>Q.map(ge=>ge.id===b.id?M:ge)),B(Q=>({...Q,renamingId:null,renameDraft:"",message:"Backup renamed."}))}catch(M){B(Q=>({...Q,error:M instanceof re?M.message:"Unable to rename the config backup."}))}}}if(!fe)return null;const mt=e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-3 grid gap-2",children:[a.plugins.map(b=>e.jsxs("label",{className:"flex items-start justify-between gap-3 rounded-[1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-2.5",children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-sm font-medium text-[var(--theme-fg)]",children:b.name}),e.jsx("span",{className:"mt-1 block text-xs leading-5 text-[var(--theme-fg-muted)]",children:b.description}),e.jsx("span",{className:"mt-2 block text-[10px] uppercase tracking-[0.16em] text-[var(--theme-fg-muted)]",children:[...b.capabilities.artifactTypes.map(j=>j.type),...b.capabilities.threadPanels.map(j=>j.kind??j.id)].join(", ")||"utility"}),e.jsx("span",{className:"mt-1 block text-[10px] uppercase tracking-[0.16em] text-[var(--theme-fg-muted)]",children:b.source==="imported"?"Imported manifest":"Built-in module"})]}),e.jsx("input",{type:"checkbox",checked:b.enabled,onChange:j=>void a.setPluginEnabled(b.id,j.currentTarget.checked),className:"mt-1 h-4 w-4 shrink-0 accent-[var(--theme-accent-solid)]"})]},b.id)),a.plugins.length===0&&e.jsx("p",{className:"rounded-[1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-3 text-xs text-[var(--theme-fg-muted)]",children:"No plugins are registered."})]}),e.jsxs("div",{className:"mt-3 border-t border-[var(--theme-border)] pt-3",children:[e.jsx("label",{className:"block text-xs font-medium text-[var(--theme-fg)]",children:"Import manifest JSON"}),e.jsx("textarea",{value:n,onChange:b=>{d(b.currentTarget.value),(o.message||o.error)&&m({busy:!1,message:null,error:null})},placeholder:'{"id":"example.viewer","name":"Example Viewer","version":"0.1.0",...}',rows:4,className:"mt-2 min-h-28 w-full resize-y rounded-[0.9rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-2 font-mono text-xs leading-5 text-[var(--theme-fg)] outline-none transition placeholder:text-[var(--theme-fg-muted)] focus:border-[var(--theme-accent-border)]"}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center justify-between gap-2",children:[e.jsx("p",{className:"max-w-[42rem] text-xs leading-5 text-[var(--theme-fg-muted)]",children:"Imports register manifest-declared artifact types. Rendering code still needs a trusted built-in frontend module."}),e.jsx("button",{type:"button",onClick:()=>void H(),disabled:!n.trim()||o.busy,className:"rounded-full border border-[var(--theme-accent-border)] bg-[var(--theme-accent-soft)] px-3 py-1.5 text-xs font-medium text-[var(--theme-accent-strong)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:border-[var(--theme-border)] disabled:bg-[var(--theme-muted)] disabled:text-[var(--theme-fg-muted)]",children:o.busy?"Importing...":"Import"})]}),o.error&&e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:o.error}),o.message&&e.jsx("p",{className:"mt-2 text-xs text-emerald-300",children:o.message})]}),a.error&&e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:a.error})]}),Ze=e.jsxs(e.Fragment,{children:[t?null:e.jsx("div",{className:"shrink-0 p-5 pb-0",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-[0.24em] text-[var(--theme-fg-muted)]",children:"Settings"}),e.jsx("h2",{className:"mt-2 text-xl font-semibold text-[var(--theme-fg)]",children:"Settings"}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-[var(--theme-fg-soft)]",children:"Choose the default backend and manage host-side runtime files."})]}),e.jsx("button",{type:"button","aria-label":"Close Settings",onClick:s==null?void 0:s.closeSettings,className:"inline-flex h-9 w-9 items-center justify-center rounded-full border border-[var(--theme-border-strong)] bg-[var(--theme-surface-strong)] text-[var(--theme-fg)] transition hover:border-[var(--theme-border-contrast)] hover:bg-[var(--theme-hover)]",children:e.jsx(fn,{})})]})}),e.jsx("div",{className:`min-h-0 flex-1 overflow-y-auto ${t?"p-0":"p-5 pt-5"}`,children:e.jsxs("div",{className:"space-y-2",children:[t?null:e.jsxs("div",{className:"rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 py-3",children:[e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:"Appearance"}),e.jsxs("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:["Choose light, dark, or follow the system setting. Active:"," ",pe,"."]})]})}),e.jsx("div",{className:"mt-3 grid gap-2 sm:grid-cols-3",children:ji.map(b=>{const j=ve===b.value;return e.jsxs("button",{type:"button",onClick:()=>s==null?void 0:s.setThemeMode(b.value),className:`block rounded-[1rem] border px-3 py-2.5 text-left transition ${j?"border-[var(--theme-accent-border)] bg-[var(--theme-accent-soft)]":"border-[var(--theme-border)] bg-[var(--theme-surface-strong)] hover:bg-[var(--theme-hover)]"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-sm font-medium text-[var(--theme-fg)]",children:b.label}),j?e.jsx("span",{className:"rounded-full border border-[var(--theme-accent-border)] bg-[var(--theme-accent-soft)] px-2 py-0.5 text-[10px] uppercase tracking-[0.18em] text-[var(--theme-accent-strong)]",children:"Active"}):null]}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:b.description})]},b.value)})})]}),s!=null&&s.setAutoCollapseCompletedTurns?e.jsx("div",{className:"rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 py-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:"Thread timeline"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:"Collapse completed turns into prompt, elapsed work, and final reply."})]}),e.jsxs("label",{className:"inline-flex min-h-10 shrink-0 items-center gap-2 text-xs font-medium text-[var(--theme-fg-soft)]",children:[e.jsx("input",{type:"checkbox",checked:T,onChange:b=>{var j;return(j=s.setAutoCollapseCompletedTurns)==null?void 0:j.call(s,b.currentTarget.checked)},className:"h-4 w-4 accent-[var(--theme-accent-solid)]"}),e.jsx("span",{children:"Auto collapse"})]})]})}):null,e.jsxs("div",{className:"rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 py-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:"Plugins"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:"Enable renderers and thread extensions loaded by this supervisor."})]}),e.jsx("button",{type:"button",onClick:()=>void a.refresh(),disabled:a.loading,className:"rounded-full border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-1.5 text-xs font-medium text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:text-[var(--theme-fg-muted)]",children:a.loading?"Loading...":"Refresh"})]}),t?e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-2 rounded-[0.95rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-2",children:[e.jsx("span",{className:"text-xs text-[var(--theme-fg-muted)]",children:W}),e.jsx("button",{type:"button",onClick:()=>g(!0),className:"rounded-full border border-[var(--theme-border-strong)] bg-[var(--theme-panel)] px-3 py-1.5 text-xs font-medium text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)]",children:"Manage"})]}):mt]}),e.jsxs("div",{className:"rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 py-3",children:[e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:"Workspace defaults"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:"Git projects clone into dev home. New workspace directories can create one missing child under this path."})]})}),e.jsxs("div",{className:"mt-3 grid gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.18em] text-[var(--theme-fg-muted)]",children:"Workspace root"}),e.jsx("p",{title:(c==null?void 0:c.workspaceRoot)??"Loading workspace root",className:"mt-1 truncate rounded-[0.9rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-2 font-mono text-xs text-[var(--theme-fg-soft)]",children:Y.loading&&!c?"Loading...":(c==null?void 0:c.workspaceRoot)??"Unavailable"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"settings-dev-home",className:"text-[11px] uppercase tracking-[0.18em] text-[var(--theme-fg-muted)]",children:"Dev home"}),e.jsxs("div",{className:"mt-1 flex flex-col gap-2 sm:flex-row",children:[e.jsx("input",{id:"settings-dev-home",value:Y.devHomeDraft,onChange:b=>I(j=>({...j,devHomeDraft:b.target.value,message:null,error:null})),placeholder:"/Users/name/dev",className:"min-w-0 flex-1 rounded-full border border-[var(--theme-border)] bg-[var(--theme-panel)] px-3 py-2 text-sm text-[var(--theme-fg)] outline-none focus:border-[var(--theme-accent-border)]"}),e.jsx("button",{type:"button","aria-label":"Save workspace defaults",onClick:()=>void Ye(),disabled:Y.loading||Y.saving||!Y.devHomeDraft.trim(),className:"rounded-full bg-[var(--theme-accent-solid)] px-4 py-2 text-xs font-medium text-[var(--theme-accent-solid-fg)] transition hover:bg-[var(--theme-accent-solid-hover)] disabled:cursor-not-allowed disabled:bg-[var(--theme-muted)] disabled:text-[var(--theme-fg-muted)]",children:Y.saving?"Saving...":"Save"})]})]})]}),Y.error?e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:Y.error}):Y.message?e.jsx("p",{className:"mt-2 text-xs text-emerald-300",children:Y.message}):null]}),e.jsxs("div",{className:"rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 py-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:"Runtime controls"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:"Inspect installed backend versions, install optional runtimes, or restart the selected backend."})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap justify-end gap-2",children:[e.jsx("button",{type:"button",onClick:()=>void xe(),disabled:C.busy||R.saving,className:"rounded-full border border-sky-400/35 bg-sky-400/10 px-3 py-1.5 text-xs font-medium text-sky-500 transition hover:bg-sky-400/16 disabled:cursor-not-allowed disabled:border-[var(--theme-border)] disabled:bg-[var(--theme-muted)] disabled:text-[var(--theme-fg-muted)]",children:C.busy?"Restarting...":"Restart"}),e.jsx("button",{type:"button",onClick:()=>void ct(),disabled:C.busy||R.saving,className:"rounded-full border border-amber-400/35 bg-amber-400/10 px-3 py-1.5 text-xs font-medium text-amber-500 transition hover:bg-amber-400/16 disabled:cursor-not-allowed disabled:border-[var(--theme-border)] disabled:bg-[var(--theme-muted)] disabled:text-[var(--theme-fg-muted)]",children:C.busy?"Working...":"Build and restart"})]})]}),e.jsx("div",{className:"mt-3 grid gap-2",children:te.map(b=>{const j=b.installation,M=!j.installed&&!!j.installCommand,Q=j.installed&&!!j.updateCommand,ge=R.saving&&R.operatingProvider===b.provider,Oe=M?"Install":"Update";return e.jsxs("div",{className:"flex flex-col gap-2 rounded-[0.95rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-[var(--theme-fg)]",children:b.displayName}),e.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${b.enabled?"border-emerald-400/35 bg-emerald-400/10 text-emerald-400":"border-[var(--theme-border)] bg-[var(--theme-muted)] text-[var(--theme-fg-muted)]"}`,children:b.enabled?"Ready":j.installed?b.status.state:"Not installed"})]}),e.jsxs("p",{className:"mt-1 truncate text-xs text-[var(--theme-fg-muted)]",children:["Version:"," ",j.installedVersion??(j.installed?"Installed":"Unavailable"),j.latestVersion?` · Latest: ${j.latestVersion}`:""]}),j.lastError?e.jsx("p",{className:"mt-1 line-clamp-2 text-xs text-rose-300",children:j.lastError}):null]}),M||Q?e.jsx("button",{type:"button","aria-label":`${M?"Install":"Update"} ${b.displayName}`,onClick:()=>void ot(b.provider,M?"install":"update"),disabled:C.busy||R.saving||!M&&!Q,className:"shrink-0 rounded-full border border-[var(--theme-border-strong)] bg-[var(--theme-panel)] px-3 py-1.5 text-xs font-medium text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:bg-[var(--theme-muted)] disabled:text-[var(--theme-fg-muted)]",children:ge?R.operatingAction==="install"?"Installing...":"Updating...":Oe}):null]},b.provider)})}),C.error?e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:C.error}):C.message?e.jsx("p",{className:"mt-2 text-xs text-emerald-300",children:C.message}):R.message?e.jsx("p",{className:`mt-2 whitespace-pre-line text-xs ${R.message.includes("requires attention")?"text-amber-300":"text-emerald-300"}`,children:R.message}):R.error?e.jsx("p",{className:"mt-2 whitespace-pre-line text-xs text-rose-300",children:R.error}):null]}),e.jsxs("div",{className:"rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 py-3",children:[e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:"Provider host files"}),e.jsxs("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:[F.displayName," exposes these editable files through its backend schema."]})]})}),e.jsxs("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:[ue.map(b=>{const j=x[b.name]??{path:b.name,exists:!1,originalContent:"",draftContent:"",loading:!1},M=j.draftContent!==j.originalContent;return e.jsx("button",{type:"button",onClick:()=>A(b.name),className:"block rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-3 text-left transition hover:bg-[var(--theme-hover)]",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:b.label}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:b.description})]}),e.jsx("div",{className:"shrink-0",children:j.loading?e.jsx("span",{className:"text-[11px] uppercase tracking-[0.2em] text-[var(--theme-fg-muted)]",children:"Loading"}):M?e.jsx("span",{className:"rounded-full border border-[var(--theme-accent-border)] bg-[var(--theme-accent-soft)] px-2 py-0.5 text-[10px] uppercase tracking-[0.18em] text-[var(--theme-accent-strong)]",children:"Unsaved"}):j.exists?e.jsx("span",{className:"rounded-full border border-emerald-400/25 bg-emerald-400/10 px-2 py-0.5 text-[10px] uppercase tracking-[0.18em] text-emerald-600 dark:text-emerald-100",children:"Ready"}):e.jsx("span",{className:"rounded-full border border-sky-300/25 bg-sky-300/10 px-2 py-0.5 text-[10px] uppercase tracking-[0.18em] text-sky-600 dark:text-sky-100",children:"New"})})]})},b.name)}),ue.length===0?e.jsx("p",{className:"rounded-[1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-3 text-xs text-[var(--theme-fg-muted)]",children:"This backend does not expose editable host files."}):null]})]}),z.configArchives?e.jsxs("div",{className:"rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 py-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:"Config archives"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:"Backup the selected backend host files, then apply a saved archive with a backend restart."})]}),e.jsx("button",{type:"button",onClick:()=>void ze(),disabled:q.creating,className:"shrink-0 rounded-full border border-[var(--theme-accent-border)] bg-[var(--theme-accent-soft)] px-3 py-1.5 text-xs font-medium text-[var(--theme-accent-strong)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:border-[var(--theme-border)] disabled:bg-[var(--theme-muted)] disabled:text-[var(--theme-fg-muted)]",children:q.creating?"Creating...":"Create backup"})]}),q.error?e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:q.error}):q.message?e.jsx("p",{className:"mt-2 text-xs text-emerald-300",children:q.message}):null,e.jsx("div",{className:"mt-3 space-y-2",children:q.loading?e.jsx("p",{className:"rounded-[1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-3 text-xs text-[var(--theme-fg-muted)]",children:"Loading backups..."}):v.length===0?e.jsx("p",{className:"rounded-[1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-3 text-xs text-[var(--theme-fg-muted)]",children:"No config backups yet."}):v.map(b=>{const j=q.renamingId===b.id;return e.jsx("div",{className:"rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-3",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[j?e.jsxs("div",{className:"flex max-w-xl gap-2",children:[e.jsx("input",{"aria-label":`Rename ${b.label}`,value:q.renameDraft,onChange:M=>B(Q=>({...Q,renameDraft:M.target.value,error:null,message:null})),className:"min-w-0 flex-1 rounded-full border border-[var(--theme-border)] bg-[var(--theme-panel)] px-3 py-1.5 text-sm text-[var(--theme-fg)] outline-none focus:border-[var(--theme-accent-border)]"}),e.jsx("button",{type:"button","aria-label":`Save archive name ${b.label}`,onClick:()=>void _e(b),className:"rounded-full bg-[var(--theme-accent-solid)] px-3 py-1.5 text-xs font-medium text-[var(--theme-accent-solid-fg)] transition hover:bg-[var(--theme-accent-solid-hover)]",children:"Save"}),e.jsx("button",{type:"button",onClick:()=>B(M=>({...M,renamingId:null,renameDraft:""})),className:"rounded-full border border-[var(--theme-border)] bg-[var(--theme-panel)] px-3 py-1.5 text-xs font-medium text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)]",children:"Cancel"})]}):e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:b.label}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2 text-[11px] text-[var(--theme-fg-muted)]",children:[e.jsxs("span",{children:["Created ",Si(b.createdAt)]}),ue.map(M=>{var Q;return e.jsxs("span",{className:"rounded-full border border-[var(--theme-border)] bg-[var(--theme-panel)] px-2 py-0.5 font-mono",children:[M.name,":"," ",(Q=b.files[M.name])!=null&&Q.exists?"saved":"missing"]},M.name)})]})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2",children:[e.jsx("button",{type:"button",onClick:()=>B(M=>({...M,renamingId:b.id,renameDraft:b.label,message:null,error:null})),disabled:j,className:"rounded-full border border-[var(--theme-border)] bg-[var(--theme-panel)] px-3 py-1.5 text-xs font-medium text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:text-[var(--theme-fg-muted)]",children:"Rename"}),e.jsx("button",{type:"button",onClick:()=>void ut(b),disabled:q.applyingId!==null,className:"rounded-full border border-emerald-400/35 bg-emerald-400/10 px-3 py-1.5 text-xs font-medium text-emerald-600 transition hover:bg-emerald-400/16 disabled:cursor-not-allowed disabled:border-[var(--theme-border)] disabled:bg-[var(--theme-muted)] disabled:text-[var(--theme-fg-muted)] dark:text-emerald-100",children:q.applyingId===b.id?"Applying...":"Apply"})]})]})},b.id)})})]}):null]})})]});return t?e.jsxs("div",{className:"flex min-h-0 flex-col overflow-hidden",children:[Ze,h?e.jsxs("div",{className:"fixed inset-0 z-[90] flex items-start justify-center p-4 pt-[max(env(safe-area-inset-top),4rem)] sm:items-center sm:pt-4",children:[e.jsx("button",{type:"button","aria-label":"Close plugins panel",onClick:()=>g(!1),className:"absolute inset-0 bg-black/35 backdrop-blur-[2px]"}),e.jsxs("section",{className:"relative z-10 flex max-h-[min(82vh,42rem)] w-full max-w-2xl flex-col overflow-hidden rounded-[1.35rem] border border-[var(--theme-border)] bg-[var(--theme-panel)] shadow-2xl shadow-black/25",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-[var(--theme-border)] px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:"Plugins"}),e.jsx("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:W})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx("button",{type:"button",onClick:()=>void a.refresh(),disabled:a.loading,className:"rounded-full border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-1.5 text-xs font-medium text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:text-[var(--theme-fg-muted)]",children:a.loading?"Loading...":"Refresh"}),e.jsx("button",{type:"button","aria-label":"Close plugins panel",onClick:()=>g(!1),className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-[var(--theme-border-strong)] bg-[var(--theme-surface-strong)] text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)]",children:e.jsx(fn,{})})]})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto p-4",children:mt})]})]}):null]}):e.jsxs("div",{className:"fixed inset-0 z-[70] flex items-start justify-center p-4 pt-[max(env(safe-area-inset-top),1rem)] sm:items-center",children:[e.jsx("button",{type:"button","aria-label":"Close Settings",onClick:s==null?void 0:s.closeSettings,className:"ui-overlay-scrim absolute inset-0 backdrop-blur-sm"}),e.jsx("section",{role:"dialog","aria-modal":"true","aria-label":"Settings",className:"relative z-10 flex max-h-[calc(100vh-2rem)] w-full max-w-4xl flex-col overflow-hidden rounded-[1.8rem] border border-[var(--theme-border)] bg-[var(--theme-panel)] shadow-2xl shadow-black/20",children:Ze}),y&&k?e.jsx("div",{className:"pointer-events-none fixed inset-0 z-[71] flex items-center justify-center p-4",children:e.jsxs("div",{className:"pointer-events-auto relative z-10 flex max-h-[min(88vh,56rem)] w-full max-w-3xl flex-col overflow-hidden rounded-[1.6rem] border border-[var(--theme-border)] bg-[var(--theme-panel)] shadow-2xl shadow-black/25",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-[var(--theme-border)] px-4 py-3 sm:px-5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:y}),e.jsx("p",{className:"mt-1 break-all font-mono text-xs text-[var(--theme-fg-muted)]",children:k.path})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[k.error?e.jsx("span",{className:"text-xs text-rose-300",children:k.error}):k.saveMessage?e.jsx("span",{className:"text-xs text-emerald-300",children:k.saveMessage}):null,e.jsx("button",{type:"button","aria-label":`Save ${y}`,onClick:()=>void wt(y),disabled:k.loading||k.saving||k.draftContent===k.originalContent,className:"rounded-full bg-[var(--theme-accent-solid)] px-4 py-2 text-sm font-medium text-[var(--theme-accent-solid-fg)] transition hover:bg-[var(--theme-accent-solid-hover)] disabled:cursor-not-allowed disabled:bg-[var(--theme-muted)] disabled:text-[var(--theme-fg-muted)]",children:k.saving?"Saving...":"Save"}),e.jsx("button",{type:"button","aria-label":"Close File Editor",onClick:()=>A(null),className:"inline-flex h-9 w-9 items-center justify-center rounded-full border border-[var(--theme-border-strong)] bg-[var(--theme-surface-strong)] text-[var(--theme-fg)] transition hover:border-[var(--theme-border-contrast)] hover:bg-[var(--theme-hover)]",children:e.jsx(fn,{})})]})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto p-4 sm:p-5",children:e.jsx("textarea",{"aria-label":`Edit ${y}`,value:k.draftContent,onChange:b=>f(j=>({...j,[y]:{...Es(y),...j[y],draftContent:b.target.value,error:null,saveMessage:null}})),spellCheck:!1,className:"min-h-[28rem] w-full rounded-[1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-3 font-mono text-[13px] leading-6 text-[var(--theme-fg)] outline-none transition focus:border-[var(--theme-accent-border)]",placeholder:k.loading?"Loading...":`Edit ${y} here`})})]})}):null]})}function Ci(t){const s=(t==null?void 0:t.trim())??"";return s?Array.from(s).slice(0,2).join("").toUpperCase():"??"}function ga(){const t=rt(),s=es(),[a,n]=r.useState(null),[d,o]=r.useState(!1);r.useEffect(()=>{if(!na())return;let y=!1;return $s().then(A=>{y||n(A.authenticated?A:null)}).catch(()=>{y||n(null)}),()=>{y=!0}},[s.pathname]),r.useEffect(()=>{o(!1)},[s.pathname]);const m=(a==null?void 0:a.user)??null,h=r.useMemo(()=>Ci(m==null?void 0:m.username),[m==null?void 0:m.username]);if(!na()||!m)return null;async function g(){await Er(),n(null),t("/relay-portal")}return e.jsxs("div",{className:"fixed right-3 top-[calc(env(safe-area-inset-top)+0.55rem)] z-50",children:[e.jsx("button",{"aria-expanded":d,"aria-haspopup":"menu","aria-label":`Relay account menu for ${m.username}`,className:"inline-flex h-10 w-10 items-center justify-center rounded-full border border-[var(--theme-border)] bg-[var(--theme-panel)] text-sm font-semibold text-[var(--theme-fg)] shadow-lg transition hover:bg-[var(--theme-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--theme-accent-ring)]",onClick:()=>o(y=>!y),type:"button",children:h}),d?e.jsxs("div",{className:"absolute right-0 mt-2 w-64 overflow-hidden rounded-xl border border-[var(--theme-border)] bg-[var(--theme-panel)] p-1 shadow-xl",role:"menu",children:[e.jsxs("div",{className:"border-b border-[var(--theme-border)] px-3 py-2",children:[e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:m.username}),e.jsx("p",{className:"truncate text-xs text-[var(--theme-fg-muted)]",children:m.email})]}),e.jsxs(It,{className:"flex items-center gap-2 rounded-lg px-3 py-2 text-sm text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)]",role:"menuitem",to:"/relay-account",children:[e.jsx(at.Settings,{className:"h-4 w-4"}),"Account settings"]}),e.jsxs(It,{className:"flex items-center gap-2 rounded-lg px-3 py-2 text-sm text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)]",role:"menuitem",to:"/relay-devices",children:[e.jsx(at.MonitorSmartphone,{className:"h-4 w-4"}),"Device management"]}),e.jsxs("button",{className:"flex w-full items-center gap-2 rounded-lg px-3 py-2 text-left text-sm text-[var(--status-danger-fg)] transition hover:bg-[var(--status-danger-bg)]",onClick:()=>void g(),role:"menuitem",type:"button",children:[e.jsx(at.LogOut,{className:"h-4 w-4"}),"Logout"]})]}):null]})}const Ti="http://127.0.0.1:8790",ba="remote-codex-control-plane-auth";function Ii(t){const s=t.baseUrl||Ti;if(t.token){const a={baseUrl:s,token:t.token};return t.email!==void 0&&(a.email=t.email),t.displayName!==void 0&&(a.displayName=t.displayName),t.expiresAt!==void 0&&(a.expiresAt=t.expiresAt),a}if(t.subject){const a={baseUrl:s,token:`dev:${t.subject}`};return t.email!==void 0&&(a.email=t.email),t.displayName!==void 0&&(a.displayName=t.displayName),a}return null}function Qt(){if(typeof window>"u")return null;const t=window.localStorage.getItem(ba);if(!t)return null;try{const s=Ii(JSON.parse(t));return!(s!=null&&s.baseUrl)||!s.token||s.expiresAt&&Date.parse(s.expiresAt)<=Date.now()?null:s}catch{return null}}function xn(t){window.localStorage.setItem(ba,JSON.stringify(t))}function jn(){window.localStorage.removeItem(ba)}function Ei(){return!!Qt()}function Ri({eyebrow:t,hidden:s,onClose:a,children:n}){return e.jsx("aside",{className:"control-right-column","aria-hidden":s,children:e.jsxs("section",{className:"control-panel control-inspector-panel",children:[e.jsxs("div",{className:"control-panel-heading",children:[e.jsx("h2",{children:"Inspector"}),e.jsx("span",{children:t}),e.jsx("button",{type:"button",className:"control-inline-icon-button",onClick:a,"aria-label":"Close details inspector",children:"x"})]}),n]})})}function Pi({topBar:t,alerts:s,children:a,sidebar:n,main:d,inspector:o,inspectorOpen:m}){const h=a??e.jsxs(e.Fragment,{children:[n,e.jsx("main",{className:"control-main-column",children:d}),e.jsx("button",{type:"button",className:"control-inspector-scrim","aria-hidden":"true",tabIndex:-1}),o]});return e.jsxs("div",{className:"control-plane-console",children:[t,e.jsx("div",{className:"control-alert-stack",children:s}),e.jsx("div",{className:`control-console-grid ${m?"inspector-open":"inspector-collapsed"}`,children:h})]})}function Ai({children:t}){return e.jsx("aside",{className:"control-explorer-panel",children:t})}function Ui({title:t,subtitle:s,actions:a}){return e.jsxs("header",{className:"control-console-header",children:[e.jsxs("div",{className:"control-window-controls","aria-hidden":"true",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}),e.jsxs("div",{className:"control-titlebar-copy",children:[e.jsx("h1",{children:t}),e.jsx("span",{children:s})]}),e.jsx("div",{className:"control-header-actions",children:a})]})}const Oi=6e4,$i=5e3,Mi=3e3,rn={estructural:"Estructural",quntur:"Quntur",farmaco:"Farmaco"};function on(t){if(!t)return"no activity yet";const s=Date.parse(t);if(!Number.isFinite(s))return t;const a=Date.now()-s,n=Math.abs(a),d=a>=0?"ago":"from now",o=6e4,m=60*o,h=24*m;return n<o?"just now":n<m?`${Math.round(n/o)}m ${d}`:n<h?`${Math.round(n/m)}h ${d}`:`${Math.round(n/h)}d ${d}`}function Dn(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function Mt(t){switch(t){case"running":return"border-[var(--status-success-border)] bg-[var(--status-success-bg)] text-[var(--status-success-fg)]";case"failed":case"degraded":case"unknown":return"border-[var(--status-danger-border)] bg-[var(--status-danger-bg)] text-[var(--status-danger-fg)]";case"stopped":return"border-[var(--status-neutral-border)] bg-[var(--status-neutral-bg)] text-[var(--status-neutral-fg)]";default:return"border-[var(--status-warning-border)] bg-[var(--status-warning-bg)] text-[var(--status-warning-fg)]"}}function Ne(t){return t?t.split(/[_\s-]+/).filter(Boolean).map(s=>`${s.charAt(0).toUpperCase()}${s.slice(1)}`).join(" "):"Unknown"}function As(t){switch(t){case"empty":return"Local workspace";case"git":return"Git workspace";default:return Ne(t)}}function Li(t){return As(t.sourceType)}function Hn(t){return t.workerSessionId?"Runtime ready":"Not started"}function Rs(t){return t?`${t.type}:${t.id}`:""}function ln(t){switch(t){case"codex":return"Codex";case"claude":return"Claude";case"opencode":return"OpenCode";default:return Ne(t)}}function za({open:t}){return e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",focusable:"false",children:e.jsx("path",{d:t?"M4.5 6.25 8 9.75l3.5-3.5":"M6.25 4.5 9.75 8l-3.5 3.5",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8"})})}function Di(){return e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",focusable:"false",children:e.jsx("path",{d:"M2.75 5.25h10.5v7H2.75zM2.75 4a1 1 0 0 1 1-1h3l1.25 1.25h4.25a1 1 0 0 1 1 1",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.25"})})}function Hi(){return e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",focusable:"false",children:e.jsx("path",{d:"M3 3.75h10v8.5H3zM5.25 6h5.5M5.25 8h5.5M5.25 10h3.5",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.25"})})}function _i(){return e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",focusable:"false",children:e.jsx("path",{d:"M4 3.25h5.25L12 6v6.75H4zM9.25 3.25V6H12M6 8.25h4M6 10.25h3",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.25"})})}function Bi(){return e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",focusable:"false",children:e.jsx("path",{d:"m3.2 10.9-.45 2.35 2.35-.45 6.95-6.95-1.9-1.9zm7.8-7.8.95-.95a1.35 1.35 0 0 1 1.9 1.9l-.95.95",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.25"})})}function Fi(){return e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",focusable:"false",children:e.jsx("path",{d:"M3 4.25h10M6.25 4.25V3h3.5v1.25M4.5 4.25l.55 8.25h5.9l.55-8.25M6.75 6.75v3.5M9.25 6.75v3.5",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.25"})})}function Va(t){switch(t){case"connecting":return"Connecting";case"ready":return"Ready";case"reconnecting":return"Reconnecting";default:return"Idle"}}function Wi(t){if(!t)return"Loading runtime";if(t.state==="starting"){const s=t.startupProgress??0;return s<25?"Request received":s<50?"Scheduling sandbox":s<90?"Preparing runtime":"Opening sandbox route"}return t.state==="stopping"?"Stopping sandbox":t.state==="running"?"Ready":t.state==="degraded"?"Checking readiness":t.state==="failed"?"Startup failed":t.state==="stopped"?"Stopped":Ne(t.state)}function qi(t){if(!t)return"Loading sandbox registry";switch(t.state){case"running":return"Healthy";case"starting":return"Waiting for runtime readiness";case"stopping":return"Shutdown in progress";case"degraded":return"Needs attention";case"failed":return"Failed";case"stopped":return"Offline";default:return"Unknown"}}function zi(t,s){const a="Sign in before managing the sandbox.";if(!t)return{start:{label:"Start",disabled:!0,title:a},stop:{label:"Stop",disabled:!0,title:a},restart:{label:"Restart",disabled:!0,title:a},health:{label:"Health",disabled:!0,title:a},inspect:{label:"Inspect",disabled:!0,title:a}};if(!s){const g="Wait for the sandbox registry to load.";return{start:{label:"Start",disabled:!0,title:g},stop:{label:"Stop",disabled:!0,title:g},restart:{label:"Restart",disabled:!0,title:g},health:{label:"Health",disabled:!0,title:g},inspect:{label:"Inspect",disabled:!0,title:g}}}const n=s.state,d=n==="running"||n==="degraded"||n==="starting",o=n==="running"||n==="degraded";return{start:{label:n==="starting"?"Starting...":n==="stopping"?"Stopping...":n==="restarting"?"Restarting...":n==="running"?"Running":n==="failed"?"Retry start":"Start",disabled:n==="running"||n==="starting"||n==="stopping"||n==="restarting"||n==="degraded",title:n==="starting"?"Sandbox startup is already in progress.":n==="running"?"Sandbox is already running.":n==="stopping"?"Wait for sandbox shutdown to finish before starting again.":n==="restarting"?"Sandbox restart is already in progress.":n==="degraded"?"Use Restart to recover a degraded sandbox.":void 0},stop:{label:"Stop",disabled:!d,title:d?void 0:"Stop is available only while the sandbox is running or starting."},restart:{label:n==="restarting"?"Restarting...":"Restart",disabled:!o,title:n==="failed"?"Use Retry start after a failed startup.":o?void 0:"Restart is available only when the sandbox is running or degraded."},health:{label:"Health",disabled:!1,title:void 0},inspect:{label:"Inspect",disabled:!1,title:void 0}}}function Vi(t){if(!t)return null;if(t.state==="running"&&t.idleTimeoutAt){const s=Date.parse(t.idleTimeoutAt);if(Number.isFinite(s)&&s>Date.now())return{tone:"warning",text:`Sandbox will stop after idle timeout at ${t.idleTimeoutAt}.`}}return t.state==="degraded"?{tone:"warning",text:t.statusReason??"Sandbox is reachable but not fully ready."}:t.state==="failed"?{tone:"danger",text:t.lastFailureMessage??t.statusReason??"Sandbox startup failed."}:t.state==="unknown"?{tone:"warning",text:t.statusReason??"Sandbox state is unknown."}:["running","starting","stopping"].includes(t.state)?null:{tone:"neutral",text:"Sandbox is offline."}}function Ji(t,s){return s?"unavailable":t?!t.enabled||!t.chemistryToolsEnabled?"not configured":t.keyPresent?t.health?"ready":"degraded":"missing key":"idle"}function Ja(t){switch(t){case"ready":return Mt("running");case"unavailable":case"missing key":return Mt("failed");case"not configured":case"idle":return Mt("stopped");default:return Mt("starting")}}function Ga(t){return t?typeof t.text=="string"?t.text.trim():t.payload===void 0?"":JSON.stringify(t.payload,null,2):""}function Ka(t){const s=t==null?void 0:t.payload;if(Array.isArray(s))return s;if(s&&typeof s=="object")for(const a of["tools","runs","items","artifacts"]){const n=s[a];if(Array.isArray(n))return n}return[]}function Ya(t,s){if(!t||typeof t!="object")return String(t??s);const a=t;for(const n of["name","tool","run_id","id","title","path"]){const d=a[n];if(typeof d=="string"&&d.trim())return d}return s}function Za(t){if(!t||typeof t!="object")return"";const s=t;return["status","type","module","execution_mode"].map(a=>{const n=s[a];return typeof n=="string"&&n.trim()?n:null}).filter(Boolean).join(" / ")}function dn({label:t,value:s,onChange:a,type:n="text"}){return e.jsxs("label",{className:"grid gap-1.5 text-xs font-medium text-[var(--theme-fg-muted)]",children:[e.jsx("span",{children:t}),e.jsx("input",{type:n,value:s,onChange:d=>a(d.currentTarget.value),className:"h-10 rounded-[0.7rem] border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 text-sm text-[var(--theme-fg)] outline-none transition focus:border-[var(--theme-accent-border)] focus:ring-2 focus:ring-[var(--theme-accent-soft)]"})]})}function Ue({children:t,onClick:s,disabled:a=!1,type:n="button",title:d,ariaLabel:o}){return e.jsx("button",{type:n,"aria-label":o,onClick:s,disabled:a,title:d,className:"h-10 rounded-[0.75rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 text-sm font-medium text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:text-[var(--theme-fg-muted)]",children:t})}function We({label:t,value:s}){const a=s&&s.trim()?s:"not assigned";return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsxs("dd",{children:[e.jsx("span",{children:a}),s?e.jsx("button",{type:"button",className:"control-copy-button",onClick:()=>{var n;(n=navigator.clipboard)==null||n.writeText(s)},children:"Copy"}):null]})]})}function Gi({status:t}){return e.jsx("span",{className:`control-status-pill compact ${Mt(t)}`,children:Ne(t)})}function _n({label:t,onEdit:s,onDelete:a}){return e.jsxs("span",{className:"control-tree-actions",children:[e.jsx("button",{type:"button",className:"control-tree-action-button",onClick:n=>{n.stopPropagation(),s()},"aria-label":`Rename ${t}`,title:`Rename ${t}`,children:e.jsx(Bi,{})}),e.jsx("button",{type:"button",className:"control-tree-action-button danger",onClick:n=>{n.stopPropagation(),a()},"aria-label":`Delete ${t}`,title:`Delete ${t}`,children:e.jsx(Fi,{})})]})}function Bn({label:t,value:s,onChange:a,onCancel:n,onSubmit:d}){return e.jsxs("form",{className:"control-tree-edit-form",onSubmit:d,children:[e.jsxs("label",{children:[e.jsx("span",{children:t}),e.jsx("input",{value:s,onChange:o=>a(o.currentTarget.value),autoFocus:!0})]}),e.jsx("button",{type:"submit",children:"Save"}),e.jsx("button",{type:"button",onClick:n,children:"Cancel"})]})}function Ki(){var nn;const t=rt(),[s,a]=r.useState(()=>{const u=Qt();return u?{baseUrl:u.baseUrl,token:u.token}:null}),[n,d]=r.useState(null),[o,m]=r.useState(null),[h,g]=r.useState(null),[y,A]=r.useState(null),[x,f]=r.useState(null),[k,C]=r.useState([]),[E,v]=r.useState(null),[J,te]=r.useState([]),[_,R]=r.useState([]),[X,c]=r.useState([]),[D,Y]=r.useState([]),[I,q]=r.useState(""),[B,ve]=r.useState(""),[fe,H]=r.useState(""),[pe,T]=r.useState(null),[le,oe]=r.useState(null),[W,F]=r.useState(null),[z,ue]=r.useState(null),[xe,ot]=r.useState("farmaco"),[ct,Ye]=r.useState(null),[wt,ze]=r.useState(null),[ut,_e]=r.useState(null),[mt,Ze]=r.useState("Computational chemistry"),[b,j]=r.useState("Molecule study"),[M,Q]=r.useState("Plan calculation"),[ge,Oe]=r.useState("codex"),[Pe,Xe]=r.useState(null),[ht,Ve]=r.useState(""),[pt,$e]=r.useState(null),[Et,Lt]=r.useState(null),[Gt,Kt]=r.useState(null),[se,ie]=r.useState(null),[me,he]=r.useState(!1),[ke,V]=r.useState(null),[Qe,Me]=r.useState(!1),[et,xt]=r.useState("summary"),[Dt,gt]=r.useState(()=>{var u;return((u=Qt())==null?void 0:u.displayName)??""}),[gs,bs]=r.useState(null),[vs,Nt]=r.useState(null),[Yt,bt]=r.useState(null),[js,we]=r.useState(null),[lt,St]=r.useState(null),[Rt,ys]=r.useState(null),[tt,ft]=r.useState({projects:!1,workspaces:!1,sessions:!1,usageEvents:!1,harness:!1}),[Pt,Je]=r.useState("idle"),Te=r.useRef(null),Ht=r.useRef(null),kt=!!(s&&n),Ce=(o==null?void 0:o.state)==="running",je=zi(kt,o),Ms=(o==null?void 0:o.state)==="starting"||(o==null?void 0:o.state)==="stopping"||(o==null?void 0:o.state)==="restarting"||(o==null?void 0:o.state)==="degraded"||typeof(o==null?void 0:o.startupProgress)=="number"&&o.startupProgress>0&&o.startupProgress<100,G=r.useMemo(()=>_.find(u=>u.id===I)??null,[_,I]),ee=r.useMemo(()=>X.find(u=>u.id===B)??null,[B,X]),ne=r.useMemo(()=>D.find(u=>u.id===fe)??null,[fe,D]),ws=kt&&!!G,ts=kt&&!!ee&&Ce,Ns=Vi(o),At=G?void 0:"Select a project before creating a workspace.",Ut=ee?Ce?void 0:"Start the sandbox before creating a session.":"Select a workspace before creating a session.",Ls=ne?Ce?void 0:"Start the sandbox before connecting a session.":"Select a session before connecting.",Ct=ee?"session":G?"workspace":"project",_t=Ct==="project"?"Project":Ct==="workspace"?"Workspace":"Session",vt=ke==="project"?"Create project":ke==="workspace"?`Create workspace in ${(G==null?void 0:G.name)??"project"}`:ke==="session"?`Create session in ${(ee==null?void 0:ee.name)??"workspace"}`:"",Bt=ke==="workspace"?At:ke==="session"?Ut:void 0,Ss=[G==null?void 0:G.name,ee==null?void 0:ee.name,ne==null?void 0:ne.title].filter(Boolean).join(" / "),Zt=Ji(z,ut),Ds=z!=null&&z.modules.length?z.modules:["farmaco","quntur","estructural"],de=Ka(ct),Ot=Ka(wt),ss=Ga(ct),ns=Ga(wt),ks=((n==null?void 0:n.displayName)??(n==null?void 0:n.email)??"U").trim().charAt(0).toUpperCase()||"U",Hs=((y==null?void 0:y.inputTokens)??0)+((y==null?void 0:y.outputTokens)??0),it=(x==null?void 0:x.totalCostUsd)??Number((y==null?void 0:y.costUsd)??0)+Number((E==null?void 0:E.costUsd)??0),as=D.filter(u=>u.status==="active").length,_s=D.filter(u=>!u.workerSessionId).length,Bs=D.filter(u=>u.status==="failed"||u.status==="closed").length,Fs=[{label:"All",value:D.length},{label:"Active",value:as},{label:"Needs runtime",value:_s},{label:"Closed",value:Bs}],Cn=(s==null?void 0:s.baseUrl)??((nn=Qt())==null?void 0:nn.baseUrl)??"not connected",Ws=(ne==null?void 0:ne.lastActivityAt)??(ne==null?void 0:ne.updatedAt)??null,Tn=(o==null?void 0:o.lastSeenAt)??(o==null?void 0:o.updatedAt)??null,qs=Wi(o),In=qi(o),En=(ee==null?void 0:ee.name)??(G==null?void 0:G.name)??"Control Plane",Rn=Ss||"Choose a project and workspace to manage sessions";async function Ge(u,N){Lt(u),Kt(null),ie(null),bs(null),Nt(null),bt(null),we(null),St(null),ys(null);try{return await N()}catch(S){if(S instanceof re&&S.payload.code==="gateway_unavailable"&&bs(S.message),S instanceof re&&S.payload.code==="quota_exceeded"){const K=S.payload.details??{},Le=typeof K.limit=="number"?K.limit:null,He=typeof K.used=="number"?K.used:null,$t=typeof K.quotaProfile=="string"?K.quotaProfile:(n==null?void 0:n.quotaProfile)??"current";Nt(Le!==null&&He!==null?`${$t} quota exhausted (${He}/${Le}).`:"Quota exceeded.")}return S instanceof re&&S.payload.code==="account_inactive"&&bt(S.message),S instanceof re&&(S.statusCode===401||S.payload.code==="unauthorized")&&(we(S.message),jn()),S instanceof re&&S.payload.code==="forbidden"&&ys(S.message),Kt(S instanceof Error?S.message:`${u} failed.`),null}finally{Lt(null)}}async function Cs(u=s){if(u){ft(N=>({...N,projects:!0,usageEvents:!0}));try{const N=await ha(u),[S,K,Le,He]=await Promise.all([Cr(u),Vo(u,10),Jo(u),Go(u,10)]);d(N.user),m(N.sandbox),A(N.usage),f(N.billing??null),C(K.events),v(Le.usage),te(He.events),R(S.projects),gt(N.user.displayName??""),q($t=>S.projects.some(On=>On.id===$t)?$t:"")}finally{ft(N=>({...N,projects:!1,usageEvents:!1}))}}}async function zs(u=s,N=xe){if(!u||!Ce){ue(null),Ye(null),ze(null),_e(null);return}ft(S=>({...S,harness:!0})),_e(null);try{const S=await rl(u);ue(S);const K=S.modules.includes(N)?N:S.modules[0]??N;if(ot(K),S.enabled&&S.keyPresent&&S.chemistryToolsEnabled){const[Le,He]=await Promise.all([La(u,K),Da(u,K)]);Ye(Le),ze(He)}else Ye(null),ze(null)}catch(S){ue(null),Ye(null),ze(null),_e(S instanceof Error?S.message:"Harness status refresh failed.")}finally{ft(S=>({...S,harness:!1}))}}r.useEffect(()=>{s&&Ge("Load control plane",async()=>{await Cs(s),ie("Control plane session is ready.")})},[]),r.useEffect(()=>{if(!s||!B){Y([]),H("");return}H(""),ft(u=>({...u,sessions:!0})),Ge("Load sessions",async()=>{try{const u=await ra(s,B);Y(u.sessions)}finally{ft(u=>({...u,sessions:!1}))}})},[s,B]),r.useEffect(()=>{if(!s||!o||!Ms)return;let u=!1;const N=setTimeout(()=>{Ma(s).then(S=>{u||m(S.sandbox)}).catch(S=>{u||St(S instanceof Error?S.message:"Sandbox health refresh failed.")})},Mi);return()=>{u=!0,clearTimeout(N)}},[s,o==null?void 0:o.state,o==null?void 0:o.startupProgress,o==null?void 0:o.updatedAt,Ms]),r.useEffect(()=>{if(!s||!Ce){ue(null),Ye(null),ze(null),_e(null);return}zs(s,xe)},[s,Ce,o==null?void 0:o.updatedAt]),r.useEffect(()=>{if(!s||!I){c([]),ve(""),Y([]),H("");return}ve(""),Y([]),H(""),ft(u=>({...u,workspaces:!0})),Ge("Load workspaces",async()=>{try{const u=await aa(s,I);c(u.workspaces)}finally{ft(u=>({...u,workspaces:!1}))}})},[s,I]),r.useEffect(()=>()=>{Te.current&&clearTimeout(Te.current),jt()},[]),r.useEffect(()=>{function u(N){N.key==="Escape"&&(he(!1),V(null),T(null),Me(!1))}return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[]);function jt(){const u=Ht.current;Ht.current=null,u&&u.readyState!==WebSocket.CLOSED&&u.close()}function yt(){Te.current&&(clearTimeout(Te.current),Te.current=null)}function Pn(u){return`${u.wsBaseUrl.replace(/\/+$/,"")}/api/sandboxes/${encodeURIComponent(u.sandboxId)}/ws?token=${encodeURIComponent(u.token)}`}function Vs(u,N="connecting"){jt();const S=Pn(u);F(S),St(null),Je(N);const K=new WebSocket(S);Ht.current=K,K.addEventListener("open",()=>{Ht.current===K&&Je("ready")}),K.addEventListener("error",()=>{Ht.current===K&&(St("Sandbox route connection failed."),Je("idle"))}),K.addEventListener("close",Le=>{Ht.current===K&&(St(Le.reason||"Sandbox route closed before the session could stay connected."),Je("idle"))})}function Js(u){if(yt(),!u)return;const N=Date.parse(u.expiresAt);if(!Number.isFinite(N))return;const S=Math.max($i,N-Date.now()-Oi);Te.current=setTimeout(()=>{Ys()},S)}async function Ft(){jn(),a(null),d(null),m(null),g(null),A(null),C([]),ys(null),R([]),c([]),Y([]),v(null),te([]),oe(null),he(!1),V(null),yt(),Je("idle"),ie("Signed out locally.")}async function De(u){u.preventDefault(),s&&await Ge("Update profile",async()=>{const N=await Ko(s,{displayName:Dt});d(N.user);const S=Qt();S&&xn({...S,email:N.user.email,displayName:N.user.displayName}),ie("Profile updated.")})}async function Gs(u){u.preventDefault(),s&&await Ge("Create project",async()=>{const N=await Yo(s,{name:mt,slug:Dn(mt)});await Cs(s),V(null),ie(`Project "${N.project.name}" created. Select it before creating a workspace.`)})}async function Ks(u){u.preventDefault(),!(!s||!G)&&await Ge("Create workspace",async()=>{const N=await Qo(s,{projectId:G.id,name:b,slug:Dn(b)}),S=await aa(s,G.id);c(S.workspaces),ve(""),Y([]),H(""),V(null),ie(`Workspace "${N.workspace.name}" created. Select it before creating a session.`)})}async function An(u){u.preventDefault(),!(!s||!ee||!Ce)&&await Ge("Create session",async()=>{const N=await el(s,ee.id,{provider:ge,title:M}),S=await ra(s,ee.id);Y(S.sessions),H(""),V(null),ie(`Session "${N.session.title}" created. Select it before connecting.`)})}async function Wt(u){s&&await Ge(`${u} sandbox`,async()=>{if(u==="start")m((await sl(s)).sandbox);else if(u==="stop")m((await nl(s)).sandbox),oe(null),F(null),jt(),yt(),Je("idle");else if(u==="restart")m((await al(s)).sandbox),oe(null),F(null),jt(),yt(),Je("idle");else{const N=await Ma(s);m(N.sandbox),ie(`Sandbox health is ${Ne(N.status.state)}.`)}})}async function rs(u){if(ot(u),!(!s||!Ce)){ft(N=>({...N,harness:!0})),_e(null);try{const[N,S]=await Promise.all([La(s,u),Da(s,u)]);Ye(N),ze(S)}catch(N){Ye(null),ze(null),_e(N instanceof Error?N.message:"Harness module refresh failed.")}finally{ft(N=>({...N,harness:!1}))}}}async function os(){!s||!o||await Ge("Inspect sandbox",async()=>{const u=await ol(s,o.id);g(u),ie("Sandbox detail loaded.")})}async function ls(u="connecting",N=fe){return!s||!o||!Ce?null:Ge("Create route token",async()=>{const S={scopes:["worker:read","worker:write","session:prompt","provider:turn:create"]};G!=null&&G.id&&(S.projectId=G.id),B&&(S.workspaceId=B),N&&(S.sessionId=N);const K=await Ir(s,o.id,S);return oe(K),Js(K),Vs(K,u),ie("Route token is available in memory."),K})}async function Ys(){if(!s||!o||o.state!=="running"||!fe)return;Je("reconnecting"),await ls("reconnecting",fe)||Je("idle")}function Xt(u){T(null),H(u.id),oe(null),F(null),jt(),yt(),Je("idle"),xt("summary"),Me(!0)}function Zs(u){Xt(u),Me(!0)}function Xs(u,N){var S;N&&(T(null),(S=navigator.clipboard)==null||S.writeText(N),ie(`${u} copied.`))}function is(u,N){Xe(u),Ve(N),T(null)}function qt(){Xe(null),Ve("")}async function ds(u){if(u.preventDefault(),!s||!Pe)return;const N=ht.trim();if(!N){Kt("Name is required.");return}const S=Pe;await Ge(`Rename ${S.type}`,async()=>{if(S.type==="project"){const K=await Zo(s,S.id,{name:N,slug:Dn(N)});R(Le=>Le.map(He=>He.id===K.project.id?K.project:He))}else if(S.type==="workspace"){const K=await Oa(s,S.id,{name:N});c(Le=>Le.map(He=>He.id===K.workspace.id?K.workspace:He))}else{const K=await $a(s,S.id,{title:N});Y(Le=>Le.map(He=>He.id===K.session.id?K.session:He))}qt(),ie(`${Ne(S.type)} renamed.`)})}function Ts(u){if(!u)return{title:"Delete item",description:"This item will be removed from the active control plane view."};if(u.type==="project"){const S=_.find(K=>K.id===u.id);return{title:`Delete project ${(S==null?void 0:S.name)??""}`.trim(),description:"The project will be archived and removed from the active project list. Its existing workspace records remain in the control plane database."}}if(u.type==="workspace"){const S=X.find(K=>K.id===u.id);return{title:`Delete workspace ${(S==null?void 0:S.name)??""}`.trim(),description:"The workspace will be marked deleted and removed from this project view. Sessions under it will no longer be shown from the active workspace browser."}}const N=D.find(S=>S.id===u.id);return{title:`Delete session ${(N==null?void 0:N.title)??""}`.trim(),description:"The session will be marked deleted and removed from this workspace view. This does not delete files in the sandbox workspace."}}async function Is(){if(!s||!pt)return;const u=pt;await Ge(`Delete ${u.type}`,async()=>{if(u.type==="project"){const N=await Xo(s,u.id);R(S=>S.filter(K=>K.id!==N.project.id)),I===N.project.id&&(q(""),ve(""),H(""),c([]),Y([]))}else if(u.type==="workspace"){const N=await Oa(s,u.id,{status:"deleted"});c(S=>S.filter(K=>K.id!==N.workspace.id)),B===N.workspace.id&&(ve(""),H(""),Y([]))}else{const N=await $a(s,u.id,{status:"deleted"});Y(S=>S.filter(K=>K.id!==N.session.id)),fe===N.session.id&&H("")}Pe&&Rs(Pe)===Rs(u)&&qt(),$e(null),oe(null),F(null),jt(),yt(),Je("idle"),ie(`${Ne(u.type)} deleted.`)})}async function Qs(u){!s||!Ce||await Ge("Close session",async()=>{const N=await tl(s,u.id);Y(S=>S.map(K=>K.id===N.session.id?N.session:K)),H(N.session.id),oe(null),F(null),jt(),yt(),Je("idle"),ie("Session finalized and disconnected.")})}async function en(u){!s||!Ce||await Ge("Resume session",async()=>{const N=await Tr(s,u.id);Y(S=>S.map(K=>K.id===N.session.id?N.session:K)),H(N.session.id),await ls("connecting",N.session.id),ie("Session resumed."),t(`/control-plane/sessions/${encodeURIComponent(N.session.id)}`)})}const Un=e.jsx(Ui,{title:En,subtitle:Rn,actions:e.jsxs(e.Fragment,{children:[o?e.jsx("span",{className:`control-status-pill ${Mt(o.state)}`,children:Ne(o.state)}):null,e.jsx(Ue,{onClick:()=>void Cs(s),disabled:!s||Et==="Load control plane",children:"Refresh"}),e.jsx(Ue,{onClick:()=>Me(u=>!u),ariaLabel:Qe?"Hide details inspector":"Show details inspector",children:"Inspector"}),e.jsxs("div",{className:"control-account-menu",children:[e.jsx("button",{type:"button",className:"control-avatar-button",onClick:()=>he(u=>!u),"aria-haspopup":"menu","aria-expanded":me,"aria-label":"Open account menu",children:ks}),me?e.jsxs("div",{className:"control-account-popover",role:"menu",children:[e.jsxs("div",{className:"control-account-identity",children:[e.jsx("span",{className:"control-avatar-badge",children:ks}),e.jsxs("div",{children:[e.jsx("strong",{children:(n==null?void 0:n.displayName)||(n==null?void 0:n.email)||"Account"}),e.jsx("span",{children:(n==null?void 0:n.email)??"Loading account"})]})]}),e.jsxs("dl",{className:"control-detail-list compact two",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Status"}),e.jsx("dd",{children:Ne((n==null?void 0:n.status)??"loading")})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Plan"}),e.jsx("dd",{children:(n==null?void 0:n.plan)??"developer"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Quota"}),e.jsx("dd",{children:(n==null?void 0:n.quotaProfile)??"default"})]})]}),e.jsxs("form",{onSubmit:De,className:"control-inline-form",children:[e.jsx(dn,{label:"Display name",value:Dt,onChange:gt}),e.jsx(Ue,{type:"submit",disabled:!s||Et==="Update profile",children:"Save"})]}),e.jsxs("div",{className:"control-usage-grid compact",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Requests"}),e.jsx("strong",{children:(y==null?void 0:y.requestCount)??0})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Tokens"}),e.jsx("strong",{children:Hs})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Total cost"}),e.jsxs("strong",{children:["$",it.toFixed(2)]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Harness"}),e.jsx("strong",{children:(E==null?void 0:E.eventCount)??0})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Compute"}),e.jsx("strong",{children:Number((E==null?void 0:E.computeUnits)??0).toFixed(1)})]}),e.jsxs("div",{children:[e.jsx("span",{children:"LLM cost"}),e.jsxs("strong",{children:["$",Number((y==null?void 0:y.costUsd)??0).toFixed(2)]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Harness cost"}),e.jsxs("strong",{children:["$",Number((E==null?void 0:E.costUsd)??0).toFixed(2)]})]})]}),e.jsxs("details",{className:"control-account-disclosure",children:[e.jsx("summary",{children:"Account details"}),e.jsx("dl",{className:"control-detail-list compact",children:e.jsx(We,{label:"Control plane API",value:Cn})})]}),e.jsxs("details",{className:"control-account-disclosure",children:[e.jsx("summary",{children:"Usage history"}),e.jsx("div",{className:"control-usage-events compact",children:tt.usageEvents?e.jsx("p",{className:"control-empty",children:"Loading LLM usage..."}):k.length===0?e.jsx("p",{className:"control-empty",children:"No LLM usage events yet."}):k.slice(0,4).map(u=>e.jsxs("div",{children:[e.jsx("strong",{children:u.model}),e.jsxs("span",{children:[u.provider,", ",u.inputTokens+u.outputTokens," tokens, $",Number(u.costUsd).toFixed(2)]}),e.jsx("small",{children:u.occurredAt})]},u.id))}),e.jsx("div",{className:"control-usage-events compact",children:tt.usageEvents?e.jsx("p",{className:"control-empty",children:"Loading Harness usage..."}):J.length===0?e.jsx("p",{className:"control-empty",children:"No Harness usage events yet."}):J.slice(0,4).map(u=>e.jsxs("div",{children:[e.jsx("strong",{children:u.tool??u.module}),e.jsxs("span",{children:[u.module,", ",u.status,", $",Number(u.costUsd).toFixed(2)]}),e.jsx("small",{children:u.occurredAt})]},u.id))})]}),e.jsx(Ue,{onClick:Ft,children:"Sign out"})]}):null]})]})}),tn=e.jsxs(e.Fragment,{children:[Gt?e.jsx("div",{className:"control-alert danger",children:Gt}):null,se?e.jsx("div",{className:"control-alert success",children:se}):null,gs?e.jsxs("div",{className:"control-alert warning",children:["LLM gateway unavailable: ",gs]}):null,vs?e.jsxs("div",{className:"control-alert danger",children:["LLM quota exceeded: ",vs]}):null,Yt?e.jsxs("div",{className:"control-alert danger",children:["Account disabled: ",Yt]}):null,js?e.jsxs("div",{className:"control-alert warning",children:["Session expired: ",js]}):null,Rt?e.jsxs("div",{className:"control-alert warning",children:["Admin access denied: ",Rt]}):null,Pt==="reconnecting"?e.jsx("div",{className:"control-alert warning",children:"Reconnecting sandbox route."}):null,Pt==="connecting"?e.jsx("div",{className:"control-alert neutral",children:"Connecting sandbox route."}):null,lt?e.jsxs("div",{className:"control-alert danger",children:["Sandbox offline: ",lt]}):null,Ns?e.jsx("div",{className:`control-alert ${Ns.tone}`,children:Ns.text}):null]}),sn=Ts(pt);return e.jsxs(e.Fragment,{children:[e.jsxs(Pi,{topBar:Un,alerts:tn,sidebar:null,main:null,inspector:null,inspectorOpen:Qe,children:[e.jsxs(Ai,{children:[e.jsxs("div",{className:"control-explorer-toolbar",children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Remote Codex"}),e.jsx("span",{children:(n==null?void 0:n.email)??"Product account"})]}),e.jsx("button",{type:"button",className:"control-icon-button",onClick:()=>V(Ct),"aria-label":`Open create panel for ${_t.toLowerCase()}`,title:`Create ${_t.toLowerCase()}`,children:"+"})]}),ke?e.jsxs("div",{className:"control-create-popover",children:[e.jsxs("div",{className:"control-panel-heading",children:[e.jsx("h2",{children:vt}),e.jsx("button",{type:"button",className:"control-icon-button quiet",onClick:()=>V(null),"aria-label":"Close create panel",children:"x"})]}),ke==="project"?e.jsxs("form",{onSubmit:Gs,className:"control-create-form",children:[e.jsx(dn,{label:"Project name",value:mt,onChange:Ze}),e.jsx(Ue,{type:"submit",disabled:!kt,children:"Create project"})]}):ke==="workspace"?e.jsxs("form",{onSubmit:Ks,className:"control-create-form",children:[e.jsx(dn,{label:"Workspace name",value:b,onChange:j}),Bt?e.jsx("p",{className:"control-rule-note",children:Bt}):null,e.jsx(Ue,{type:"submit",disabled:!ws,title:At,children:"Create workspace"})]}):e.jsxs("form",{onSubmit:An,className:"control-create-form",children:[e.jsx(dn,{label:"Session title",value:M,onChange:Q}),e.jsxs("label",{className:"control-field",children:[e.jsx("span",{children:"Provider"}),e.jsxs("select",{value:ge,onChange:u=>Oe(u.currentTarget.value),disabled:!ts,children:[e.jsx("option",{value:"codex",children:"Codex"}),e.jsx("option",{value:"claude",children:"Claude"}),e.jsx("option",{value:"opencode",children:"OpenCode"})]})]}),Bt?e.jsx("p",{className:"control-rule-note",children:Bt}):null,e.jsx(Ue,{type:"submit",disabled:!ts,title:Ut,children:"Create session"})]})]}):null,e.jsxs("div",{className:"control-sidebar-body",children:[e.jsxs("section",{className:"control-sidebar-section",children:[e.jsxs("div",{className:"control-sidebar-section-title",children:[e.jsx("span",{children:"Workspace"}),e.jsx("strong",{children:(ee==null?void 0:ee.name)??(G==null?void 0:G.name)??"Not selected"})]}),e.jsxs("div",{className:"control-context-card",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Project"}),e.jsx("strong",{children:(G==null?void 0:G.name)??"Choose project"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Workspace"}),e.jsx("strong",{children:(ee==null?void 0:ee.name)??"Choose workspace"})]})]})]}),e.jsxs("section",{className:"control-sidebar-section",children:[e.jsxs("div",{className:"control-sidebar-section-title",children:[e.jsx("span",{children:"Sessions"}),e.jsx("strong",{children:D.length})]}),e.jsx("div",{className:"control-nav-list","aria-label":"Session filters",children:Fs.map((u,N)=>e.jsxs("button",{type:"button",className:`control-nav-row ${N===0?"selected":""}`,children:[e.jsx("span",{children:u.label}),e.jsx("strong",{children:u.value})]},u.label))})]}),e.jsxs("section",{className:"control-sidebar-section",children:[e.jsx("div",{className:"control-sidebar-section-title",children:e.jsx("span",{children:"System"})}),e.jsxs("div",{className:"control-nav-list","aria-label":"System navigation",children:[e.jsxs("button",{type:"button",className:"control-nav-row","aria-label":`Open sandbox details, ${Ne(o==null?void 0:o.state)}`,onClick:()=>{xt("summary"),Me(!0)},children:[e.jsx("span",{children:"Sandbox"}),e.jsx("strong",{children:Ne(o==null?void 0:o.state)})]}),e.jsxs("button",{type:"button",className:"control-nav-row",onClick:()=>he(!0),children:[e.jsx("span",{children:"Usage"}),e.jsxs("strong",{children:["$",it.toFixed(2)]})]}),e.jsxs("button",{type:"button",className:"control-nav-row",onClick:()=>he(!0),children:[e.jsx("span",{children:"Settings"}),e.jsx("strong",{children:(n==null?void 0:n.plan)??"dev"})]})]})]})]}),e.jsx("div",{className:"control-explorer-tree",children:tt.projects?e.jsx("p",{className:"control-empty",children:"Loading projects..."}):_.length===0?e.jsx("p",{className:"control-empty",children:"No projects yet."}):_.map(u=>e.jsxs("div",{className:"control-tree-group",children:[Rs(Pe)===`project:${u.id}`?e.jsx(Bn,{label:"Project name",value:ht,onChange:Ve,onCancel:qt,onSubmit:ds}):e.jsxs("div",{className:`control-tree-item ${I===u.id?"selected":""}`,children:[e.jsxs("button",{type:"button","aria-label":`Select project ${u.name}`,onClick:()=>{q(u.id),ve(""),Y([]),H(""),oe(null),F(null),jt(),yt(),Je("idle")},className:"control-tree-row project",children:[e.jsx("span",{className:"control-tree-caret",children:e.jsx(za,{open:I===u.id})}),e.jsx("span",{className:"control-tree-icon",children:e.jsx(Di,{})}),e.jsx("strong",{children:u.name}),e.jsx("small",{children:Ne(u.status)})]}),e.jsx(_n,{label:`project ${u.name}`,onEdit:()=>is({type:"project",id:u.id},u.name),onDelete:()=>$e({type:"project",id:u.id})})]}),I===u.id?e.jsx("div",{className:"control-tree-children",children:tt.workspaces?e.jsx("p",{className:"control-empty",children:"Loading workspaces..."}):X.length===0?e.jsx("p",{className:"control-empty",children:"No workspaces in this project."}):X.map(N=>e.jsxs("div",{className:"control-tree-group",children:[Rs(Pe)===`workspace:${N.id}`?e.jsx(Bn,{label:"Workspace name",value:ht,onChange:Ve,onCancel:qt,onSubmit:ds}):e.jsxs("div",{className:`control-tree-item ${B===N.id?"selected":""}`,children:[e.jsxs("button",{type:"button","aria-label":`Select workspace ${N.name}`,onClick:()=>{ve(N.id),H(""),oe(null),F(null),jt(),yt(),Je("idle")},className:"control-tree-row workspace",children:[e.jsx("span",{className:"control-tree-caret",children:e.jsx(za,{open:B===N.id})}),e.jsx("span",{className:"control-tree-icon",children:e.jsx(Hi,{})}),e.jsx("strong",{children:N.name}),e.jsx("small",{children:Li(N)})]}),e.jsx(_n,{label:`workspace ${N.name}`,onEdit:()=>is({type:"workspace",id:N.id},N.name),onDelete:()=>$e({type:"workspace",id:N.id})})]}),B===N.id?e.jsx("div",{className:"control-tree-children sessions",children:tt.sessions?e.jsx("p",{className:"control-empty",children:"Loading sessions..."}):D.length===0?e.jsx("p",{className:"control-empty",children:"No sessions for this workspace."}):D.map(S=>e.jsx("div",{className:"control-tree-group",children:Rs(Pe)===`session:${S.id}`?e.jsx(Bn,{label:"Session title",value:ht,onChange:Ve,onCancel:qt,onSubmit:ds}):e.jsxs("div",{className:`control-tree-item ${fe===S.id?"selected":""}`,children:[e.jsxs("button",{type:"button","aria-label":`Open session ${S.title} from workspace browser`,onClick:()=>void Xt(S),className:"control-tree-row session",children:[e.jsx("span",{className:"control-tree-caret"}),e.jsx("span",{className:"control-tree-icon",children:e.jsx(_i,{})}),e.jsx("strong",{children:S.title}),e.jsxs("small",{children:[ln(S.provider)," / ",Ne(S.status),S.workerSessionId?"":" / Not started"]})]}),e.jsx(_n,{label:`session ${S.title}`,onEdit:()=>is({type:"session",id:S.id},S.title),onDelete:()=>$e({type:"session",id:S.id})})]})},S.id))}):null]},N.id))}):null]},u.id))})]}),e.jsxs("main",{className:"control-main-column",children:[e.jsxs("section",{className:"control-workspace-hero","aria-label":"Current control plane context",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Current workspace"}),e.jsx("h2",{children:(ee==null?void 0:ee.name)??(G==null?void 0:G.name)??"Select a workspace"}),e.jsx("p",{children:ee?`${(G==null?void 0:G.name)??"Project"} · ${As(ee.sourceType)}`:"Pick a project and workspace before creating sessions."})]}),e.jsxs("div",{className:"control-workspace-hero-actions",children:[e.jsx("span",{className:`control-status-pill ${Mt((o==null?void 0:o.state)??"unknown")}`,children:Ne(o==null?void 0:o.state)}),e.jsx(Ue,{onClick:()=>void Wt("start"),disabled:je.start.disabled,title:je.start.title,ariaLabel:`Sandbox ${je.start.label}`,children:je.start.label}),e.jsx(Ue,{onClick:()=>void Wt("restart"),disabled:je.restart.disabled,title:je.restart.title,ariaLabel:"Sandbox restart",children:je.restart.label}),e.jsx(Ue,{onClick:()=>void Wt("health"),disabled:je.health.disabled,title:je.health.title,ariaLabel:"Sandbox health",children:je.health.label}),e.jsxs(Ue,{onClick:()=>V(Ct),disabled:Ct==="workspace"?!ws:Ct==="session"?!ts:!kt,title:Ct==="workspace"?At:Ct==="session"?Ut:void 0,children:["New ",_t]})]})]}),e.jsxs("section",{className:"control-overview-strip","aria-label":"Control plane overview",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Projects"}),e.jsx("strong",{children:_.length})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Workspaces"}),e.jsx("strong",{children:X.length})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Active sessions"}),e.jsx("strong",{children:as})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Sandbox"}),e.jsx("strong",{children:Ne(o==null?void 0:o.state)})]})]}),e.jsxs("section",{className:"control-panel control-session-list-panel",children:[e.jsxs("div",{className:"control-panel-heading",children:[e.jsx("h2",{children:"Sessions"}),e.jsx("span",{children:ee?`${D.length} in workspace`:"Select workspace"})]}),ee?e.jsxs(e.Fragment,{children:[Ut?e.jsx("p",{className:"control-rule-note",children:Ut}):null,tt.sessions?e.jsx("p",{className:"control-empty",children:"Loading sessions..."}):D.length===0?e.jsx("p",{className:"control-empty",children:"No sessions in this workspace. Start the sandbox, then create a session."}):e.jsx("div",{className:"control-session-list",role:"list","aria-label":"Workspace sessions",children:D.map(u=>e.jsxs("article",{role:"listitem",className:`control-session-row ${fe===u.id?"selected":""}`,children:[e.jsxs("button",{type:"button","aria-label":`Open session ${u.title} summary`,className:"control-session-row-main",onClick:()=>void Xt(u),children:[e.jsx("strong",{children:u.title}),e.jsxs("span",{children:[ln(u.provider)," · ",on(u.lastActivityAt??u.updatedAt)]})]}),e.jsxs("div",{className:"control-session-row-state",children:[e.jsx(Gi,{status:u.status}),e.jsx("span",{children:Hn(u)})]}),e.jsxs("div",{className:"control-session-row-actions",children:[e.jsx(Ue,{onClick:()=>void en(u),disabled:!s||!Ce,title:Ce?void 0:"Start the sandbox before opening this session.",ariaLabel:`${u.workerSessionId?"Resume":"Start"} session ${u.title} from summary`,children:u.workerSessionId?"Resume":"Start"}),e.jsxs("div",{className:"control-row-menu",children:[e.jsx("button",{type:"button",className:"control-row-menu-trigger","aria-label":`More actions for session ${u.title}`,"aria-haspopup":"menu","aria-expanded":pe===u.id,onClick:()=>T(N=>N===u.id?null:u.id),children:"..."}),pe===u.id?e.jsxs("div",{className:"control-row-menu-popover",role:"menu",children:[e.jsx("button",{type:"button",role:"menuitem",onClick:()=>Zs(u),children:"Show details"}),e.jsx("button",{type:"button",role:"menuitem",onClick:()=>Xs("Session ID",u.id),children:"Copy session ID"}),u.sandboxId?e.jsx("button",{type:"button",role:"menuitem",onClick:()=>Xs("Sandbox ID",u.sandboxId),children:"Copy sandbox ID"}):null,e.jsx("button",{type:"button",role:"menuitem",disabled:!s||!u.workerSessionId||!Ce,title:u.workerSessionId?void 0:"Session has not been started yet.",onClick:()=>{T(null),Qs(u)},children:"Close session"})]}):null]})]})]},u.id))}),e.jsx("div",{className:"control-action-row start",children:e.jsx(Ue,{onClick:()=>V("session"),disabled:!ts,title:Ut,children:"Create session"})})]}):e.jsx("p",{className:"control-empty",children:"Choose a workspace from the browser to see its sessions."})]}),e.jsxs("section",{className:"control-panel control-selected-panel control-context-summary-panel",children:[e.jsxs("div",{className:"control-panel-heading",children:[e.jsx("h2",{children:ne?"Selected session":ee?"Workspace context":G?"Project context":"Selection"}),e.jsx("span",{children:ne?Ne(ne.status):ee?As(ee.sourceType):G?Ne(G.status):"Root"})]}),ne?e.jsxs(e.Fragment,{children:[e.jsxs("dl",{className:"control-detail-list compact summary",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Title"}),e.jsx("dd",{children:ne.title})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Provider"}),e.jsx("dd",{children:ln(ne.provider)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Status"}),e.jsx("dd",{children:e.jsx("span",{className:`control-status-pill compact ${Mt(ne.status)}`,children:Ne(ne.status)})})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Last activity"}),e.jsx("dd",{children:on(Ws)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Sandbox"}),e.jsx("dd",{children:Ce?"Ready":Ne(o==null?void 0:o.state)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Runtime"}),e.jsx("dd",{children:Hn(ne)})]})]}),e.jsxs("div",{className:"control-action-row start",children:[e.jsx(Ue,{onClick:()=>void en(ne),disabled:!s||!Ce,title:Ce?void 0:"Start the sandbox before opening this session.",ariaLabel:`${ne.workerSessionId?"Resume":"Start"} session ${ne.title} from detail`,children:ne.workerSessionId?"Resume":"Start sandbox session"}),e.jsx(Ue,{onClick:()=>{xt("metadata"),Me(!0)},children:"Details"})]})]}):ee?e.jsx(e.Fragment,{children:e.jsxs("dl",{className:"control-detail-list compact summary",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Workspace"}),e.jsx("dd",{children:ee.name})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Project"}),e.jsx("dd",{children:(G==null?void 0:G.name)??ee.projectId})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Source"}),e.jsx("dd",{children:As(ee.sourceType)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Sessions"}),e.jsx("dd",{children:D.length})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Active"}),e.jsx("dd",{children:as})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Not started"}),e.jsx("dd",{children:_s})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Sandbox"}),e.jsx("dd",{children:Ne(o==null?void 0:o.state)})]})]})}):G?e.jsxs(e.Fragment,{children:[e.jsxs("dl",{className:"control-detail-list compact summary",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Selected project"}),e.jsx("dd",{children:G.name})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Status"}),e.jsx("dd",{children:Ne(G.status)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Workspaces"}),e.jsx("dd",{children:X.length})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Path"}),e.jsx("dd",{children:Ss})]})]}),e.jsx("div",{className:"control-action-row start",children:e.jsx(Ue,{onClick:()=>V("workspace"),disabled:!ws,title:At,children:"Create workspace"})})]}):e.jsx("p",{className:"control-empty",children:"Select a project to open the workspace hierarchy."})]})]}),Qe?e.jsx("button",{type:"button",className:"control-inspector-scrim","aria-hidden":"true",tabIndex:-1,onClick:()=>Me(!1)}):null,e.jsxs(Ri,{eyebrow:ne?"Session":ee?"Workspace":G?"Project":"Sandbox",hidden:!Qe,onClose:()=>Me(!1),children:[e.jsx("div",{className:"control-inspector-tabs",role:"tablist","aria-label":"Inspector sections",children:["summary","metadata","route","logs"].map(u=>e.jsx("button",{type:"button",role:"tab","aria-selected":et===u,className:et===u?"selected":"",onClick:()=>xt(u),children:u==="summary"?"Summary":u==="metadata"?"Metadata":u==="route"?"Route":"Logs"},u))}),et==="summary"?e.jsxs("div",{className:"control-inspector-tab-panel",role:"tabpanel",children:[e.jsxs("div",{className:"control-inspector-section",children:[e.jsxs("div",{className:"control-panel-heading compact",children:[e.jsx("h2",{children:"Sandbox"}),o?e.jsx("span",{children:o.resourceProfile}):null]}),o?e.jsxs("dl",{className:"control-detail-list compact summary",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"State"}),e.jsx("dd",{children:e.jsx("span",{className:`control-status-pill compact ${Mt(o.state)}`,children:Ne(o.state)})})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Stage"}),e.jsx("dd",{children:qs})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Health"}),e.jsx("dd",{children:In})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Last seen"}),e.jsx("dd",{children:on(Tn)})]})]}):e.jsx("p",{className:"control-empty",children:"Loading sandbox registry."})]}),e.jsxs("div",{className:"control-action-row",children:[e.jsx(Ue,{onClick:()=>void Wt("stop"),disabled:je.stop.disabled,title:je.stop.title,children:je.stop.label}),e.jsx(Ue,{onClick:os,disabled:je.inspect.disabled,title:je.inspect.title,children:je.inspect.label})]}),o&&typeof o.startupProgress=="number"&&o.startupProgress>0&&o.startupProgress<100?e.jsxs("div",{className:"control-progress",children:[e.jsx("span",{children:qs}),e.jsxs("span",{children:[o.startupProgress,"%"]}),e.jsx("div",{children:e.jsx("i",{style:{width:`${o.startupProgress}%`}})})]}):null,ne||ee||G?e.jsxs("div",{className:"control-inspector-section",children:[e.jsxs("div",{className:"control-panel-heading compact",children:[e.jsx("h2",{children:ne?"Session":ee?"Workspace":"Project"}),e.jsx("span",{children:ne?Ne(ne.status):ee?As(ee.sourceType):Ne(G==null?void 0:G.status)})]}),e.jsx("dl",{className:"control-detail-list compact summary",children:ne?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Title"}),e.jsx("dd",{children:ne.title})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Provider"}),e.jsx("dd",{children:ln(ne.provider)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Runtime"}),e.jsx("dd",{children:Hn(ne)})]})]}):ee?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Workspace"}),e.jsx("dd",{children:ee.name})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Sessions"}),e.jsx("dd",{children:D.length})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Active"}),e.jsx("dd",{children:as})]})]}):G?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Project"}),e.jsx("dd",{children:G.name})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Workspaces"}),e.jsx("dd",{children:X.length})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Status"}),e.jsx("dd",{children:Ne(G.status)})]})]}):null})]}):e.jsxs("div",{className:"control-inspector-empty",children:[e.jsx("strong",{children:"No object selected"}),e.jsx("span",{children:"Select a project, workspace, or session to inspect its metadata."})]}),e.jsxs("div",{className:"control-inspector-section",children:[e.jsxs("div",{className:"control-panel-heading compact",children:[e.jsx("h2",{children:"Harness"}),e.jsx("span",{className:`control-status-pill ${Ja(Zt)}`,children:Ne(Zt)})]}),Ce?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"control-action-row",children:e.jsx(Ue,{onClick:()=>void zs(s,xe),disabled:!s||tt.harness,children:tt.harness?"Checking...":"Refresh"})}),ut?e.jsxs("div",{className:"control-alert warning",children:["Harness unavailable: ",ut]}):null,e.jsxs("dl",{className:"control-detail-list compact summary",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Key"}),e.jsx("dd",{children:z!=null&&z.keyPresent?"Present":"Not present"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Chemistry"}),e.jsx("dd",{children:z!=null&&z.chemistryToolsEnabled?"Enabled":"Disabled"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Health"}),e.jsx("dd",{children:z!=null&&z.health?"OK":"Not available"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Module"}),e.jsx("dd",{children:rn[xe]})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Tools"}),e.jsx("dd",{children:de.length||"folder index"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Runs"}),e.jsx("dd",{children:Ot.length||"history available"})]})]})]}):e.jsx("p",{className:"control-empty",children:"Start the sandbox to inspect Harness tools."})]})]}):null,et==="metadata"?e.jsxs("div",{className:"control-inspector-tab-panel",role:"tabpanel",children:[ne?e.jsxs("section",{className:"control-inspector-section",children:[e.jsx("div",{className:"control-panel-heading compact",children:e.jsx("h2",{children:"Session metadata"})}),e.jsxs("dl",{className:"control-detail-list",children:[e.jsx(We,{label:"Session ID",value:ne.id}),e.jsx(We,{label:"Worker session",value:ne.workerSessionId}),e.jsx(We,{label:"Workspace ID",value:ne.workspaceId}),e.jsx(We,{label:"Sandbox ID",value:ne.sandboxId}),e.jsxs("div",{children:[e.jsx("dt",{children:"Created"}),e.jsx("dd",{children:ne.createdAt})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Updated"}),e.jsx("dd",{children:ne.updatedAt})]})]})]}):null,ee?e.jsxs("section",{className:"control-inspector-section",children:[e.jsx("div",{className:"control-panel-heading compact",children:e.jsx("h2",{children:"Workspace metadata"})}),e.jsxs("dl",{className:"control-detail-list",children:[e.jsx(We,{label:"Workspace ID",value:ee.id}),e.jsx(We,{label:"Project ID",value:ee.projectId}),e.jsx(We,{label:"Path",value:ee.path}),e.jsxs("div",{children:[e.jsx("dt",{children:"Slug"}),e.jsx("dd",{children:ee.slug})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Created"}),e.jsx("dd",{children:ee.createdAt})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Updated"}),e.jsx("dd",{children:ee.updatedAt})]})]})]}):null,G?e.jsxs("section",{className:"control-inspector-section",children:[e.jsx("div",{className:"control-panel-heading compact",children:e.jsx("h2",{children:"Project metadata"})}),e.jsxs("dl",{className:"control-detail-list",children:[e.jsx(We,{label:"Project ID",value:G.id}),e.jsxs("div",{children:[e.jsx("dt",{children:"Slug"}),e.jsx("dd",{children:G.slug})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Created"}),e.jsx("dd",{children:G.createdAt})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Updated"}),e.jsx("dd",{children:G.updatedAt})]})]})]}):null,o?e.jsxs("section",{className:"control-inspector-section",children:[e.jsx("div",{className:"control-panel-heading compact",children:e.jsx("h2",{children:"Sandbox metadata"})}),e.jsxs("dl",{className:"control-detail-list",children:[e.jsx(We,{label:"Sandbox ID",value:o.id}),e.jsx(We,{label:"Image",value:o.image}),e.jsx(We,{label:"Worker ID",value:o.workerServiceName}),e.jsx(We,{label:"S3 prefix",value:o.s3Prefix}),o.statusReason?e.jsxs("div",{children:[e.jsx("dt",{children:"Status"}),e.jsx("dd",{children:o.statusReason})]}):null,o.lastFailureCode?e.jsxs("div",{children:[e.jsx("dt",{children:"Failure"}),e.jsx("dd",{children:o.lastFailureCode})]}):null,o.lastFailureMessage?e.jsxs("div",{children:[e.jsx("dt",{children:"Failure message"}),e.jsx("dd",{children:o.lastFailureMessage})]}):null,e.jsxs("div",{children:[e.jsx("dt",{children:"Created"}),e.jsx("dd",{children:o.createdAt})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Updated"}),e.jsx("dd",{children:o.updatedAt})]})]})]}):null]}):null,et==="route"?e.jsxs("div",{className:"control-inspector-tab-panel",role:"tabpanel",children:[e.jsxs("section",{className:"control-inspector-section",children:[e.jsxs("div",{className:"control-panel-heading compact",children:[e.jsx("h2",{children:"Route"}),e.jsx(Ue,{onClick:()=>void ls("connecting",fe),disabled:!Ce||!ne,title:Ls,children:"Create route token"})]}),le?e.jsxs("dl",{className:"control-detail-list compact summary route-token",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Session"}),e.jsx("dd",{children:(ne==null?void 0:ne.title)??fe})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Connection"}),e.jsx("dd",{children:Va(Pt)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Token"}),e.jsxs("dd",{children:[on(le.expiresAt)," expiry"]})]})]}):e.jsx("p",{className:"control-empty",children:ne?`Selected session: ${ne.title}. Create a route token after the sandbox is running.`:"Select a session before creating a route token."})]}),le?e.jsxs("section",{className:"control-inspector-section",children:[e.jsx("div",{className:"control-panel-heading compact",children:e.jsx("h2",{children:"Route metadata"})}),e.jsxs("dl",{className:"control-detail-list",children:[e.jsx(We,{label:"Router URL",value:le.routerBaseUrl}),e.jsx(We,{label:"WebSocket URL",value:le.wsBaseUrl}),e.jsx(We,{label:"Worker socket",value:W}),e.jsxs("div",{children:[e.jsx("dt",{children:"Connection"}),e.jsx("dd",{children:Va(Pt)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Expires"}),e.jsx("dd",{children:le.expiresAt})]})]})]}):null]}):null,et==="logs"?e.jsxs("div",{className:"control-inspector-tab-panel",role:"tabpanel",children:[e.jsxs("section",{className:"control-inspector-section",children:[e.jsxs("div",{className:"control-panel-heading compact",children:[e.jsx("h2",{children:"Harness details"}),e.jsx("span",{className:`control-status-pill ${Ja(Zt)}`,children:Ne(Zt)})]}),Ce?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"control-segment-row",role:"tablist","aria-label":"Harness modules",children:Ds.map(u=>e.jsx("button",{type:"button",role:"tab","aria-selected":xe===u,className:xe===u?"selected":"",onClick:()=>void rs(u),disabled:tt.harness||!(z!=null&&z.enabled)||!z.keyPresent,children:rn[u]},u))}),e.jsxs("dl",{className:"control-detail-list",children:[e.jsx(We,{label:"Base URL",value:z==null?void 0:z.baseUrl}),e.jsxs("div",{children:[e.jsx("dt",{children:"Enabled"}),e.jsx("dd",{children:z!=null&&z.enabled?"yes":"no"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Modules"}),e.jsx("dd",{children:Ds.map(u=>rn[u]).join(", ")})]})]}),e.jsxs("div",{className:"control-usage-events compact",children:[e.jsxs("div",{children:[e.jsxs("strong",{children:[rn[xe]," tools"]}),e.jsxs("small",{children:[de.length," advertised"]})]}),de.slice(0,5).map((u,N)=>e.jsxs("div",{children:[e.jsx("strong",{children:Ya(u,`tool-${N+1}`)}),e.jsx("span",{children:Za(u)||"tool"})]},`${xe}-tool-${N}`)),de.length===0&&ss?e.jsx("div",{children:e.jsx("span",{children:ss.slice(0,180)})}):null,de.length===0&&!ss?e.jsx("p",{className:"control-empty",children:"No tools reported for this module."}):null]}),e.jsxs("div",{className:"control-usage-events compact",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Recent runs"}),e.jsxs("small",{children:[Ot.length," reported"]})]}),Ot.slice(0,4).map((u,N)=>e.jsxs("div",{children:[e.jsx("strong",{children:Ya(u,`run-${N+1}`)}),e.jsx("span",{children:Za(u)||"run"})]},`${xe}-run-${N}`)),Ot.length===0&&ns?e.jsx("div",{children:e.jsx("span",{children:ns.slice(0,180)})}):null,Ot.length===0&&!ns?e.jsx("p",{className:"control-empty",children:"No runs reported yet."}):null]})]}):e.jsx("p",{className:"control-empty",children:"Start the sandbox to inspect Harness tools."})]}),h?e.jsxs("section",{className:"control-inspector-section",children:[e.jsxs("div",{className:"control-panel-heading compact",children:[e.jsx("h2",{children:"Admin inspection"}),e.jsx("span",{children:Ne(h.runtimeStatus.state)})]}),e.jsxs("dl",{className:"control-detail-list",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Namespace"}),e.jsx("dd",{children:h.sandbox.k8sNamespace??h.runtimeStatus.k8sNamespace??"not assigned"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Pod"}),e.jsx("dd",{children:h.sandbox.k8sPodName??h.runtimeStatus.k8sPodName??"not assigned"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Endpoint"}),e.jsx("dd",{children:h.endpoint.routerBaseUrl??"not assigned"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Worker URL"}),e.jsx("dd",{children:h.workerBaseUrl??"not assigned"})]})]}),h.runtimeStatus.statusReason?e.jsx("p",{className:"control-empty",children:h.runtimeStatus.statusReason}):null,e.jsx("div",{className:"control-usage-events",children:h.recentLifecycleErrors.length===0?e.jsx("p",{className:"control-empty",children:"No lifecycle audit entries."}):h.recentLifecycleErrors.slice(0,5).map(u=>e.jsxs("div",{children:[e.jsx("strong",{children:u.action}),e.jsx("small",{children:u.createdAt})]},u.id))})]}):e.jsxs("div",{className:"control-inspector-empty",children:[e.jsx("strong",{children:"No admin inspection loaded"}),e.jsx("span",{children:"Use Inspect from Summary to load sandbox runtime diagnostics."})]})]}):null]})]}),e.jsx(wn,{open:!!pt,title:sn.title,description:sn.description,confirmLabel:"Delete",busy:!!(Et!=null&&Et.startsWith("Delete ")),onCancel:()=>$e(null),onConfirm:Is})]})}const Yi="http://127.0.0.1:8790";function Xa({children:t}){const s=es(),[a,n]=r.useState(null);return r.useEffect(()=>{let d=!1;return Promise.resolve().then(()=>{d||n(Ei())}),()=>{d=!0}},[s.pathname]),a===null?e.jsx("div",{className:"grid min-h-[60vh] place-items-center text-sm text-[var(--theme-fg-muted)]",children:"Loading account session..."}):a?t:e.jsx(Os,{to:"/control-plane/login",replace:!0,state:{from:s}})}function Zi(t){return{baseUrl:t.baseUrl,token:t.token}}function Xi(){if(typeof window>"u")return null;const t=new URLSearchParams(window.location.search),s=t.get("control_plane_token"),a=t.get("control_plane_expires_at"),n=t.get("control_plane_base_url"),d=t.get("auth_error");return{token:s,expiresAt:a,baseUrl:n,error:d}}function Qi(){var Y;const t=rt(),s=es(),a=Qt(),[n,d]=r.useState("login"),[o,m]=r.useState((a==null?void 0:a.baseUrl)??Yi),[h,g]=r.useState((a==null?void 0:a.email)??"dev@example.com"),[y,A]=r.useState((a==null?void 0:a.displayName)??"Developer"),[x,f]=r.useState(""),[k,C]=r.useState(!1),[E,v]=r.useState(null),[J,te]=r.useState(null),_=s.state,R=((Y=_==null?void 0:_.from)==null?void 0:Y.pathname)??"/control-plane",X=r.useMemo(()=>{if(typeof window>"u")return;const I=new URL(window.location.href);return I.search="",I.toString()},[]);r.useEffect(()=>{const I=Xi();if(!I)return;if(I.error){te(`OAuth sign in failed: ${I.error}`);return}if(!I.token||!I.baseUrl)return;const q={baseUrl:I.baseUrl,token:I.token};I.expiresAt&&(q.expiresAt=I.expiresAt),xn(q),ha(Zi(q)).then(B=>{xn({...q,email:B.user.email,displayName:B.user.displayName}),t("/control-plane",{replace:!0})}).catch(B=>{jn(),te(B instanceof Error?B.message:"Unable to finish OAuth sign in.")})},[t]);async function c(I){I.preventDefault(),C(!0),te(null),v(null);try{const q=n==="register"?await qo(o,{email:h,password:x,displayName:y||null}):await zo(o,{email:h,password:x});xn({baseUrl:o,token:q.session.token,expiresAt:q.session.expiresAt,email:q.user.email,displayName:q.user.displayName}),v("Account session is ready."),t(R,{replace:!0})}catch(q){q instanceof re&&q.payload.code==="conflict"?te("An account already exists for this email. Use sign in instead."):te(q instanceof Error?q.message:"Unable to authenticate.")}finally{C(!1)}}function D(I){window.location.assign(Wo(o,I,X))}return e.jsx("div",{className:"control-auth-shell",children:e.jsxs("section",{className:"control-auth-panel","aria-label":"Control plane account login",children:[e.jsxs("div",{className:"control-auth-aside",children:[e.jsx("p",{className:"control-kicker",children:"Remote Codex"}),e.jsx("h1",{children:"Control plane sign in"}),e.jsx("p",{children:"Use a product account to manage sandboxes, workspaces, route tokens, and usage from the cloud control plane."}),e.jsxs("div",{className:"control-auth-checks","aria-label":"Login capabilities",children:[e.jsx("span",{children:"Google"}),e.jsx("span",{children:"GitHub"}),e.jsx("span",{children:"Email password"})]})]}),e.jsxs("form",{onSubmit:c,className:"control-auth-form",children:[e.jsxs("div",{className:"control-auth-tabs",role:"tablist","aria-label":"Authentication mode",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":n==="login",onClick:()=>d("login"),children:"Sign in"}),e.jsx("button",{type:"button",role:"tab","aria-selected":n==="register",onClick:()=>d("register"),children:"Create account"})]}),e.jsxs("label",{className:"control-field",children:[e.jsx("span",{children:"Control plane URL"}),e.jsx("input",{value:o,onChange:I=>m(I.currentTarget.value)})]}),e.jsxs("div",{className:"control-oauth-row",children:[e.jsx("button",{type:"button",onClick:()=>D("google"),children:"Continue with Google"}),e.jsx("button",{type:"button",onClick:()=>D("github"),children:"Continue with GitHub"})]}),e.jsx("div",{className:"control-auth-divider",children:e.jsx("span",{children:"Email"})}),n==="register"?e.jsxs("label",{className:"control-field",children:[e.jsx("span",{children:"Display name"}),e.jsx("input",{value:y,onChange:I=>A(I.currentTarget.value)})]}):null,e.jsxs("label",{className:"control-field",children:[e.jsx("span",{children:"Email address"}),e.jsx("input",{type:"email",value:h,autoComplete:"email",onChange:I=>g(I.currentTarget.value)})]}),e.jsxs("label",{className:"control-field",children:[e.jsx("span",{children:"Password"}),e.jsx("input",{type:"password",value:x,autoComplete:n==="register"?"new-password":"current-password",minLength:8,onChange:I=>f(I.currentTarget.value)})]}),J?e.jsx("p",{className:"control-auth-error",children:J}):null,E?e.jsx("p",{className:"control-auth-message",children:E}):null,e.jsx("button",{type:"submit",className:"control-primary-button",disabled:k,children:k?"Working...":n==="register"?"Create account":"Sign in"})]})]})})}function ed(t){return t.sandboxMode??(t.approvalMode==="guarded"?"workspace-write":"danger-full-access")}function td(t,s){const a=new Set(s.map(n=>n.id));return[...s,...t.filter(n=>!a.has(n.id))]}function zt(t,s){const a=new Set(s.map(n=>n.id));return[...t.filter(n=>!a.has(n.id)),...s]}function sd(t,s){return{...t,pendingRequests:[...t.pendingRequests.filter(a=>a.id!==s.id),s]}}function nd(t,s){const a=t.pendingRequests.filter(n=>n.id!==s);return a.length===t.pendingRequests.length?t:{...t,pendingRequests:a}}function ia(t,s,a){const n=s.filter(h=>!a.has(h.id)),d=t.filter(h=>!a.has(h.id));if(d.length===0)return n;const o=new Map(n.map(h=>[h.id,h]));return[...d.map(h=>o.get(h.id)??h),...n.filter(h=>!d.some(g=>g.id===h.id))].sort((h,g)=>h.createdAt.localeCompare(g.createdAt))}function ad(t){if(!t||typeof t!="object")return!1;const s=t;return typeof s.id=="string"&&(s.kind==="requestUserInput"||s.kind==="planDecision")&&typeof s.title=="string"&&typeof s.createdAt=="string"&&Array.isArray(s.questions)}function qr(t,s){var o,m;if(!t||t.kind!==s.kind)return s;const a=h=>{let g=h;const y=typeof s.sequence=="number"&&Number.isFinite(s.sequence)?s.sequence:typeof t.sequence=="number"&&Number.isFinite(t.sequence)?t.sequence:null;y!==null&&g.sequence!==y&&(g={...g,sequence:y});const A=typeof s.transcriptOrder=="number"&&Number.isFinite(s.transcriptOrder)?s.transcriptOrder:typeof t.transcriptOrder=="number"&&Number.isFinite(t.transcriptOrder)?t.transcriptOrder:null;return A!==null&&g.transcriptOrder!==A&&(g={...g,transcriptOrder:A}),g};if(t.kind==="agentMessage"&&s.kind==="agentMessage")return a(t.text.length>s.text.length?{...s,text:t.text,sequence:s.sequence??t.sequence??null}:s);const n=((o=t.detailText)==null?void 0:o.trim())||t.text.trim(),d=((m=s.detailText)==null?void 0:m.trim())||s.text.trim();return a(n.length>d.length?t:s)}function rd(t,s,a){if(!t||s&&s.turnId!==t.turnId)return s;const n=a.find(x=>x.id===t.turnId),d=new Map((n==null?void 0:n.items.map(x=>[x.id,x]))??[]),o=(n==null?void 0:n.items.filter(x=>x.kind==="agentMessage").map(x=>x.text.trim()).filter(Boolean))??[],m=x=>x.kind==="agentMessage"&&x.text.trim().length>0&&o.some(f=>f.includes(x.text.trim()));if(!s){const x=t.items.filter(f=>{const k=d.get(f.id);return k?k.kind!==f.kind||typeof f.sequence=="number"&&Number.isFinite(f.sequence)&&k.sequence!==f.sequence:!m(f)});return x.length===0?null:{...t,items:x}}const h=new Map(t.items.map(x=>[x.id,x])),g=new Map(s.items.map(x=>[x.id,x])),A=[...t.items.map(x=>x.id),...s.items.map(x=>x.id).filter(x=>!h.has(x))].map(x=>{const f=g.get(x),k=h.get(x);if(!f){const C=d.get(x);return!C&&k&&m(k)||C&&C.kind===(k==null?void 0:k.kind)&&!(k&&typeof k.sequence=="number"&&Number.isFinite(k.sequence)&&C.sequence!==k.sequence)?null:k??null}return qr(k,f)}).filter(x=>!!x);return A.length===0?null:{turnId:s.turnId,items:A,updatedAt:s.updatedAt.localeCompare(t.updatedAt)>=0?s.updatedAt:t.updatedAt}}function Ps(t,s){const a=t.filter(n=>n.id!==s.id);return[s,...a]}function od(t){return`${t.threadId}:${t.objective}:${t.createdAt}`}function ld(t,s){const a=Date.parse(t.updatedAt)||0,d=(Date.parse(s.updatedAt)||0)>=a?s:t,o=d===s?t:s;return{...d,localGoalId:d.localGoalId??o.localGoalId??null}}function zr(t){const s=new Map;for(const a of t){const n=od(a),d=s.get(n);s.set(n,d?ld(d,a):a)}return[...s.values()].sort((a,n)=>Date.parse(n.updatedAt)-Date.parse(a.updatedAt))}function cn(t,s){return zr([s,...t])}function id(t){const s=new Intl.NumberFormat(void 0,{notation:"compact",maximumFractionDigits:1});return t.tokenBudget===null?`${s.format(t.tokensUsed)} tok`:`${s.format(t.tokensUsed)}/${s.format(t.tokenBudget)} tok`}function dd(t){const s=Math.max(0,Math.floor(t/60)),a=Math.floor(s/60),n=s%60;return a>0?`${a}h ${n}m`:`${s}m`}function Qa(t,s){if(!s)return null;const a=t.find(n=>n.model===s);return a?a.supportedReasoningEfforts.length>1:null}function cd(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`client-${Date.now()}-${Math.random().toString(16).slice(2,10)}`}function Us(t,s){return(t==null?void 0:t.items.some(a=>a.kind==="userMessage"&&a.text.trim()===s))??!1}function er(t){return t.replace(/\s*\[PHOTO\s+[^\]]+\]\s*/g," ").replace(/\s+/g," ").trim()}function gn(t,s){const a=er(s);return a?(t==null?void 0:t.items.some(n=>n.kind==="userMessage"&&er(n.text)===a))??!1:!1}function Fn(t){return(t==null?void 0:t.items.some(s=>s.kind==="userMessage"&&/\[PHOTO\s+\.\/\.temp\/threads\/[^\]]+\]/.test(s.text)))??!1}function ud(t,s){return t.find(a=>Us(a,s))??(s.includes("[PHOTO ")?t.find(a=>gn(a,s))??null:null)}function md(t,s,a,n){let d=!1;const o=t.map(m=>m.id!==s?m:(d=!0,{...m,tokenUsage:a,priceEstimate:n}));return d?o:t}const hd=3e3,pd=6e4,fd=5e3,xd=2147e6,gd=["worker:read","worker:write","session:prompt","provider:turn:create","provider:turn:interrupt"];function bd(t){if(!t)return"no activity yet";const s=Date.parse(t);if(!Number.isFinite(s))return t;const a=Date.now()-s,n=Math.abs(a),d=a>=0?"ago":"from now",o=6e4,m=60*o,h=24*m;return n<o?"just now":n<m?`${Math.round(n/o)}m ${d}`:n<h?`${Math.round(n/m)}h ${d}`:`${Math.round(n/h)}d ${d}`}function vd({title:t,children:s}){const[a,n]=r.useState(!1);return e.jsxs("section",{className:"control-metadata-disclosure",children:[e.jsxs("button",{type:"button","aria-expanded":a,onClick:()=>n(d=>!d),className:"control-metadata-trigger",children:[e.jsx("span",{children:t}),e.jsx("span",{children:a?"Hide":"Show"})]}),a?s:null]})}function Re({label:t,value:s}){const a=s&&s.trim()?s:"not assigned";return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsxs("dd",{children:[e.jsx("span",{children:a}),s?e.jsx("button",{type:"button",className:"control-copy-button",onClick:()=>{var n;(n=navigator.clipboard)==null||n.writeText(s)},children:"Copy"}):null]})]})}function jd(t){if(!t||typeof t!="object")return null;const s=t,a=Array.isArray(s.content)?s.content.filter(n=>typeof n=="string"):typeof s.content=="string"?[s.content]:[];return a.length===0?null:{content:a.join(`
|
|
5
|
-
`),format:typeof s.format=="string"?s.format:"text",name:typeof s.name=="string"?s.name:null}}function yd({selected:t,onClose:s}){const a=ca(),[n,d]=r.useState(t.kind==="artifact"?"preview":"logs"),[o,m]=r.useState(!0),h=t.kind==="artifact"?t.artifact:null,g=t.kind==="historyDetail"?t.detail:null,y=t.item,A=h?jd(h.payload):null,x=h?a.renderArtifact({artifact:h,expanded:o,onToggleExpanded:()=>m(k=>!k)}):null,f=[{id:"preview",label:"Preview"},{id:"source",label:"Source"},{id:"logs",label:"Logs"},{id:"metadata",label:"Metadata"}];return e.jsxs("aside",{className:"control-artifact-inspector","aria-label":"Thread inspector",children:[e.jsxs("header",{className:"control-artifact-inspector-header",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{children:(h==null?void 0:h.type)??y.kind}),e.jsx("h2",{children:(h==null?void 0:h.title)??(g==null?void 0:g.title)??y.text??"Timeline detail"})]}),e.jsx("button",{type:"button",onClick:s,"aria-label":"Close thread inspector",children:"x"})]}),e.jsx("div",{className:"control-artifact-tabs",role:"tablist","aria-label":"Thread details",children:f.map(k=>e.jsx("button",{type:"button",role:"tab","aria-selected":n===k.id,onClick:()=>d(k.id),children:k.label},k.id))}),e.jsxs("div",{className:"control-artifact-panel",children:[n==="preview"?t.kind!=="artifact"?e.jsx("div",{className:"control-artifact-empty",children:"Preview is available for artifacts. Open Logs for this item detail."}):x?e.jsx("div",{className:"control-artifact-preview",children:x}):e.jsx("div",{className:"control-artifact-empty",children:"No renderer is enabled for this artifact type."}):null,n==="source"?g?e.jsx("pre",{className:"control-artifact-source-raw",children:g.text}):A?e.jsxs("div",{className:"control-artifact-source",children:[e.jsxs("div",{children:[e.jsx("span",{children:A.format}),A.name?e.jsx("strong",{children:A.name}):null]}),e.jsx("pre",{children:A.content})]}):e.jsx("pre",{className:"control-artifact-source-raw",children:JSON.stringify(h==null?void 0:h.payload,null,2)}):null,n==="logs"?e.jsx("div",{className:"control-artifact-logs",children:g?e.jsx("pre",{children:g.text}):e.jsxs("dl",{className:"control-detail-list",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Timeline item"}),e.jsx("dd",{children:y.text||y.previewText||(h==null?void 0:h.summaryText)||"Artifact created"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Status"}),e.jsx("dd",{children:y.status??"completed"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Source turn"}),e.jsx("dd",{children:(h==null?void 0:h.sourceTurnId)??y.sourceTurnId??"not assigned"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Source item"}),e.jsx("dd",{children:(h==null?void 0:h.sourceItemId)??y.id})]})]})}):null,n==="metadata"?e.jsxs("dl",{className:"control-detail-list",children:[e.jsx(Re,{label:"Timeline item id",value:y.id}),e.jsx(Re,{label:"Timeline kind",value:y.kind}),h?e.jsxs(e.Fragment,{children:[e.jsx(Re,{label:"Artifact id",value:h.id}),e.jsx(Re,{label:"Plugin id",value:h.pluginId}),e.jsx(Re,{label:"Artifact type",value:h.type}),e.jsx(Re,{label:"Created",value:ps(h.createdAt)}),e.jsx(Re,{label:"Source turn",value:h.sourceTurnId}),e.jsx(Re,{label:"Source item",value:h.sourceItemId})]}):e.jsxs(e.Fragment,{children:[e.jsx(Re,{label:"Detail id",value:g==null?void 0:g.id}),e.jsx(Re,{label:"Detail kind",value:g==null?void 0:g.kind})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Payload"}),e.jsx("dd",{children:e.jsx("pre",{children:JSON.stringify(h?h.payload:{item:y,detail:g},null,2)})})]})]}):null]})]})}const wd=[],Nd=[],Sd=[],kd={sessions:{list:!1,read:!0,resume:!0,importLocal:!1},turns:{start:!0,streamInput:!1,steer:!1,interrupt:!0,compact:!1},branching:{fork:!1,hardRollback:!1,resumeAt:!1,rewindFiles:!1},controls:{planMode:!1,permissionRequests:!1,sandboxMode:!1,performanceMode:!1,goals:!1},management:{models:!1,mcpStatus:!1,skills:!1,hooks:!1,hookTrust:!1,hostConfigFiles:!1,providerSettings:!1},usage:{contextWindow:!0,tokenUsage:!0,costUsd:!1}};function Cd(){const t=Qt();return t?{baseUrl:t.baseUrl,token:t.token}:null}function Vr(t){switch(t){case"idle":case"running":case"interrupted":case"failed":case"not_loaded":case"system_error":return t;case"active":return"idle";default:return"not_loaded"}}function tr(t,s,a){const n=a==null?void 0:a.thread;return{id:t.id,workspaceId:s.id,provider:t.provider,providerSessionId:t.workerSessionId??(n==null?void 0:n.providerSessionId)??null,source:"supervisor",title:t.title||(n==null?void 0:n.title)||"Remote session",model:(n==null?void 0:n.model)??null,reasoningEffort:(n==null?void 0:n.reasoningEffort)??null,fastMode:(n==null?void 0:n.fastMode)??!1,collaborationMode:(n==null?void 0:n.collaborationMode)??"default",approvalMode:(n==null?void 0:n.approvalMode)??"guarded",sandboxMode:(n==null?void 0:n.sandboxMode)??null,status:(n==null?void 0:n.status)??Vr(t.status),summaryText:(n==null?void 0:n.summaryText)??null,lastError:(n==null?void 0:n.lastError)??null,activeTurnId:(n==null?void 0:n.activeTurnId)??null,isLoaded:!!(n!=null&&n.isLoaded),isPinned:!1,createdAt:t.createdAt,updatedAt:(n==null?void 0:n.updatedAt)??t.updatedAt,lastTurnStartedAt:(n==null?void 0:n.lastTurnStartedAt)??t.lastActivityAt,lastTurnCompletedAt:(n==null?void 0:n.lastTurnCompletedAt)??null,...n!=null&&n.contextUsage?{contextUsage:n.contextUsage}:{}}}function Td(t,s,a){const n=new URL(`/api/sandboxes/${encodeURIComponent(t.sandboxId)}/api/threads/${encodeURIComponent(s)}/assets/image`,t.routerBaseUrl);return n.searchParams.set("path",a),n.toString()}const Id={status:"not_created",connectionButtonDisabled:!0,connectionButtonLabel:"Remote shell unavailable",shellInputEnabled:!1,isConnecting:!1,isCommandRunning:!1,promptLabel:"Remote shell adapter not connected",isMobileShell:!1,hasShell:!1,busy:!1,loading:!1,error:"Remote sandbox shell routing is not connected yet."};function Wn(t){return t instanceof re&&t.statusCode===401&&t.payload.code==="invalid_route_token"}function sr(t){return t instanceof re&&(t.statusCode===404||t.statusCode===409)}function Jr(t,s){return Object.is(t,s)?!0:JSON.stringify(t)===JSON.stringify(s)}function qn(t,s){let a=t.length!==s.length||t.some((o,m)=>{var h;return o.id!==((h=s[m])==null?void 0:h.id)});const n=new Map(t.map(o=>[o.id,o])),d=s.map(o=>{const m=n.get(o.id);return m&&Jr(m,o)?m:(a=!0,o)});return a?d:t}function un(t,s){return Jr(t,s)?t:s}function Ed(t,s){if(!t)return s;const a=qn(t.turns,zt(t.turns,s.turns)),n=qn(t.pendingRequests,ia(t.pendingRequests,s.pendingRequests,new Set)),d={...s,turns:a,pendingRequests:n,pendingSteers:qn(t.pendingSteers,s.pendingSteers)};return("answeredRequestNotes"in s||"answeredRequestNotes"in t)&&(d.answeredRequestNotes=un(t.answeredRequestNotes,s.answeredRequestNotes)??[]),("activityNotes"in s||"activityNotes"in t)&&(d.activityNotes=un(t.activityNotes,s.activityNotes)??[]),("livePlan"in s||"livePlan"in t)&&(d.livePlan=un(t.livePlan,s.livePlan)??null),("liveItems"in s||"liveItems"in t)&&(d.liveItems=un(t.liveItems,s.liveItems)??null),d}function Rd(){return e.jsx(Pd,{})}function Pd(){const{sessionId:t=""}=ur(),s=rt(),a=Jt(),n=r.useMemo(Cd,[]),[d,o]=r.useState(null),[m,h]=r.useState(null),[g,y]=r.useState(null),[A,x]=r.useState([]),[f,k]=r.useState(null),[C,E]=r.useState(null),[v,J]=r.useState(null),[te,_]=r.useState({prompt:"",attachments:[]}),[R,X]=r.useState(!0),[c,D]=r.useState(!1),[Y,I]=r.useState(null),[q,B]=r.useState(0),[ve,fe]=r.useState("chat"),[H,pe]=r.useState(!0),[T,le]=r.useState(null),oe=r.useRef(!1),W=r.useRef(null),F=r.useRef(null),z=r.useCallback(se=>{J(ie=>{const me=Ed(ie,se);return F.current=me,me})},[]),ue=r.useCallback(async se=>{if(!n)return null;const ie=await Ir(n,se.sandbox.id,{projectId:se.project.id,workspaceId:se.workspace.id,sessionId:se.session.id,scopes:gd});return E(ie),ie},[n]),xe=r.useCallback(async()=>!d||!m||!g||!f||d.state!=="running"?null:ue({sandbox:d,project:m,workspace:g,session:f}),[ue,m,d,f,g]),ot=r.useCallback(async()=>{if(!n)return s("/control-plane/login",{replace:!0}),null;X(!0),I(null);try{const se=await ha(n);if(o(se.sandbox),se.sandbox.state!=="running")return k(null),E(null),J(null),F.current=null,I("Sandbox is not running. Start the sandbox from the control plane before opening chat."),null;const ie=await Cr(n);for(const me of ie.projects){const he=await aa(n,me.id);for(const ke of he.workspaces){const V=await ra(n,ke.id),Qe=V.sessions.find(gt=>gt.id===t);if(!Qe)continue;const Me=await Tr(n,Qe.id),et=V.sessions.map(gt=>gt.id===Me.session.id?Me.session:gt),xt=await ue({sandbox:se.sandbox,project:me,workspace:ke,session:Me.session});if(!xt)return I("Unable to issue a router token for this session."),null;if(h(me),y(ke),x(et),k(Me.session),!Me.session.workerSessionId)return J(null),F.current=null,I("Session resumed, but the worker did not return a thread id."),null;const Dt=await us(xt,Me.session.workerSessionId);return z(Dt),B(gt=>gt+1),{session:Me.session,token:xt,detail:Dt}}}return I("Session was not found in any project workspace."),null}catch(se){return se instanceof re&&se.payload.code==="unauthorized"?(jn(),s("/control-plane/login",{replace:!0}),null):(I(se instanceof Error?se.message:"Unable to open control-plane session."),null)}finally{X(!1)}},[z,n,ue,s,t]);r.useEffect(()=>{ot()},[ot]),r.useEffect(()=>{le(null)},[t]),r.useEffect(()=>{if(W.current&&(window.clearTimeout(W.current),W.current=null),!C)return;const se=Date.parse(C.expiresAt);if(!Number.isFinite(se))return;const ie=Math.max(fd,Math.min(xd,se-Date.now()-pd));return W.current=window.setTimeout(()=>{xe().catch(me=>{I(me instanceof Error?me.message:"Unable to refresh router token.")})},ie),()=>{W.current&&(window.clearTimeout(W.current),W.current=null)}},[xe,C]);const ct=r.useCallback(async(se={})=>{if(!(!C||!(f!=null&&f.workerSessionId))){se.silent||I(null);try{z(await us(C,f.workerSessionId))}catch(ie){if(Wn(ie))try{const me=await xe();if(me&&f.workerSessionId){z(await us(me,f.workerSessionId));return}}catch(me){I(me instanceof Error?me.message:"Unable to refresh worker thread.");return}if(sr(ie)&&!oe.current){oe.current=!0;try{await ot();return}finally{oe.current=!1}}I(ie instanceof Error?ie.message:"Unable to refresh worker thread.")}}},[z,ot,xe,C,f==null?void 0:f.workerSessionId]);r.useEffect(()=>{if(!((v==null?void 0:v.thread.status)==="running"||!!(v!=null&&v.thread.activeTurnId)||c)||!C||!(f!=null&&f.workerSessionId))return;const ie=window.setInterval(()=>{ct({silent:!0})},hd);return()=>window.clearInterval(ie)},[v==null?void 0:v.thread.activeTurnId,v==null?void 0:v.thread.status,ct,C,c,f==null?void 0:f.workerSessionId]);async function Ye(se){const ie=se.prompt.trim();if(!ie||!C||!(f!=null&&f.workerSessionId))return!1;D(!0),I(null);try{return await $n(C,f.workerSessionId,{prompt:ie}),_({prompt:"",attachments:[]}),await ct(),B(me=>me+1),!0}catch(me){if(Wn(me))try{const he=await xe();if(!he||!f.workerSessionId)throw me;await $n(he,f.workerSessionId,{prompt:ie});const ke=await us(he,f.workerSessionId);return z(ke),_({prompt:"",attachments:[]}),B(V=>V+1),!0}catch(he){return I(he instanceof Error?he.message:"Unable to send prompt."),!1}if(sr(me)&&!oe.current){oe.current=!0;try{const he=await ot();if(!(he!=null&&he.session.workerSessionId))throw me;await $n(he.token,he.session.workerSessionId,{prompt:ie});const ke=await us(he.token,he.session.workerSessionId);return z(ke),_({prompt:"",attachments:[]}),B(V=>V+1),!0}catch(he){return I(he instanceof Error?he.message:"Unable to send prompt."),!1}finally{oe.current=!1}}return I(me instanceof Error?me.message:"Unable to send prompt."),!1}finally{D(!1)}}async function wt(){var se,ie;if(!(!C||!(f!=null&&f.workerSessionId))){D(!0),I(null);try{const me=((se=F.current)==null?void 0:se.thread.activeTurnId)??void 0,he=await Ha(C,f.workerSessionId,me?{turnId:me}:{});J(ke=>ke&&{...ke,thread:he}),await ct({silent:!0})}catch(me){if(Wn(me))try{const he=await xe();if(!he||!f.workerSessionId)throw me;const ke=((ie=F.current)==null?void 0:ie.thread.activeTurnId)??void 0,V=await Ha(he,f.workerSessionId,ke?{turnId:ke}:{});J(Qe=>Qe&&{...Qe,thread:V}),z(await us(he,f.workerSessionId));return}catch(he){I(he instanceof Error?he.message:"Unable to interrupt turn.");return}I(me instanceof Error?me.message:"Unable to interrupt turn.")}finally{D(!1)}}}const ze=C?f!=null&&f.workerSessionId?void 0:"Reconnect this session before sending a prompt.":"Waiting for a router token...",ut=g?A.map(se=>tr(se,g,se.id===(f==null?void 0:f.id)?v:null)):[],_e=f&&g?tr(f,g,v):null,mt=_e&&ut.every(se=>se.id!==_e.id)?[_e,...ut]:ut,Ze=(v==null?void 0:v.thread.status)??Vr(f==null?void 0:f.status),b=fr(Ze),j=(v==null?void 0:v.thread.lastTurnStartedAt)??(v==null?void 0:v.thread.updatedAt)??(f==null?void 0:f.lastActivityAt)??(f==null?void 0:f.updatedAt)??null,M=(f==null?void 0:f.provider)??(v==null?void 0:v.thread.provider)??"codex",Q=(v==null?void 0:v.thread.model)??"default model",ge=(C==null?void 0:C.expiresAt)??null,Oe=e.jsxs("div",{className:"control-session-meta",children:[e.jsxs("dl",{className:"control-detail-list compact summary two",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Status"}),e.jsx("dd",{children:b})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Provider"}),e.jsx("dd",{children:M})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Workspace"}),e.jsx("dd",{children:(g==null?void 0:g.name)??(v==null?void 0:v.workspace.label)??"Unavailable"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Project"}),e.jsx("dd",{children:(m==null?void 0:m.name)??"None"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Model"}),e.jsx("dd",{children:Q})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Last activity"}),e.jsx("dd",{children:bd(j)})]})]}),e.jsx(vd,{title:"Diagnostics",children:e.jsxs("dl",{className:"control-detail-list",children:[e.jsx(Re,{label:"Control session id",value:(f==null?void 0:f.id)??t}),e.jsx(Re,{label:"Worker thread id",value:f==null?void 0:f.workerSessionId}),e.jsx(Re,{label:"Workspace path",value:(g==null?void 0:g.path)??(v==null?void 0:v.workspace.absPath)}),e.jsx(Re,{label:"Workspace id",value:g==null?void 0:g.id}),e.jsx(Re,{label:"Project id",value:m==null?void 0:m.id}),e.jsx(Re,{label:"Sandbox id",value:d==null?void 0:d.id}),e.jsx(Re,{label:"Router URL",value:(C==null?void 0:C.routerBaseUrl)??(d==null?void 0:d.routerBaseUrl)}),e.jsx(Re,{label:"Image",value:d==null?void 0:d.image}),e.jsx(Re,{label:"Worker service",value:d==null?void 0:d.workerServiceName}),e.jsx(Re,{label:"Session updated",value:ps((f==null?void 0:f.updatedAt)??null)}),e.jsx(Re,{label:"Route token expires",value:ps(ge)})]})})]}),Pe=e.jsx("div",{className:"space-y-4 text-sm",children:e.jsxs("section",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs uppercase tracking-[0.2em] text-[var(--theme-fg-muted)]",children:"Remote Session"}),e.jsx("button",{type:"button",onClick:()=>void ot(),disabled:R,className:"block w-full rounded-xl border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-2 text-left text-sm text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:opacity-60",children:R?"Reconnecting...":"Reconnect session"}),e.jsx("button",{type:"button",onClick:()=>void ct(),disabled:!C,className:"block w-full rounded-xl border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-2 text-left text-sm text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:opacity-60",children:"Refresh worker thread"})]})}),Xe=r.useCallback(se=>{le({kind:"artifact",...se})},[]),ht=r.useCallback(se=>{le({kind:"historyDetail",...se})},[]),Ve=r.useCallback(async se=>{if(!C||!(f!=null&&f.workerSessionId))throw new Error("Reconnect this session before loading item details.");return ll(C,f.workerSessionId,se)},[C,f==null?void 0:f.workerSessionId]),pt=r.useMemo(()=>({scrollRequestKey:q,className:"thread-timeline-surface min-h-0 flex-1",onTailVisibilityChange:pe,answeredRequestNotes:(v==null?void 0:v.answeredRequestNotes)??wd,activityNotes:(v==null?void 0:v.activityNotes)??Nd,pendingSteers:(v==null?void 0:v.pendingSteers)??Sd,onLoadHistoryItemDetail:Ve,onSelectArtifact:Xe,onSelectHistoryItemDetail:ht}),[v==null?void 0:v.activityNotes,v==null?void 0:v.answeredRequestNotes,v==null?void 0:v.pendingSteers,Xe,ht,Ve,q]),$e=v?{busy:c,error:Y,model:v.thread.model,reasoningEffort:v.thread.reasoningEffort,fastMode:v.thread.fastMode??!1,collaborationMode:v.thread.collaborationMode,contextUsage:v.thread.contextUsage,capabilities:kd,toolboxItems:[],followTail:H,threadConnected:v.thread.isLoaded,disabled:!!ze,...ze?{disabledPlaceholder:ze}:{},draftPrompt:te.prompt,draftAttachments:te.attachments,onDraftChange:_,canInterrupt:!!v.thread.activeTurnId,onInterrupt:wt,shellControlState:Id,onToggleView:()=>fe("shell"),onToggleFollow:()=>B(se=>se+1)}:null,Et=e.jsx("span",{className:"control-session-status-badge",children:b}),Lt=e.jsx("div",{className:"flex min-h-0 flex-1 items-center justify-center p-4 sm:p-6",children:e.jsxs("div",{className:"thread-empty-surface max-w-md rounded-[1.6rem] border px-6 py-8 text-center",children:[e.jsx("p",{className:"text-base font-medium text-[var(--theme-fg)]",children:"Remote shell transport unavailable"}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-[var(--theme-fg-muted)]",children:"The Terminal plugin is enabled, but this control-plane route does not yet provide the remote shell API adapter used by the main supervisor thread page."}),e.jsx("button",{type:"button",onClick:()=>fe("chat"),className:"mt-5 inline-flex h-9 items-center rounded-full border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-4 text-sm font-medium text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--theme-ring)] focus:ring-offset-2 focus:ring-offset-[var(--theme-surface)]",children:"Switch to chat"})]})}),Gt=r.useCallback(se=>C&&(f!=null&&f.workerSessionId)?Td(C,f.workerSessionId,se):"",[C,f==null?void 0:f.workerSessionId]),Kt=r.useMemo(()=>({openThread:se=>{s(`/control-plane/sessions/${se}`)},getThreadHref:se=>`/control-plane/sessions/${se}`,getNewThreadHref:()=>"/control-plane",sendPrompt:Ye,interrupt:wt,getImageAssetUrl:Gt,shell:null}),[Gt,s]);return e.jsxs("div",{className:"control-chat-workspace",children:[e.jsx(pr,{threads:mt,detail:v,status:null,loading:R,error:R?null:Y,adapter:Kt,currentWorkspaceId:(g==null?void 0:g.id)??null,currentWorkspaceLabel:(g==null?void 0:g.name)??(v==null?void 0:v.workspace.label)??null,metaContent:Oe,settingsContent:Pe,surfaceActions:Et,appMenuButton:e.jsx(bo,{}),appNavigationMenu:e.jsx(go,{currentPath:`/control-plane/sessions/${t}`,items:[{label:"Control Plane",href:"/control-plane"},{label:"Workspaces",href:"/workspaces"}],onNavigate:s}),onCloseAppNavigation:(a==null?void 0:a.closeNav)??(()=>{}),activeView:ve,timelineProps:pt,shellEffectiveTheme:(a==null?void 0:a.effectiveTheme)??"dark",shellThemeMode:(a==null?void 0:a.themeMode)??"system",...a!=null&&a.setThemeMode?{onShellThemeModeChange:a.setThemeMode}:{},shellUnavailableContent:Lt,shellDisconnectedContent:Lt,shellContent:Lt,loadingContent:e.jsx("div",{className:"flex flex-1 items-center justify-center px-6 py-12 text-center text-[var(--theme-fg-muted)]",children:"Opening worker thread..."}),emptyContent:e.jsx("div",{className:"flex flex-1 items-center justify-center px-6 py-12 text-center text-[var(--theme-fg-muted)]",children:"No worker thread is connected yet."}),...f?{currentThreadId:f.id}:{},...$e?{composerProps:$e}:{}}),T?e.jsx("div",{className:"control-artifact-inspector-overlay",children:e.jsx(yd,{selected:T,onClose:()=>le(null)})}):null]})}function Ad({onLogin:t}){const[s,a]=r.useState(""),[n,d]=r.useState(""),[o,m]=r.useState(null),[h,g]=r.useState(!1);async function y(A){A.preventDefault(),m(null),g(!0);try{await t({username:s,password:n})}catch(x){x instanceof re?m(x.payload.message):m("Unable to sign in.")}finally{g(!1)}}return e.jsx("main",{className:"flex min-h-screen items-center justify-center bg-[var(--app-bg)] px-4 py-8 text-[var(--app-fg)]",children:e.jsxs("section",{className:"w-full max-w-sm rounded-[1.35rem] border border-[var(--theme-border)] bg-[var(--theme-panel)] p-5 shadow-2xl shadow-[color-mix(in_oklch,var(--app-fg)_14%,transparent)] sm:p-6",children:[e.jsxs("div",{className:"mb-5",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-muted)]",children:"Supervisor Access"}),e.jsx("h1",{className:"mt-2 text-2xl font-semibold tracking-normal text-[var(--theme-fg)]",children:"Sign in"}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-[var(--theme-muted)]",children:"Use the admin credentials configured on this Remote Codex server."})]}),e.jsxs("form",{onSubmit:y,className:"space-y-4",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm font-medium text-[var(--theme-fg-soft)]",children:"Username"}),e.jsx("input",{autoComplete:"username",autoFocus:!0,className:"mt-2 h-11 w-full rounded-xl border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 text-sm text-[var(--theme-fg)] outline-none transition focus:border-[var(--theme-accent-solid)] focus:ring-2 focus:ring-[var(--theme-accent-border)]",disabled:h,name:"username",onChange:A=>a(A.target.value),value:s})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm font-medium text-[var(--theme-fg-soft)]",children:"Password"}),e.jsx("input",{autoComplete:"current-password",className:"mt-2 h-11 w-full rounded-xl border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 text-sm text-[var(--theme-fg)] outline-none transition focus:border-[var(--theme-accent-solid)] focus:ring-2 focus:ring-[var(--theme-accent-border)]",disabled:h,name:"password",onChange:A=>d(A.target.value),type:"password",value:n})]}),o&&e.jsx("p",{className:"rounded-xl border border-[var(--status-danger-border)] bg-[var(--status-danger-bg)] px-3 py-2 text-sm text-[var(--status-danger-fg)]",children:o}),e.jsx("button",{className:"h-11 w-full rounded-xl bg-[var(--theme-accent-solid)] px-4 text-sm font-semibold text-[var(--theme-accent-solid-fg)] transition hover:bg-[var(--theme-accent-solid-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--theme-accent-border)] disabled:cursor-not-allowed disabled:opacity-60",disabled:h||!s.trim()||!n,type:"submit",children:h?"Signing in...":"Sign in"})]})]})})}function zn(t,s){return t instanceof re?t.payload.message:t instanceof Error?t.message:s}function Ud(){var I;const[t,s]=r.useState(null),[a,n]=r.useState(""),[d,o]=r.useState(""),[m,h]=r.useState(""),[g,y]=r.useState(""),[A,x]=r.useState(!0),[f,k]=r.useState(!1),[C,E]=r.useState(!1),[v,J]=r.useState(null),[te,_]=r.useState(null),[R,X]=r.useState(!1);async function c(){var q;x(!0),_(null);try{xs();const B=await $s();s(B),n(((q=B.user)==null?void 0:q.username)??"")}catch(B){_(zn(B,"Unable to load account."))}finally{x(!1)}}r.useEffect(()=>{c()},[]);async function D(q){q.preventDefault(),k(!0),_(null),J(null);try{const B=await hl({username:a});s(ve=>ve!=null&&ve.authenticated?{...ve,user:B}:ve),n(B.username),J("Account updated.")}catch(B){_(zn(B,"Unable to update account."))}finally{k(!1)}}async function Y(q){q.preventDefault(),E(!0),_(null),J(null);try{if(m!==g){_("New passwords do not match.");return}await pl({currentPassword:d,newPassword:m}),o(""),h(""),y(""),J("Password changed.")}catch(B){_(zn(B,"Unable to change password."))}finally{E(!1)}}return e.jsx("main",{className:"min-h-screen bg-[var(--app-bg)] px-4 py-6 text-[var(--app-fg)] sm:px-6",children:e.jsxs("div",{className:"mx-auto w-full max-w-4xl space-y-5 pr-12 sm:pr-0",children:[e.jsxs("header",{className:"border-b border-[var(--theme-border)] pb-5",children:[e.jsx(It,{className:"text-sm text-[var(--theme-accent-strong)]",to:"/workspaces",children:"Back to workspaces"}),e.jsx("p",{className:"mt-4 text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-fg-muted)]",children:"Relay Account"}),e.jsx("h1",{className:"mt-2 text-2xl font-semibold text-[var(--theme-fg)]",children:"Account settings"})]}),A?e.jsx("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4 text-sm text-[var(--theme-fg-muted)]",children:"Loading account..."}):t!=null&&t.authenticated?e.jsxs(e.Fragment,{children:[te?e.jsx(nr,{tone:"danger",children:te}):null,v?e.jsx(nr,{tone:"success",children:v}):null,e.jsxs("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:"Profile"}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"Username changes apply to future shares and login."})]}),e.jsxs("form",{className:"space-y-4",onSubmit:D,children:[e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Email",e.jsx("input",{className:"relay-input mt-2 w-full",disabled:!0,readOnly:!0,value:((I=t.user)==null?void 0:I.email)??""})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-end",children:[e.jsxs("label",{className:"block flex-1 text-sm text-[var(--theme-fg-soft)]",children:["Username",e.jsx("input",{className:"relay-input mt-2 w-full",onChange:q=>n(q.target.value),value:a})]}),e.jsxs("button",{className:"relay-button-primary inline-flex h-10 items-center justify-center gap-2",disabled:f||!a.trim(),type:"submit",children:[e.jsx(at.Save,{className:"h-4 w-4"}),"Save"]})]}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-2",onClick:()=>X(!0),type:"button",children:[R?e.jsx(at.CheckCircle2,{className:"h-4 w-4"}):e.jsx(at.MailCheck,{className:"h-4 w-4"}),R?"Verification queued":"Verify email"]})]})]}),e.jsxs("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:"Password"}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"Use at least 8 characters."})]}),e.jsxs("form",{className:"grid gap-4 sm:grid-cols-3",onSubmit:Y,children:[e.jsx(Vn,{label:"Current password",value:d,onChange:o}),e.jsx(Vn,{label:"New password",value:m,onChange:h}),e.jsx(Vn,{label:"Confirm password",value:g,onChange:y}),e.jsxs("button",{className:"relay-button-primary inline-flex h-10 items-center justify-center gap-2 sm:col-span-3 sm:w-fit",disabled:C||!d||m.length<8||!g,type:"submit",children:[e.jsx(at.Save,{className:"h-4 w-4"}),"Change password"]})]})]})]}):e.jsx("section",{className:"rounded-lg border border-[var(--status-danger-border)] bg-[var(--status-danger-bg)] p-4 text-sm text-[var(--status-danger-fg)]",children:"Relay login is required."})]})})}function Vn({label:t,value:s,onChange:a}){return e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:[t,e.jsx("input",{autoComplete:"new-password",className:"relay-input mt-2 w-full",onChange:n=>a(n.target.value),type:"password",value:s})]})}function nr({tone:t,children:s}){return e.jsx("div",{className:`rounded-lg border px-3 py-2 text-sm ${t==="danger"?"border-[var(--status-danger-border)] bg-[var(--status-danger-bg)] text-[var(--status-danger-fg)]":"border-[var(--status-success-border)] bg-[var(--status-success-bg)] text-[var(--status-success-fg)]"}`,children:s})}function Jn(t){return t instanceof re?t.payload.message:t instanceof Error?t.message:"Unable to update relay admin state."}function Od(){const[t,s]=r.useState(null),[a,n]=r.useState(!0),[d,o]=r.useState(null),[m,h]=r.useState(null);async function g(){n(!0),o(null);try{xs(),s(await gl())}catch(x){o(Jn(x))}finally{n(!1)}}r.useEffect(()=>{g()},[]);async function y(x){h("registration"),o(null);try{const f=await bl(x);s(k=>k&&{...k,registrationEnabled:f.registrationEnabled})}catch(f){o(Jn(f))}finally{h(null)}}async function A(x,f){h(x),o(null);try{const k=await vl(x,f);s(C=>C&&{...C,users:C.users.map(E=>E.id===k.id?k:E)})}catch(k){o(Jn(k))}finally{h(null)}}return e.jsxs("main",{className:"min-h-screen bg-[var(--app-bg)] px-4 py-6 text-[var(--app-fg)] sm:px-6",children:[e.jsx(ga,{}),e.jsxs("div",{className:"mx-auto flex w-full max-w-6xl flex-col gap-5",children:[e.jsxs("header",{className:"flex flex-col gap-3 border-b border-[var(--theme-border)] pb-5 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-fg-muted)]",children:"Relay Admin"}),e.jsx("h1",{className:"mt-2 text-2xl font-semibold text-[var(--theme-fg)]",children:"Users and devices"}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"Manage relay accounts, registration, and connected devices."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(It,{className:"relay-button-secondary",to:"/relay-portal",children:"Portal"}),e.jsx("button",{className:"relay-button-secondary",onClick:()=>void g(),type:"button",children:"Refresh"})]})]}),a?e.jsx("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4 text-sm text-[var(--theme-fg-muted)]",children:"Loading relay admin..."}):d?e.jsx("section",{className:"rounded-lg border border-[var(--status-danger-border)] bg-[var(--status-danger-bg)] p-4 text-sm text-[var(--status-danger-fg)]",children:d}):t?e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:"Registration"}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"New users can create relay accounts without email verification."})]}),e.jsx("button",{className:"relay-button-primary",disabled:m==="registration",onClick:()=>void y(!t.registrationEnabled),type:"button",children:t.registrationEnabled?"Disable":"Enable"})]})}),e.jsxs("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:"Users"}),e.jsx("div",{className:"mt-4 overflow-x-auto",children:e.jsxs("table",{className:"w-full min-w-[44rem] border-collapse text-left text-sm",children:[e.jsx("thead",{className:"text-xs uppercase tracking-[0.16em] text-[var(--theme-fg-muted)]",children:e.jsxs("tr",{children:[e.jsx("th",{className:"border-b border-[var(--theme-border)] py-2 pr-3",children:"User"}),e.jsx("th",{className:"border-b border-[var(--theme-border)] py-2 pr-3",children:"Email"}),e.jsx("th",{className:"border-b border-[var(--theme-border)] py-2 pr-3",children:"Role"}),e.jsx("th",{className:"border-b border-[var(--theme-border)] py-2 pr-3",children:"Status"}),e.jsx("th",{className:"border-b border-[var(--theme-border)] py-2 pr-3",children:"Actions"})]})}),e.jsx("tbody",{children:t.users.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"border-b border-[var(--theme-border)] py-3 pr-3 font-medium text-[var(--theme-fg)]",children:x.username}),e.jsx("td",{className:"border-b border-[var(--theme-border)] py-3 pr-3 text-[var(--theme-fg-muted)]",children:x.email}),e.jsx("td",{className:"border-b border-[var(--theme-border)] py-3 pr-3 text-[var(--theme-fg-muted)]",children:x.role}),e.jsx("td",{className:"border-b border-[var(--theme-border)] py-3 pr-3 text-[var(--theme-fg-muted)]",children:x.enabled?"Enabled":"Disabled"}),e.jsx("td",{className:"border-b border-[var(--theme-border)] py-3 pr-3",children:e.jsx("button",{className:"relay-button-secondary",disabled:m===x.id||x.role==="admin",onClick:()=>void A(x.id,!x.enabled),type:"button",children:x.enabled?"Disable":"Enable"})})]},x.id))})]})})]}),e.jsxs("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:"Devices"}),e.jsx("div",{className:"mt-4 grid gap-3 lg:grid-cols-2",children:t.devices.map(x=>e.jsxs("article",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`h-2.5 w-2.5 rounded-full ${x.connected?"bg-emerald-500":"bg-[var(--theme-fg-muted)]"}`}),e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:x.name})]}),e.jsx("p",{className:"mt-2 font-mono text-xs text-[var(--theme-fg-muted)]",children:x.id}),e.jsxs("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:["Owner: ",x.ownerUserId]})]},x.id))})]})]}):null]})]})}function Gn(t,s){return t instanceof re?t.payload.message:t instanceof Error?t.message:s}function $d(){const t=rt(),[s,a]=r.useState(null),[n,d]=r.useState(""),[o,m]=r.useState(null),[h,g]=r.useState(null),[y,A]=r.useState(!0),[x,f]=r.useState(null),[k,C]=r.useState(null);async function E(){A(!0),C(null);try{xs(),a(await Rr())}catch(R){C(Gn(R,"Unable to load devices."))}finally{A(!1)}}r.useEffect(()=>{E()},[]);async function v(R){R.preventDefault(),f("create"),C(null);try{const X=await Pr({name:n});m(X),d(""),await E()}catch(X){C(Gn(X,"Unable to create device."))}finally{f(null)}}async function J(R){f(R.id),C(null);try{await Ar(R.id),(o==null?void 0:o.device.id)===R.id&&m(null),await E()}catch(X){C(Gn(X,"Unable to delete device."))}finally{f(null)}}function te(R){bn(R.id),vn(null),t("/workspaces")}async function _(R){var c;const X=R.token;if(!X){C("This device token is not available. Create a new device token for devices created before token storage was enabled.");return}try{await((c=navigator.clipboard)==null?void 0:c.writeText(Gr(X))),g(R.id),window.setTimeout(()=>{g(D=>D===R.id?null:D)},1600)}catch{}}return e.jsx("main",{className:"min-h-screen bg-[var(--app-bg)] px-4 py-6 text-[var(--app-fg)] sm:px-6",children:e.jsxs("div",{className:"mx-auto w-full max-w-6xl space-y-5 pr-12 sm:pr-0",children:[e.jsxs("header",{className:"flex flex-col gap-3 border-b border-[var(--theme-border)] pb-5 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{children:[e.jsx(It,{className:"text-sm text-[var(--theme-accent-strong)]",to:"/workspaces",children:"Back to workspaces"}),e.jsx("p",{className:"mt-4 text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-fg-muted)]",children:"Relay Devices"}),e.jsx("h1",{className:"mt-2 text-2xl font-semibold text-[var(--theme-fg)]",children:"Device management"})]}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-2",onClick:()=>void E(),type:"button",children:[e.jsx(at.RefreshCcw,{className:"h-4 w-4"}),"Refresh"]})]}),k?e.jsx(Dd,{tone:"danger",children:k}):null,o?e.jsx(Ld,{result:o}):null,e.jsxs("section",{className:"grid gap-4 lg:grid-cols-[minmax(20rem,0.8fr)_minmax(0,1.2fr)]",children:[e.jsxs("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsxs("div",{className:"mb-4 flex items-start gap-3",children:[e.jsx("span",{className:"inline-flex h-9 w-9 items-center justify-center rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] text-[var(--theme-fg)]",children:e.jsx(at.Plus,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:"Add device"}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"Create a token for one private supervisor."})]})]}),e.jsxs("form",{className:"space-y-3",onSubmit:v,children:[e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Device name",e.jsx("input",{className:"relay-input mt-2 w-full",onChange:R=>d(R.target.value),placeholder:"MacBook Pro",value:n})]}),e.jsxs("button",{className:"relay-button-primary inline-flex h-10 w-full items-center justify-center gap-2",disabled:x==="create"||!n.trim(),type:"submit",children:[e.jsx(at.MonitorSmartphone,{className:"h-4 w-4"}),"Create device token"]})]})]}),e.jsxs("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:"Devices"}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"Connect to an online device before opening workspaces."})]}),e.jsx("span",{className:"rounded-full border border-[var(--theme-border)] px-2 py-0.5 text-xs text-[var(--theme-fg-muted)]",children:(s==null?void 0:s.devices.length)??0})]}),y?e.jsx("p",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-4 text-sm text-[var(--theme-fg-muted)]",children:"Loading devices..."}):s!=null&&s.devices.length?e.jsx("div",{className:"space-y-3",children:s.devices.map(R=>e.jsx(Md,{busy:x===R.id,copiedSetup:h===R.id,device:R,onConnect:()=>te(R),onCopySetup:()=>void _(R),onDelete:()=>void J(R),setupTokenAvailable:!!R.token},R.id))}):e.jsx("div",{className:"rounded-lg border border-dashed border-[var(--theme-border)] bg-[var(--theme-surface)] p-5 text-sm text-[var(--theme-fg-muted)]",children:"No devices yet. Create a token, then start `remote-codex relay-supervisor` on your private machine."})]})]})]})})}function Md({device:t,busy:s,copiedSetup:a,onConnect:n,onCopySetup:d,onDelete:o,setupTokenAvailable:m}){return e.jsxs("article",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-3",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:`h-2.5 w-2.5 rounded-full ${t.connected?"bg-[var(--status-success-fg)]":"bg-[var(--theme-fg-muted)]"}`}),e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:t.name})]}),e.jsx("p",{className:"mt-1 font-mono text-xs text-[var(--theme-fg-muted)]",children:t.tokenPreview}),e.jsx("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:t.connected?`Online since ${or(t.connectedAt)}`:`Offline. Last heartbeat: ${or(t.lastHeartbeatAt)}`})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-2",onClick:d,title:m?"Copy relay supervisor setup command":"Device token is not available. Create a new device token for devices created before token storage was enabled.",disabled:!m,type:"button",children:[e.jsx(at.Copy,{className:"h-4 w-4"}),a?"Copied":"Copy setup"]}),e.jsxs("button",{className:"relay-button-primary inline-flex items-center gap-2",disabled:!t.connected,onClick:n,type:"button",children:[e.jsx(at.Plug,{className:"h-4 w-4"}),"Connect"]}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-2",disabled:s,onClick:o,type:"button",children:[e.jsx(at.Trash2,{className:"h-4 w-4"}),"Delete"]})]})]}),m?null:e.jsx("p",{className:"mt-3 rounded-md border border-[var(--theme-border)] bg-[var(--theme-panel)] px-3 py-2 text-xs text-[var(--theme-fg-muted)]",children:"Token not available for this device. Create a new device token to copy a ready-to-run setup command."})]})}function Ld({result:t}){const s=Gr(t.token);return e.jsxs("section",{className:"rounded-lg border border-[var(--theme-accent-border)] bg-[var(--theme-accent-soft)] p-4",children:[e.jsxs("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:["Token created for ",t.device.name]}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"Store this token now. It will not be shown again."}),e.jsx(ar,{label:"Device token",value:t.token}),e.jsx(ar,{label:"Supervisor command",value:s})]})}function ar({label:t,value:s}){async function a(){var n;try{await((n=navigator.clipboard)==null?void 0:n.writeText(s))}catch{}}return e.jsxs("div",{className:"mt-3",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-[0.14em] text-[var(--theme-fg-muted)]",children:t}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-1 px-2 py-1 text-xs",onClick:()=>void a(),type:"button",children:[e.jsx(at.Copy,{className:"h-3.5 w-3.5"}),"Copy"]})]}),e.jsx("code",{className:"block break-all rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] px-3 py-2 font-mono text-xs text-[var(--theme-fg)]",children:s})]})}function Dd({tone:t,children:s}){return e.jsx("div",{className:"rounded-lg border border-[var(--status-danger-border)] bg-[var(--status-danger-bg)] px-3 py-2 text-sm text-[var(--status-danger-fg)]",children:s})}function Gr(t){const s=Hd();return[`REMOTE_CODEX_RELAY_SERVER_URL=${rr(s)} \\`,`REMOTE_CODEX_RELAY_AGENT_TOKEN=${rr(t)} \\`,"remote-codex relay-supervisor"].join(`
|
|
6
|
-
`)}function rr(t){return/^[A-Za-z0-9_./:@%+=,~-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function Hd(){return typeof window>"u"?"wss://relay.example.com":window.location.origin.replace(/^https:\/\//,"wss://").replace(/^http:\/\//,"ws://")}function or(t){return t?new Date(t).toLocaleString():"never"}function kn(t,s){return t instanceof re?t.payload.message:t instanceof Error?t.message:s}function Kr(){var R,X;const t=rt(),[s,a]=r.useState(null),[n,d]=r.useState(null),[o,m]=r.useState(!0),[h,g]=r.useState(null),[y,A]=r.useState(null);async function x(){m(!0),g(null);try{xs();const c=await $s();a(c),c.authenticated?d(await Rr()):d(null)}catch(c){g(kn(c,"Unable to load relay portal."))}finally{m(!1)}}r.useEffect(()=>{x()},[]);async function f(){A(null),await x()}async function k(c){const D=await Pr({name:c});A(D),await x()}async function C(c){await Ar(c),await x()}async function E(c){await fl(c),await x()}async function v(c){await xl(c),await x()}async function J(){await Er(),a(await $s()),d(null),A(null)}function te(c){bn(c),vn(null),t("/workspaces")}function _(c,D){bn(c),vn(D),t(`/threads/${encodeURIComponent(D)}`)}return o?e.jsx(Kn,{children:"Checking relay session..."}):s!=null&&s.authenticated?e.jsx(Kn,{children:e.jsxs("div",{className:"mx-auto flex w-full max-w-6xl flex-col gap-5",children:[e.jsxs("header",{className:"flex flex-col gap-3 border-b border-[var(--theme-border)] pb-5 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-fg-muted)]",children:"Relay Portal"}),e.jsx("h1",{className:"mt-2 text-2xl font-semibold text-[var(--theme-fg)]",children:(R=s.user)==null?void 0:R.username}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"Manage devices and shared Remote Codex sessions."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[((X=s.user)==null?void 0:X.role)==="admin"?e.jsx(It,{className:"relay-button-secondary",to:"/relay-admin",children:"Admin"}):null,e.jsx("button",{className:"relay-button-secondary",onClick:()=>void x(),type:"button",children:"Refresh"}),e.jsx("button",{className:"relay-button-secondary",onClick:()=>void J(),type:"button",children:"Sign out"})]})]}),h?e.jsx(da,{tone:"danger",children:h}):null,y?e.jsxs(da,{tone:"accent",children:["Device token for ",y.device.name,". Store it on the device as REMOTE_CODEX_RELAY_AGENT_TOKEN. It will not be shown again.",e.jsx("code",{className:"mt-2 block break-all rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] px-3 py-2 font-mono text-xs",children:y.token}),e.jsx("code",{className:"mt-2 block break-all rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] px-3 py-2 font-mono text-xs",children:Wd(y.token)})]}):null,e.jsxs("section",{className:"grid gap-4 lg:grid-cols-[minmax(0,1.2fr)_minmax(20rem,0.8fr)]",children:[e.jsxs(Yn,{title:"Devices",description:"Owned devices and sessions shared with you.",children:[e.jsx(Bd,{onCreate:k}),e.jsx("div",{className:"mt-4 divide-y divide-[var(--theme-border)] rounded-lg border border-[var(--theme-border)]",children:n!=null&&n.devices.length?n.devices.map(c=>e.jsxs("div",{className:"flex flex-col gap-3 p-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`h-2.5 w-2.5 rounded-full ${c.connected?"bg-emerald-500":"bg-[var(--theme-fg-muted)]"}`}),e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:c.name})]}),e.jsx("p",{className:"mt-1 font-mono text-xs text-[var(--theme-fg-muted)]",children:c.tokenPreview}),e.jsx("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:c.connected?`Online. Last heartbeat: ${lr(c.lastHeartbeatAt??c.connectedAt)}`:`Offline. Last online: ${lr(c.lastHeartbeatAt??c.connectedAt)}`})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{className:"relay-button-primary",disabled:!c.connected,onClick:()=>te(c.id),type:"button",children:"Open"}),e.jsx("button",{className:"relay-button-secondary",onClick:()=>void C(c.id),type:"button",children:"Delete"})]})]},c.id)):e.jsx("p",{className:"p-3 text-sm text-[var(--theme-fg-muted)]",children:"No devices yet."})}),e.jsxs("div",{className:"mt-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("h3",{className:"text-sm font-semibold text-[var(--theme-fg)]",children:"Shared"}),e.jsx("span",{className:"rounded-full border border-[var(--theme-border)] px-2 py-0.5 text-[11px] text-[var(--theme-fg-muted)]",children:(n==null?void 0:n.sharedWithMe.length)??0})]}),e.jsx("div",{className:"mt-3 space-y-3",children:n!=null&&n.sharedWithMe.length?n.sharedWithMe.map(c=>e.jsx("article",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-3",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:c.label||c.threadId}),e.jsxs("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:[c.ownerUsername," / ",c.deviceName]})]}),e.jsx("button",{className:"relay-button-primary",onClick:()=>_(c.deviceId,c.threadId),type:"button",children:"Continue"})]})},c.id)):e.jsx("p",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-3 text-sm text-[var(--theme-fg-muted)]",children:"No shared sessions."})})]})]}),e.jsx(Yn,{title:"Invite",description:"Share a single thread with another relay user.",children:e.jsx(Fd,{devices:(n==null?void 0:n.devices)??[],onShare:E})})]}),e.jsx("section",{children:e.jsx(Yn,{title:"Shared By Me",description:"Active invitations you created.",children:e.jsx("div",{className:"space-y-3",children:n!=null&&n.sharedByMe.length?n.sharedByMe.map(c=>e.jsxs("article",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-3",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:c.label||c.threadId}),e.jsxs("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:["Shared with ",c.targetUsername," on ",c.deviceName]}),e.jsx("button",{className:"relay-button-secondary mt-3",onClick:()=>void v(c.id),type:"button",children:"Revoke"})]},c.id)):e.jsx("p",{className:"text-sm text-[var(--theme-fg-muted)]",children:"No active shares."})})})})]})}):e.jsx(Kn,{children:e.jsx(_d,{registrationEnabled:(s==null?void 0:s.registrationEnabled)??!0,initialError:h,onAuthenticated:f})})}function _d({registrationEnabled:t,initialError:s,onAuthenticated:a}){const[n,d]=r.useState("login"),[o,m]=r.useState(""),[h,g]=r.useState(""),[y,A]=r.useState(""),[x,f]=r.useState(""),[k,C]=r.useState(""),[E,v]=r.useState(s),[J,te]=r.useState(!1);async function _(R){R.preventDefault(),te(!0),v(null);try{n==="login"?await ul({identifier:o,password:x}):await ml({email:h,username:y,password:x,registrationPassword:k}),await a()}catch(X){v(kn(X,"Unable to authenticate with relay."))}finally{te(!1)}}return e.jsxs("section",{className:"w-full max-w-sm rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-5 shadow-xl shadow-black/10",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-fg-muted)]",children:"Relay Access"}),e.jsx("h1",{className:"mt-2 text-2xl font-semibold text-[var(--theme-fg)]",children:n==="login"?"Sign in":"Create account"}),e.jsxs("form",{className:"mt-5 space-y-4",onSubmit:_,children:[n==="login"?e.jsx(Vt,{autoComplete:"username",label:"Email or username",onChange:m,value:o}):e.jsxs(e.Fragment,{children:[e.jsx(Vt,{autoComplete:"email",label:"Email",onChange:g,value:h}),e.jsx(Vt,{autoComplete:"username",label:"Username",onChange:A,value:y}),e.jsx(Vt,{autoComplete:"one-time-code",label:"Registration password",onChange:C,type:"password",value:k})]}),e.jsx(Vt,{autoComplete:n==="login"?"current-password":"new-password",label:"Password",onChange:f,type:"password",value:x}),E?e.jsx(da,{tone:"danger",children:E}):null,e.jsx("button",{className:"relay-button-primary h-11 w-full",disabled:J,type:"submit",children:J?"Working...":n==="login"?"Sign in":"Register"})]}),e.jsx("button",{className:"mt-4 text-sm text-[var(--theme-accent-strong)] disabled:text-[var(--theme-fg-muted)]",disabled:n==="login"?!t:!1,onClick:()=>d(n==="login"?"register":"login"),type:"button",children:n==="login"?t?"Create relay account":"Registration is disabled":"Use an existing account"})]})}function Bd({onCreate:t}){const[s,a]=r.useState(""),[n,d]=r.useState(!1),[o,m]=r.useState(null);async function h(g){g.preventDefault(),d(!0),m(null);try{await t(s),a("")}catch(y){m(kn(y,"Unable to create device."))}finally{d(!1)}}return e.jsxs("form",{className:"flex flex-col gap-2 sm:flex-row",onSubmit:h,children:[e.jsx("input",{className:"relay-input min-w-0 flex-1",onChange:g=>a(g.target.value),placeholder:"Device name",value:s}),e.jsx("button",{className:"relay-button-primary",disabled:n||!s.trim(),type:"submit",children:"Create"}),o?e.jsx("p",{className:"text-sm text-[var(--status-danger-fg)]",children:o}):null]})}function Fd({devices:t,onShare:s}){const a=r.useMemo(()=>{var v;return((v=t[0])==null?void 0:v.id)??""},[t]),[n,d]=r.useState(a),[o,m]=r.useState(""),[h,g]=r.useState(""),[y,A]=r.useState(""),[x,f]=r.useState(!1),[k,C]=r.useState(null);r.useEffect(()=>{!n&&a&&d(a)},[n,a]);async function E(v){v.preventDefault(),f(!0),C(null);try{await s({targetUsername:o,deviceId:n,threadId:h,...y.trim()?{label:y}:{}}),m(""),g(""),A(""),C("Invitation created.")}catch(J){C(kn(J,"Unable to create invitation."))}finally{f(!1)}}return e.jsxs("form",{className:"space-y-3",onSubmit:E,children:[e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Device",e.jsx("select",{className:"relay-input mt-2 w-full",onChange:v=>d(v.target.value),value:n,children:t.map(v=>e.jsx("option",{value:v.id,children:v.name},v.id))})]}),e.jsx(Vt,{label:"Username",onChange:m,value:o}),e.jsx(Vt,{label:"Thread ID",onChange:g,value:h}),e.jsx(Vt,{label:"Label",onChange:A,value:y}),k?e.jsx("p",{className:"text-sm text-[var(--theme-fg-muted)]",children:k}):null,e.jsx("button",{className:"relay-button-primary",disabled:x||!n||!o.trim()||!h.trim(),type:"submit",children:"Invite"})]})}function Kn({children:t}){return e.jsxs("main",{className:"min-h-screen bg-[var(--app-bg)] px-4 py-6 text-[var(--app-fg)] sm:px-6",children:[e.jsx(ga,{}),e.jsx("div",{className:"flex min-h-[calc(100vh-3rem)] items-center justify-center",children:t})]})}function Yn({title:t,description:s,children:a}){return e.jsxs("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:t}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:s})]}),a]})}function Vt({label:t,value:s,onChange:a,type:n="text",autoComplete:d}){return e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:[t,e.jsx("input",{autoComplete:d,className:"relay-input mt-2 w-full",onChange:o=>a(o.target.value),type:n,value:s})]})}function da({tone:t,children:s}){return e.jsx("div",{className:`rounded-lg border px-3 py-2 text-sm ${t==="danger"?"border-[var(--status-danger-border)] bg-[var(--status-danger-bg)] text-[var(--status-danger-fg)]":"border-[var(--theme-accent-border)] bg-[var(--theme-accent-soft)] text-[var(--theme-fg)]"}`,children:s})}function Wd(t){return`REMOTE_CODEX_RELAY_SERVER_URL=${qd()} REMOTE_CODEX_RELAY_AGENT_TOKEN=${t} remote-codex relay-supervisor`}function qd(){return typeof window>"u"?"wss://relay.example.com":window.location.origin.replace(/^https:\/\//,"wss://").replace(/^http:\/\//,"ws://")}function lr(t){return t??"never"}const ir=3,zd=10,Vd=1e3,Jd=2e3,Zn=5500,Gd=3e3,Xn=0,ms=1,mn=3,Kd=["read-only","workspace-write","danger-full-access"],Yd=[],Zd=[],Xd=[],Qd={workspace:!0,toolUsage:!1,guide:!1,threadGraph:!1,extensions:!1,defaultTab:"workspace"};function ec(){return e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-3.5 w-3.5 fill-current",children:e.jsx("path",{d:"M5.75 1.75c-.97 0-1.75.78-1.75 1.75v.25H3.5c-.97 0-1.75.78-1.75 1.75v6c0 .97.78 1.75 1.75 1.75h4.75c.97 0 1.75-.78 1.75-1.75v-.25h.5c.97 0 1.75-.78 1.75-1.75v-6c0-.97-.78-1.75-1.75-1.75h-4.75Zm-.5 2V3.5c0-.28.22-.5.5-.5h4.75c.28 0 .5.22.5.5v6a.5.5 0 0 1-.5.5H10v-4.5c0-.97-.78-1.75-1.75-1.75h-3Zm-1.75 1.25h4.75c.28 0 .5.22.5.5v6a.5.5 0 0 1-.5.5H3.5a.5.5 0 0 1-.5-.5v-6c0-.28.22-.5.5-.5Z"})})}function tc(){return e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-4 w-4 fill-none stroke-current",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M4.25 2.25h5.2l2.3 2.3v9.2h-7.5a2 2 0 0 1-2-2v-7.5a2 2 0 0 1 2-2Z"}),e.jsx("path",{d:"M9.25 2.5v2.25h2.25"}),e.jsx("path",{d:"M7 6.75v4"}),e.jsx("path",{d:"m5.45 9.35 1.55 1.55 1.55-1.55"})]})}function hn({status:t}){return e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-4.5 w-4.5 fill-none stroke-current",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M2.5 6.75A8.22 8.22 0 0 1 8 4.5c2.14 0 4.1.8 5.5 2.25"}),e.jsx("path",{d:"M4.75 9a4.95 4.95 0 0 1 6.5 0"}),e.jsx("path",{d:"M6.9 11.3a1.9 1.9 0 0 1 2.2 0"}),t==="connected"?e.jsx("path",{d:"m6.7 13.2.9.9 1.7-2"}):t==="offline"?e.jsx("path",{d:"M3 3l10 10"}):t==="detached"?null:e.jsxs(e.Fragment,{children:[e.jsx("path",{d:"M11.8 11.1a2.2 2.2 0 0 1-1.8 2.7"}),e.jsx("path",{d:"m10.7 11.35 1.3-.55-.55-1.3"})]})]})}function sc(t,s){if(!t)return"Thread disconnected";switch(s.status){case"connected":return"Realtime updates connected";case"reconnecting":return"Realtime updates reconnecting";case"offline":return"Browser offline";case"checking":return"Checking realtime connection"}}function nc(){var Ea;const{id:t=""}=ur(),s=rt(),a=Jt(),n=ca(),d=r.useRef(""),o=r.useRef(null),m=r.useRef(null),h=r.useRef(null),g=r.useRef(!1),y=r.useRef(null),A=r.useRef(null),x=r.useRef(typeof navigator>"u"?!0:navigator.onLine),f=r.useRef(!1),k=r.useRef(null),C=r.useRef(null),E=r.useRef(0),v=r.useRef(0),J=r.useRef(null),te=r.useRef(null),_=r.useRef(null),R=r.useRef(null),X=r.useRef(new Set),[c,D]=r.useState(null),[Y,I]=r.useState([]),[q,B]=r.useState([]),[ve,fe]=r.useState(null),[H,pe]=r.useState(null),[T,le]=r.useState(null),[oe,W]=r.useState(""),[F,z]=r.useState(null),[ue,xe]=r.useState(null),[ot,ct]=r.useState(!0),[Ye,wt]=r.useState(0),[ze,ut]=r.useState(!0),[_e,mt]=r.useState(!1),[Ze,b]=r.useState(!1),[j,M]=r.useState("chat"),Q=n.getThreadPanels().some(l=>l.kind==="terminal"),ge=r.useMemo(()=>({fetchState:ql,createShell:Jl,terminateShell:Gl,updateShell:Kl,connectSocket:xi}),[]),Oe=r.useCallback(l=>`/threads/${l}`,[]),Pe=r.useCallback(l=>{s(`/threads/${l}`)},[s]),Xe=r.useCallback(l=>l?`/threads/new?workspaceId=${encodeURIComponent(l)}`:"/threads/new",[]),ht=r.useCallback(({threadId:l,path:i})=>`/api/threads/${l}/assets/image?path=${encodeURIComponent(i)}`,[]),[Ve,pt]=r.useState({prompt:"",attachments:[]}),[$e,Et]=r.useState(!1),[Lt,Gt]=r.useState(0),[Kt,se]=r.useState(0),[ie,me]=r.useState(0),[he,ke]=r.useState(!1),[V,Qe]=r.useState(null),[Me,et]=r.useState(!1),[xt,Dt]=r.useState(!1),[gt,gs]=r.useState(!1),[bs,vs]=r.useState(null),[Nt,Yt]=r.useState("idle"),[bt,js]=r.useState({status:x.current?"checking":"offline",browserOnline:x.current,healthOk:!1,socketOpen:!1,lastHealthyAt:null}),[we,lt]=r.useState(null),[St,Rt]=r.useState([]),[ys,tt]=r.useState({status:"idle",data:null,error:null}),[ft,Pt]=r.useState({status:"idle",data:null,error:null}),[Je,Te]=r.useState({status:"idle",data:null,error:null}),[Ht,kt]=r.useState({status:"idle",data:null,error:null}),[Ce,je]=r.useState({status:"idle",data:null,error:null}),[Ms,G]=r.useState(!1),[ee,ne]=r.useState(!1),[ws,ts]=r.useState(()=>new Set),[Ns,At]=r.useState(!1),[Ut,Ls]=r.useState(!1),[Ct,_t]=r.useState({status:"idle",data:null,error:null}),[vt,Bt]=r.useState(null),[Ss,Zt]=r.useState(!1),[Ds,de]=r.useState(null),Ot=((Ea=T==null?void 0:T.hostConfigFiles.find(l=>{var i;return(i=l.roles)==null?void 0:i.includes("mcp")}))==null?void 0:Ea.name)??null,ss=r.useCallback(()=>{const l=d.current;d.current="",o.current=null,l&&r.startTransition(()=>{W(i=>i+l)})},[]),ns=r.useCallback(l=>{d.current+=l,o.current===null&&(o.current=window.requestAnimationFrame(()=>{ss()}))},[ss]),ks=r.useCallback((l,i)=>{xe(p=>{const P=(p==null?void 0:p.turnId)===l?p.items:[],O=P.findIndex(Ae=>Ae.id===i.id),Z=qr(P[O],i),ce=O>=0?P.map((Ae,L)=>L===O?Z:Ae):[...P,Z];return{turnId:l,items:ce,updatedAt:new Date().toISOString()}})},[]),Hs=r.useCallback((l,i,p,P)=>{xe(O=>{const Z=(O==null?void 0:O.turnId)===l?O.items:[],ce=Z.find(Be=>Be.id===i),Ae=(ce==null?void 0:ce.kind)==="agentMessage"?{...ce,text:`${ce.text}${p}`,sequence:P??ce.sequence??null}:{id:i,kind:"agentMessage",text:p,sequence:P},L=Z.findIndex(Be=>Be.id===i),Ke=L>=0?Z.map((Be,Fe)=>Fe===L?Ae:Be):[...Z,Ae];return{turnId:l,items:Ke,updatedAt:new Date().toISOString()}})},[]),it=r.useCallback(()=>{d.current="",o.current!==null&&(window.cancelAnimationFrame(o.current),o.current=null)},[]);r.useEffect(()=>{tt({status:"idle",data:null,error:null}),Pt({status:"idle",data:null,error:null}),Te({status:"idle",data:null,error:null}),kt({status:"idle",data:null,error:null}),je({status:"idle",data:null,error:null}),At(!1),_t({status:"idle",data:null,error:null})},[t]);const as=r.useCallback(async()=>{if(t){_t(l=>({status:"loading",data:l.data,error:null}));try{const l=await Bl(t);_t({status:"ready",data:l,error:null})}catch(l){const i=l instanceof re?l.payload.message:"Unable to load export turns.";_t(p=>({status:"failed",data:p.data,error:i}))}}},[t]);async function _s(l){if(t){de(null),Ls(!0);try{const{blob:i,filename:p}=await Wl(t,l),P=URL.createObjectURL(i),O=document.createElement("a");O.href=P,O.download=p,document.body.append(O),O.click(),O.remove(),window.setTimeout(()=>URL.revokeObjectURL(P),3e4),At(!1)}catch(i){const p=i instanceof re?i.payload.message:"Unable to export transcript.";de(p)}finally{Ls(!1)}}}async function Bs(){if(t){je(l=>{var i;return{status:"loading",data:l.data??((i=_.current)==null?void 0:i.goal)??null,error:null}});try{const l=await ei(t);je({status:"ready",data:l.goal,error:null}),D(i=>i&&(l.goal?{...i,goal:l.goal,goalHistory:cn(i.goalHistory??[],l.goal)}:{...i,goal:l.goal}))}catch(l){je(i=>({status:"failed",data:i.data,error:l instanceof re?l.payload.message:"Unable to load goal."}))}}}async function Fs(l){if(t){je(i=>{var p;return{status:"loading",data:i.data??((p=_.current)==null?void 0:p.goal)??null,error:null}});try{const i=await ti(t,l);je({status:"ready",data:i.goal,error:null}),D(p=>p&&(i.goal?{...p,goal:i.goal,goalHistory:cn(p.goalHistory??[],i.goal)}:{...p,goal:i.goal}))}catch(i){throw je(p=>({status:"failed",data:p.data,error:i instanceof re?i.payload.message:"Unable to update goal."})),i}}}async function Cn(){if(t){je(l=>{var i;return{status:"loading",data:l.data??((i=_.current)==null?void 0:i.goal)??null,error:null}});try{const l=await si(t);je({status:"ready",data:null,error:null}),D(i=>i&&(l.goalHistory?{...i,goal:null,goalHistory:l.goalHistory}:{...i,goal:null}))}catch(l){throw je(i=>({status:"failed",data:i.data,error:l instanceof re?l.payload.message:"Unable to clear goal."})),l}}}async function Ws(l){ne(!0);try{await Fs({status:l})}finally{ne(!1)}}async function Tn(){ne(!0);try{await Cn()}finally{ne(!1)}}async function qs(){if(t){tt(l=>({status:"loading",data:l.data,error:null}));try{const l=await ai(t);tt({status:"ready",data:l,error:null})}catch(l){tt(i=>({status:"failed",data:i.data,error:l instanceof re?l.payload.message:"Unable to load skills."}))}}}async function In(){if(t){Pt(l=>({status:"loading",data:l.data,error:null}));try{const l=await ri(t);Pt({status:"ready",data:l,error:null})}catch(l){Pt(i=>({status:"failed",data:i.data,error:l instanceof re?l.payload.message:"Unable to load MCP servers."}))}}}async function En(){if(t){Te(l=>({status:"loading",data:l.data,error:null}));try{const l=await oi(t);Te({status:"ready",data:l,error:null})}catch(l){Te(i=>({status:"failed",data:i.data,error:l instanceof re?l.payload.message:"Unable to load hooks."}))}}}async function Rn(l){if(t){Te(i=>({status:"loading",data:i.data,error:null}));try{const i=await li(t,l);Te({status:"ready",data:i,error:null})}catch(i){throw Te(p=>({status:"failed",data:p.data,error:i instanceof re?i.payload.message:"Unable to create hook."})),i}}}async function Ge(l){if(t){Te(i=>({status:"loading",data:i.data,error:null}));try{const i=await ii(t,l);Te({status:"ready",data:i,error:null})}catch(i){throw Te(p=>({status:"failed",data:p.data,error:i instanceof re?i.payload.message:"Unable to update hook."})),i}}}async function Cs(l){if(t){Te(i=>({status:"loading",data:i.data,error:null}));try{const i=await di(t,l);Te({status:"ready",data:i,error:null})}catch(i){throw Te(p=>({status:"failed",data:p.data,error:i instanceof re?i.payload.message:"Unable to trust hook."})),i}}}async function zs(l){if(t){Te(i=>({status:"loading",data:i.data,error:null}));try{const i=await ci(t,l);Te({status:"ready",data:i,error:null})}catch(i){throw Te(p=>({status:"failed",data:p.data,error:i instanceof re?i.payload.message:"Unable to untrust hook."})),i}}}async function jt(){if(t){kt(l=>({status:"loading",data:l.data,error:null}));try{const l=await ni(t);kt({status:"ready",data:l,error:null})}catch(l){kt(i=>({status:"failed",data:i.data,error:l instanceof re?l.payload.message:"Unable to load turns for forking."}))}}}async function yt(){if(!t)return;const l=await qa(t,{mode:"latest"});I(i=>Ps(i,l.thread.thread)),s(`/threads/${l.thread.thread.id}`)}async function Pn(l){if(!t)return;const i=await qa(t,{mode:"turn",turnId:l});I(p=>Ps(p,i.thread.thread)),s(`/threads/${i.thread.thread.id}`)}const Vs=r.useCallback(l=>{const i=R.current,p=i&&Object.keys(i).length>0?{...l,thread:{...l.thread,...i}}:l,P=_.current;_.current=p,z(p.livePlan??null);const O=P?zt(P.turns,p.turns):p.turns;xe(L=>rd(L,p.liveItems??null,O)),je(L=>L.status==="idle"?L:{...L,data:p.goal??null});const Z=p.thread.activeTurnId===null&&p.thread.status!=="running";D(L=>L&&!p.goalHistory?{...p,turns:zt(L.turns,p.turns),pendingRequests:ia(L.pendingRequests,p.pendingRequests,X.current),...L.goalHistory?{goalHistory:L.goalHistory}:{}}:L?{...p,turns:zt(L.turns,p.turns),pendingRequests:ia(L.pendingRequests,p.pendingRequests,X.current)}:p),I(L=>Ps(L,p.thread));const ce=new Map(p.turns.map(L=>[L.id,L])),Ae=new Set((p.pendingSteers??[]).map(L=>L.clientRequestId).filter(L=>!!L));Rt(L=>L.filter(Ke=>{if(Ae.has(Ke.clientRequestId))return!1;const Be=ce.get(Ke.turnId);return!(!Be||Us(Be,Ke.prompt)||p.thread.activeTurnId!==Ke.turnId&&Be.status!=="inProgress")})),lt(L=>{if(!L)return L;const Ke=L.serverTurnId??L.id,Be=p.turns.some($=>$.id===Ke),Fe=ce.get(Ke)??null,ye=ud(p.turns,L.prompt),w=!!ye;if(ye&&!L.serverTurnId)return{...L,id:ye.id,serverTurnId:ye.id,status:L.status==="failed"?L.status:ye.status==="inProgress"?"inProgress":L.status};if(Fe&&L.serverTurnId)return Us(Fe,L.prompt)||L.prompt.includes("[PHOTO ")&&(gn(Fe,L.prompt)||Fn(Fe))?Fe.status==="inProgress"?{...L,id:Fe.id,serverTurnId:Fe.id,status:L.status==="failed"?L.status:"inProgress"}:null:{...L,id:Fe.id,serverTurnId:Fe.id,status:L.status==="failed"?L.status:"inProgress"};if(!L.serverTurnId&&L.prompt.includes("[PHOTO ")&&p.thread.activeTurnId&&p.thread.status==="running"){const $=ce.get(p.thread.activeTurnId);if($&&Fn($))return{...L,id:$.id,serverTurnId:$.id,status:L.status==="failed"?L.status:"inProgress"}}return Be||Z&&w?null:L}),(Z||te.current&&p.turns.some(L=>L.id===te.current))&&(te.current=null,it(),W(""),z(null),xe(null))},[it]);r.useEffect(()=>{_.current=c},[c]);const Js=r.useCallback(async({seedThread:l}={})=>{var ce;const i=v.current+1;v.current=i;const p=(l==null?void 0:l.provider)??((ce=_.current)==null?void 0:ce.thread.provider)??"codex",[P,O,Z]=await Promise.allSettled([Mr(),Ur(p),oa(p)]);v.current===i&&(P.status==="fulfilled"?I(l?Ps(P.value,l):P.value):l&&I(Ae=>Ps(Ae,l)),O.status==="fulfilled"&&(J.current=p,fe(O.value.status),pe(O.value.capabilities),le(O.value.managementSchema)),Z.status==="fulfilled"&&(J.current=p,B(Z.value)))},[]),Ft=r.useCallback(async({showLoading:l=!0,clearError:i=!0,reportError:p=!0,limit:P=ir}={})=>{const O=E.current+1;E.current=O,l&&ut(!0),i&&de(null);try{const Z=await Ba(t,{limit:P});if(E.current!==O)return;Vs(Z),J.current!==Z.thread.provider&&Js({seedThread:Z.thread})}catch(Z){if(E.current!==O||!p)return;de(Z instanceof Error?Z.message:"Unable to load thread detail.")}finally{E.current===O&&ut(!1)}},[Vs,t,Js]),De=r.useCallback(()=>{var Ae;const l=((Ae=m.current)==null?void 0:Ae.readyState)??mn,i=l===ms,p=x.current,P=Date.now(),O=y.current!==null&&P-Date.parse(y.current)<=Zn,Z=A.current!==null&&P-A.current<=Zn;let ce;p?i&&Z?ce="connected":l===Xn||h.current!==null||O||Z||g.current?ce="reconnecting":ce="checking":ce="offline",js(L=>L.status===ce&&L.browserOnline===p&&L.healthOk===O&&L.socketOpen===i&&L.lastHealthyAt===y.current?L:{status:ce,browserOnline:p,healthOk:O,socketOpen:i,lastHealthyAt:y.current})},[]);r.useEffect(()=>{E.current+=1,v.current+=1,D(null),pt({prompt:"",attachments:[]}),mt(!1),Yt("idle"),lt(null),Rt([]),xe(null),R.current=null,te.current=null,X.current=new Set,y.current=null,A.current=null,f.current=!1,x.current=typeof navigator>"u"?!0:navigator.onLine,js({status:x.current?"checking":"offline",browserOnline:x.current,healthOk:!1,socketOpen:!1,lastHealthyAt:null})},[t]),r.useEffect(()=>{if(Nt==="idle")return;const l=window.setTimeout(()=>{Yt("idle")},Nt==="copied"?1200:1600);return()=>{window.clearTimeout(l)}},[Nt]),r.useEffect(()=>{if(typeof document>"u")return;const{documentElement:l,body:i}=document;return l.classList.add("thread-detail-scroll-locked"),i.classList.add("thread-detail-scroll-locked"),()=>{l.classList.remove("thread-detail-scroll-locked"),i.classList.remove("thread-detail-scroll-locked")}},[]),r.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const l=window.matchMedia("(max-width: 639px)"),i=()=>Et(l.matches);return i(),l.addEventListener("change",i),()=>{l.removeEventListener("change",i)}},[]),r.useEffect(()=>{var i,p;if(typeof window>"u")return;const l=()=>{const P=window.visualViewport,O=P?Math.max(0,Math.round(window.innerHeight-P.height-P.offsetTop)):0;me(O),document.documentElement.style.setProperty("--thread-detail-keyboard-inset",`${O}px`)};return l(),(i=window.visualViewport)==null||i.addEventListener("resize",l),(p=window.visualViewport)==null||p.addEventListener("scroll",l),window.addEventListener("resize",l),()=>{var P,O;(P=window.visualViewport)==null||P.removeEventListener("resize",l),(O=window.visualViewport)==null||O.removeEventListener("scroll",l),window.removeEventListener("resize",l),document.documentElement.style.removeProperty("--thread-detail-keyboard-inset")}},[]),r.useEffect(()=>{if(typeof document>"u")return;const l=()=>{const i=document.activeElement,p=C.current,P=p==null?void 0:p.querySelector('[aria-label="Prompt"]');ke(!!(i&&P&&(i===P||P.contains(i))))};return l(),document.addEventListener("focusin",l),document.addEventListener("focusout",l),()=>{document.removeEventListener("focusin",l),document.removeEventListener("focusout",l)}},[j,c==null?void 0:c.thread.id,$e]),r.useEffect(()=>{const l=C.current;if(!l||typeof ResizeObserver>"u")return;const i=l.querySelector("form")??l,p=()=>{Gt(Math.max(l.getBoundingClientRect().height,i.getBoundingClientRect().height))};p();const P=new ResizeObserver(()=>{p()});return P.observe(i),()=>{P.disconnect()}},[j,$e]),r.useEffect(()=>{var P,O;const l=C.current;if(!l||!$e||j!=="chat"){se(0);return}const i=()=>{const Z=l.getBoundingClientRect();se(Math.max(0,Math.ceil(window.innerHeight-Z.top)))};i(),window.addEventListener("resize",i),(P=window.visualViewport)==null||P.addEventListener("resize",i),(O=window.visualViewport)==null||O.addEventListener("scroll",i);let p=null;return typeof ResizeObserver<"u"&&(p=new ResizeObserver(i),p.observe(l)),()=>{var Z,ce;window.removeEventListener("resize",i),(Z=window.visualViewport)==null||Z.removeEventListener("resize",i),(ce=window.visualViewport)==null||ce.removeEventListener("scroll",i),p==null||p.disconnect()}},[j,c==null?void 0:c.thread.id,$e,ie,he]),r.useEffect(()=>{Ft({showLoading:!0,limit:ir})},[Ft]),r.useEffect(()=>{let l=!1,i=null;const p=()=>{Ft({showLoading:!1,clearError:!1,reportError:!1})},P=()=>{h.current!==null&&(window.clearTimeout(h.current),h.current=null)},O=()=>{l||!x.current||h.current!==null||(h.current=window.setTimeout(()=>{h.current=null,!l&&L()},Vd),De())},Z=()=>{const w=m.current;if(m.current=null,w)try{w.close()}catch{}},ce=w=>{if(w.threadId===t){if(w.type==="thread.output.delta"&&typeof w.payload.delta=="string"){const $=typeof w.payload.turnId=="string"?w.payload.turnId:null,ae=typeof w.payload.itemId=="string"?w.payload.itemId:null,Ie=typeof w.payload.sequence=="number"&&Number.isFinite(w.payload.sequence)?w.payload.sequence:null;$&&ae?Hs($,ae,w.payload.delta,Ie):ns(w.payload.delta),$&<(be=>be&&(be.serverTurnId===null||be.serverTurnId===$)?{...be,serverTurnId:$,id:$,status:be.status==="failed"?be.status:"inProgress",tokenUsage:be.tokenUsage}:be)}if(w.type==="thread.context.updated"){const $=w.payload.contextUsage&&typeof w.payload.contextUsage=="object"?w.payload.contextUsage:null;if($){const ae=$;D(Ie=>Ie&&{...Ie,thread:{...Ie.thread,contextUsage:ae}}),I(Ie=>Ie.map(be=>be.id===t?{...be,contextUsage:ae}:be))}}if(w.type==="thread.turn.token.updated"&&typeof w.payload.turnId=="string"&&w.payload.tokenUsage&&typeof w.payload.tokenUsage=="object"){const $=w.payload.turnId,ae=w.payload.tokenUsage,Ie=w.payload.priceEstimate&&typeof w.payload.priceEstimate=="object"?w.payload.priceEstimate:null;D(be=>{if(!be)return be;const st=md(be.turns,$,ae,Ie);return st===be.turns?be:{...be,turns:st}}),lt(be=>be&&(be.serverTurnId===$||be.id===$)?{...be,tokenUsage:ae,priceEstimate:Ie}:be)}if(w.type==="thread.turn.started"||w.type==="thread.turn.completed"||w.type==="thread.turn.failed"||w.type==="thread.updated"||w.type==="thread.goal.updated"||w.type==="thread.goal.cleared"||w.type==="thread.request.created"||w.type==="thread.request.resolved"){if(w.type==="thread.goal.updated"){const $=w.payload.goal&&typeof w.payload.goal=="object"?w.payload.goal:null,ae=Array.isArray(w.payload.goalHistory)?w.payload.goalHistory:null;je({status:"ready",data:$,error:null}),D(Ie=>Ie&&(ae?{...Ie,goal:$,goalHistory:ae}:$?{...Ie,goal:$,goalHistory:cn(Ie.goalHistory??[],$)}:{...Ie,goal:$}))}if(w.type==="thread.goal.cleared"){const $=Array.isArray(w.payload.goalHistory)?w.payload.goalHistory:null;je({status:"ready",data:null,error:null}),D(ae=>ae&&($?{...ae,goal:null,goalHistory:$}:{...ae,goal:null}))}if(p(),w.type==="thread.turn.started"){it(),W(""),xe(null),te.current=null;const $=typeof w.payload.turnId=="string"?w.payload.turnId:null;$&<(ae=>ae&&{...ae,serverTurnId:$,id:$,status:ae.status==="failed"?ae.status:"inProgress",error:null,tokenUsage:ae.tokenUsage})}if(w.type==="thread.turn.completed"||w.type==="thread.turn.failed"){it(),W("");const $=typeof w.payload.turnId=="string"?w.payload.turnId:null;$&&(te.current=$,w.type==="thread.turn.failed"&<(ae=>ae&&(ae.serverTurnId===$||ae.id===$)?{...ae,status:"failed",error:typeof w.payload.error=="string"?w.payload.error:"Unable to complete the turn.",tokenUsage:ae.tokenUsage}:ae))}}if(w.type==="thread.request.created"&&ad(w.payload.request)&&(X.current.delete(w.payload.request.id),D($=>$&&sd($,w.payload.request))),w.type==="thread.request.resolved"&&typeof w.payload.requestId=="string"){const $=w.payload.requestId;X.current.add($),D(ae=>ae&&nd(ae,$))}if((w.type==="thread.item.started"||w.type==="thread.item.completed")&&w.payload.item&&typeof w.payload.item=="object"&&typeof w.payload.turnId=="string"){const $=w.payload.turnId,ae=w.payload.item;typeof ae.id=="string"&&typeof ae.text=="string"&&ks($,ae)}w.type==="thread.plan.updated"&&Array.isArray(w.payload.plan)&&z({turnId:String(w.payload.turnId??""),explanation:typeof w.payload.explanation=="string"?w.payload.explanation:null,plan:w.payload.plan})}},Ae=()=>{const w=m.current;if(!(!w||w.readyState!==ms))try{w.send(JSON.stringify({type:"supervisor.ping",timestamp:new Date().toISOString()}))}catch{f.current=!0,Z(),O(),De()}},L=()=>{var ae;if(l||!x.current){De();return}const w=((ae=m.current)==null?void 0:ae.readyState)??mn;if(w===Xn||w===ms){De();return}const $=Hr(ce);m.current=$,De(),$.addEventListener("message",Ie=>{if(m.current===$)try{const be=JSON.parse(Ie.data);(be.type==="supervisor.connected"||be.type==="supervisor.pong")&&(A.current=Date.now(),De())}catch{}}),$.addEventListener("open",()=>{m.current===$&&(f.current=!0,p(),Ae(),De())}),$.addEventListener("close",()=>{m.current===$&&(m.current=null),f.current=!0,O(),De()}),$.addEventListener("error",()=>{m.current===$&&(m.current=null),f.current=!0,O(),De()})},Ke=async()=>{var w;if(!(l||!x.current||g.current)){g.current=!0,De();try{await El();const $=f.current;y.current=new Date().toISOString(),$&&(f.current=!1,p()),(((w=m.current)==null?void 0:w.readyState)??mn)!==ms&&L()}catch{y.current=null,f.current=!0,O()}finally{g.current=!1,De()}}},Be=()=>{x.current=!0,f.current=!0,De(),L(),Ke()},Fe=()=>{x.current=!1,y.current=null,A.current=null,f.current=!0,P(),Z(),De()},ye=()=>{var ae;if(l||!x.current){De();return}const w=((ae=m.current)==null?void 0:ae.readyState)??mn,$=A.current===null?null:Date.now()-A.current;w===ms&&$!==null&&$>Zn?(f.current=!0,Z(),O()):w===ms?Ae():w!==Xn&&L(),Ke(),De()};return window.addEventListener("online",Be),window.addEventListener("offline",Fe),L(),Ke(),i=window.setInterval(ye,Jd),()=>{l=!0,window.removeEventListener("online",Be),window.removeEventListener("offline",Fe),P(),i!==null&&window.clearInterval(i),it(),Z()}},[Hs,it,t,Ft,ns,De,ks]),r.useEffect(()=>{if(!((c==null?void 0:c.thread.activeTurnId)!==null||(c==null?void 0:c.thread.status)==="running"||we!==null||St.length>0||oe.length>0||F!==null||ue!==null))return;const i=window.setInterval(()=>{Ft({showLoading:!1,clearError:!1,reportError:!1})},Gd);return()=>{window.clearInterval(i)}},[c==null?void 0:c.thread.activeTurnId,c==null?void 0:c.thread.status,oe.length,ue,F,Ft,St.length,we]);const Gs=r.useCallback(async()=>{var l;if(!(!c||c.turns.length===0||_e)){mt(!0),de(null);try{const i=(l=c.turns[0])==null?void 0:l.id,p=await Ba(t,{limit:zd,...i?{beforeTurnId:i}:{}});D(P=>P?{...p,turns:td(P.turns,p.turns)}:p),I(P=>P.map(O=>O.id===p.thread.id?p.thread:O))}catch(i){de(i instanceof Error?i.message:"Unable to load earlier turns.")}finally{mt(!1)}}},[c,t,_e]);async function Ks(l){var Ke,Be,Fe;if(j==="shell"){if((c==null?void 0:c.thread.isLoaded)===!1)return await Wt({attachShell:!0}),!1;let ye=!1;if((V==null?void 0:V.shellInputEnabled)!==!0&&((V==null?void 0:V.loading)===!1&&(V==null?void 0:V.isConnecting)!==!0&&(V==null?void 0:V.status)!=="creating"&&(V==null?void 0:V.status)!=="workspace_missing"&&(await((Ke=k.current)==null?void 0:Ke.toggleConnection()),ye=!0),(V==null?void 0:V.isConnecting)===!0))return de("Connecting to the shell. Try again after it attaches."),!1;if(((Be=k.current)==null?void 0:Be.sendCommand(l.prompt))??!1)de(null);else return de(ye?"Shell is still attaching. Try again after it connects.":"Connect the shell before sending commands."),!1;return!0}b(!0),de(null),wt(ye=>ye+1);const i=_.current,p=i?{...i.thread,...R.current??{}}:null,P=(p==null?void 0:p.model)??null,O=(p==null?void 0:p.reasoningEffort)??null,Z=cd(),ce=`optimistic-${Date.now()}`,Ae=`optimistic-steer-${Z}`,L=new Date().toISOString();try{let ye=_.current;if(ye&&!ye.thread.isLoaded){const Ee={...ye.thread,...R.current??{}},dt=await Fa(t,{...ye.thread.model?{model:ye.thread.model}:{},...ye.thread.sandboxMode?{sandboxMode:ye.thread.sandboxMode}:{}}),nt={...dt,thread:{...dt.thread,model:Ee.model??dt.thread.model,reasoningEffort:Ee.reasoningEffort??dt.thread.reasoningEffort,collaborationMode:Ee.collaborationMode??dt.thread.collaborationMode,sandboxMode:Ee.sandboxMode??dt.thread.sandboxMode??null}};ye=nt,_.current=nt,D(an=>an?{...nt,turns:zt(an.turns,nt.turns)}:nt),I(an=>an.map(Ra=>Ra.id===nt.thread.id?nt.thread:Ra))}const w=ye?{...ye.thread,...R.current??{}}:null,$=(w==null?void 0:w.status)==="running"?w.activeTurnId:null,ae=j==="chat"&&!!$;ae&&$?Rt(Ee=>[...Ee,{id:Ae,clientRequestId:Z,turnId:$,prompt:l.prompt,createdAt:L,status:"steering"}]):(it(),W(""),lt({id:ce,serverTurnId:null,startedAt:L,status:"sending",error:null,prompt:l.prompt,model:P,reasoningEffort:O,reasoningEffortAvailable:Qa(q,P),tokenUsage:null,priceEstimate:null}));const Ie={prompt:l.prompt,clientRequestId:Z,...w!=null&&w.model?{model:w.model}:{},...w!=null&&w.reasoningEffort?{reasoningEffort:w.reasoningEffort}:{},...w!=null&&w.collaborationMode?{collaborationMode:w.collaborationMode}:{},...w!=null&&w.sandboxMode?{sandboxMode:w.sandboxMode}:{},...(Fe=l.attachments)!=null&&Fe.length?{attachments:l.attachments}:{}},be=await Zl(t,Ie),st=R.current&&Object.keys(R.current).length>0?{...be,...R.current}:be;D(Ee=>Ee&&{...Ee,thread:st}),I(Ee=>Ee.map(dt=>dt.id===st.id?st:dt)),ae&&$?st.activeTurnId!==null&&st.activeTurnId!==$&&st.lastTurnStartedAt!==(w==null?void 0:w.lastTurnStartedAt)?(it(),W(""),z(null),Rt(dt=>dt.filter(nt=>nt.id!==Ae)),lt({id:ce,serverTurnId:st.activeTurnId,startedAt:st.lastTurnStartedAt??L,status:"inProgress",error:null,prompt:l.prompt,model:P,reasoningEffort:O,reasoningEffortAvailable:Qa(q,P),tokenUsage:null,priceEstimate:null})):Rt(dt=>dt.map(nt=>nt.id===Ae?{...nt,turnId:st.activeTurnId??nt.turnId,status:"accepted"}:nt)):(lt(Ee=>Ee&&Ee.id===ce?{...Ee,id:st.activeTurnId??Ee.id,serverTurnId:st.activeTurnId??Ee.serverTurnId,status:"inProgress",error:null,tokenUsage:Ee.tokenUsage,priceEstimate:Ee.priceEstimate}:Ee),z(null)),pt({prompt:"",attachments:[]})}catch(ye){const w=ye instanceof re?ye.payload.message:ye instanceof Error?ye.message:"Unable to send prompt.";ye instanceof re?de(ye.payload.message):de(w),Rt($=>$.filter(ae=>ae.clientRequestId!==Z)),lt($=>$&&$.id===ce?{...$,status:"failed",error:w}:$)}finally{b(!1)}}async function An(){const l=c==null?void 0:c.thread.providerSessionId;if(l)try{await navigator.clipboard.writeText(l),Yt("copied")}catch{Yt("failed")}}async function Wt(l){if(c){b(!0),de(null),it(),W("");try{if(c.thread.isLoaded){const p=await Yl(t);D(P=>P?{...p,turns:zt(P.turns,p.turns)}:p),Qe(null),I(P=>P.map(O=>O.id===p.thread.id?p.thread:O)),et(!1);return}const i=await Fa(t,{...c.thread.model?{model:c.thread.model}:{},...c.thread.sandboxMode?{sandboxMode:c.thread.sandboxMode}:{}});D(p=>p?{...i,turns:zt(p.turns,i.turns)}:i),I(p=>p.map(P=>P.id===i.thread.id?i.thread:P)),l!=null&&l.attachShell&&j==="shell"&&et(!0)}catch(i){de(i instanceof Error?i.message:"Unable to change connection state.")}finally{b(!1)}}}async function rs(){var l;if(j==="shell"){const i=((l=k.current)==null?void 0:l.sendControl("ctrl_c"))??!1;de(i?null:"Connect the shell before sending Ctrl-C.");return}b(!0),de(null);try{const i=c!=null&&c.thread.activeTurnId?await Wa(t,{turnId:c.thread.activeTurnId}):await Wa(t);D(p=>p&&{...p,thread:i}),I(p=>p.map(P=>P.id===i.id?i:P)),it(),W("")}catch(i){de(i instanceof Error?i.message:"Unable to interrupt turn.")}finally{b(!1)}}async function os(l){if(!c)return;const i=c,p={...R.current??{},...l.model!==void 0?{model:l.model}:{},...l.reasoningEffort!==void 0?{reasoningEffort:l.reasoningEffort}:{},...l.fastMode!==void 0?{fastMode:l.fastMode}:{},...l.collaborationMode!==void 0?{collaborationMode:l.collaborationMode}:{},...l.sandboxMode!==void 0?{sandboxMode:l.sandboxMode}:{}},P={...c.thread,...p};Dt(!0),R.current=p,_.current={...c,thread:P},D(O=>O&&{...O,thread:P}),I(O=>O.map(Z=>Z.id===P.id?{...Z,...P}:Z));try{const O=await Xl(t,{...l.model!==void 0?{model:l.model}:{},...l.reasoningEffort!==void 0?{reasoningEffort:l.reasoningEffort}:{},...l.fastMode!==void 0?{fastMode:l.fastMode}:{},...l.collaborationMode!==void 0?{collaborationMode:l.collaborationMode}:{},...l.sandboxMode!==void 0?{sandboxMode:l.sandboxMode}:{}});R.current=null,_.current=i?{...i,thread:O}:null,D(Z=>Z&&{...Z,thread:O}),I(Z=>Z.map(ce=>ce.id===O.id?O:ce))}catch(O){R.current=null,_.current=i,D(i),I(Z=>Z.map(ce=>ce.id===i.thread.id?i.thread:ce)),de(O instanceof Error?O.message:"Unable to update thread settings.")}finally{Dt(!1)}}const ls=r.useCallback(async(l,i)=>{vs(l),de(null);try{const p=await ui(t,l,i);D(P=>P?{...p,turns:zt(P.turns,p.turns)}:p),z(p.livePlan??null),xe(p.liveItems??null)}catch(p){de(p instanceof Error?p.message:"Unable to answer this request.")}finally{vs(null)}},[t]),Ys=r.useCallback(l=>Ml(t,l),[t]);async function Xt(){if(c){gs(!0),de(null);try{const l=await Ql(t);D(i=>i&&{...i,thread:l}),I(i=>i.map(p=>p.id===l.id?l:p))}catch(l){de(l instanceof Error?l.message:"Unable to compact this thread context.")}finally{gs(!1)}}}async function Zs(l,i){try{const p=await Lr(l,{title:i});I(P=>P.map(O=>O.id===p.id?{...O,title:p.title,updatedAt:p.updatedAt}:O)),D(P=>P&&P.thread.id===p.id?{...P,thread:{...P.thread,title:p.title,updatedAt:p.updatedAt}}:P)}catch(p){throw de(p instanceof Error?p.message:"Unable to rename thread."),p}}async function Xs(){if(vt){Zt(!0),de(null);try{await Dr(vt.id),I(i=>i.filter(p=>p.id!==vt.id));const l=vt.id===(c==null?void 0:c.thread.id);if(Bt(null),l){const i=Y.find(p=>p.id!==vt.id&&p.workspaceId===(c==null?void 0:c.thread.workspaceId))??Y.find(p=>p.id!==vt.id);s(i?`/threads/${i.id}`:"/threads")}}catch(l){de(l instanceof Error?l.message:"Unable to delete thread.")}finally{Zt(!1)}}}function is(){M(l=>l==="chat"?(c!=null&&c.thread.isLoaded&&et(!0),"shell"):"chat")}async function qt(){var i;const l=await((i=k.current)==null?void 0:i.copyLastCommandOutput());de(l?null:"Unable to copy the last shell command output.")}function ds(l){var p,P;const i=l==="clear"?((p=k.current)==null?void 0:p.sendCommand("clear"))??!1:((P=k.current)==null?void 0:P.sendControl(l))??!1;de(i?null:"Connect the shell before sending control input.")}r.useEffect(()=>{if(!(!Me||j!=="shell"||!k.current||(c==null?void 0:c.thread.isLoaded)===!1||(V==null?void 0:V.loading)!==!1)){if((V==null?void 0:V.status)==="attached"){et(!1);return}et(!1),k.current.toggleConnection()}},[j,c==null?void 0:c.thread.isLoaded,Me,V==null?void 0:V.loading,V==null?void 0:V.status]),r.useEffect(()=>{if(j!=="shell")return;const l=window.requestAnimationFrame(()=>{var i;(i=k.current)==null||i.refreshLayout({syncBackendSize:!1})});return()=>{window.cancelAnimationFrame(l)}},[j]);const Ts=c&&c.workspacePathStatus==="missing"?"Restore this workspace path on the current machine before continuing.":null,Is=$e&&j==="chat",Qs=Is&&he?ie:0,en=Math.max(Lt,144),Un=Math.max(Kt,en+Qs),tn=Is?Un+12:0,sn=c?e.jsxs("dl",{className:"space-y-4 text-sm",children:[e.jsxs("div",{className:"relative pr-9",children:[e.jsx("dt",{className:"text-[var(--theme-fg-muted)]",children:"Session ID"}),e.jsx("dd",{className:"mt-1 break-all text-[var(--theme-fg)]",children:c.thread.providerSessionId??"Unavailable"}),c.thread.providerSessionId&&e.jsx("button",{type:"button","aria-label":"Copy session ID",title:Nt==="copied"?"Copied":Nt==="failed"?"Copy failed":"Copy session ID",onClick:()=>void An(),className:`thread-mobile-hit-target absolute bottom-0 right-0 inline-flex h-5 w-5 items-center justify-center rounded-full border shadow-sm shadow-stone-950/25 backdrop-blur transition ${Nt==="copied"?"ui-status-info":Nt==="failed"?"ui-status-danger":"border-[var(--theme-border)] bg-[var(--theme-surface-strong)] text-[var(--theme-fg-soft)] hover:bg-[var(--theme-hover)] hover:text-[var(--theme-fg)]"}`,children:e.jsx("span",{className:"scale-[0.72]",children:e.jsx(ec,{})})})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[var(--theme-fg-muted)]",children:"Source"}),e.jsx("dd",{className:"mt-1 text-[var(--theme-fg)]",children:c.thread.source==="local_codex_import"?`Imported local ${c.thread.provider} session`:`${c.thread.provider} supervisor thread`})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[var(--theme-fg-muted)]",children:"Status"}),e.jsx("dd",{className:"mt-1 text-[var(--theme-fg)]",children:fr(c.thread.status)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[var(--theme-fg-muted)]",children:"Created"}),e.jsx("dd",{className:"mt-1 text-[var(--theme-fg)]",children:ps(c.thread.createdAt)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[var(--theme-fg-muted)]",children:"Workspace"}),e.jsx("dd",{className:"mt-1 break-words text-[var(--theme-fg)]",children:c.workspace.absPath})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[var(--theme-fg-muted)]",children:"Workspace path"}),e.jsx("dd",{className:"mt-1 text-[var(--theme-fg)]",children:c.workspacePathStatus==="present"?"Present":"Missing on this machine"})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[var(--theme-fg-muted)]",children:"Active turn"}),e.jsx("dd",{className:"mt-1 text-[var(--theme-fg)]",children:c.thread.activeTurnId??"None"})]})]}):null,nn=c&&(H!=null&&H.controls.sandboxMode)?e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-[0.2em] text-[var(--theme-fg-muted)]",children:"Sandbox Mode"}),e.jsx("div",{className:"mt-2 space-y-1.5",children:Kd.map(l=>{const i=ed(c.thread)===l;return e.jsx("button",{type:"button",disabled:xt,onClick:()=>void os({sandboxMode:l}),className:`block w-full rounded-xl border px-3 py-2 text-left text-sm transition ${i?"ui-status-warning":"border-[var(--theme-border)] bg-[var(--theme-surface-strong)] text-[var(--theme-fg-soft)] hover:bg-[var(--theme-hover)] hover:text-[var(--theme-fg)]"} disabled:cursor-not-allowed disabled:opacity-60`,children:l},l)})})]})}):null,u=(we==null?void 0:we.serverTurnId)??null,N=we&&c?c.turns.find(l=>(Us(l,we.prompt)||we.prompt.includes("[PHOTO ")&&(gn(l,we.prompt)||Fn(l)))&&(u&&l.id===u||l.id===we.id||Us(l,we.prompt)||we.prompt.includes("[PHOTO ")&&gn(l,we.prompt)))??null:null,S=r.useMemo(()=>we&&!N?{id:we.id,startedAt:we.startedAt,status:we.status,error:we.error,model:we.model,reasoningEffort:we.reasoningEffort,reasoningEffortAvailable:we.reasoningEffortAvailable,tokenUsage:we.tokenUsage,priceEstimate:we.priceEstimate,items:[{id:`${we.id}-user-message`,kind:"userMessage",text:we.prompt}]}:null,[N,we]),K=(c==null?void 0:c.thread.isLoaded)??!1,Le=K?bt.status==="connected"?"ui-action-success shadow-lg shadow-stone-950/20":bt.status==="reconnecting"?"thread-live-connection-reconnecting ui-status-success shadow-lg shadow-stone-950/20":bt.status==="offline"?"ui-status-danger shadow-lg shadow-stone-950/20":"ui-status-warning shadow-lg shadow-stone-950/20":"host-icon-button border shadow-lg shadow-black/10",He=sc(K,bt),$t=[He,K?null:"Tap to connect this thread",bt.lastHealthyAt?`Last healthy ${ps(bt.lastHealthyAt)}`:null].filter(Boolean).join(" · "),On=K?e.jsx("div",{role:"status","aria-live":"polite","aria-label":He,title:$t,className:`inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition ${Le}`,children:e.jsx(hn,{status:bt.status})}):e.jsx("button",{type:"button",onClick:()=>void Wt(),disabled:Ze||!c,"aria-label":Ze?"Connecting thread":"Connect thread",title:Ze?"Connecting thread":$t,className:`inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition ${Le}`,children:e.jsx(hn,{status:"detached"})}),so=K?e.jsx("div",{title:$t,className:`hidden lg:inline-flex h-9 w-9 items-center justify-center rounded-full transition ${Le}`,children:e.jsx(hn,{status:bt.status})}):e.jsx("button",{type:"button",onClick:()=>void Wt(),disabled:Ze||!c,title:Ze?"Connecting thread":$t,className:`hidden lg:inline-flex h-9 w-9 items-center justify-center rounded-full transition ${Le}`,children:e.jsx(hn,{status:"detached"})}),va=Ce.data??(c==null?void 0:c.goal)??null,ja=(c==null?void 0:c.goalHistory)??[],ya=va?cn(ja,va):zr(ja),wa=(H==null?void 0:H.controls.goals)??!1,no=e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-4 w-4 fill-none stroke-current",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("circle",{cx:"8",cy:"8",r:"5.5"}),e.jsx("circle",{cx:"8",cy:"8",r:"2"}),e.jsx("path",{d:"M8 1.7v2M8 12.3v2M1.7 8h2M12.3 8h2"})]}),ao=Ms&&wa?e.jsxs("div",{className:"host-dialog w-96 max-w-[calc(100vw-1.5rem)] rounded-3xl border p-3 text-left shadow-2xl shadow-black/20 backdrop-blur-xl",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"host-page-title text-sm font-semibold",children:"Goal monitor"}),e.jsx("p",{className:"host-muted text-xs",children:"Current thread only"})]}),e.jsx("button",{type:"button",onClick:()=>G(!1),className:"host-secondary-button rounded-full border px-2.5 py-1 text-xs transition",children:"Close"})]}),Ce.error?e.jsx("p",{className:"host-error mt-3 rounded-2xl border px-3 py-2 text-xs",children:Ce.error}):null,e.jsx("div",{className:"mt-3 max-h-[28rem] space-y-2 overflow-auto pr-1",children:ya.length===0?e.jsx("p",{className:"host-empty-state rounded-2xl border px-3 py-3 text-sm",children:"No goals in this thread yet."}):ya.map(l=>{const i=`${l.threadId}:${l.objective}:${l.createdAt}`,p=ws.has(i),P=["active","paused","budgetLimited"].includes(l.status);return e.jsxs("div",{className:`rounded-2xl border px-3 py-3 ${P?"ui-status-info":"host-surface-strong"}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("button",{type:"button",onClick:()=>ts(O=>{const Z=new Set(O);return Z.has(i)?Z.delete(i):Z.add(i),Z}),className:"min-w-0 flex-1 text-left",children:e.jsx("p",{className:`text-sm font-medium leading-5 ${p?"":"line-clamp-2"}`,children:l.objective})}),e.jsx("span",{className:"host-muted shrink-0 rounded-full border border-[var(--theme-border)] px-2 py-1 text-[10px] uppercase tracking-[0.14em]",children:l.status})]}),e.jsxs("div",{className:"host-muted mt-2 flex flex-wrap gap-2 text-[11px]",children:[e.jsx("span",{children:dd(l.timeUsedSeconds)}),e.jsx("span",{children:id(l)}),e.jsxs("span",{title:ps(l.updatedAt),children:["Updated ",new Date(l.updatedAt).toLocaleTimeString()]})]}),P?e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",disabled:ee||l.status==="active",onClick:()=>void Ws("active"),className:"ui-status-info rounded-full px-3 py-1.5 text-xs transition disabled:cursor-not-allowed disabled:opacity-50",children:"Continue"}),e.jsx("button",{type:"button",disabled:ee||l.status==="paused",onClick:()=>void Ws("paused"),className:"host-secondary-button rounded-full border px-3 py-1.5 text-xs transition disabled:cursor-not-allowed disabled:opacity-50",children:"Pause"}),e.jsx("button",{type:"button",disabled:ee,onClick:()=>void Tn(),className:"rounded-full border border-[var(--status-danger-border)] px-3 py-1.5 text-xs text-[var(--status-danger-fg)] transition hover:bg-[var(--status-danger-bg)] disabled:cursor-not-allowed disabled:opacity-50",children:"Terminate"})]}):null]},i)})})]}):null,Na=wa?e.jsx("button",{type:"button","aria-label":"Open goal monitor",title:"Open goal monitor",onClick:()=>{G(l=>!l),Bs()},className:"ui-status-info inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full shadow-lg shadow-stone-950/20 transition lg:h-9 lg:w-9",children:no}):null,Sa=e.jsx("button",{type:"button","aria-label":"Export transcript",title:"Export transcript",onClick:()=>At(!0),disabled:!c,className:"host-icon-button inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full border shadow-lg shadow-black/10 transition disabled:cursor-not-allowed disabled:opacity-50 lg:h-9 lg:w-9",children:e.jsx(tc,{})}),ro=e.jsxs("div",{className:"relative flex items-center justify-end gap-1.5",children:[Sa,Na,On]}),oo=e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[Sa,Na,so]}),lo=r.useMemo(()=>({livePlan:F,liveItems:ue,respondingRequestId:bs,onRespondToRequest:ls,scrollRequestKey:Ye,bottomSpacer:tn,className:"thread-timeline-surface min-h-0 flex-1",onTailVisibilityChange:ct,loadingEarlier:_e,onLoadEarlier:Gs,onOpenThread:Pe,answeredRequestNotes:(c==null?void 0:c.answeredRequestNotes)??Yd,activityNotes:(c==null?void 0:c.activityNotes)??Zd,pendingSteers:(c==null?void 0:c.pendingSteers)??Xd,optimisticSteers:St,optimisticTurn:S}),[c==null?void 0:c.answeredRequestNotes,c==null?void 0:c.activityNotes,c==null?void 0:c.pendingSteers,Gs,ls,ue,F,_e,Pe,St,bs,Ye,tn,S]),ka=c?{busy:j==="chat"?Ze:!1,settingsBusy:xt,error:null,model:c.thread.model,reasoningEffort:c.thread.reasoningEffort,fastMode:c.thread.fastMode??!1,collaborationMode:c.thread.collaborationMode,modelOptions:q,contextUsage:c.thread.contextUsage,capabilities:H,toolboxItems:(T==null?void 0:T.toolboxItems)??[],hookCommandTemplates:(T==null?void 0:T.hookCommandTemplates)??[],mcpConfigFormat:(T==null?void 0:T.mcpConfigFormat)??"none",followTail:ot,threadConnected:c.thread.isLoaded,shellAvailable:Q,disabled:!!Ts,...Ts?{disabledPlaceholder:Ts}:{},shellControlState:V,draftPrompt:Ve.prompt,draftAttachments:Ve.attachments,onDraftChange:pt,canInterrupt:!!c.thread.activeTurnId,onInterrupt:rs,onCompact:Xt,onOpenForkTurns:jt,onForkLatest:yt,onForkTurn:Pn,onOpenSkills:qs,onOpenMcp:In,onOpenHooks:En,onCreateHook:Rn,onUpdateHook:Ge,onTrustHook:Cs,onUntrustHook:zs,goalState:Ce,onOpenGoal:Bs,onUpdateGoal:Fs,...Ot?{onReadProviderConfig:()=>Or(c.thread.provider,Ot),onWriteProviderConfig:l=>$r(c.thread.provider,Ot,{content:l})}:{},onToggleFollow:()=>wt(l=>l+1),onUpdateSettings:os,onToggleView:is,onShellCopy:qt,onShellControl:ds,compactBusy:gt,skillsState:ys,mcpState:ft,hooksState:Je,forkTurnOptionsState:Ht}:null,Ca=c?{busy:Ze,settingsBusy:!1,error:c.thread.isLoaded?(V==null?void 0:V.error)??null:null,followTail:!1,capabilities:H,toolboxItems:(T==null?void 0:T.toolboxItems)??[],hookCommandTemplates:(T==null?void 0:T.hookCommandTemplates)??[],mcpConfigFormat:(T==null?void 0:T.mcpConfigFormat)??"none",threadConnected:c.thread.isLoaded,shellAvailable:Q,shellControlState:V,canInterrupt:!!(c.thread.isLoaded&&(V!=null&&V.isCommandRunning)),onInterrupt:rs,onToggleView:is,onShellCopy:qt,onShellControl:ds}:null,Ta=r.useCallback(l=>c?ht({threadId:c.thread.id,path:l}):"",[c==null?void 0:c.thread.id,ht]),Ia=r.useMemo(()=>{const l=(c==null?void 0:c.workspace.id)??null;return l?{listTree:()=>Rl(l),readFile:i=>Pl(l,{path:i.path,...i.offset!==void 0?{offset:i.offset}:{},...i.limit!==void 0?{limit:i.limit}:{}}),getRawFileUrl:i=>Al(l,{path:i.path}),uploadFile:i=>Ol(l,{file:i.file}),writeFile:async i=>{await $l(l,{path:i.path,content:i.content})},downloadNode:async i=>{de(null);try{const p=await Ul(l,{path:i.path}),P=URL.createObjectURL(p.blob),O=document.createElement("a");O.href=P,O.download=p.filename,document.body.append(O),O.click(),O.remove(),URL.revokeObjectURL(P)}catch(p){de(p instanceof re?p.payload.message:p instanceof Error?p.message:"Workspace download failed.")}}}:null},[c==null?void 0:c.workspace.id]),io=r.useMemo(()=>({openThread:Pe,getThreadHref:Oe,getNewThreadHref:Xe,renameThread:Zs,deleteThread:Bt,sendPrompt:Ks,interrupt:rs,compact:Xt,updateSettings:os,loadHistoryItemDetail:Ys,getImageAssetUrl:Ta,workspace:Ia,shell:ge}),[Ta,Xe,Oe,Xt,rs,Ys,Ks,Zs,os,ge,Pe,Ia]),co=c!=null&&c.thread.workspaceId?`/threads?workspaceId=${encodeURIComponent(c.thread.workspaceId)}`:"/workspaces",uo=e.jsxs(e.Fragment,{children:[e.jsx(vo,{open:Ns,busy:Ut,turnsState:Ct,onCancel:()=>{Ut||At(!1)},onLoadTurns:as,onExport:_s}),e.jsx(wn,{open:vt!==null,title:"Delete Thread",description:vt?`Delete ${Oo(vt.title)} from supervisor. The backend session id will no longer appear in this workspace list.`:"",confirmLabel:"Delete Thread",busy:Ss,onCancel:()=>{Ss||Bt(null)},onConfirm:()=>void Xs()})]});return e.jsx(pr,{threads:Y,detail:c,status:ve,loading:ze,error:ze?null:Ds,plugins:n,adapter:io,metaContent:sn,settingsContent:nn,globalSettingsContent:e.jsx(xa,{embedded:!0}),mobileHeaderAction:ro,workspaceReturnHref:co,onCloseAppNavigation:(a==null?void 0:a.closeNav)??(()=>{}),surfaceActions:oo,floatingPanel:ao,workspaceFeatures:Qd,activeView:j,liveOutput:oe,timelineProps:lo,timelineComponent:yo,useFloatingMobileComposer:Is,floatingMobileComposerBottomOffset:Qs,composerHostRef:C,shellPanelRef:k,shellPanelComponent:jo,shellEffectiveTheme:(a==null?void 0:a.effectiveTheme)??"dark",shellThemeMode:(a==null?void 0:a.themeMode)??"system",...a!=null&&a.setThemeMode?{onShellThemeModeChange:a.setThemeMode}:{},onShellStateChange:Qe,loadingContent:e.jsx("div",{className:"host-muted flex flex-1 items-center justify-center px-6 py-12 text-center",children:"Loading thread detail..."}),emptyContent:e.jsx("div",{className:"host-muted flex flex-1 items-center justify-center px-6 py-12 text-center",children:"Unable to resolve this thread."}),dialogs:uo,...ka?{composerProps:ka}:{},...Ca?{shellComposerProps:Ca}:{}})}function ac(){const t=rt(),[s,a]=r.useState(""),[n,d]=r.useState(Tt),[o,m]=r.useState([]),[h,g]=r.useState(!0),[y,A]=r.useState(!1),[x,f]=r.useState(null);r.useEffect(()=>{let E=!1;return g(!0),pa().then(v=>{var te,_;if(E)return;m(v);const J=((te=v.find(R=>R.isDefault&&R.enabled))==null?void 0:te.provider)??((_=v.find(R=>R.enabled))==null?void 0:_.provider)??Tt;d(J)}).catch(()=>{E||m([])}).finally(()=>{E||g(!1)}),()=>{E=!0}},[]);const k=r.useMemo(()=>o.length>0?o:[{provider:Tt,displayName:Pa[Tt].displayName,enabled:!0}],[o]);async function C(E){E.preventDefault();const v=s.trim();if(!v){f("Session ID is required.");return}A(!0),f(null);try{const J=await Vl({sessionId:v,provider:n});t(`/threads/${J.thread.id}`)}catch(J){J instanceof re?f(J.payload.message):f(J instanceof Error?J.message:"Unable to import session.")}finally{A(!1)}}return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("p",{className:"host-page-eyebrow text-xs uppercase tracking-[0.3em]",children:"Import Session"}),e.jsx("h2",{className:"host-page-title mt-2 text-3xl font-semibold",children:"Bring in a local backend session"}),e.jsx("p",{className:"host-page-description mt-3 max-w-3xl text-sm leading-6",children:"Select the backend and paste a session ID from this machine. Supervisor will recover the workspace path, reuse an existing workspace when possible, or create one with the last folder name as the default label."}),e.jsx("p",{className:"host-muted mt-2 max-w-3xl text-sm leading-6",children:"Imported history appears immediately, but sending a new prompt still requires a manual Resume / Connect."})]}),e.jsxs("form",{onSubmit:C,className:"host-panel space-y-5 rounded-3xl border p-6",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"backend-provider",className:"host-form-label text-sm font-medium",children:"Backend"}),e.jsx("select",{id:"backend-provider",value:n,onChange:E=>d(E.target.value),disabled:y||h,className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition",children:k.map(E=>e.jsxs("option",{value:E.provider,children:[E.displayName||Pa[E.provider].displayName,E.enabled?"":" (not ready)"]},E.provider))})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"session-id",className:"host-form-label text-sm font-medium",children:"Session ID"}),e.jsx("input",{id:"session-id",value:s,onChange:E=>a(E.target.value),placeholder:"019d6fb7-7033-7a30-a2c7-74d0919e87d4",className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition"})]}),x&&e.jsx("div",{className:"host-error rounded-2xl border px-4 py-3 text-sm",children:x}),e.jsx("div",{className:"flex flex-wrap items-center gap-3",children:e.jsx("button",{type:"submit",disabled:y,className:"ui-action-primary rounded-full px-5 py-3 font-medium transition disabled:cursor-not-allowed",children:y?"Importing...":"Import Session"})})]})]})}function yn(t){return t.enabled&&t.capabilities.sessions.resume&&t.capabilities.turns.start}function rc(t,s){var n;const a=t.find(d=>d.provider===s);return a&&yn(a)?a.provider:((n=t.find(yn))==null?void 0:n.provider)??Tt}function oc(){const t=rt(),s=Jt(),[a]=mr(),[n,d]=r.useState([]),[o,m]=r.useState([]),[h,g]=r.useState([]),[y,A]=r.useState((s==null?void 0:s.defaultBackend)??Tt),[x,f]=r.useState(""),[k,C]=r.useState(""),E=a.get("title"),[v,J]=r.useState(()=>E??""),[te,_]=r.useState("yolo"),[R,X]=r.useState(!0),[c,D]=r.useState(!1),[Y,I]=r.useState(null),q=a.get("workspaceId"),B=(s==null?void 0:s.defaultBackend)??Tt;r.useEffect(()=>{let H=!1;return Promise.all([fa(),pa()]).then(async([pe,T])=>{var F,z,ue;if(H)return;const le=rc(T,B);A(le),m(T);const oe=await oa(le);if(H)return;d(pe),g(oe);const W=pe.some(xe=>xe.id===q)?q:((F=pe[0])==null?void 0:F.id)??"";f(W),C(((z=oe.find(xe=>xe.isDefault))==null?void 0:z.model)??((ue=oe[0])==null?void 0:ue.model)??"")}).catch(pe=>{H||I(pe instanceof Error?pe.message:"Unable to load creation form data.")}).finally(()=>{H||X(!1)}),()=>{H=!0}},[B,q]),r.useEffect(()=>{if(!y)return;let H=!1;return g([]),C(""),I(null),oa(y).then(pe=>{var T,le;H||(g(pe),C(((T=pe.find(oe=>oe.isDefault))==null?void 0:T.model)??((le=pe[0])==null?void 0:le.model)??""))}).catch(pe=>{H||(g([]),C(""),I(pe instanceof Error?pe.message:"Unable to load backend models."))}),()=>{H=!0}},[y]);function ve(){if(window.history.length>1){t(-1);return}if(q){t(`/threads?workspaceId=${encodeURIComponent(q)}`);return}t("/workspaces")}async function fe(H){H.preventDefault(),D(!0),I(null);try{const pe=await zl(v.trim()?{workspaceId:x,provider:y,model:k,approvalMode:te,title:v.trim()}:{workspaceId:x,provider:y,model:k,approvalMode:te});t(`/threads/${pe.id}`)}catch(pe){pe instanceof re?I(pe.payload.message):I(pe instanceof Error?pe.message:"Unable to create thread.")}finally{D(!1)}}return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("p",{className:"host-page-eyebrow text-xs uppercase tracking-[0.3em]",children:"New Thread"}),e.jsx("h2",{className:"host-page-title mt-2 text-3xl font-semibold",children:"Start a backend session"}),e.jsx("p",{className:"host-page-description mt-3 max-w-2xl text-sm leading-6",children:"Choose the workspace, model, and approval mode that should back the new thread."})]}),R?e.jsx("div",{className:"host-empty-state rounded-3xl border px-6 py-12 text-center",children:"Loading creation form..."}):e.jsxs("form",{onSubmit:fe,className:"host-panel space-y-5 rounded-3xl border p-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"host-form-label text-sm font-medium",htmlFor:"thread-backend",children:"Backend"}),e.jsx("select",{id:"thread-backend",value:y,onChange:H=>{const pe=H.target.value;A(pe)},className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition",children:o.map(H=>e.jsxs("option",{value:H.provider,disabled:!yn(H),children:[H.displayName,yn(H)?"":" (not available)"]},H.provider))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"host-form-label text-sm font-medium",htmlFor:"thread-workspace",children:"Workspace"}),e.jsx("select",{id:"thread-workspace",value:x,onChange:H=>f(H.target.value),className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition",children:n.map(H=>e.jsxs("option",{value:H.id,children:[H.label," · ",H.absPath]},H.id))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"host-form-label text-sm font-medium",htmlFor:"thread-model",children:"Model"}),e.jsxs("select",{id:"thread-model",value:k,onChange:H=>C(H.target.value),disabled:h.length===0,className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition",children:[h.length===0?e.jsx("option",{value:"",children:"No models available"}):null,h.map(H=>e.jsxs("option",{value:H.model,children:[H.displayName," · ",H.model]},H.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"host-form-label text-sm font-medium",htmlFor:"thread-title",children:"Title"}),e.jsx("input",{id:"thread-title",value:v,onChange:H=>J(H.target.value),placeholder:"Optional. Falls back to first prompt.",className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"host-form-label text-sm font-medium",htmlFor:"thread-approval-mode",children:"Approval mode"}),e.jsxs("select",{id:"thread-approval-mode",value:te,onChange:H=>_(H.target.value),className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition",children:[e.jsx("option",{value:"yolo",children:"yolo"}),e.jsx("option",{value:"guarded",children:"guarded"})]})]}),Y&&e.jsx("div",{className:"host-error rounded-2xl border px-4 py-3 text-sm",children:Y}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("button",{type:"submit",disabled:c||!x||!k,className:"ui-action-primary rounded-full px-5 py-3 font-medium transition disabled:cursor-not-allowed",children:c?"Creating...":"Create Thread"}),e.jsx("button",{type:"button",onClick:ve,disabled:c,className:"host-secondary-button rounded-full border px-5 py-3 font-medium transition disabled:cursor-not-allowed disabled:opacity-60",children:"Cancel"})]})]})]})}function lc(t){return t?`/threads/new?workspaceId=${encodeURIComponent(t)}`:"/threads/new"}function ic({getThreadHref:t,onOpenThread:s,getNewThreadHref:a,renderThreadLink:n,onCloseAppNavigation:d,...o}){const m=rt(),h=Jt(),g=d??(h==null?void 0:h.closeNav),y=o.effectiveTheme??(h==null?void 0:h.effectiveTheme),A=o.themeMode??(h==null?void 0:h.themeMode),x=o.onThemeModeChange??(h==null?void 0:h.setThemeMode);return e.jsx(wo,{...o,workspaceReturnHref:o.workspaceReturnHref??"/workspaces",globalSettingsContent:o.globalSettingsContent??e.jsx(xa,{embedded:!0}),...y?{effectiveTheme:y}:{},...A?{themeMode:A}:{},...x?{onThemeModeChange:x}:{},getThreadHref:t??(f=>`/threads/${f}`),onOpenThread:s??(f=>m(`/threads/${f}`)),getNewThreadHref:a??lc,renderThreadLink:n??(({thread:f,children:k,className:C,onClick:E})=>e.jsx(It,{to:`/threads/${f.id}`,className:C,onClick:E,children:k})),...g?{onCloseAppNavigation:g}:{}})}function Yr({open:t,title:s,label:a,value:n,busy:d=!1,onChange:o,onCancel:m,onSubmit:h}){if(r.useEffect(()=>{if(!t)return;function y(A){A.key==="Escape"&&!d&&m()}return window.addEventListener("keydown",y),()=>{window.removeEventListener("keydown",y)}},[d,m,t]),!t)return null;function g(y){y.preventDefault(),h()}return mo.createPortal(e.jsxs("div",{className:"fixed inset-0 z-[95] flex items-center justify-center p-4 sm:p-6",children:[e.jsx("button",{type:"button","aria-label":"Close rename dialog",onClick:m,disabled:d,className:"ui-overlay-scrim absolute inset-0 backdrop-blur-sm disabled:cursor-not-allowed"}),e.jsxs("form",{role:"dialog","aria-modal":"true","aria-label":s,onSubmit:g,className:"host-dialog relative z-[1] w-full max-w-md rounded-[1.6rem] border p-5 shadow-2xl shadow-black/20 sm:p-6",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"host-page-title text-sm font-medium",children:s}),e.jsx("p",{className:"host-muted mt-1 text-sm",children:"Changes are saved only after confirmation."})]}),e.jsx("button",{type:"button","aria-label":"Close dialog",onClick:m,disabled:d,className:"host-icon-button inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-full border transition disabled:cursor-not-allowed disabled:opacity-60",children:e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-4 w-4 fill-current",children:e.jsx("path",{d:"M3.22 2.47 8 7.25l4.78-4.78 1.06 1.06L9.06 8.31l4.78 4.78-1.06 1.06L8 9.37l-4.78 4.78-1.06-1.06 4.78-4.78-4.78-4.78 1.06-1.06Z"})})})]}),e.jsxs("div",{className:"mt-5",children:[e.jsx("label",{htmlFor:"rename-dialog-input",className:"host-form-label text-sm font-medium",children:a}),e.jsx("input",{id:"rename-dialog-input","aria-label":a,autoFocus:!0,value:n,onChange:y=>o(y.target.value),className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition"})]}),e.jsxs("div",{className:"mt-5 flex items-center justify-end gap-2",children:[e.jsx("button",{type:"button",onClick:m,disabled:d,className:"host-secondary-button rounded-full border px-4 py-2 text-sm font-medium transition disabled:cursor-not-allowed disabled:opacity-60",children:"Cancel"}),e.jsx("button",{type:"submit",disabled:d||!n.trim(),className:"ui-action-success rounded-full px-4 py-2 text-sm font-medium transition disabled:cursor-not-allowed",children:"Save"})]})]})]}),document.body)}function dc(){const[t]=mr(),s=rt(),a=Jt(),n=t.get("workspaceId"),[d,o]=r.useState([]),[m,h]=r.useState([]),[g,y]=r.useState(null),[A,x]=r.useState(!0),[f,k]=r.useState(null),[C,E]=r.useState(null),[v,J]=r.useState(""),[te,_]=r.useState(null),[R,X]=r.useState(null),[c,D]=r.useState(!1),Y=(a==null?void 0:a.defaultBackend)??Tt,I=r.useCallback(async()=>{x(!0),k(null);try{const[W,F,z]=await Promise.all([Ur(Y).then(ue=>ue.status),Mr(),fa()]);y(W),o(F),h(z)}catch(W){k(W instanceof Error?W.message:"Unable to load threads.")}finally{x(!1)}},[Y]);r.useEffect(()=>{if(n===null)return;I();const W=Hr(F=>{o(z=>z.map(ue=>ue.id===F.threadId?{...ue,status:F.type==="thread.updated"&&typeof F.payload.status=="string"?F.payload.status:ue.status,lastError:(F.type==="thread.turn.failed"||F.type==="thread.turn.completed")&&typeof F.payload.error=="string"?F.payload.error:ue.lastError,title:F.type==="thread.updated"&&typeof F.payload.title=="string"?F.payload.title:ue.title}:ue))});return()=>{W.close()}},[I,n]);const q=Object.fromEntries(m.map(W=>[W.id,W.label])),B=m.find(W=>W.id===n)??null,ve=r.useMemo(()=>n?d.filter(W=>W.workspaceId===n):[],[n,d]),fe=ve.filter(W=>W.status==="running").length,H=n?`/threads/new?workspaceId=${encodeURIComponent(n)}`:"/threads/new";if(n===null)return e.jsx(Os,{to:"/workspaces",replace:!0});function pe(){switch(g==null?void 0:g.state){case"ready":return"bg-emerald-400 shadow-[0_0_0_3px_rgba(52,211,153,0.14)]";case"starting":return"bg-amber-300 shadow-[0_0_0_3px_rgba(252,211,77,0.12)]";case"degraded":case"failed":return"bg-rose-400 shadow-[0_0_0_3px_rgba(251,113,133,0.14)]";default:return"bg-stone-500 shadow-[0_0_0_3px_rgba(120,113,108,0.14)]"}}async function T(W,F){try{const z=await Lr(W,{title:F});o(ue=>ue.map(xe=>xe.id===z.id?{...xe,title:z.title,updatedAt:z.updatedAt}:xe))}catch(z){throw k(z instanceof Error?z.message:"Unable to rename thread."),z}}async function le(){if(!C)return;const W=v.trim();if(W){_(C);try{await T(C,W),E(null),J("")}finally{_(null)}}}async function oe(){if(R){D(!0);try{await Dr(R.id),o(W=>W.filter(F=>F.id!==R.id)),X(null)}catch(W){k(W instanceof Error?W.message:"Unable to delete thread.")}finally{D(!1)}}}return e.jsx(ic,{threads:d,workspaceLabels:q,status:g,loading:A,error:f,viewportConstrained:n!==null,showMobileAppMenu:!0,showMobileThreadNavToggle:!1,showMobileNewThreadShortcut:!1,currentWorkspaceId:n,currentWorkspaceLabel:(B==null?void 0:B.label)??null,onRenameThread:T,onDeleteThread:X,children:e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"host-panel flex min-h-0 flex-1 flex-col overflow-hidden rounded-[2rem] border shadow-2xl shadow-black/10",children:[e.jsx("div",{className:"border-b border-[var(--theme-border)] px-4 py-3 sm:px-6 sm:py-4",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("h2",{className:"host-page-title min-w-0 truncate text-base font-semibold sm:text-lg",title:B?`${B.label} threads`:"All threads",children:B?B.label:"All Threads"}),e.jsx(It,{to:H,className:"ui-action-primary inline-flex h-9 shrink-0 items-center rounded-full px-3.5 text-xs font-medium uppercase tracking-[0.18em] transition",children:"New Thread"})]})}),e.jsx("div",{className:"px-4 py-3 sm:px-6 sm:py-4",children:e.jsxs("article",{className:"host-surface-strong inline-flex min-w-[12rem] max-w-full items-center gap-3 rounded-[1.25rem] border px-3.5 py-2.5",children:[e.jsx("span",{"aria-hidden":"true",className:`h-2.5 w-2.5 shrink-0 rounded-full ${pe()}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"host-muted truncate text-[11px] uppercase tracking-[0.22em]",children:"Supervisor"}),e.jsx("p",{className:"host-soft truncate text-sm",children:(g==null?void 0:g.lastError)??((g==null?void 0:g.state)==="ready"?"Ready":(g==null?void 0:g.state)??"Checking")})]})]})}),!A&&!f&&ve.length>0&&e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col border-t border-[var(--theme-border)] px-4 py-4 sm:px-6 sm:py-5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"host-muted text-xs uppercase tracking-[0.28em]",children:"Recent Threads"}),e.jsxs("span",{className:"host-warning-pill rounded-full border px-2 py-0.5 text-[11px] font-medium uppercase tracking-[0.18em]",children:[ve.length," total"]}),fe>0&&e.jsxs("span",{className:"host-muted text-xs",children:["· ",fe," running"]})]}),e.jsx("div",{className:"mt-3 min-h-0 flex-1",children:e.jsx(No,{threads:ve,currentWorkspaceId:n,workspaceLabels:q,onOpenThread:W=>s(`/threads/${W}`),onBeginRenameThread:W=>{E(W.id),J(W.title)},onDeleteThread:W=>X(W),scrollable:!0,maxHeightClassName:"max-h-full",showDeleteButton:!0,showSessionCopyButton:!0})})]}),!A&&!f&&ve.length===0&&e.jsx("div",{className:"host-muted border-t border-[var(--theme-border)] px-4 py-6 text-sm sm:px-6",children:"No threads available in this workspace."})]}),e.jsx(Yr,{open:C!==null,title:"Rename Thread",label:"Thread Title",value:v,busy:te!==null,onChange:J,onCancel:()=>{E(null),J("")},onSubmit:()=>void le()}),e.jsx(wn,{open:R!==null,title:"Delete Thread",description:R?`Delete ${Po(R.title)} from supervisor. The backend session id will no longer appear in this workspace list.`:"",confirmLabel:"Delete Thread",busy:c,onCancel:()=>{c||X(null)},onConfirm:()=>void oe()})]})})}function dr(t){const s=t.trim(),a=s.replace(/[\\/]+$/,"");if(!a)return"";if(Zr(s)){const d=(a.split(/[?#]/)[0]??a).split(/[/:]/).filter(Boolean).at(-1)??"";return d.endsWith(".git")?d.slice(0,-4):d}return a.split(/[\\/]/).filter(Boolean).at(-1)??""}function Zr(t){const s=t.trim();return/^https?:\/\/.+/i.test(s)||/^ssh:\/\/.+/i.test(s)||/^git@[^:]+:.+/.test(s)}function cc({initialPath:t="",initialLabel:s="",submitLabel:a="Save Workspace",error:n,busy:d=!1,onSubmit:o}){const m=dr(t),[h,g]=r.useState(t),[y,A]=r.useState(s||m),[x,f]=r.useState(null),k=r.useRef(m);r.useEffect(()=>{const E=dr(h);A(v=>!v.trim()||v===k.current?E:v),k.current=E},[h]);async function C(E){E.preventDefault();const v=h.trim();if(!v){f("Workspace path or Git URL is required.");return}f(null);const J=y.trim(),te=Zr(v)?"gitUrl":"absPath";await o(J?{[te]:v,label:J}:{[te]:v})}return e.jsxs("form",{onSubmit:C,className:"host-panel space-y-5 rounded-3xl border p-6",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"workspace-path",className:"host-form-label text-sm font-medium",children:"Path or Git URL"}),e.jsx("input",{id:"workspace-path",name:"absPath",value:h,onChange:E=>g(E.target.value),placeholder:"/Users/name/project or https://github.com/owner/repo.git",className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition"}),e.jsx("p",{className:"host-muted mt-2 text-xs",children:"Absolute paths register local directories. Git URLs clone into the configured dev home."})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"workspace-label",className:"host-form-label text-sm font-medium",children:"Display label"}),e.jsx("input",{id:"workspace-label",name:"label",value:y,onChange:E=>A(E.target.value),placeholder:"Optional override",className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition"}),e.jsx("p",{className:"host-muted mt-2 text-xs",children:"Defaults to the last folder name. You can override it."})]}),(x||n)&&e.jsx("div",{className:"host-error rounded-2xl border px-4 py-3 text-sm",children:x??n}),e.jsx("button",{type:"submit",disabled:d,className:"ui-action-primary rounded-full px-5 py-3 font-medium transition disabled:cursor-not-allowed",children:d?"Saving...":a})]})}function uc(){const t=rt(),[s,a]=r.useState(null),[n,d]=r.useState(!1);async function o(m){d(!0),a(null);try{const h=await mi(m);t(`/threads?workspaceId=${encodeURIComponent(h.id)}`)}catch(h){h instanceof re?a(h.payload.message):a(h instanceof Error?h.message:"Unable to create workspace.")}finally{d(!1)}}return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("p",{className:"host-page-eyebrow text-xs uppercase tracking-[0.3em]",children:"Add Workspace"}),e.jsx("h2",{className:"host-page-title mt-2 text-3xl font-semibold",children:"Create a workspace"}),e.jsx("p",{className:"host-page-description mt-3 max-w-2xl text-sm leading-6",children:"Register an existing local directory, create one missing child directory under dev home, or clone a Git repository into dev home."})]}),e.jsx(cc,{busy:n,error:s,submitLabel:"Create Workspace",onSubmit:o})]})}function cr(t){return Date.parse(t.lastOpenedAt??t.createdAt)}function mc(t,s){return t.isFavorite!==s.isFavorite?t.isFavorite?-1:1:cr(s)-cr(t)}function hc(t){return t?new Date(t).toLocaleString():"Never opened"}function pc(t,s=28){return t.length<=s?t:`...${t.slice(-(s-3))}`}function fc({active:t}){return e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:`h-3.5 w-3.5 fill-current ${t?"rotate-[18deg]":"rotate-[8deg]"}`,children:e.jsx("path",{d:"M10.7 1.75c.34 0 .62.28.62.63v1.24l1.43 1.42c.24.24.24.62 0 .86l-1.1 1.1v2.02c0 .17-.07.33-.19.45l-1.5 1.5v2.28c0 .28-.18.53-.44.6a.62.62 0 0 1-.69-.24L7.2 12.4l-2.83 2.83a.625.625 0 1 1-.88-.88l2.83-2.83-2.2-1.62a.62.62 0 0 1-.24-.69c.08-.26.32-.44.6-.44h2.28l1.5-1.5a.64.64 0 0 1 .45-.18h2.02l1.1-1.11-1.42-1.42H9.07a.63.63 0 0 1-.62-.63c0-.34.28-.62.62-.62h1.63Z"})})}function xc(){return e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-3.5 w-3.5 fill-current",children:e.jsx("path",{d:"M6.1 1.75h3.8c.75 0 1.4.52 1.57 1.25h2.03c.35 0 .63.28.63.63 0 .34-.28.62-.63.62h-.66l-.62 8.03c-.08 1.09-.99 1.97-2.08 1.97H5.86c-1.09 0-2-.88-2.08-1.97l-.62-8.03H2.5a.62.62 0 1 1 0-1.25h2.03c.17-.73.82-1.25 1.57-1.25Zm0 1.25c-.07 0-.14.03-.19.08A.26.26 0 0 0 5.84 3h4.32a.26.26 0 0 0-.07-.17.26.26 0 0 0-.19-.08H6.1Zm-1.07 1.25.61 7.93c.03.44.4.79.84.79h3.04c.44 0 .81-.35.84-.79l.61-7.93H5.03Zm1.53 1.32c.35 0 .62.28.62.62v4.19a.62.62 0 1 1-1.24 0V6.19c0-.34.28-.62.62-.62Zm2.82 0c.34 0 .62.28.62.62v4.19a.62.62 0 1 1-1.24 0V6.19c0-.34.28-.62.62-.62Z"})})}function gc(){const t=rt(),[s,a]=r.useState([]),[n,d]=r.useState(!0),[o,m]=r.useState(null),[h,g]=r.useState(null),[y,A]=r.useState(null),[x,f]=r.useState(null),[k,C]=r.useState(""),[E,v]=r.useState(null),[J,te]=r.useState(null),[_,R]=r.useState(null),[X,c]=r.useState(!1);async function D(){d(!0),A(null);try{a(await fa())}catch(T){A(T instanceof Error?T.message:"Unable to load workspaces.")}finally{d(!1)}}r.useEffect(()=>{D(),il().then(T=>{m(T),g(null)}).catch(T=>{g(T instanceof Error?T.message:"Unable to load supervisor config.")})},[]);async function Y(T){const le={...T,isFavorite:!T.isFavorite};a(oe=>oe.map(W=>W.id===T.id?le:W));try{const oe=await fi(T.id,{isFavorite:!T.isFavorite});a(W=>W.map(F=>F.id===oe.id?oe:F))}catch(oe){a(W=>W.map(F=>F.id===T.id?T:F)),A(oe instanceof Error?oe.message:"Unable to update workspace.")}}async function I(T){const le=k.trim();if(le){v(T);try{const oe=await hi(T,{label:le});a(W=>W.map(F=>F.id===oe.id?oe:F)),f(null),C("")}catch(oe){A(oe instanceof Error?oe.message:"Unable to rename workspace.")}finally{v(null)}}}function q(T){f(T.id),C(T.label)}function B(){f(null),C("")}function ve(T){t(`/threads?workspaceId=${encodeURIComponent(T)}`)}async function fe(){if(_){c(!0);try{await pi(_.id),a(T=>T.filter(le=>le.id!==_.id)),R(null)}catch(T){A(T instanceof Error?T.message:"Unable to delete workspace.")}finally{c(!1)}}}function H(T,le){(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),ve(le))}const pe=r.useMemo(()=>[...s].sort(mc),[s]);return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"host-topbar sticky top-[env(safe-area-inset-top)] z-20 -mx-4 border-b px-2.5 py-2 backdrop-blur sm:mx-0 sm:rounded-[1.4rem] sm:border sm:px-4",children:e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 sm:gap-2",children:[e.jsx(Fr,{}),e.jsx(It,{to:"/threads/import",className:"host-info-pill inline-flex h-8 shrink-0 items-center rounded-full border px-2.5 text-[11px] font-medium uppercase tracking-[0.14em] transition sm:px-3 sm:text-xs sm:tracking-[0.18em]",children:"Import"}),e.jsx(It,{to:"/workspaces/new",className:"ui-action-primary inline-flex h-8 shrink-0 items-center rounded-full px-2.5 text-[11px] font-medium uppercase tracking-[0.14em] transition sm:px-3 sm:text-xs sm:tracking-[0.18em]",children:"Create"}),e.jsx("div",{className:"min-w-0 flex-1 text-right",children:e.jsx("p",{className:"host-page-eyebrow truncate text-[11px] uppercase tracking-[0.24em]",children:"Workspaces"})})]}),e.jsx(Wr,{className:"absolute left-0 top-[calc(100%+0.5rem)] z-30 w-[min(22rem,calc(100vw-1rem))]"})]})}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1fr)_20rem]",children:[e.jsxs("section",{className:"min-w-0 space-y-4",children:[n&&e.jsx("div",{className:"host-empty-state rounded-[1.6rem] border px-6 py-12 text-center",children:"Loading workspace registry..."}),y&&e.jsx("div",{className:"host-error rounded-[1.4rem] border px-4 py-4",children:y}),!n&&!y&&s.length===0&&e.jsxs("div",{className:"host-empty-state rounded-[1.6rem] border border-dashed px-6 py-12 text-center",children:[e.jsx("p",{className:"host-page-title text-lg font-medium",children:"No workspaces yet"}),e.jsx("p",{className:"host-muted mt-2 text-sm",children:"Add a local directory inside the configured workspace root to start building the registry."})]}),!n&&pe.length>0&&e.jsx("div",{className:"space-y-2 overflow-x-hidden",children:pe.map(T=>e.jsxs("article",{role:"link",tabIndex:0,onClick:()=>ve(T.id),onKeyDown:le=>H(le,T.id),className:"host-card relative overflow-hidden rounded-[1.35rem] border px-4 py-3 transition",children:[e.jsxs("div",{className:"absolute right-2.5 top-2.5 flex items-center gap-1.5",children:[e.jsx("button",{type:"button","aria-label":`Delete workspace ${T.label}`,title:"Delete workspace",onClick:le=>{le.stopPropagation(),R(T)},className:"inline-flex h-7 w-7 items-center justify-center rounded-full border border-[var(--status-danger-border)] bg-[var(--status-danger-bg)] text-[var(--status-danger-fg)] transition hover:bg-[var(--status-danger-border)]",children:e.jsx(xc,{})}),e.jsx("button",{type:"button","aria-label":T.isFavorite?`Unpin workspace ${T.label}`:`Pin workspace ${T.label}`,title:T.isFavorite?"Unpin workspace":"Pin workspace",onClick:le=>{le.stopPropagation(),Y(T)},className:`inline-flex h-7 w-7 items-center justify-center rounded-full border transition ${T.isFavorite?"host-warning-pill":"host-icon-button"}`,children:e.jsx(fc,{active:T.isFavorite})})]}),e.jsx("div",{className:"flex min-w-0 items-start gap-3 pr-[4.6rem]",children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[e.jsx("p",{className:"host-page-title min-w-0 max-w-full truncate text-base font-semibold sm:text-lg",title:T.label,children:T.label}),e.jsx("button",{type:"button",onClick:le=>{le.stopPropagation(),q(T)},"aria-label":`Rename workspace ${T.label}`,className:"host-muted inline-flex h-4 w-4 shrink-0 items-center justify-center transition hover:text-[var(--theme-fg)]",children:e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-3 w-3 fill-current",children:e.jsx("path",{d:"m11.9 1.6 2.5 2.5-8.2 8.2-3.3.7.7-3.3 8.3-8.1Zm-7.3 8.7-.3 1.3 1.3-.3 6.9-6.9-1-1-6.9 6.9Zm8.8-7.8-1-1-1 1 1 1 1-1Z"})})})]}),e.jsx("button",{type:"button","aria-label":T.absPath,title:T.absPath,onClick:le=>{le.stopPropagation(),te(T.absPath)},className:"host-muted mt-1 inline-block max-w-full overflow-hidden whitespace-nowrap text-left text-[9px] leading-4 transition hover:text-[var(--theme-fg-soft)]",children:pc(T.absPath)}),e.jsx("div",{className:"host-muted mt-2 flex flex-wrap items-center gap-2 text-xs",children:e.jsxs("span",{className:"min-w-0 truncate",children:["Last opened: ",hc(T.lastOpenedAt)]})})]})})]},T.id))})]}),e.jsx(bc,{config:o,error:h,workspaceCount:s.length})]}),e.jsx(Yr,{open:x!==null,title:"Rename Workspace",label:"Workspace Label",value:k,busy:E!==null,onChange:C,onCancel:B,onSubmit:()=>x?I(x):void 0}),e.jsx(So,{open:J!==null,title:"Workspace Path",text:J??"",onClose:()=>te(null)}),e.jsx(wn,{open:_!==null,title:"Delete Workspace",description:_?`Delete ${_.label} from supervisor. This also removes its threads and local supervisor metadata.`:"",confirmLabel:"Delete Workspace",busy:X,onCancel:()=>{X||R(null)},onConfirm:()=>void fe()})]})}function bc({config:t,error:s,workspaceCount:a}){return e.jsxs("aside",{className:"space-y-3 xl:sticky xl:top-[calc(env(safe-area-inset-top)+4.25rem)] xl:self-start",children:[e.jsxs("section",{className:"rounded-[1.2rem] border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.18em] text-[var(--theme-fg-muted)]",children:"Supervisor"}),e.jsxs("dl",{className:"mt-4 space-y-3",children:[e.jsx(pn,{label:"Workspace root",value:(t==null?void 0:t.workspaceRoot)??"Loading..."}),e.jsx(pn,{label:"Environment",value:t?`${t.environment} · ${t.host}:${t.port}`:s??"Loading..."}),e.jsx(pn,{label:"Version",value:t?`${t.appName} ${t.appVersion}`:"Loading..."}),e.jsx(pn,{label:"Workspaces",value:String(a)})]})]}),s?e.jsx("section",{className:"rounded-[1.2rem] border border-[var(--status-warning-border)] bg-[var(--status-warning-bg)] p-4 text-sm text-[var(--status-warning-fg)]",children:"Runtime metadata is unavailable. Workspace actions may still work if a relay device is connected."}):null]})}function pn({label:t,value:s}){return e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-[var(--theme-fg-muted)]",children:t}),e.jsx("dd",{className:"mt-1 break-words font-mono text-xs leading-5 text-[var(--theme-fg)]",children:s})]})}const Xr="remote-codex-theme-mode",Qr="remote-codex-default-backend",eo="remote-codex-auto-collapse-completed-turns";function to(){return!1}function vc(){return to()?e.jsx(Os,{to:"/control-plane",replace:!0}):e.jsx(Os,{to:"/workspaces",replace:!0})}function jc({children:t}){const s=es(),a=s.pathname.startsWith("/control-plane")||s.pathname==="/"&&to(),n=r.useMemo(()=>a?{}:{fetchPlugins:Ll,importPlugin:Dl,updatePlugin:Hl,deletePlugin:_l},[a]);return e.jsx(ko,{adapter:n,children:t})}function yc(){if(typeof window>"u")return"system";const t=window.localStorage.getItem(Xr);return t==="light"||t==="dark"||t==="system"?t:"system"}function wc(){if(typeof window>"u")return Tt;const t=window.localStorage.getItem(Qr);return Eo(t)??Tt}function Nc(){return typeof window>"u"?!0:window.localStorage.getItem(eo)!=="false"}function Sc(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function kc({themeMode:t,setThemeMode:s,effectiveTheme:a}){const[n,d]=r.useState(!1),[o,m]=r.useState(!1),[h,g]=r.useState(wc),[y,A]=r.useState(Nc),x=es(),f=/^\/threads\/[^/]+$/.test(x.pathname),k=/^\/control-plane\/sessions\/[^/]+$/.test(x.pathname),C=x.pathname==="/threads",E=f||k||C,v=C||f||k,J=f||k,te=x.pathname==="/workspaces",_=x.pathname.startsWith("/control-plane"),R=te||C||_;r.useEffect(()=>{d(!1)},[x.pathname,x.search]);function X(Y){g(Y),window.localStorage.setItem(Qr,Y)}function c(Y){A(Y),window.localStorage.setItem(eo,Y?"true":"false")}const D={navOpen:n,openNav:()=>d(!0),toggleNav:()=>d(Y=>!Y),closeNav:()=>d(!1),settingsOpen:o,openSettings:()=>{d(!1),m(!0)},closeSettings:()=>m(!1),themeMode:t,setThemeMode:s,effectiveTheme:a,defaultBackend:h,setDefaultBackend:X,autoCollapseCompletedTurns:y,setAutoCollapseCompletedTurns:c};return e.jsxs(Co.Provider,{value:D,children:[e.jsxs("div",{className:`bg-[var(--app-bg)] text-[var(--app-fg)] ${E?"fixed inset-0 overflow-hidden overscroll-none":"min-h-screen"}`,children:[te?e.jsx(ga,{}):null,!R&&!J&&e.jsxs("div",{className:"fixed left-4 top-4 z-50",children:[e.jsx(Fr,{}),e.jsx(Wr,{className:"mt-3 w-[min(22rem,calc(100vw-2rem))]"})]}),e.jsx("main",{className:`mx-auto w-full ${v?"max-w-none":"max-w-[1600px]"} ${E?"absolute inset-0 pb-0 sm:pb-4":"pb-4"} ${v?f||k?"pt-0":C?"pt-[env(safe-area-inset-top)] sm:pt-4":"pt-[calc(env(safe-area-inset-top)+4rem)] sm:pt-4":te||_?"pt-[env(safe-area-inset-top)] sm:pt-4":"pt-4"} ${E?f||k?"overflow-hidden overscroll-none px-0":"overflow-hidden overscroll-none px-0 sm:px-6":"px-4 sm:px-6"}`,children:e.jsx("section",{className:`min-w-0 ${E?f||k?"h-full min-h-0 overflow-hidden overscroll-none":"h-full overflow-hidden overscroll-none":""}`,children:e.jsx(po,{})})})]}),e.jsx(xa,{})]})}function Cc({children:t}){const[s,a]=r.useState({status:"checking"});async function n(m){try{const h=await dl();if(m!=null&&m())return;a(!h.authRequired||h.authenticated?{status:"authenticated"}:{status:"loginRequired",session:h,error:null})}catch(h){if(m!=null&&m())return;if(h instanceof re&&h.statusCode===401){a({status:"loginRequired",session:{authenticated:!1,username:null,expiresAt:null,mode:"server",authRequired:!0},error:null});return}a({status:"unavailable",error:h instanceof Error?h.message:"Unable to check supervisor access."})}}r.useEffect(()=>{let m=!1;return n(()=>m),()=>{m=!0}},[]);async function d(m){await cl(m),a({status:"authenticated"})}function o(){a({status:"checking"}),n()}return s.status==="checking"?e.jsx("main",{className:"flex min-h-screen items-center justify-center bg-[var(--app-bg)] px-4 text-sm text-[var(--theme-muted)]",children:"Checking supervisor access..."}):s.status==="unavailable"?e.jsx("main",{className:"flex min-h-screen items-center justify-center bg-[var(--app-bg)] px-4 text-[var(--app-fg)]",children:e.jsxs("section",{className:"w-full max-w-md rounded-[1.35rem] border border-[var(--theme-border)] bg-[var(--theme-panel)] p-5 shadow-2xl shadow-[color-mix(in_oklch,var(--app-fg)_14%,transparent)] sm:p-6",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-muted)]",children:"Supervisor Access"}),e.jsx("h1",{className:"mt-2 text-2xl font-semibold tracking-normal text-[var(--theme-fg)]",children:"Unable to reach supervisor"}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-[var(--theme-muted)]",children:s.error}),e.jsx("button",{className:"mt-5 h-11 rounded-xl bg-[var(--theme-accent-solid)] px-4 text-sm font-semibold text-[var(--theme-accent-solid-fg)] transition hover:bg-[var(--theme-accent-solid-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--theme-accent-border)]",onClick:o,type:"button",children:"Retry"})]})}):s.status==="loginRequired"?e.jsxs(e.Fragment,{children:[s.error&&e.jsx("div",{className:"fixed left-1/2 top-4 z-50 w-[min(28rem,calc(100vw-2rem))] -translate-x-1/2 rounded-xl border border-[var(--status-warning-border)] bg-[var(--status-warning-bg)] px-3 py-2 text-sm text-[var(--status-warning-fg)]",children:s.error}),e.jsx(Ad,{onLogin:d})]}):t}function Tc({children:t}){const[s,a]=r.useState({status:"checking"});return r.useEffect(()=>{let n=!1;return $s().then(d=>{n||a(d.authenticated?{status:"authenticated",session:d}:{status:"loginRequired"})}).catch(()=>{n||a({status:"loginRequired"})}),()=>{n=!0}},[]),s.status==="checking"?e.jsx("main",{className:"flex min-h-screen items-center justify-center bg-[var(--app-bg)] px-4 text-sm text-[var(--theme-muted)]",children:"Checking relay access..."}):s.status==="loginRequired"?e.jsx(Kr,{}):t}function Ic({children:t}){return es().pathname.startsWith("/control-plane")?t:na()?e.jsx(Tc,{children:t}):e.jsx(Cc,{children:t})}function Ec({themeMode:t,setThemeMode:s,effectiveTheme:a}){return e.jsxs(hr,{children:[e.jsx(qe,{path:"/",element:e.jsx(Os,{to:"/workspaces",replace:!0})}),e.jsxs(qe,{element:e.jsx(kc,{themeMode:t,setThemeMode:s,effectiveTheme:a}),children:[e.jsx(qe,{path:"/workspaces",element:e.jsx(gc,{})}),e.jsx(qe,{path:"/workspaces/new",element:e.jsx(uc,{})}),e.jsx(qe,{path:"/relay-account",element:e.jsx(Ud,{})}),e.jsx(qe,{path:"/relay-devices",element:e.jsx($d,{})}),e.jsx(qe,{path:"/control-plane/login",element:e.jsx(Qi,{})}),e.jsx(qe,{path:"/control-plane",element:e.jsx(Xa,{children:e.jsx(Ki,{})})}),e.jsx(qe,{path:"/control-plane/sessions/:sessionId",element:e.jsx(Xa,{children:e.jsx(Rd,{})})}),e.jsx(qe,{path:"/threads",element:e.jsx(dc,{})}),e.jsx(qe,{path:"/threads/import",element:e.jsx(ac,{})}),e.jsx(qe,{path:"/threads/new",element:e.jsx(oc,{})}),e.jsx(qe,{path:"/threads/:id",element:e.jsx(nc,{})})]})]})}function Rc(){const[t,s]=r.useState(()=>yc()),[a,n]=r.useState(()=>Sc()),d=t==="system"?a:t;return r.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const o=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{n(o.matches?"dark":"light")};return m(),typeof o.addEventListener=="function"?o.addEventListener("change",m):o.addListener(m),()=>{typeof o.removeEventListener=="function"?o.removeEventListener("change",m):o.removeListener(m)}},[]),r.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(Xr,t)},[t]),r.useEffect(()=>{const o=document.documentElement;o.dataset.themeMode=t,o.dataset.themeEffective=d,o.style.colorScheme=d},[d,t]),e.jsx("div",{className:"theme-shell theme-scrollbar",children:e.jsx(ho,{children:e.jsx(jc,{children:e.jsxs(hr,{children:[e.jsx(qe,{path:"/",element:e.jsx(vc,{})}),e.jsx(qe,{path:"/relay-portal",element:e.jsx(Kr,{})}),e.jsx(qe,{path:"/relay-admin",element:e.jsx(Od,{})}),e.jsx(qe,{path:"/*",element:e.jsx(Ic,{children:e.jsx(Ec,{themeMode:t,setThemeMode:s,effectiveTheme:d})})})]})})})})}fo.createRoot(document.getElementById("root")).render(e.jsx(xo.StrictMode,{children:e.jsx(Rc,{})}));
|
|
3
|
+
${a}`:t.message}function Es(t){return{path:t,exists:!1,originalContent:"",draftContent:"",loading:!1,saving:!1,error:null,saveMessage:null}}function Fr({className:t=""}){const s=Jt();return s?e.jsx("button",{type:"button","aria-label":s.navOpen?"Close Navigation":"Open Navigation","aria-expanded":s.navOpen,"aria-controls":"app-shell-navigation-menu",onClick:s.toggleNav,className:`inline-flex h-10 w-10 shrink-0 items-center justify-center text-[var(--theme-fg)] transition hover:text-[var(--theme-fg-soft)] ${t}`.trim(),children:s.navOpen?e.jsx(fn,{}):e.jsx(vi,{})}):null}function Wr({className:t=""}){const s=Jt(),a=es(),n=at(),d=r.useRef(null),o=a.pathname==="/workspaces",m=a.pathname==="/threads/import";return r.useEffect(()=>{if(!(s!=null&&s.navOpen))return;const h=s;function g(y){const A=y.target;if(!A)return;const x=d.current;x!=null&&x.contains(A)||A instanceof Element&&A.closest('[aria-controls="app-shell-navigation-menu"]')||h.closeNav()}return document.addEventListener("pointerdown",g),()=>{document.removeEventListener("pointerdown",g)}},[s]),s!=null&&s.navOpen?e.jsxs("div",{ref:d,id:"app-shell-navigation-menu",onPointerDown:h=>{h.stopPropagation()},onMouseDown:h=>{h.stopPropagation()},onTouchStart:h=>{h.stopPropagation()},className:`rounded-[1.8rem] border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4 shadow-2xl shadow-black/15 backdrop-blur ${t}`.trim(),children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-base font-semibold tracking-wide text-[var(--theme-accent-strong)]",children:"Remote Codex"}),e.jsx("p",{className:"mt-1 text-xs uppercase tracking-[0.24em] text-[var(--theme-fg-muted)]",children:"Navigation"})]}),e.jsxs("nav",{className:"mt-4 flex flex-col gap-1.5 text-sm",children:[e.jsx("button",{type:"button",disabled:o,onClick:()=>{o||(s.closeNav(),n("/workspaces"))},className:Mn(o),children:"Workspaces"}),e.jsx("button",{type:"button",disabled:m,onClick:()=>{m||(s.closeNav(),n("/threads/import"))},className:Mn(m),children:"Import Session"}),e.jsx("button",{type:"button",onClick:()=>{s.openSettings()},className:Mn(),children:"Settings"})]})]}):null}function xa({embedded:t=!1}={}){const s=Jt(),a=ca(),[n,d]=r.useState(""),[o,m]=r.useState({busy:!1,message:null,error:null}),[h,g]=r.useState(!1),[y,A]=r.useState(null),[x,f]=r.useState({}),k=y?x[y]:null,[C,E]=r.useState({busy:!1,message:null,error:null}),[v,J]=r.useState([]),[te,_]=r.useState(hs),[R,X]=r.useState({loading:!1,saving:!1,error:null,operatingProvider:null,operatingAction:null,message:null}),[c,D]=r.useState(null),[Y,I]=r.useState({devHomeDraft:"",loading:!1,saving:!1,message:null,error:null}),[q,B]=r.useState({loading:!1,creating:!1,applyingId:null,renamingId:null,renameDraft:"",message:null,error:null}),je=(s==null?void 0:s.themeMode)??"system",fe=t||!!(s!=null&&s.settingsOpen);async function H(){const b=n.trim();if(!(!b||o.busy)){m({busy:!0,message:null,error:null});try{await a.importPluginManifest({manifestJson:b,enabled:!0}),d(""),m({busy:!1,message:"Plugin manifest imported.",error:null})}catch(j){m({busy:!1,message:null,error:j instanceof Error?j.message:"Unable to import plugin manifest."})}}}const he=(s==null?void 0:s.effectiveTheme)??"dark",T=(s==null?void 0:s.autoCollapseCompletedTurns)??!0,le=(s==null?void 0:s.defaultBackend)??xr,oe=a.plugins.filter(b=>b.enabled).length,W=a.loading?"Loading...":`${oe}/${a.plugins.length} enabled`,F=te.find(b=>b.provider===le)??hs.find(b=>b.provider===le)??hs[0],z=F.managementSchema??Ni(F.provider),ce=z.hostConfigFiles;r.useEffect(()=>{if(!fe||t||!s||!z.configArchives)return;const b=s;function j(M){M.key==="Escape"&&b.closeSettings()}return window.addEventListener("keydown",j),()=>{window.removeEventListener("keydown",j)}},[z.configArchives,t,fe,s]),r.useEffect(()=>{if(!fe)return;let b=!1;return X(j=>({...j,loading:!0,error:null})),pa().then(j=>{if(b)return;const M=[...j.map(Ln),...hs.filter(Q=>!j.some(be=>be.provider===Q.provider))];_(M),X(Q=>({...Q,loading:!1}))}).catch(j=>{b||(_(hs),X(M=>({...M,loading:!1,error:j instanceof re?j.message:"Unable to load backend settings."})))}),()=>{b=!0}},[fe]),r.useEffect(()=>{if(!fe)return;let b=!1;return I(j=>({...j,loading:!0,message:null,error:null})),jl().then(j=>{b||(D(j),I(M=>({...M,devHomeDraft:j.devHome,loading:!1})))}).catch(j=>{b||I(M=>({...M,loading:!1,error:j instanceof re?j.message:"Unable to load workspace settings."}))}),()=>{b=!0}},[fe]),r.useEffect(()=>{if(!fe||!F.capabilities.management.hostConfigFiles)return;let b=!1;async function j(){f(Q=>{const be={...Q};for(const $e of ce)be[$e.name]={...Es($e.name),...Q[$e.name],loading:!0,saving:!1,error:null,saveMessage:null};return be});const M=await Promise.allSettled(ce.map(async Q=>({name:Q.name,result:await Or(F.provider,Q.name)})));b||f(Q=>{var $e,Ue;const be={...Q};for(const Ze of M){if(Ze.status==="fulfilled"){const{name:pt,result:Me}=Ze.value;be[pt]={path:Me.path,exists:Me.exists,originalContent:Me.content,draftContent:Me.content,loading:!1,saving:!1,error:null,saveMessage:null};continue}const ht=Ze.reason instanceof re?Ze.reason.message:"Unable to load the file.",Ve=(($e=ce[M.indexOf(Ze)])==null?void 0:$e.name)??((Ue=ce[0])==null?void 0:Ue.name);Ve&&(be[Ve]={...Es(Ve),...be[Ve],loading:!1,saving:!1,error:ht,saveMessage:null})}return be})}return j(),()=>{b=!0}},[F.capabilities.management.hostConfigFiles,F.provider,ce,fe]),r.useEffect(()=>{if(!fe)return;let b=!1;async function j(){B(M=>({...M,loading:!0,error:null,message:null}));try{const M=await Sl(F.provider);if(b)return;J(M),B(Q=>({...Q,loading:!1}))}catch(M){if(b)return;B(Q=>({...Q,loading:!1,error:M instanceof re?M.message:"Unable to load config archives."}))}}return j(),()=>{b=!0}},[F.provider,z.configArchives,fe]);async function xe(){if(!(C.busy||R.saving)){E({busy:!0,message:null,error:null});try{const b=await wl(F.provider),j=Ln(b);E({busy:!1,message:j.status.state==="ready"?`${j.displayName} backend restarted.`:`${j.displayName} backend state: ${j.status.state}`,error:null}),_(M=>M.map(Q=>Q.provider===j.provider?j:Q))}catch(b){E({busy:!1,message:null,error:b instanceof re?b.message:"Unable to restart the app server."})}}}async function rt(b,j){if(C.busy||R.saving)return;const M=te.find(Q=>Q.provider===b);X(Q=>({...Q,saving:!0,operatingProvider:b,operatingAction:j,message:null,error:null}));try{const Q=await Nl(b,j),be=Ln(Q);_($e=>$e.map(Ue=>Ue.provider===be.provider?be:Ue)),X($e=>({...$e,saving:!1,operatingProvider:null,operatingAction:null,message:be.installation.lastError?`${be.displayName} ${j==="install"?"installed":"updated"}, but requires attention:
|
|
4
|
+
${be.installation.lastError}`:`${be.displayName} ${j==="install"?"installed":"updated"}.`,error:null}))}catch(Q){X(be=>({...be,saving:!1,operatingProvider:null,operatingAction:null,message:null,error:Q instanceof re?ki(Q):`Unable to ${j} ${(M==null?void 0:M.displayName)??b}.`}))}}async function ct(){if(!(C.busy||R.saving)){E({busy:!0,message:null,error:null});try{await Il(),E({busy:!1,message:"Build and restart launched. The page may disconnect briefly.",error:null})}catch(b){E({busy:!1,message:null,error:b instanceof re?b.message:"Unable to launch build and restart."})}}}async function Ke(){const b=Y.devHomeDraft.trim();if(!(!b||Y.saving)){I(j=>({...j,saving:!0,message:null,error:null}));try{const j=await yl({devHome:b});D(j),I(M=>({...M,devHomeDraft:j.devHome,saving:!1,message:"Workspace defaults saved."}))}catch(j){I(M=>({...M,saving:!1,error:j instanceof re?j.message:"Unable to save workspace settings."}))}}}async function wt(b){const j=x[b];if(!(!j||j.saving)){f(M=>({...M,[b]:{...Es(b),...M[b],saving:!0,error:null,saveMessage:null}}));try{const M=await $r(F.provider,b,{content:j.draftContent});f(Q=>({...Q,[b]:{path:M.path,exists:M.exists,originalContent:M.content,draftContent:M.content,loading:!1,saving:!1,error:null,saveMessage:"Saved"}}))}catch(M){f(Q=>({...Q,[b]:{...Es(b),...Q[b],saving:!1,error:M instanceof re?M.message:"Unable to save the file.",saveMessage:null}}))}}}async function ze(){if(!q.creating){B(b=>({...b,creating:!0,message:null,error:null}));try{const b=await kl(F.provider);J(j=>[b,...j]),B(j=>({...j,creating:!1,message:"Backup created."}))}catch(b){B(j=>({...j,creating:!1,error:b instanceof re?b.message:"Unable to create a config backup."}))}}}async function ut(b){if(!q.applyingId){B(j=>({...j,applyingId:b.id,message:null,error:null}));try{const j=await Tl(F.provider,b.id);B(M=>({...M,applyingId:null,message:j.status.state==="ready"?`Applied "${j.archive.label}" and restarted ${F.displayName}.`:`Applied "${j.archive.label}". ${F.displayName} state: ${j.status.state}.`}))}catch(j){B(M=>({...M,applyingId:null,error:j instanceof re?j.message:"Unable to apply the config archive."}))}}}async function Be(b){const j=q.renameDraft.trim();if(!(!j||q.renamingId!==b.id)){B(M=>({...M,message:null,error:null}));try{const M=await Cl(F.provider,b.id,{label:j});J(Q=>Q.map(be=>be.id===b.id?M:be)),B(Q=>({...Q,renamingId:null,renameDraft:"",message:"Backup renamed."}))}catch(M){B(Q=>({...Q,error:M instanceof re?M.message:"Unable to rename the config backup."}))}}}if(!fe)return null;const mt=e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-3 grid gap-2",children:[a.plugins.map(b=>e.jsxs("label",{className:"flex items-start justify-between gap-3 rounded-[1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-2.5",children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-sm font-medium text-[var(--theme-fg)]",children:b.name}),e.jsx("span",{className:"mt-1 block text-xs leading-5 text-[var(--theme-fg-muted)]",children:b.description}),e.jsx("span",{className:"mt-2 block text-[10px] uppercase tracking-[0.16em] text-[var(--theme-fg-muted)]",children:[...b.capabilities.artifactTypes.map(j=>j.type),...b.capabilities.threadPanels.map(j=>j.kind??j.id)].join(", ")||"utility"}),e.jsx("span",{className:"mt-1 block text-[10px] uppercase tracking-[0.16em] text-[var(--theme-fg-muted)]",children:b.source==="imported"?"Imported manifest":"Built-in module"})]}),e.jsx("input",{type:"checkbox",checked:b.enabled,onChange:j=>void a.setPluginEnabled(b.id,j.currentTarget.checked),className:"mt-1 h-4 w-4 shrink-0 accent-[var(--theme-accent-solid)]"})]},b.id)),a.plugins.length===0&&e.jsx("p",{className:"rounded-[1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-3 text-xs text-[var(--theme-fg-muted)]",children:"No plugins are registered."})]}),e.jsxs("div",{className:"mt-3 border-t border-[var(--theme-border)] pt-3",children:[e.jsx("label",{className:"block text-xs font-medium text-[var(--theme-fg)]",children:"Import manifest JSON"}),e.jsx("textarea",{value:n,onChange:b=>{d(b.currentTarget.value),(o.message||o.error)&&m({busy:!1,message:null,error:null})},placeholder:'{"id":"example.viewer","name":"Example Viewer","version":"0.1.0",...}',rows:4,className:"mt-2 min-h-28 w-full resize-y rounded-[0.9rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-2 font-mono text-xs leading-5 text-[var(--theme-fg)] outline-none transition placeholder:text-[var(--theme-fg-muted)] focus:border-[var(--theme-accent-border)]"}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center justify-between gap-2",children:[e.jsx("p",{className:"max-w-[42rem] text-xs leading-5 text-[var(--theme-fg-muted)]",children:"Imports register manifest-declared artifact types. Rendering code still needs a trusted built-in frontend module."}),e.jsx("button",{type:"button",onClick:()=>void H(),disabled:!n.trim()||o.busy,className:"rounded-full border border-[var(--theme-accent-border)] bg-[var(--theme-accent-soft)] px-3 py-1.5 text-xs font-medium text-[var(--theme-accent-strong)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:border-[var(--theme-border)] disabled:bg-[var(--theme-muted)] disabled:text-[var(--theme-fg-muted)]",children:o.busy?"Importing...":"Import"})]}),o.error&&e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:o.error}),o.message&&e.jsx("p",{className:"mt-2 text-xs text-emerald-300",children:o.message})]}),a.error&&e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:a.error})]}),Ye=e.jsxs(e.Fragment,{children:[t?null:e.jsx("div",{className:"shrink-0 p-5 pb-0",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-[0.24em] text-[var(--theme-fg-muted)]",children:"Settings"}),e.jsx("h2",{className:"mt-2 text-xl font-semibold text-[var(--theme-fg)]",children:"Settings"}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-[var(--theme-fg-soft)]",children:"Choose the default backend and manage host-side runtime files."})]}),e.jsx("button",{type:"button","aria-label":"Close Settings",onClick:s==null?void 0:s.closeSettings,className:"inline-flex h-9 w-9 items-center justify-center rounded-full border border-[var(--theme-border-strong)] bg-[var(--theme-surface-strong)] text-[var(--theme-fg)] transition hover:border-[var(--theme-border-contrast)] hover:bg-[var(--theme-hover)]",children:e.jsx(fn,{})})]})}),e.jsx("div",{className:`min-h-0 flex-1 overflow-y-auto ${t?"p-0":"p-5 pt-5"}`,children:e.jsxs("div",{className:"space-y-2",children:[t?null:e.jsxs("div",{className:"rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 py-3",children:[e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:"Appearance"}),e.jsxs("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:["Choose light, dark, or follow the system setting. Active:"," ",he,"."]})]})}),e.jsx("div",{className:"mt-3 grid gap-2 sm:grid-cols-3",children:ji.map(b=>{const j=je===b.value;return e.jsxs("button",{type:"button",onClick:()=>s==null?void 0:s.setThemeMode(b.value),className:`block rounded-[1rem] border px-3 py-2.5 text-left transition ${j?"border-[var(--theme-accent-border)] bg-[var(--theme-accent-soft)]":"border-[var(--theme-border)] bg-[var(--theme-surface-strong)] hover:bg-[var(--theme-hover)]"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-sm font-medium text-[var(--theme-fg)]",children:b.label}),j?e.jsx("span",{className:"rounded-full border border-[var(--theme-accent-border)] bg-[var(--theme-accent-soft)] px-2 py-0.5 text-[10px] uppercase tracking-[0.18em] text-[var(--theme-accent-strong)]",children:"Active"}):null]}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:b.description})]},b.value)})})]}),s!=null&&s.setAutoCollapseCompletedTurns?e.jsx("div",{className:"rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 py-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:"Thread timeline"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:"Collapse completed turns into prompt, elapsed work, and final reply."})]}),e.jsxs("label",{className:"inline-flex min-h-10 shrink-0 items-center gap-2 text-xs font-medium text-[var(--theme-fg-soft)]",children:[e.jsx("input",{type:"checkbox",checked:T,onChange:b=>{var j;return(j=s.setAutoCollapseCompletedTurns)==null?void 0:j.call(s,b.currentTarget.checked)},className:"h-4 w-4 accent-[var(--theme-accent-solid)]"}),e.jsx("span",{children:"Auto collapse"})]})]})}):null,e.jsxs("div",{className:"rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 py-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:"Plugins"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:"Enable renderers and thread extensions loaded by this supervisor."})]}),e.jsx("button",{type:"button",onClick:()=>void a.refresh(),disabled:a.loading,className:"rounded-full border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-1.5 text-xs font-medium text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:text-[var(--theme-fg-muted)]",children:a.loading?"Loading...":"Refresh"})]}),t?e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-2 rounded-[0.95rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-2",children:[e.jsx("span",{className:"text-xs text-[var(--theme-fg-muted)]",children:W}),e.jsx("button",{type:"button",onClick:()=>g(!0),className:"rounded-full border border-[var(--theme-border-strong)] bg-[var(--theme-panel)] px-3 py-1.5 text-xs font-medium text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)]",children:"Manage"})]}):mt]}),e.jsxs("div",{className:"rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 py-3",children:[e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:"Workspace defaults"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:"Git projects clone into dev home. New workspace directories can create one missing child under this path."})]})}),e.jsxs("div",{className:"mt-3 grid gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.18em] text-[var(--theme-fg-muted)]",children:"Workspace root"}),e.jsx("p",{title:(c==null?void 0:c.workspaceRoot)??"Loading workspace root",className:"mt-1 truncate rounded-[0.9rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-2 font-mono text-xs text-[var(--theme-fg-soft)]",children:Y.loading&&!c?"Loading...":(c==null?void 0:c.workspaceRoot)??"Unavailable"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"settings-dev-home",className:"text-[11px] uppercase tracking-[0.18em] text-[var(--theme-fg-muted)]",children:"Dev home"}),e.jsxs("div",{className:"mt-1 flex flex-col gap-2 sm:flex-row",children:[e.jsx("input",{id:"settings-dev-home",value:Y.devHomeDraft,onChange:b=>I(j=>({...j,devHomeDraft:b.target.value,message:null,error:null})),placeholder:"/Users/name/dev",className:"min-w-0 flex-1 rounded-full border border-[var(--theme-border)] bg-[var(--theme-panel)] px-3 py-2 text-sm text-[var(--theme-fg)] outline-none focus:border-[var(--theme-accent-border)]"}),e.jsx("button",{type:"button","aria-label":"Save workspace defaults",onClick:()=>void Ke(),disabled:Y.loading||Y.saving||!Y.devHomeDraft.trim(),className:"rounded-full bg-[var(--theme-accent-solid)] px-4 py-2 text-xs font-medium text-[var(--theme-accent-solid-fg)] transition hover:bg-[var(--theme-accent-solid-hover)] disabled:cursor-not-allowed disabled:bg-[var(--theme-muted)] disabled:text-[var(--theme-fg-muted)]",children:Y.saving?"Saving...":"Save"})]})]})]}),Y.error?e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:Y.error}):Y.message?e.jsx("p",{className:"mt-2 text-xs text-emerald-300",children:Y.message}):null]}),e.jsxs("div",{className:"rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 py-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:"Runtime controls"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:"Inspect installed backend versions, install optional runtimes, or restart the selected backend."})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap justify-end gap-2",children:[e.jsx("button",{type:"button",onClick:()=>void xe(),disabled:C.busy||R.saving,className:"rounded-full border border-sky-400/35 bg-sky-400/10 px-3 py-1.5 text-xs font-medium text-sky-500 transition hover:bg-sky-400/16 disabled:cursor-not-allowed disabled:border-[var(--theme-border)] disabled:bg-[var(--theme-muted)] disabled:text-[var(--theme-fg-muted)]",children:C.busy?"Restarting...":"Restart"}),e.jsx("button",{type:"button",onClick:()=>void ct(),disabled:C.busy||R.saving,className:"rounded-full border border-amber-400/35 bg-amber-400/10 px-3 py-1.5 text-xs font-medium text-amber-500 transition hover:bg-amber-400/16 disabled:cursor-not-allowed disabled:border-[var(--theme-border)] disabled:bg-[var(--theme-muted)] disabled:text-[var(--theme-fg-muted)]",children:C.busy?"Working...":"Build and restart"})]})]}),e.jsx("div",{className:"mt-3 grid gap-2",children:te.map(b=>{const j=b.installation,M=!j.installed&&!!j.installCommand,Q=j.installed&&!!j.updateCommand,be=R.saving&&R.operatingProvider===b.provider,$e=M?"Install":"Update";return e.jsxs("div",{className:"flex flex-col gap-2 rounded-[0.95rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-[var(--theme-fg)]",children:b.displayName}),e.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${b.enabled?"border-emerald-400/35 bg-emerald-400/10 text-emerald-400":"border-[var(--theme-border)] bg-[var(--theme-muted)] text-[var(--theme-fg-muted)]"}`,children:b.enabled?"Ready":j.installed?b.status.state:"Not installed"})]}),e.jsxs("p",{className:"mt-1 truncate text-xs text-[var(--theme-fg-muted)]",children:["Version:"," ",j.installedVersion??(j.installed?"Installed":"Unavailable"),j.latestVersion?` · Latest: ${j.latestVersion}`:""]}),j.lastError?e.jsx("p",{className:"mt-1 line-clamp-2 text-xs text-rose-300",children:j.lastError}):null]}),M||Q?e.jsx("button",{type:"button","aria-label":`${M?"Install":"Update"} ${b.displayName}`,onClick:()=>void rt(b.provider,M?"install":"update"),disabled:C.busy||R.saving||!M&&!Q,className:"shrink-0 rounded-full border border-[var(--theme-border-strong)] bg-[var(--theme-panel)] px-3 py-1.5 text-xs font-medium text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:bg-[var(--theme-muted)] disabled:text-[var(--theme-fg-muted)]",children:be?R.operatingAction==="install"?"Installing...":"Updating...":$e}):null]},b.provider)})}),C.error?e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:C.error}):C.message?e.jsx("p",{className:"mt-2 text-xs text-emerald-300",children:C.message}):R.message?e.jsx("p",{className:`mt-2 whitespace-pre-line text-xs ${R.message.includes("requires attention")?"text-amber-300":"text-emerald-300"}`,children:R.message}):R.error?e.jsx("p",{className:"mt-2 whitespace-pre-line text-xs text-rose-300",children:R.error}):null]}),e.jsxs("div",{className:"rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 py-3",children:[e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:"Provider host files"}),e.jsxs("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:[F.displayName," exposes these editable files through its backend schema."]})]})}),e.jsxs("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:[ce.map(b=>{const j=x[b.name]??{path:b.name,exists:!1,originalContent:"",draftContent:"",loading:!1},M=j.draftContent!==j.originalContent;return e.jsx("button",{type:"button",onClick:()=>A(b.name),className:"block rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-3 text-left transition hover:bg-[var(--theme-hover)]",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:b.label}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:b.description})]}),e.jsx("div",{className:"shrink-0",children:j.loading?e.jsx("span",{className:"text-[11px] uppercase tracking-[0.2em] text-[var(--theme-fg-muted)]",children:"Loading"}):M?e.jsx("span",{className:"rounded-full border border-[var(--theme-accent-border)] bg-[var(--theme-accent-soft)] px-2 py-0.5 text-[10px] uppercase tracking-[0.18em] text-[var(--theme-accent-strong)]",children:"Unsaved"}):j.exists?e.jsx("span",{className:"rounded-full border border-emerald-400/25 bg-emerald-400/10 px-2 py-0.5 text-[10px] uppercase tracking-[0.18em] text-emerald-600 dark:text-emerald-100",children:"Ready"}):e.jsx("span",{className:"rounded-full border border-sky-300/25 bg-sky-300/10 px-2 py-0.5 text-[10px] uppercase tracking-[0.18em] text-sky-600 dark:text-sky-100",children:"New"})})]})},b.name)}),ce.length===0?e.jsx("p",{className:"rounded-[1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-3 text-xs text-[var(--theme-fg-muted)]",children:"This backend does not expose editable host files."}):null]})]}),z.configArchives?e.jsxs("div",{className:"rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 py-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:"Config archives"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:"Backup the selected backend host files, then apply a saved archive with a backend restart."})]}),e.jsx("button",{type:"button",onClick:()=>void ze(),disabled:q.creating,className:"shrink-0 rounded-full border border-[var(--theme-accent-border)] bg-[var(--theme-accent-soft)] px-3 py-1.5 text-xs font-medium text-[var(--theme-accent-strong)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:border-[var(--theme-border)] disabled:bg-[var(--theme-muted)] disabled:text-[var(--theme-fg-muted)]",children:q.creating?"Creating...":"Create backup"})]}),q.error?e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:q.error}):q.message?e.jsx("p",{className:"mt-2 text-xs text-emerald-300",children:q.message}):null,e.jsx("div",{className:"mt-3 space-y-2",children:q.loading?e.jsx("p",{className:"rounded-[1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-3 text-xs text-[var(--theme-fg-muted)]",children:"Loading backups..."}):v.length===0?e.jsx("p",{className:"rounded-[1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-3 text-xs text-[var(--theme-fg-muted)]",children:"No config backups yet."}):v.map(b=>{const j=q.renamingId===b.id;return e.jsx("div",{className:"rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-3",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[j?e.jsxs("div",{className:"flex max-w-xl gap-2",children:[e.jsx("input",{"aria-label":`Rename ${b.label}`,value:q.renameDraft,onChange:M=>B(Q=>({...Q,renameDraft:M.target.value,error:null,message:null})),className:"min-w-0 flex-1 rounded-full border border-[var(--theme-border)] bg-[var(--theme-panel)] px-3 py-1.5 text-sm text-[var(--theme-fg)] outline-none focus:border-[var(--theme-accent-border)]"}),e.jsx("button",{type:"button","aria-label":`Save archive name ${b.label}`,onClick:()=>void Be(b),className:"rounded-full bg-[var(--theme-accent-solid)] px-3 py-1.5 text-xs font-medium text-[var(--theme-accent-solid-fg)] transition hover:bg-[var(--theme-accent-solid-hover)]",children:"Save"}),e.jsx("button",{type:"button",onClick:()=>B(M=>({...M,renamingId:null,renameDraft:""})),className:"rounded-full border border-[var(--theme-border)] bg-[var(--theme-panel)] px-3 py-1.5 text-xs font-medium text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)]",children:"Cancel"})]}):e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:b.label}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2 text-[11px] text-[var(--theme-fg-muted)]",children:[e.jsxs("span",{children:["Created ",Si(b.createdAt)]}),ce.map(M=>{var Q;return e.jsxs("span",{className:"rounded-full border border-[var(--theme-border)] bg-[var(--theme-panel)] px-2 py-0.5 font-mono",children:[M.name,":"," ",(Q=b.files[M.name])!=null&&Q.exists?"saved":"missing"]},M.name)})]})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2",children:[e.jsx("button",{type:"button",onClick:()=>B(M=>({...M,renamingId:b.id,renameDraft:b.label,message:null,error:null})),disabled:j,className:"rounded-full border border-[var(--theme-border)] bg-[var(--theme-panel)] px-3 py-1.5 text-xs font-medium text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:text-[var(--theme-fg-muted)]",children:"Rename"}),e.jsx("button",{type:"button",onClick:()=>void ut(b),disabled:q.applyingId!==null,className:"rounded-full border border-emerald-400/35 bg-emerald-400/10 px-3 py-1.5 text-xs font-medium text-emerald-600 transition hover:bg-emerald-400/16 disabled:cursor-not-allowed disabled:border-[var(--theme-border)] disabled:bg-[var(--theme-muted)] disabled:text-[var(--theme-fg-muted)] dark:text-emerald-100",children:q.applyingId===b.id?"Applying...":"Apply"})]})]})},b.id)})})]}):null]})})]});return t?e.jsxs("div",{className:"flex min-h-0 flex-col overflow-hidden",children:[Ye,h?e.jsxs("div",{className:"fixed inset-0 z-[90] flex items-start justify-center p-4 pt-[max(env(safe-area-inset-top),4rem)] sm:items-center sm:pt-4",children:[e.jsx("button",{type:"button","aria-label":"Close plugins panel",onClick:()=>g(!1),className:"absolute inset-0 bg-black/35 backdrop-blur-[2px]"}),e.jsxs("section",{className:"relative z-10 flex max-h-[min(82vh,42rem)] w-full max-w-2xl flex-col overflow-hidden rounded-[1.35rem] border border-[var(--theme-border)] bg-[var(--theme-panel)] shadow-2xl shadow-black/25",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 border-b border-[var(--theme-border)] px-4 py-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:"Plugins"}),e.jsx("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:W})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx("button",{type:"button",onClick:()=>void a.refresh(),disabled:a.loading,className:"rounded-full border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-1.5 text-xs font-medium text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:text-[var(--theme-fg-muted)]",children:a.loading?"Loading...":"Refresh"}),e.jsx("button",{type:"button","aria-label":"Close plugins panel",onClick:()=>g(!1),className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-[var(--theme-border-strong)] bg-[var(--theme-surface-strong)] text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)]",children:e.jsx(fn,{})})]})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto p-4",children:mt})]})]}):null]}):e.jsxs("div",{className:"fixed inset-0 z-[70] flex items-start justify-center p-4 pt-[max(env(safe-area-inset-top),1rem)] sm:items-center",children:[e.jsx("button",{type:"button","aria-label":"Close Settings",onClick:s==null?void 0:s.closeSettings,className:"ui-overlay-scrim absolute inset-0 backdrop-blur-sm"}),e.jsx("section",{role:"dialog","aria-modal":"true","aria-label":"Settings",className:"relative z-10 flex max-h-[calc(100vh-2rem)] w-full max-w-4xl flex-col overflow-hidden rounded-[1.8rem] border border-[var(--theme-border)] bg-[var(--theme-panel)] shadow-2xl shadow-black/20",children:Ye}),y&&k?e.jsx("div",{className:"pointer-events-none fixed inset-0 z-[71] flex items-center justify-center p-4",children:e.jsxs("div",{className:"pointer-events-auto relative z-10 flex max-h-[min(88vh,56rem)] w-full max-w-3xl flex-col overflow-hidden rounded-[1.6rem] border border-[var(--theme-border)] bg-[var(--theme-panel)] shadow-2xl shadow-black/25",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-[var(--theme-border)] px-4 py-3 sm:px-5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:y}),e.jsx("p",{className:"mt-1 break-all font-mono text-xs text-[var(--theme-fg-muted)]",children:k.path})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[k.error?e.jsx("span",{className:"text-xs text-rose-300",children:k.error}):k.saveMessage?e.jsx("span",{className:"text-xs text-emerald-300",children:k.saveMessage}):null,e.jsx("button",{type:"button","aria-label":`Save ${y}`,onClick:()=>void wt(y),disabled:k.loading||k.saving||k.draftContent===k.originalContent,className:"rounded-full bg-[var(--theme-accent-solid)] px-4 py-2 text-sm font-medium text-[var(--theme-accent-solid-fg)] transition hover:bg-[var(--theme-accent-solid-hover)] disabled:cursor-not-allowed disabled:bg-[var(--theme-muted)] disabled:text-[var(--theme-fg-muted)]",children:k.saving?"Saving...":"Save"}),e.jsx("button",{type:"button","aria-label":"Close File Editor",onClick:()=>A(null),className:"inline-flex h-9 w-9 items-center justify-center rounded-full border border-[var(--theme-border-strong)] bg-[var(--theme-surface-strong)] text-[var(--theme-fg)] transition hover:border-[var(--theme-border-contrast)] hover:bg-[var(--theme-hover)]",children:e.jsx(fn,{})})]})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto p-4 sm:p-5",children:e.jsx("textarea",{"aria-label":`Edit ${y}`,value:k.draftContent,onChange:b=>f(j=>({...j,[y]:{...Es(y),...j[y],draftContent:b.target.value,error:null,saveMessage:null}})),spellCheck:!1,className:"min-h-[28rem] w-full rounded-[1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-3 font-mono text-[13px] leading-6 text-[var(--theme-fg)] outline-none transition focus:border-[var(--theme-accent-border)]",placeholder:k.loading?"Loading...":`Edit ${y} here`})})]})}):null]})}function Ci(t){const s=(t==null?void 0:t.trim())??"";return s?Array.from(s).slice(0,2).join("").toUpperCase():"??"}function ga(){const t=at(),s=es(),[a,n]=r.useState(null),[d,o]=r.useState(!1);r.useEffect(()=>{if(!na())return;let y=!1;return $s().then(A=>{y||n(A.authenticated?A:null)}).catch(()=>{y||n(null)}),()=>{y=!0}},[s.pathname]),r.useEffect(()=>{o(!1)},[s.pathname]);const m=(a==null?void 0:a.user)??null,h=r.useMemo(()=>Ci(m==null?void 0:m.username),[m==null?void 0:m.username]);if(!na()||!m)return null;async function g(){await Er(),n(null),t("/relay-portal")}return e.jsxs("div",{className:"fixed right-3 top-[calc(env(safe-area-inset-top)+0.55rem)] z-50",children:[e.jsx("button",{"aria-expanded":d,"aria-haspopup":"menu","aria-label":`Relay account menu for ${m.username}`,className:"inline-flex h-10 w-10 items-center justify-center rounded-full border border-[var(--theme-border)] bg-[var(--theme-panel)] text-sm font-semibold text-[var(--theme-fg)] shadow-lg transition hover:bg-[var(--theme-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--theme-accent-ring)]",onClick:()=>o(y=>!y),type:"button",children:h}),d?e.jsxs("div",{className:"absolute right-0 mt-2 w-64 overflow-hidden rounded-xl border border-[var(--theme-border)] bg-[var(--theme-panel)] p-1 shadow-xl",role:"menu",children:[e.jsxs("div",{className:"border-b border-[var(--theme-border)] px-3 py-2",children:[e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:m.username}),e.jsx("p",{className:"truncate text-xs text-[var(--theme-fg-muted)]",children:m.email})]}),e.jsxs(It,{className:"flex items-center gap-2 rounded-lg px-3 py-2 text-sm text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)]",role:"menuitem",to:"/relay-account",children:[e.jsx(nt.Settings,{className:"h-4 w-4"}),"Account settings"]}),e.jsxs(It,{className:"flex items-center gap-2 rounded-lg px-3 py-2 text-sm text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)]",role:"menuitem",to:"/relay-devices",children:[e.jsx(nt.MonitorSmartphone,{className:"h-4 w-4"}),"Device management"]}),e.jsxs("button",{className:"flex w-full items-center gap-2 rounded-lg px-3 py-2 text-left text-sm text-[var(--status-danger-fg)] transition hover:bg-[var(--status-danger-bg)]",onClick:()=>void g(),role:"menuitem",type:"button",children:[e.jsx(nt.LogOut,{className:"h-4 w-4"}),"Logout"]})]}):null]})}const Ti="http://127.0.0.1:8790",ba="remote-codex-control-plane-auth";function Ii(t){const s=t.baseUrl||Ti;if(t.token){const a={baseUrl:s,token:t.token};return t.email!==void 0&&(a.email=t.email),t.displayName!==void 0&&(a.displayName=t.displayName),t.expiresAt!==void 0&&(a.expiresAt=t.expiresAt),a}if(t.subject){const a={baseUrl:s,token:`dev:${t.subject}`};return t.email!==void 0&&(a.email=t.email),t.displayName!==void 0&&(a.displayName=t.displayName),a}return null}function Qt(){if(typeof window>"u")return null;const t=window.localStorage.getItem(ba);if(!t)return null;try{const s=Ii(JSON.parse(t));return!(s!=null&&s.baseUrl)||!s.token||s.expiresAt&&Date.parse(s.expiresAt)<=Date.now()?null:s}catch{return null}}function xn(t){window.localStorage.setItem(ba,JSON.stringify(t))}function jn(){window.localStorage.removeItem(ba)}function Ei(){return!!Qt()}function Ri({eyebrow:t,hidden:s,onClose:a,children:n}){return e.jsx("aside",{className:"control-right-column","aria-hidden":s,children:e.jsxs("section",{className:"control-panel control-inspector-panel",children:[e.jsxs("div",{className:"control-panel-heading",children:[e.jsx("h2",{children:"Inspector"}),e.jsx("span",{children:t}),e.jsx("button",{type:"button",className:"control-inline-icon-button",onClick:a,"aria-label":"Close details inspector",children:"x"})]}),n]})})}function Pi({topBar:t,alerts:s,children:a,sidebar:n,main:d,inspector:o,inspectorOpen:m}){const h=a??e.jsxs(e.Fragment,{children:[n,e.jsx("main",{className:"control-main-column",children:d}),e.jsx("button",{type:"button",className:"control-inspector-scrim","aria-hidden":"true",tabIndex:-1}),o]});return e.jsxs("div",{className:"control-plane-console",children:[t,e.jsx("div",{className:"control-alert-stack",children:s}),e.jsx("div",{className:`control-console-grid ${m?"inspector-open":"inspector-collapsed"}`,children:h})]})}function Ai({children:t}){return e.jsx("aside",{className:"control-explorer-panel",children:t})}function Ui({title:t,subtitle:s,actions:a}){return e.jsxs("header",{className:"control-console-header",children:[e.jsxs("div",{className:"control-window-controls","aria-hidden":"true",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}),e.jsxs("div",{className:"control-titlebar-copy",children:[e.jsx("h1",{children:t}),e.jsx("span",{children:s})]}),e.jsx("div",{className:"control-header-actions",children:a})]})}const Oi=6e4,$i=5e3,Mi=3e3,rn={estructural:"Estructural",quntur:"Quntur",farmaco:"Farmaco"};function on(t){if(!t)return"no activity yet";const s=Date.parse(t);if(!Number.isFinite(s))return t;const a=Date.now()-s,n=Math.abs(a),d=a>=0?"ago":"from now",o=6e4,m=60*o,h=24*m;return n<o?"just now":n<m?`${Math.round(n/o)}m ${d}`:n<h?`${Math.round(n/m)}h ${d}`:`${Math.round(n/h)}d ${d}`}function Dn(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function Mt(t){switch(t){case"running":return"border-[var(--status-success-border)] bg-[var(--status-success-bg)] text-[var(--status-success-fg)]";case"failed":case"degraded":case"unknown":return"border-[var(--status-danger-border)] bg-[var(--status-danger-bg)] text-[var(--status-danger-fg)]";case"stopped":return"border-[var(--status-neutral-border)] bg-[var(--status-neutral-bg)] text-[var(--status-neutral-fg)]";default:return"border-[var(--status-warning-border)] bg-[var(--status-warning-bg)] text-[var(--status-warning-fg)]"}}function Ne(t){return t?t.split(/[_\s-]+/).filter(Boolean).map(s=>`${s.charAt(0).toUpperCase()}${s.slice(1)}`).join(" "):"Unknown"}function As(t){switch(t){case"empty":return"Local workspace";case"git":return"Git workspace";default:return Ne(t)}}function Li(t){return As(t.sourceType)}function Hn(t){return t.workerSessionId?"Runtime ready":"Not started"}function Rs(t){return t?`${t.type}:${t.id}`:""}function ln(t){switch(t){case"codex":return"Codex";case"claude":return"Claude";case"opencode":return"OpenCode";default:return Ne(t)}}function za({open:t}){return e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",focusable:"false",children:e.jsx("path",{d:t?"M4.5 6.25 8 9.75l3.5-3.5":"M6.25 4.5 9.75 8l-3.5 3.5",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8"})})}function Di(){return e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",focusable:"false",children:e.jsx("path",{d:"M2.75 5.25h10.5v7H2.75zM2.75 4a1 1 0 0 1 1-1h3l1.25 1.25h4.25a1 1 0 0 1 1 1",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.25"})})}function Hi(){return e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",focusable:"false",children:e.jsx("path",{d:"M3 3.75h10v8.5H3zM5.25 6h5.5M5.25 8h5.5M5.25 10h3.5",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.25"})})}function _i(){return e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",focusable:"false",children:e.jsx("path",{d:"M4 3.25h5.25L12 6v6.75H4zM9.25 3.25V6H12M6 8.25h4M6 10.25h3",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.25"})})}function Bi(){return e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",focusable:"false",children:e.jsx("path",{d:"m3.2 10.9-.45 2.35 2.35-.45 6.95-6.95-1.9-1.9zm7.8-7.8.95-.95a1.35 1.35 0 0 1 1.9 1.9l-.95.95",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.25"})})}function Fi(){return e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",focusable:"false",children:e.jsx("path",{d:"M3 4.25h10M6.25 4.25V3h3.5v1.25M4.5 4.25l.55 8.25h5.9l.55-8.25M6.75 6.75v3.5M9.25 6.75v3.5",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.25"})})}function Va(t){switch(t){case"connecting":return"Connecting";case"ready":return"Ready";case"reconnecting":return"Reconnecting";default:return"Idle"}}function Wi(t){if(!t)return"Loading runtime";if(t.state==="starting"){const s=t.startupProgress??0;return s<25?"Request received":s<50?"Scheduling sandbox":s<90?"Preparing runtime":"Opening sandbox route"}return t.state==="stopping"?"Stopping sandbox":t.state==="running"?"Ready":t.state==="degraded"?"Checking readiness":t.state==="failed"?"Startup failed":t.state==="stopped"?"Stopped":Ne(t.state)}function qi(t){if(!t)return"Loading sandbox registry";switch(t.state){case"running":return"Healthy";case"starting":return"Waiting for runtime readiness";case"stopping":return"Shutdown in progress";case"degraded":return"Needs attention";case"failed":return"Failed";case"stopped":return"Offline";default:return"Unknown"}}function zi(t,s){const a="Sign in before managing the sandbox.";if(!t)return{start:{label:"Start",disabled:!0,title:a},stop:{label:"Stop",disabled:!0,title:a},restart:{label:"Restart",disabled:!0,title:a},health:{label:"Health",disabled:!0,title:a},inspect:{label:"Inspect",disabled:!0,title:a}};if(!s){const g="Wait for the sandbox registry to load.";return{start:{label:"Start",disabled:!0,title:g},stop:{label:"Stop",disabled:!0,title:g},restart:{label:"Restart",disabled:!0,title:g},health:{label:"Health",disabled:!0,title:g},inspect:{label:"Inspect",disabled:!0,title:g}}}const n=s.state,d=n==="running"||n==="degraded"||n==="starting",o=n==="running"||n==="degraded";return{start:{label:n==="starting"?"Starting...":n==="stopping"?"Stopping...":n==="restarting"?"Restarting...":n==="running"?"Running":n==="failed"?"Retry start":"Start",disabled:n==="running"||n==="starting"||n==="stopping"||n==="restarting"||n==="degraded",title:n==="starting"?"Sandbox startup is already in progress.":n==="running"?"Sandbox is already running.":n==="stopping"?"Wait for sandbox shutdown to finish before starting again.":n==="restarting"?"Sandbox restart is already in progress.":n==="degraded"?"Use Restart to recover a degraded sandbox.":void 0},stop:{label:"Stop",disabled:!d,title:d?void 0:"Stop is available only while the sandbox is running or starting."},restart:{label:n==="restarting"?"Restarting...":"Restart",disabled:!o,title:n==="failed"?"Use Retry start after a failed startup.":o?void 0:"Restart is available only when the sandbox is running or degraded."},health:{label:"Health",disabled:!1,title:void 0},inspect:{label:"Inspect",disabled:!1,title:void 0}}}function Vi(t){if(!t)return null;if(t.state==="running"&&t.idleTimeoutAt){const s=Date.parse(t.idleTimeoutAt);if(Number.isFinite(s)&&s>Date.now())return{tone:"warning",text:`Sandbox will stop after idle timeout at ${t.idleTimeoutAt}.`}}return t.state==="degraded"?{tone:"warning",text:t.statusReason??"Sandbox is reachable but not fully ready."}:t.state==="failed"?{tone:"danger",text:t.lastFailureMessage??t.statusReason??"Sandbox startup failed."}:t.state==="unknown"?{tone:"warning",text:t.statusReason??"Sandbox state is unknown."}:["running","starting","stopping"].includes(t.state)?null:{tone:"neutral",text:"Sandbox is offline."}}function Ji(t,s){return s?"unavailable":t?!t.enabled||!t.chemistryToolsEnabled?"not configured":t.keyPresent?t.health?"ready":"degraded":"missing key":"idle"}function Ja(t){switch(t){case"ready":return Mt("running");case"unavailable":case"missing key":return Mt("failed");case"not configured":case"idle":return Mt("stopped");default:return Mt("starting")}}function Ga(t){return t?typeof t.text=="string"?t.text.trim():t.payload===void 0?"":JSON.stringify(t.payload,null,2):""}function Ka(t){const s=t==null?void 0:t.payload;if(Array.isArray(s))return s;if(s&&typeof s=="object")for(const a of["tools","runs","items","artifacts"]){const n=s[a];if(Array.isArray(n))return n}return[]}function Ya(t,s){if(!t||typeof t!="object")return String(t??s);const a=t;for(const n of["name","tool","run_id","id","title","path"]){const d=a[n];if(typeof d=="string"&&d.trim())return d}return s}function Za(t){if(!t||typeof t!="object")return"";const s=t;return["status","type","module","execution_mode"].map(a=>{const n=s[a];return typeof n=="string"&&n.trim()?n:null}).filter(Boolean).join(" / ")}function dn({label:t,value:s,onChange:a,type:n="text"}){return e.jsxs("label",{className:"grid gap-1.5 text-xs font-medium text-[var(--theme-fg-muted)]",children:[e.jsx("span",{children:t}),e.jsx("input",{type:n,value:s,onChange:d=>a(d.currentTarget.value),className:"h-10 rounded-[0.7rem] border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 text-sm text-[var(--theme-fg)] outline-none transition focus:border-[var(--theme-accent-border)] focus:ring-2 focus:ring-[var(--theme-accent-soft)]"})]})}function Oe({children:t,onClick:s,disabled:a=!1,type:n="button",title:d,ariaLabel:o}){return e.jsx("button",{type:n,"aria-label":o,onClick:s,disabled:a,title:d,className:"h-10 rounded-[0.75rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 text-sm font-medium text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:text-[var(--theme-fg-muted)]",children:t})}function We({label:t,value:s}){const a=s&&s.trim()?s:"not assigned";return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsxs("dd",{children:[e.jsx("span",{children:a}),s?e.jsx("button",{type:"button",className:"control-copy-button",onClick:()=>{var n;(n=navigator.clipboard)==null||n.writeText(s)},children:"Copy"}):null]})]})}function Gi({status:t}){return e.jsx("span",{className:`control-status-pill compact ${Mt(t)}`,children:Ne(t)})}function _n({label:t,onEdit:s,onDelete:a}){return e.jsxs("span",{className:"control-tree-actions",children:[e.jsx("button",{type:"button",className:"control-tree-action-button",onClick:n=>{n.stopPropagation(),s()},"aria-label":`Rename ${t}`,title:`Rename ${t}`,children:e.jsx(Bi,{})}),e.jsx("button",{type:"button",className:"control-tree-action-button danger",onClick:n=>{n.stopPropagation(),a()},"aria-label":`Delete ${t}`,title:`Delete ${t}`,children:e.jsx(Fi,{})})]})}function Bn({label:t,value:s,onChange:a,onCancel:n,onSubmit:d}){return e.jsxs("form",{className:"control-tree-edit-form",onSubmit:d,children:[e.jsxs("label",{children:[e.jsx("span",{children:t}),e.jsx("input",{value:s,onChange:o=>a(o.currentTarget.value),autoFocus:!0})]}),e.jsx("button",{type:"submit",children:"Save"}),e.jsx("button",{type:"button",onClick:n,children:"Cancel"})]})}function Ki(){var nn;const t=at(),[s,a]=r.useState(()=>{const u=Qt();return u?{baseUrl:u.baseUrl,token:u.token}:null}),[n,d]=r.useState(null),[o,m]=r.useState(null),[h,g]=r.useState(null),[y,A]=r.useState(null),[x,f]=r.useState(null),[k,C]=r.useState([]),[E,v]=r.useState(null),[J,te]=r.useState([]),[_,R]=r.useState([]),[X,c]=r.useState([]),[D,Y]=r.useState([]),[I,q]=r.useState(""),[B,je]=r.useState(""),[fe,H]=r.useState(""),[he,T]=r.useState(null),[le,oe]=r.useState(null),[W,F]=r.useState(null),[z,ce]=r.useState(null),[xe,rt]=r.useState("farmaco"),[ct,Ke]=r.useState(null),[wt,ze]=r.useState(null),[ut,Be]=r.useState(null),[mt,Ye]=r.useState("Computational chemistry"),[b,j]=r.useState("Molecule study"),[M,Q]=r.useState("Plan calculation"),[be,$e]=r.useState("codex"),[Ue,Ze]=r.useState(null),[ht,Ve]=r.useState(""),[pt,Me]=r.useState(null),[Et,Lt]=r.useState(null),[Gt,Kt]=r.useState(null),[se,ie]=r.useState(null),[ue,me]=r.useState(!1),[ke,V]=r.useState(null),[Xe,Le]=r.useState(!1),[Qe,xt]=r.useState("summary"),[Dt,gt]=r.useState(()=>{var u;return((u=Qt())==null?void 0:u.displayName)??""}),[gs,bs]=r.useState(null),[vs,Nt]=r.useState(null),[Yt,bt]=r.useState(null),[js,we]=r.useState(null),[ot,St]=r.useState(null),[Rt,ys]=r.useState(null),[et,ft]=r.useState({projects:!1,workspaces:!1,sessions:!1,usageEvents:!1,harness:!1}),[Pt,Je]=r.useState("idle"),Ie=r.useRef(null),Ht=r.useRef(null),kt=!!(s&&n),Ce=(o==null?void 0:o.state)==="running",ye=zi(kt,o),Ms=(o==null?void 0:o.state)==="starting"||(o==null?void 0:o.state)==="stopping"||(o==null?void 0:o.state)==="restarting"||(o==null?void 0:o.state)==="degraded"||typeof(o==null?void 0:o.startupProgress)=="number"&&o.startupProgress>0&&o.startupProgress<100,G=r.useMemo(()=>_.find(u=>u.id===I)??null,[_,I]),ee=r.useMemo(()=>X.find(u=>u.id===B)??null,[B,X]),ne=r.useMemo(()=>D.find(u=>u.id===fe)??null,[fe,D]),ws=kt&&!!G,ts=kt&&!!ee&&Ce,Ns=Vi(o),At=G?void 0:"Select a project before creating a workspace.",Ut=ee?Ce?void 0:"Start the sandbox before creating a session.":"Select a workspace before creating a session.",Ls=ne?Ce?void 0:"Start the sandbox before connecting a session.":"Select a session before connecting.",Ct=ee?"session":G?"workspace":"project",_t=Ct==="project"?"Project":Ct==="workspace"?"Workspace":"Session",vt=ke==="project"?"Create project":ke==="workspace"?`Create workspace in ${(G==null?void 0:G.name)??"project"}`:ke==="session"?`Create session in ${(ee==null?void 0:ee.name)??"workspace"}`:"",Bt=ke==="workspace"?At:ke==="session"?Ut:void 0,Ss=[G==null?void 0:G.name,ee==null?void 0:ee.name,ne==null?void 0:ne.title].filter(Boolean).join(" / "),Zt=Ji(z,ut),Ds=z!=null&&z.modules.length?z.modules:["farmaco","quntur","estructural"],de=Ka(ct),Ot=Ka(wt),ss=Ga(ct),ns=Ga(wt),ks=((n==null?void 0:n.displayName)??(n==null?void 0:n.email)??"U").trim().charAt(0).toUpperCase()||"U",Hs=((y==null?void 0:y.inputTokens)??0)+((y==null?void 0:y.outputTokens)??0),lt=(x==null?void 0:x.totalCostUsd)??Number((y==null?void 0:y.costUsd)??0)+Number((E==null?void 0:E.costUsd)??0),as=D.filter(u=>u.status==="active").length,_s=D.filter(u=>!u.workerSessionId).length,Bs=D.filter(u=>u.status==="failed"||u.status==="closed").length,Fs=[{label:"All",value:D.length},{label:"Active",value:as},{label:"Needs runtime",value:_s},{label:"Closed",value:Bs}],Cn=(s==null?void 0:s.baseUrl)??((nn=Qt())==null?void 0:nn.baseUrl)??"not connected",Ws=(ne==null?void 0:ne.lastActivityAt)??(ne==null?void 0:ne.updatedAt)??null,Tn=(o==null?void 0:o.lastSeenAt)??(o==null?void 0:o.updatedAt)??null,qs=Wi(o),In=qi(o),En=(ee==null?void 0:ee.name)??(G==null?void 0:G.name)??"Control Plane",Rn=Ss||"Choose a project and workspace to manage sessions";async function Ge(u,N){Lt(u),Kt(null),ie(null),bs(null),Nt(null),bt(null),we(null),St(null),ys(null);try{return await N()}catch(S){if(S instanceof re&&S.payload.code==="gateway_unavailable"&&bs(S.message),S instanceof re&&S.payload.code==="quota_exceeded"){const K=S.payload.details??{},De=typeof K.limit=="number"?K.limit:null,_e=typeof K.used=="number"?K.used:null,$t=typeof K.quotaProfile=="string"?K.quotaProfile:(n==null?void 0:n.quotaProfile)??"current";Nt(De!==null&&_e!==null?`${$t} quota exhausted (${_e}/${De}).`:"Quota exceeded.")}return S instanceof re&&S.payload.code==="account_inactive"&&bt(S.message),S instanceof re&&(S.statusCode===401||S.payload.code==="unauthorized")&&(we(S.message),jn()),S instanceof re&&S.payload.code==="forbidden"&&ys(S.message),Kt(S instanceof Error?S.message:`${u} failed.`),null}finally{Lt(null)}}async function Cs(u=s){if(u){ft(N=>({...N,projects:!0,usageEvents:!0}));try{const N=await ha(u),[S,K,De,_e]=await Promise.all([Cr(u),Vo(u,10),Jo(u),Go(u,10)]);d(N.user),m(N.sandbox),A(N.usage),f(N.billing??null),C(K.events),v(De.usage),te(_e.events),R(S.projects),gt(N.user.displayName??""),q($t=>S.projects.some(On=>On.id===$t)?$t:"")}finally{ft(N=>({...N,projects:!1,usageEvents:!1}))}}}async function zs(u=s,N=xe){if(!u||!Ce){ce(null),Ke(null),ze(null),Be(null);return}ft(S=>({...S,harness:!0})),Be(null);try{const S=await rl(u);ce(S);const K=S.modules.includes(N)?N:S.modules[0]??N;if(rt(K),S.enabled&&S.keyPresent&&S.chemistryToolsEnabled){const[De,_e]=await Promise.all([La(u,K),Da(u,K)]);Ke(De),ze(_e)}else Ke(null),ze(null)}catch(S){ce(null),Ke(null),ze(null),Be(S instanceof Error?S.message:"Harness status refresh failed.")}finally{ft(S=>({...S,harness:!1}))}}r.useEffect(()=>{s&&Ge("Load control plane",async()=>{await Cs(s),ie("Control plane session is ready.")})},[]),r.useEffect(()=>{if(!s||!B){Y([]),H("");return}H(""),ft(u=>({...u,sessions:!0})),Ge("Load sessions",async()=>{try{const u=await ra(s,B);Y(u.sessions)}finally{ft(u=>({...u,sessions:!1}))}})},[s,B]),r.useEffect(()=>{if(!s||!o||!Ms)return;let u=!1;const N=setTimeout(()=>{Ma(s).then(S=>{u||m(S.sandbox)}).catch(S=>{u||St(S instanceof Error?S.message:"Sandbox health refresh failed.")})},Mi);return()=>{u=!0,clearTimeout(N)}},[s,o==null?void 0:o.state,o==null?void 0:o.startupProgress,o==null?void 0:o.updatedAt,Ms]),r.useEffect(()=>{if(!s||!Ce){ce(null),Ke(null),ze(null),Be(null);return}zs(s,xe)},[s,Ce,o==null?void 0:o.updatedAt]),r.useEffect(()=>{if(!s||!I){c([]),je(""),Y([]),H("");return}je(""),Y([]),H(""),ft(u=>({...u,workspaces:!0})),Ge("Load workspaces",async()=>{try{const u=await aa(s,I);c(u.workspaces)}finally{ft(u=>({...u,workspaces:!1}))}})},[s,I]),r.useEffect(()=>()=>{Ie.current&&clearTimeout(Ie.current),jt()},[]),r.useEffect(()=>{function u(N){N.key==="Escape"&&(me(!1),V(null),T(null),Le(!1))}return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[]);function jt(){const u=Ht.current;Ht.current=null,u&&u.readyState!==WebSocket.CLOSED&&u.close()}function yt(){Ie.current&&(clearTimeout(Ie.current),Ie.current=null)}function Pn(u){return`${u.wsBaseUrl.replace(/\/+$/,"")}/api/sandboxes/${encodeURIComponent(u.sandboxId)}/ws?token=${encodeURIComponent(u.token)}`}function Vs(u,N="connecting"){jt();const S=Pn(u);F(S),St(null),Je(N);const K=new WebSocket(S);Ht.current=K,K.addEventListener("open",()=>{Ht.current===K&&Je("ready")}),K.addEventListener("error",()=>{Ht.current===K&&(St("Sandbox route connection failed."),Je("idle"))}),K.addEventListener("close",De=>{Ht.current===K&&(St(De.reason||"Sandbox route closed before the session could stay connected."),Je("idle"))})}function Js(u){if(yt(),!u)return;const N=Date.parse(u.expiresAt);if(!Number.isFinite(N))return;const S=Math.max($i,N-Date.now()-Oi);Ie.current=setTimeout(()=>{Ys()},S)}async function Ft(){jn(),a(null),d(null),m(null),g(null),A(null),C([]),ys(null),R([]),c([]),Y([]),v(null),te([]),oe(null),me(!1),V(null),yt(),Je("idle"),ie("Signed out locally.")}async function He(u){u.preventDefault(),s&&await Ge("Update profile",async()=>{const N=await Ko(s,{displayName:Dt});d(N.user);const S=Qt();S&&xn({...S,email:N.user.email,displayName:N.user.displayName}),ie("Profile updated.")})}async function Gs(u){u.preventDefault(),s&&await Ge("Create project",async()=>{const N=await Yo(s,{name:mt,slug:Dn(mt)});await Cs(s),V(null),ie(`Project "${N.project.name}" created. Select it before creating a workspace.`)})}async function Ks(u){u.preventDefault(),!(!s||!G)&&await Ge("Create workspace",async()=>{const N=await Qo(s,{projectId:G.id,name:b,slug:Dn(b)}),S=await aa(s,G.id);c(S.workspaces),je(""),Y([]),H(""),V(null),ie(`Workspace "${N.workspace.name}" created. Select it before creating a session.`)})}async function An(u){u.preventDefault(),!(!s||!ee||!Ce)&&await Ge("Create session",async()=>{const N=await el(s,ee.id,{provider:be,title:M}),S=await ra(s,ee.id);Y(S.sessions),H(""),V(null),ie(`Session "${N.session.title}" created. Select it before connecting.`)})}async function Wt(u){s&&await Ge(`${u} sandbox`,async()=>{if(u==="start")m((await sl(s)).sandbox);else if(u==="stop")m((await nl(s)).sandbox),oe(null),F(null),jt(),yt(),Je("idle");else if(u==="restart")m((await al(s)).sandbox),oe(null),F(null),jt(),yt(),Je("idle");else{const N=await Ma(s);m(N.sandbox),ie(`Sandbox health is ${Ne(N.status.state)}.`)}})}async function rs(u){if(rt(u),!(!s||!Ce)){ft(N=>({...N,harness:!0})),Be(null);try{const[N,S]=await Promise.all([La(s,u),Da(s,u)]);Ke(N),ze(S)}catch(N){Ke(null),ze(null),Be(N instanceof Error?N.message:"Harness module refresh failed.")}finally{ft(N=>({...N,harness:!1}))}}}async function os(){!s||!o||await Ge("Inspect sandbox",async()=>{const u=await ol(s,o.id);g(u),ie("Sandbox detail loaded.")})}async function ls(u="connecting",N=fe){return!s||!o||!Ce?null:Ge("Create route token",async()=>{const S={scopes:["worker:read","worker:write","session:prompt","provider:turn:create"]};G!=null&&G.id&&(S.projectId=G.id),B&&(S.workspaceId=B),N&&(S.sessionId=N);const K=await Ir(s,o.id,S);return oe(K),Js(K),Vs(K,u),ie("Route token is available in memory."),K})}async function Ys(){if(!s||!o||o.state!=="running"||!fe)return;Je("reconnecting"),await ls("reconnecting",fe)||Je("idle")}function Xt(u){T(null),H(u.id),oe(null),F(null),jt(),yt(),Je("idle"),xt("summary"),Le(!0)}function Zs(u){Xt(u),Le(!0)}function Xs(u,N){var S;N&&(T(null),(S=navigator.clipboard)==null||S.writeText(N),ie(`${u} copied.`))}function is(u,N){Ze(u),Ve(N),T(null)}function qt(){Ze(null),Ve("")}async function ds(u){if(u.preventDefault(),!s||!Ue)return;const N=ht.trim();if(!N){Kt("Name is required.");return}const S=Ue;await Ge(`Rename ${S.type}`,async()=>{if(S.type==="project"){const K=await Zo(s,S.id,{name:N,slug:Dn(N)});R(De=>De.map(_e=>_e.id===K.project.id?K.project:_e))}else if(S.type==="workspace"){const K=await Oa(s,S.id,{name:N});c(De=>De.map(_e=>_e.id===K.workspace.id?K.workspace:_e))}else{const K=await $a(s,S.id,{title:N});Y(De=>De.map(_e=>_e.id===K.session.id?K.session:_e))}qt(),ie(`${Ne(S.type)} renamed.`)})}function Ts(u){if(!u)return{title:"Delete item",description:"This item will be removed from the active control plane view."};if(u.type==="project"){const S=_.find(K=>K.id===u.id);return{title:`Delete project ${(S==null?void 0:S.name)??""}`.trim(),description:"The project will be archived and removed from the active project list. Its existing workspace records remain in the control plane database."}}if(u.type==="workspace"){const S=X.find(K=>K.id===u.id);return{title:`Delete workspace ${(S==null?void 0:S.name)??""}`.trim(),description:"The workspace will be marked deleted and removed from this project view. Sessions under it will no longer be shown from the active workspace browser."}}const N=D.find(S=>S.id===u.id);return{title:`Delete session ${(N==null?void 0:N.title)??""}`.trim(),description:"The session will be marked deleted and removed from this workspace view. This does not delete files in the sandbox workspace."}}async function Is(){if(!s||!pt)return;const u=pt;await Ge(`Delete ${u.type}`,async()=>{if(u.type==="project"){const N=await Xo(s,u.id);R(S=>S.filter(K=>K.id!==N.project.id)),I===N.project.id&&(q(""),je(""),H(""),c([]),Y([]))}else if(u.type==="workspace"){const N=await Oa(s,u.id,{status:"deleted"});c(S=>S.filter(K=>K.id!==N.workspace.id)),B===N.workspace.id&&(je(""),H(""),Y([]))}else{const N=await $a(s,u.id,{status:"deleted"});Y(S=>S.filter(K=>K.id!==N.session.id)),fe===N.session.id&&H("")}Ue&&Rs(Ue)===Rs(u)&&qt(),Me(null),oe(null),F(null),jt(),yt(),Je("idle"),ie(`${Ne(u.type)} deleted.`)})}async function Qs(u){!s||!Ce||await Ge("Close session",async()=>{const N=await tl(s,u.id);Y(S=>S.map(K=>K.id===N.session.id?N.session:K)),H(N.session.id),oe(null),F(null),jt(),yt(),Je("idle"),ie("Session finalized and disconnected.")})}async function en(u){!s||!Ce||await Ge("Resume session",async()=>{const N=await Tr(s,u.id);Y(S=>S.map(K=>K.id===N.session.id?N.session:K)),H(N.session.id),await ls("connecting",N.session.id),ie("Session resumed."),t(`/control-plane/sessions/${encodeURIComponent(N.session.id)}`)})}const Un=e.jsx(Ui,{title:En,subtitle:Rn,actions:e.jsxs(e.Fragment,{children:[o?e.jsx("span",{className:`control-status-pill ${Mt(o.state)}`,children:Ne(o.state)}):null,e.jsx(Oe,{onClick:()=>void Cs(s),disabled:!s||Et==="Load control plane",children:"Refresh"}),e.jsx(Oe,{onClick:()=>Le(u=>!u),ariaLabel:Xe?"Hide details inspector":"Show details inspector",children:"Inspector"}),e.jsxs("div",{className:"control-account-menu",children:[e.jsx("button",{type:"button",className:"control-avatar-button",onClick:()=>me(u=>!u),"aria-haspopup":"menu","aria-expanded":ue,"aria-label":"Open account menu",children:ks}),ue?e.jsxs("div",{className:"control-account-popover",role:"menu",children:[e.jsxs("div",{className:"control-account-identity",children:[e.jsx("span",{className:"control-avatar-badge",children:ks}),e.jsxs("div",{children:[e.jsx("strong",{children:(n==null?void 0:n.displayName)||(n==null?void 0:n.email)||"Account"}),e.jsx("span",{children:(n==null?void 0:n.email)??"Loading account"})]})]}),e.jsxs("dl",{className:"control-detail-list compact two",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Status"}),e.jsx("dd",{children:Ne((n==null?void 0:n.status)??"loading")})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Plan"}),e.jsx("dd",{children:(n==null?void 0:n.plan)??"developer"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Quota"}),e.jsx("dd",{children:(n==null?void 0:n.quotaProfile)??"default"})]})]}),e.jsxs("form",{onSubmit:He,className:"control-inline-form",children:[e.jsx(dn,{label:"Display name",value:Dt,onChange:gt}),e.jsx(Oe,{type:"submit",disabled:!s||Et==="Update profile",children:"Save"})]}),e.jsxs("div",{className:"control-usage-grid compact",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Requests"}),e.jsx("strong",{children:(y==null?void 0:y.requestCount)??0})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Tokens"}),e.jsx("strong",{children:Hs})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Total cost"}),e.jsxs("strong",{children:["$",lt.toFixed(2)]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Harness"}),e.jsx("strong",{children:(E==null?void 0:E.eventCount)??0})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Compute"}),e.jsx("strong",{children:Number((E==null?void 0:E.computeUnits)??0).toFixed(1)})]}),e.jsxs("div",{children:[e.jsx("span",{children:"LLM cost"}),e.jsxs("strong",{children:["$",Number((y==null?void 0:y.costUsd)??0).toFixed(2)]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Harness cost"}),e.jsxs("strong",{children:["$",Number((E==null?void 0:E.costUsd)??0).toFixed(2)]})]})]}),e.jsxs("details",{className:"control-account-disclosure",children:[e.jsx("summary",{children:"Account details"}),e.jsx("dl",{className:"control-detail-list compact",children:e.jsx(We,{label:"Control plane API",value:Cn})})]}),e.jsxs("details",{className:"control-account-disclosure",children:[e.jsx("summary",{children:"Usage history"}),e.jsx("div",{className:"control-usage-events compact",children:et.usageEvents?e.jsx("p",{className:"control-empty",children:"Loading LLM usage..."}):k.length===0?e.jsx("p",{className:"control-empty",children:"No LLM usage events yet."}):k.slice(0,4).map(u=>e.jsxs("div",{children:[e.jsx("strong",{children:u.model}),e.jsxs("span",{children:[u.provider,", ",u.inputTokens+u.outputTokens," tokens, $",Number(u.costUsd).toFixed(2)]}),e.jsx("small",{children:u.occurredAt})]},u.id))}),e.jsx("div",{className:"control-usage-events compact",children:et.usageEvents?e.jsx("p",{className:"control-empty",children:"Loading Harness usage..."}):J.length===0?e.jsx("p",{className:"control-empty",children:"No Harness usage events yet."}):J.slice(0,4).map(u=>e.jsxs("div",{children:[e.jsx("strong",{children:u.tool??u.module}),e.jsxs("span",{children:[u.module,", ",u.status,", $",Number(u.costUsd).toFixed(2)]}),e.jsx("small",{children:u.occurredAt})]},u.id))})]}),e.jsx(Oe,{onClick:Ft,children:"Sign out"})]}):null]})]})}),tn=e.jsxs(e.Fragment,{children:[Gt?e.jsx("div",{className:"control-alert danger",children:Gt}):null,se?e.jsx("div",{className:"control-alert success",children:se}):null,gs?e.jsxs("div",{className:"control-alert warning",children:["LLM gateway unavailable: ",gs]}):null,vs?e.jsxs("div",{className:"control-alert danger",children:["LLM quota exceeded: ",vs]}):null,Yt?e.jsxs("div",{className:"control-alert danger",children:["Account disabled: ",Yt]}):null,js?e.jsxs("div",{className:"control-alert warning",children:["Session expired: ",js]}):null,Rt?e.jsxs("div",{className:"control-alert warning",children:["Admin access denied: ",Rt]}):null,Pt==="reconnecting"?e.jsx("div",{className:"control-alert warning",children:"Reconnecting sandbox route."}):null,Pt==="connecting"?e.jsx("div",{className:"control-alert neutral",children:"Connecting sandbox route."}):null,ot?e.jsxs("div",{className:"control-alert danger",children:["Sandbox offline: ",ot]}):null,Ns?e.jsx("div",{className:`control-alert ${Ns.tone}`,children:Ns.text}):null]}),sn=Ts(pt);return e.jsxs(e.Fragment,{children:[e.jsxs(Pi,{topBar:Un,alerts:tn,sidebar:null,main:null,inspector:null,inspectorOpen:Xe,children:[e.jsxs(Ai,{children:[e.jsxs("div",{className:"control-explorer-toolbar",children:[e.jsxs("div",{children:[e.jsx("h2",{children:"Remote Codex"}),e.jsx("span",{children:(n==null?void 0:n.email)??"Product account"})]}),e.jsx("button",{type:"button",className:"control-icon-button",onClick:()=>V(Ct),"aria-label":`Open create panel for ${_t.toLowerCase()}`,title:`Create ${_t.toLowerCase()}`,children:"+"})]}),ke?e.jsxs("div",{className:"control-create-popover",children:[e.jsxs("div",{className:"control-panel-heading",children:[e.jsx("h2",{children:vt}),e.jsx("button",{type:"button",className:"control-icon-button quiet",onClick:()=>V(null),"aria-label":"Close create panel",children:"x"})]}),ke==="project"?e.jsxs("form",{onSubmit:Gs,className:"control-create-form",children:[e.jsx(dn,{label:"Project name",value:mt,onChange:Ye}),e.jsx(Oe,{type:"submit",disabled:!kt,children:"Create project"})]}):ke==="workspace"?e.jsxs("form",{onSubmit:Ks,className:"control-create-form",children:[e.jsx(dn,{label:"Workspace name",value:b,onChange:j}),Bt?e.jsx("p",{className:"control-rule-note",children:Bt}):null,e.jsx(Oe,{type:"submit",disabled:!ws,title:At,children:"Create workspace"})]}):e.jsxs("form",{onSubmit:An,className:"control-create-form",children:[e.jsx(dn,{label:"Session title",value:M,onChange:Q}),e.jsxs("label",{className:"control-field",children:[e.jsx("span",{children:"Provider"}),e.jsxs("select",{value:be,onChange:u=>$e(u.currentTarget.value),disabled:!ts,children:[e.jsx("option",{value:"codex",children:"Codex"}),e.jsx("option",{value:"claude",children:"Claude"}),e.jsx("option",{value:"opencode",children:"OpenCode"})]})]}),Bt?e.jsx("p",{className:"control-rule-note",children:Bt}):null,e.jsx(Oe,{type:"submit",disabled:!ts,title:Ut,children:"Create session"})]})]}):null,e.jsxs("div",{className:"control-sidebar-body",children:[e.jsxs("section",{className:"control-sidebar-section",children:[e.jsxs("div",{className:"control-sidebar-section-title",children:[e.jsx("span",{children:"Workspace"}),e.jsx("strong",{children:(ee==null?void 0:ee.name)??(G==null?void 0:G.name)??"Not selected"})]}),e.jsxs("div",{className:"control-context-card",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Project"}),e.jsx("strong",{children:(G==null?void 0:G.name)??"Choose project"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Workspace"}),e.jsx("strong",{children:(ee==null?void 0:ee.name)??"Choose workspace"})]})]})]}),e.jsxs("section",{className:"control-sidebar-section",children:[e.jsxs("div",{className:"control-sidebar-section-title",children:[e.jsx("span",{children:"Sessions"}),e.jsx("strong",{children:D.length})]}),e.jsx("div",{className:"control-nav-list","aria-label":"Session filters",children:Fs.map((u,N)=>e.jsxs("button",{type:"button",className:`control-nav-row ${N===0?"selected":""}`,children:[e.jsx("span",{children:u.label}),e.jsx("strong",{children:u.value})]},u.label))})]}),e.jsxs("section",{className:"control-sidebar-section",children:[e.jsx("div",{className:"control-sidebar-section-title",children:e.jsx("span",{children:"System"})}),e.jsxs("div",{className:"control-nav-list","aria-label":"System navigation",children:[e.jsxs("button",{type:"button",className:"control-nav-row","aria-label":`Open sandbox details, ${Ne(o==null?void 0:o.state)}`,onClick:()=>{xt("summary"),Le(!0)},children:[e.jsx("span",{children:"Sandbox"}),e.jsx("strong",{children:Ne(o==null?void 0:o.state)})]}),e.jsxs("button",{type:"button",className:"control-nav-row",onClick:()=>me(!0),children:[e.jsx("span",{children:"Usage"}),e.jsxs("strong",{children:["$",lt.toFixed(2)]})]}),e.jsxs("button",{type:"button",className:"control-nav-row",onClick:()=>me(!0),children:[e.jsx("span",{children:"Settings"}),e.jsx("strong",{children:(n==null?void 0:n.plan)??"dev"})]})]})]})]}),e.jsx("div",{className:"control-explorer-tree",children:et.projects?e.jsx("p",{className:"control-empty",children:"Loading projects..."}):_.length===0?e.jsx("p",{className:"control-empty",children:"No projects yet."}):_.map(u=>e.jsxs("div",{className:"control-tree-group",children:[Rs(Ue)===`project:${u.id}`?e.jsx(Bn,{label:"Project name",value:ht,onChange:Ve,onCancel:qt,onSubmit:ds}):e.jsxs("div",{className:`control-tree-item ${I===u.id?"selected":""}`,children:[e.jsxs("button",{type:"button","aria-label":`Select project ${u.name}`,onClick:()=>{q(u.id),je(""),Y([]),H(""),oe(null),F(null),jt(),yt(),Je("idle")},className:"control-tree-row project",children:[e.jsx("span",{className:"control-tree-caret",children:e.jsx(za,{open:I===u.id})}),e.jsx("span",{className:"control-tree-icon",children:e.jsx(Di,{})}),e.jsx("strong",{children:u.name}),e.jsx("small",{children:Ne(u.status)})]}),e.jsx(_n,{label:`project ${u.name}`,onEdit:()=>is({type:"project",id:u.id},u.name),onDelete:()=>Me({type:"project",id:u.id})})]}),I===u.id?e.jsx("div",{className:"control-tree-children",children:et.workspaces?e.jsx("p",{className:"control-empty",children:"Loading workspaces..."}):X.length===0?e.jsx("p",{className:"control-empty",children:"No workspaces in this project."}):X.map(N=>e.jsxs("div",{className:"control-tree-group",children:[Rs(Ue)===`workspace:${N.id}`?e.jsx(Bn,{label:"Workspace name",value:ht,onChange:Ve,onCancel:qt,onSubmit:ds}):e.jsxs("div",{className:`control-tree-item ${B===N.id?"selected":""}`,children:[e.jsxs("button",{type:"button","aria-label":`Select workspace ${N.name}`,onClick:()=>{je(N.id),H(""),oe(null),F(null),jt(),yt(),Je("idle")},className:"control-tree-row workspace",children:[e.jsx("span",{className:"control-tree-caret",children:e.jsx(za,{open:B===N.id})}),e.jsx("span",{className:"control-tree-icon",children:e.jsx(Hi,{})}),e.jsx("strong",{children:N.name}),e.jsx("small",{children:Li(N)})]}),e.jsx(_n,{label:`workspace ${N.name}`,onEdit:()=>is({type:"workspace",id:N.id},N.name),onDelete:()=>Me({type:"workspace",id:N.id})})]}),B===N.id?e.jsx("div",{className:"control-tree-children sessions",children:et.sessions?e.jsx("p",{className:"control-empty",children:"Loading sessions..."}):D.length===0?e.jsx("p",{className:"control-empty",children:"No sessions for this workspace."}):D.map(S=>e.jsx("div",{className:"control-tree-group",children:Rs(Ue)===`session:${S.id}`?e.jsx(Bn,{label:"Session title",value:ht,onChange:Ve,onCancel:qt,onSubmit:ds}):e.jsxs("div",{className:`control-tree-item ${fe===S.id?"selected":""}`,children:[e.jsxs("button",{type:"button","aria-label":`Open session ${S.title} from workspace browser`,onClick:()=>void Xt(S),className:"control-tree-row session",children:[e.jsx("span",{className:"control-tree-caret"}),e.jsx("span",{className:"control-tree-icon",children:e.jsx(_i,{})}),e.jsx("strong",{children:S.title}),e.jsxs("small",{children:[ln(S.provider)," / ",Ne(S.status),S.workerSessionId?"":" / Not started"]})]}),e.jsx(_n,{label:`session ${S.title}`,onEdit:()=>is({type:"session",id:S.id},S.title),onDelete:()=>Me({type:"session",id:S.id})})]})},S.id))}):null]},N.id))}):null]},u.id))})]}),e.jsxs("main",{className:"control-main-column",children:[e.jsxs("section",{className:"control-workspace-hero","aria-label":"Current control plane context",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Current workspace"}),e.jsx("h2",{children:(ee==null?void 0:ee.name)??(G==null?void 0:G.name)??"Select a workspace"}),e.jsx("p",{children:ee?`${(G==null?void 0:G.name)??"Project"} · ${As(ee.sourceType)}`:"Pick a project and workspace before creating sessions."})]}),e.jsxs("div",{className:"control-workspace-hero-actions",children:[e.jsx("span",{className:`control-status-pill ${Mt((o==null?void 0:o.state)??"unknown")}`,children:Ne(o==null?void 0:o.state)}),e.jsx(Oe,{onClick:()=>void Wt("start"),disabled:ye.start.disabled,title:ye.start.title,ariaLabel:`Sandbox ${ye.start.label}`,children:ye.start.label}),e.jsx(Oe,{onClick:()=>void Wt("restart"),disabled:ye.restart.disabled,title:ye.restart.title,ariaLabel:"Sandbox restart",children:ye.restart.label}),e.jsx(Oe,{onClick:()=>void Wt("health"),disabled:ye.health.disabled,title:ye.health.title,ariaLabel:"Sandbox health",children:ye.health.label}),e.jsxs(Oe,{onClick:()=>V(Ct),disabled:Ct==="workspace"?!ws:Ct==="session"?!ts:!kt,title:Ct==="workspace"?At:Ct==="session"?Ut:void 0,children:["New ",_t]})]})]}),e.jsxs("section",{className:"control-overview-strip","aria-label":"Control plane overview",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Projects"}),e.jsx("strong",{children:_.length})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Workspaces"}),e.jsx("strong",{children:X.length})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Active sessions"}),e.jsx("strong",{children:as})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Sandbox"}),e.jsx("strong",{children:Ne(o==null?void 0:o.state)})]})]}),e.jsxs("section",{className:"control-panel control-session-list-panel",children:[e.jsxs("div",{className:"control-panel-heading",children:[e.jsx("h2",{children:"Sessions"}),e.jsx("span",{children:ee?`${D.length} in workspace`:"Select workspace"})]}),ee?e.jsxs(e.Fragment,{children:[Ut?e.jsx("p",{className:"control-rule-note",children:Ut}):null,et.sessions?e.jsx("p",{className:"control-empty",children:"Loading sessions..."}):D.length===0?e.jsx("p",{className:"control-empty",children:"No sessions in this workspace. Start the sandbox, then create a session."}):e.jsx("div",{className:"control-session-list",role:"list","aria-label":"Workspace sessions",children:D.map(u=>e.jsxs("article",{role:"listitem",className:`control-session-row ${fe===u.id?"selected":""}`,children:[e.jsxs("button",{type:"button","aria-label":`Open session ${u.title} summary`,className:"control-session-row-main",onClick:()=>void Xt(u),children:[e.jsx("strong",{children:u.title}),e.jsxs("span",{children:[ln(u.provider)," · ",on(u.lastActivityAt??u.updatedAt)]})]}),e.jsxs("div",{className:"control-session-row-state",children:[e.jsx(Gi,{status:u.status}),e.jsx("span",{children:Hn(u)})]}),e.jsxs("div",{className:"control-session-row-actions",children:[e.jsx(Oe,{onClick:()=>void en(u),disabled:!s||!Ce,title:Ce?void 0:"Start the sandbox before opening this session.",ariaLabel:`${u.workerSessionId?"Resume":"Start"} session ${u.title} from summary`,children:u.workerSessionId?"Resume":"Start"}),e.jsxs("div",{className:"control-row-menu",children:[e.jsx("button",{type:"button",className:"control-row-menu-trigger","aria-label":`More actions for session ${u.title}`,"aria-haspopup":"menu","aria-expanded":he===u.id,onClick:()=>T(N=>N===u.id?null:u.id),children:"..."}),he===u.id?e.jsxs("div",{className:"control-row-menu-popover",role:"menu",children:[e.jsx("button",{type:"button",role:"menuitem",onClick:()=>Zs(u),children:"Show details"}),e.jsx("button",{type:"button",role:"menuitem",onClick:()=>Xs("Session ID",u.id),children:"Copy session ID"}),u.sandboxId?e.jsx("button",{type:"button",role:"menuitem",onClick:()=>Xs("Sandbox ID",u.sandboxId),children:"Copy sandbox ID"}):null,e.jsx("button",{type:"button",role:"menuitem",disabled:!s||!u.workerSessionId||!Ce,title:u.workerSessionId?void 0:"Session has not been started yet.",onClick:()=>{T(null),Qs(u)},children:"Close session"})]}):null]})]})]},u.id))}),e.jsx("div",{className:"control-action-row start",children:e.jsx(Oe,{onClick:()=>V("session"),disabled:!ts,title:Ut,children:"Create session"})})]}):e.jsx("p",{className:"control-empty",children:"Choose a workspace from the browser to see its sessions."})]}),e.jsxs("section",{className:"control-panel control-selected-panel control-context-summary-panel",children:[e.jsxs("div",{className:"control-panel-heading",children:[e.jsx("h2",{children:ne?"Selected session":ee?"Workspace context":G?"Project context":"Selection"}),e.jsx("span",{children:ne?Ne(ne.status):ee?As(ee.sourceType):G?Ne(G.status):"Root"})]}),ne?e.jsxs(e.Fragment,{children:[e.jsxs("dl",{className:"control-detail-list compact summary",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Title"}),e.jsx("dd",{children:ne.title})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Provider"}),e.jsx("dd",{children:ln(ne.provider)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Status"}),e.jsx("dd",{children:e.jsx("span",{className:`control-status-pill compact ${Mt(ne.status)}`,children:Ne(ne.status)})})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Last activity"}),e.jsx("dd",{children:on(Ws)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Sandbox"}),e.jsx("dd",{children:Ce?"Ready":Ne(o==null?void 0:o.state)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Runtime"}),e.jsx("dd",{children:Hn(ne)})]})]}),e.jsxs("div",{className:"control-action-row start",children:[e.jsx(Oe,{onClick:()=>void en(ne),disabled:!s||!Ce,title:Ce?void 0:"Start the sandbox before opening this session.",ariaLabel:`${ne.workerSessionId?"Resume":"Start"} session ${ne.title} from detail`,children:ne.workerSessionId?"Resume":"Start sandbox session"}),e.jsx(Oe,{onClick:()=>{xt("metadata"),Le(!0)},children:"Details"})]})]}):ee?e.jsx(e.Fragment,{children:e.jsxs("dl",{className:"control-detail-list compact summary",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Workspace"}),e.jsx("dd",{children:ee.name})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Project"}),e.jsx("dd",{children:(G==null?void 0:G.name)??ee.projectId})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Source"}),e.jsx("dd",{children:As(ee.sourceType)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Sessions"}),e.jsx("dd",{children:D.length})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Active"}),e.jsx("dd",{children:as})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Not started"}),e.jsx("dd",{children:_s})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Sandbox"}),e.jsx("dd",{children:Ne(o==null?void 0:o.state)})]})]})}):G?e.jsxs(e.Fragment,{children:[e.jsxs("dl",{className:"control-detail-list compact summary",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Selected project"}),e.jsx("dd",{children:G.name})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Status"}),e.jsx("dd",{children:Ne(G.status)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Workspaces"}),e.jsx("dd",{children:X.length})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Path"}),e.jsx("dd",{children:Ss})]})]}),e.jsx("div",{className:"control-action-row start",children:e.jsx(Oe,{onClick:()=>V("workspace"),disabled:!ws,title:At,children:"Create workspace"})})]}):e.jsx("p",{className:"control-empty",children:"Select a project to open the workspace hierarchy."})]})]}),Xe?e.jsx("button",{type:"button",className:"control-inspector-scrim","aria-hidden":"true",tabIndex:-1,onClick:()=>Le(!1)}):null,e.jsxs(Ri,{eyebrow:ne?"Session":ee?"Workspace":G?"Project":"Sandbox",hidden:!Xe,onClose:()=>Le(!1),children:[e.jsx("div",{className:"control-inspector-tabs",role:"tablist","aria-label":"Inspector sections",children:["summary","metadata","route","logs"].map(u=>e.jsx("button",{type:"button",role:"tab","aria-selected":Qe===u,className:Qe===u?"selected":"",onClick:()=>xt(u),children:u==="summary"?"Summary":u==="metadata"?"Metadata":u==="route"?"Route":"Logs"},u))}),Qe==="summary"?e.jsxs("div",{className:"control-inspector-tab-panel",role:"tabpanel",children:[e.jsxs("div",{className:"control-inspector-section",children:[e.jsxs("div",{className:"control-panel-heading compact",children:[e.jsx("h2",{children:"Sandbox"}),o?e.jsx("span",{children:o.resourceProfile}):null]}),o?e.jsxs("dl",{className:"control-detail-list compact summary",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"State"}),e.jsx("dd",{children:e.jsx("span",{className:`control-status-pill compact ${Mt(o.state)}`,children:Ne(o.state)})})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Stage"}),e.jsx("dd",{children:qs})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Health"}),e.jsx("dd",{children:In})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Last seen"}),e.jsx("dd",{children:on(Tn)})]})]}):e.jsx("p",{className:"control-empty",children:"Loading sandbox registry."})]}),e.jsxs("div",{className:"control-action-row",children:[e.jsx(Oe,{onClick:()=>void Wt("stop"),disabled:ye.stop.disabled,title:ye.stop.title,children:ye.stop.label}),e.jsx(Oe,{onClick:os,disabled:ye.inspect.disabled,title:ye.inspect.title,children:ye.inspect.label})]}),o&&typeof o.startupProgress=="number"&&o.startupProgress>0&&o.startupProgress<100?e.jsxs("div",{className:"control-progress",children:[e.jsx("span",{children:qs}),e.jsxs("span",{children:[o.startupProgress,"%"]}),e.jsx("div",{children:e.jsx("i",{style:{width:`${o.startupProgress}%`}})})]}):null,ne||ee||G?e.jsxs("div",{className:"control-inspector-section",children:[e.jsxs("div",{className:"control-panel-heading compact",children:[e.jsx("h2",{children:ne?"Session":ee?"Workspace":"Project"}),e.jsx("span",{children:ne?Ne(ne.status):ee?As(ee.sourceType):Ne(G==null?void 0:G.status)})]}),e.jsx("dl",{className:"control-detail-list compact summary",children:ne?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Title"}),e.jsx("dd",{children:ne.title})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Provider"}),e.jsx("dd",{children:ln(ne.provider)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Runtime"}),e.jsx("dd",{children:Hn(ne)})]})]}):ee?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Workspace"}),e.jsx("dd",{children:ee.name})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Sessions"}),e.jsx("dd",{children:D.length})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Active"}),e.jsx("dd",{children:as})]})]}):G?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Project"}),e.jsx("dd",{children:G.name})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Workspaces"}),e.jsx("dd",{children:X.length})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Status"}),e.jsx("dd",{children:Ne(G.status)})]})]}):null})]}):e.jsxs("div",{className:"control-inspector-empty",children:[e.jsx("strong",{children:"No object selected"}),e.jsx("span",{children:"Select a project, workspace, or session to inspect its metadata."})]}),e.jsxs("div",{className:"control-inspector-section",children:[e.jsxs("div",{className:"control-panel-heading compact",children:[e.jsx("h2",{children:"Harness"}),e.jsx("span",{className:`control-status-pill ${Ja(Zt)}`,children:Ne(Zt)})]}),Ce?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"control-action-row",children:e.jsx(Oe,{onClick:()=>void zs(s,xe),disabled:!s||et.harness,children:et.harness?"Checking...":"Refresh"})}),ut?e.jsxs("div",{className:"control-alert warning",children:["Harness unavailable: ",ut]}):null,e.jsxs("dl",{className:"control-detail-list compact summary",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Key"}),e.jsx("dd",{children:z!=null&&z.keyPresent?"Present":"Not present"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Chemistry"}),e.jsx("dd",{children:z!=null&&z.chemistryToolsEnabled?"Enabled":"Disabled"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Health"}),e.jsx("dd",{children:z!=null&&z.health?"OK":"Not available"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Module"}),e.jsx("dd",{children:rn[xe]})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Tools"}),e.jsx("dd",{children:de.length||"folder index"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Runs"}),e.jsx("dd",{children:Ot.length||"history available"})]})]})]}):e.jsx("p",{className:"control-empty",children:"Start the sandbox to inspect Harness tools."})]})]}):null,Qe==="metadata"?e.jsxs("div",{className:"control-inspector-tab-panel",role:"tabpanel",children:[ne?e.jsxs("section",{className:"control-inspector-section",children:[e.jsx("div",{className:"control-panel-heading compact",children:e.jsx("h2",{children:"Session metadata"})}),e.jsxs("dl",{className:"control-detail-list",children:[e.jsx(We,{label:"Session ID",value:ne.id}),e.jsx(We,{label:"Worker session",value:ne.workerSessionId}),e.jsx(We,{label:"Workspace ID",value:ne.workspaceId}),e.jsx(We,{label:"Sandbox ID",value:ne.sandboxId}),e.jsxs("div",{children:[e.jsx("dt",{children:"Created"}),e.jsx("dd",{children:ne.createdAt})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Updated"}),e.jsx("dd",{children:ne.updatedAt})]})]})]}):null,ee?e.jsxs("section",{className:"control-inspector-section",children:[e.jsx("div",{className:"control-panel-heading compact",children:e.jsx("h2",{children:"Workspace metadata"})}),e.jsxs("dl",{className:"control-detail-list",children:[e.jsx(We,{label:"Workspace ID",value:ee.id}),e.jsx(We,{label:"Project ID",value:ee.projectId}),e.jsx(We,{label:"Path",value:ee.path}),e.jsxs("div",{children:[e.jsx("dt",{children:"Slug"}),e.jsx("dd",{children:ee.slug})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Created"}),e.jsx("dd",{children:ee.createdAt})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Updated"}),e.jsx("dd",{children:ee.updatedAt})]})]})]}):null,G?e.jsxs("section",{className:"control-inspector-section",children:[e.jsx("div",{className:"control-panel-heading compact",children:e.jsx("h2",{children:"Project metadata"})}),e.jsxs("dl",{className:"control-detail-list",children:[e.jsx(We,{label:"Project ID",value:G.id}),e.jsxs("div",{children:[e.jsx("dt",{children:"Slug"}),e.jsx("dd",{children:G.slug})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Created"}),e.jsx("dd",{children:G.createdAt})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Updated"}),e.jsx("dd",{children:G.updatedAt})]})]})]}):null,o?e.jsxs("section",{className:"control-inspector-section",children:[e.jsx("div",{className:"control-panel-heading compact",children:e.jsx("h2",{children:"Sandbox metadata"})}),e.jsxs("dl",{className:"control-detail-list",children:[e.jsx(We,{label:"Sandbox ID",value:o.id}),e.jsx(We,{label:"Image",value:o.image}),e.jsx(We,{label:"Worker ID",value:o.workerServiceName}),e.jsx(We,{label:"S3 prefix",value:o.s3Prefix}),o.statusReason?e.jsxs("div",{children:[e.jsx("dt",{children:"Status"}),e.jsx("dd",{children:o.statusReason})]}):null,o.lastFailureCode?e.jsxs("div",{children:[e.jsx("dt",{children:"Failure"}),e.jsx("dd",{children:o.lastFailureCode})]}):null,o.lastFailureMessage?e.jsxs("div",{children:[e.jsx("dt",{children:"Failure message"}),e.jsx("dd",{children:o.lastFailureMessage})]}):null,e.jsxs("div",{children:[e.jsx("dt",{children:"Created"}),e.jsx("dd",{children:o.createdAt})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Updated"}),e.jsx("dd",{children:o.updatedAt})]})]})]}):null]}):null,Qe==="route"?e.jsxs("div",{className:"control-inspector-tab-panel",role:"tabpanel",children:[e.jsxs("section",{className:"control-inspector-section",children:[e.jsxs("div",{className:"control-panel-heading compact",children:[e.jsx("h2",{children:"Route"}),e.jsx(Oe,{onClick:()=>void ls("connecting",fe),disabled:!Ce||!ne,title:Ls,children:"Create route token"})]}),le?e.jsxs("dl",{className:"control-detail-list compact summary route-token",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Session"}),e.jsx("dd",{children:(ne==null?void 0:ne.title)??fe})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Connection"}),e.jsx("dd",{children:Va(Pt)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Token"}),e.jsxs("dd",{children:[on(le.expiresAt)," expiry"]})]})]}):e.jsx("p",{className:"control-empty",children:ne?`Selected session: ${ne.title}. Create a route token after the sandbox is running.`:"Select a session before creating a route token."})]}),le?e.jsxs("section",{className:"control-inspector-section",children:[e.jsx("div",{className:"control-panel-heading compact",children:e.jsx("h2",{children:"Route metadata"})}),e.jsxs("dl",{className:"control-detail-list",children:[e.jsx(We,{label:"Router URL",value:le.routerBaseUrl}),e.jsx(We,{label:"WebSocket URL",value:le.wsBaseUrl}),e.jsx(We,{label:"Worker socket",value:W}),e.jsxs("div",{children:[e.jsx("dt",{children:"Connection"}),e.jsx("dd",{children:Va(Pt)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Expires"}),e.jsx("dd",{children:le.expiresAt})]})]})]}):null]}):null,Qe==="logs"?e.jsxs("div",{className:"control-inspector-tab-panel",role:"tabpanel",children:[e.jsxs("section",{className:"control-inspector-section",children:[e.jsxs("div",{className:"control-panel-heading compact",children:[e.jsx("h2",{children:"Harness details"}),e.jsx("span",{className:`control-status-pill ${Ja(Zt)}`,children:Ne(Zt)})]}),Ce?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"control-segment-row",role:"tablist","aria-label":"Harness modules",children:Ds.map(u=>e.jsx("button",{type:"button",role:"tab","aria-selected":xe===u,className:xe===u?"selected":"",onClick:()=>void rs(u),disabled:et.harness||!(z!=null&&z.enabled)||!z.keyPresent,children:rn[u]},u))}),e.jsxs("dl",{className:"control-detail-list",children:[e.jsx(We,{label:"Base URL",value:z==null?void 0:z.baseUrl}),e.jsxs("div",{children:[e.jsx("dt",{children:"Enabled"}),e.jsx("dd",{children:z!=null&&z.enabled?"yes":"no"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Modules"}),e.jsx("dd",{children:Ds.map(u=>rn[u]).join(", ")})]})]}),e.jsxs("div",{className:"control-usage-events compact",children:[e.jsxs("div",{children:[e.jsxs("strong",{children:[rn[xe]," tools"]}),e.jsxs("small",{children:[de.length," advertised"]})]}),de.slice(0,5).map((u,N)=>e.jsxs("div",{children:[e.jsx("strong",{children:Ya(u,`tool-${N+1}`)}),e.jsx("span",{children:Za(u)||"tool"})]},`${xe}-tool-${N}`)),de.length===0&&ss?e.jsx("div",{children:e.jsx("span",{children:ss.slice(0,180)})}):null,de.length===0&&!ss?e.jsx("p",{className:"control-empty",children:"No tools reported for this module."}):null]}),e.jsxs("div",{className:"control-usage-events compact",children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Recent runs"}),e.jsxs("small",{children:[Ot.length," reported"]})]}),Ot.slice(0,4).map((u,N)=>e.jsxs("div",{children:[e.jsx("strong",{children:Ya(u,`run-${N+1}`)}),e.jsx("span",{children:Za(u)||"run"})]},`${xe}-run-${N}`)),Ot.length===0&&ns?e.jsx("div",{children:e.jsx("span",{children:ns.slice(0,180)})}):null,Ot.length===0&&!ns?e.jsx("p",{className:"control-empty",children:"No runs reported yet."}):null]})]}):e.jsx("p",{className:"control-empty",children:"Start the sandbox to inspect Harness tools."})]}),h?e.jsxs("section",{className:"control-inspector-section",children:[e.jsxs("div",{className:"control-panel-heading compact",children:[e.jsx("h2",{children:"Admin inspection"}),e.jsx("span",{children:Ne(h.runtimeStatus.state)})]}),e.jsxs("dl",{className:"control-detail-list",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Namespace"}),e.jsx("dd",{children:h.sandbox.k8sNamespace??h.runtimeStatus.k8sNamespace??"not assigned"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Pod"}),e.jsx("dd",{children:h.sandbox.k8sPodName??h.runtimeStatus.k8sPodName??"not assigned"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Endpoint"}),e.jsx("dd",{children:h.endpoint.routerBaseUrl??"not assigned"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Worker URL"}),e.jsx("dd",{children:h.workerBaseUrl??"not assigned"})]})]}),h.runtimeStatus.statusReason?e.jsx("p",{className:"control-empty",children:h.runtimeStatus.statusReason}):null,e.jsx("div",{className:"control-usage-events",children:h.recentLifecycleErrors.length===0?e.jsx("p",{className:"control-empty",children:"No lifecycle audit entries."}):h.recentLifecycleErrors.slice(0,5).map(u=>e.jsxs("div",{children:[e.jsx("strong",{children:u.action}),e.jsx("small",{children:u.createdAt})]},u.id))})]}):e.jsxs("div",{className:"control-inspector-empty",children:[e.jsx("strong",{children:"No admin inspection loaded"}),e.jsx("span",{children:"Use Inspect from Summary to load sandbox runtime diagnostics."})]})]}):null]})]}),e.jsx(wn,{open:!!pt,title:sn.title,description:sn.description,confirmLabel:"Delete",busy:!!(Et!=null&&Et.startsWith("Delete ")),onCancel:()=>Me(null),onConfirm:Is})]})}const Yi="http://127.0.0.1:8790";function Xa({children:t}){const s=es(),[a,n]=r.useState(null);return r.useEffect(()=>{let d=!1;return Promise.resolve().then(()=>{d||n(Ei())}),()=>{d=!0}},[s.pathname]),a===null?e.jsx("div",{className:"grid min-h-[60vh] place-items-center text-sm text-[var(--theme-fg-muted)]",children:"Loading account session..."}):a?t:e.jsx(Os,{to:"/control-plane/login",replace:!0,state:{from:s}})}function Zi(t){return{baseUrl:t.baseUrl,token:t.token}}function Xi(){if(typeof window>"u")return null;const t=new URLSearchParams(window.location.search),s=t.get("control_plane_token"),a=t.get("control_plane_expires_at"),n=t.get("control_plane_base_url"),d=t.get("auth_error");return{token:s,expiresAt:a,baseUrl:n,error:d}}function Qi(){var Y;const t=at(),s=es(),a=Qt(),[n,d]=r.useState("login"),[o,m]=r.useState((a==null?void 0:a.baseUrl)??Yi),[h,g]=r.useState((a==null?void 0:a.email)??"dev@example.com"),[y,A]=r.useState((a==null?void 0:a.displayName)??"Developer"),[x,f]=r.useState(""),[k,C]=r.useState(!1),[E,v]=r.useState(null),[J,te]=r.useState(null),_=s.state,R=((Y=_==null?void 0:_.from)==null?void 0:Y.pathname)??"/control-plane",X=r.useMemo(()=>{if(typeof window>"u")return;const I=new URL(window.location.href);return I.search="",I.toString()},[]);r.useEffect(()=>{const I=Xi();if(!I)return;if(I.error){te(`OAuth sign in failed: ${I.error}`);return}if(!I.token||!I.baseUrl)return;const q={baseUrl:I.baseUrl,token:I.token};I.expiresAt&&(q.expiresAt=I.expiresAt),xn(q),ha(Zi(q)).then(B=>{xn({...q,email:B.user.email,displayName:B.user.displayName}),t("/control-plane",{replace:!0})}).catch(B=>{jn(),te(B instanceof Error?B.message:"Unable to finish OAuth sign in.")})},[t]);async function c(I){I.preventDefault(),C(!0),te(null),v(null);try{const q=n==="register"?await qo(o,{email:h,password:x,displayName:y||null}):await zo(o,{email:h,password:x});xn({baseUrl:o,token:q.session.token,expiresAt:q.session.expiresAt,email:q.user.email,displayName:q.user.displayName}),v("Account session is ready."),t(R,{replace:!0})}catch(q){q instanceof re&&q.payload.code==="conflict"?te("An account already exists for this email. Use sign in instead."):te(q instanceof Error?q.message:"Unable to authenticate.")}finally{C(!1)}}function D(I){window.location.assign(Wo(o,I,X))}return e.jsx("div",{className:"control-auth-shell",children:e.jsxs("section",{className:"control-auth-panel","aria-label":"Control plane account login",children:[e.jsxs("div",{className:"control-auth-aside",children:[e.jsx("p",{className:"control-kicker",children:"Remote Codex"}),e.jsx("h1",{children:"Control plane sign in"}),e.jsx("p",{children:"Use a product account to manage sandboxes, workspaces, route tokens, and usage from the cloud control plane."}),e.jsxs("div",{className:"control-auth-checks","aria-label":"Login capabilities",children:[e.jsx("span",{children:"Google"}),e.jsx("span",{children:"GitHub"}),e.jsx("span",{children:"Email password"})]})]}),e.jsxs("form",{onSubmit:c,className:"control-auth-form",children:[e.jsxs("div",{className:"control-auth-tabs",role:"tablist","aria-label":"Authentication mode",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":n==="login",onClick:()=>d("login"),children:"Sign in"}),e.jsx("button",{type:"button",role:"tab","aria-selected":n==="register",onClick:()=>d("register"),children:"Create account"})]}),e.jsxs("label",{className:"control-field",children:[e.jsx("span",{children:"Control plane URL"}),e.jsx("input",{value:o,onChange:I=>m(I.currentTarget.value)})]}),e.jsxs("div",{className:"control-oauth-row",children:[e.jsx("button",{type:"button",onClick:()=>D("google"),children:"Continue with Google"}),e.jsx("button",{type:"button",onClick:()=>D("github"),children:"Continue with GitHub"})]}),e.jsx("div",{className:"control-auth-divider",children:e.jsx("span",{children:"Email"})}),n==="register"?e.jsxs("label",{className:"control-field",children:[e.jsx("span",{children:"Display name"}),e.jsx("input",{value:y,onChange:I=>A(I.currentTarget.value)})]}):null,e.jsxs("label",{className:"control-field",children:[e.jsx("span",{children:"Email address"}),e.jsx("input",{type:"email",value:h,autoComplete:"email",onChange:I=>g(I.currentTarget.value)})]}),e.jsxs("label",{className:"control-field",children:[e.jsx("span",{children:"Password"}),e.jsx("input",{type:"password",value:x,autoComplete:n==="register"?"new-password":"current-password",minLength:8,onChange:I=>f(I.currentTarget.value)})]}),J?e.jsx("p",{className:"control-auth-error",children:J}):null,E?e.jsx("p",{className:"control-auth-message",children:E}):null,e.jsx("button",{type:"submit",className:"control-primary-button",disabled:k,children:k?"Working...":n==="register"?"Create account":"Sign in"})]})]})})}function ed(t){return t.sandboxMode??(t.approvalMode==="guarded"?"workspace-write":"danger-full-access")}function td(t,s){const a=new Set(s.map(n=>n.id));return[...s,...t.filter(n=>!a.has(n.id))]}function zt(t,s){const a=new Set(s.map(n=>n.id));return[...t.filter(n=>!a.has(n.id)),...s]}function sd(t,s){return{...t,pendingRequests:[...t.pendingRequests.filter(a=>a.id!==s.id),s]}}function nd(t,s){const a=t.pendingRequests.filter(n=>n.id!==s);return a.length===t.pendingRequests.length?t:{...t,pendingRequests:a}}function ia(t,s,a){const n=s.filter(h=>!a.has(h.id)),d=t.filter(h=>!a.has(h.id));if(d.length===0)return n;const o=new Map(n.map(h=>[h.id,h]));return[...d.map(h=>o.get(h.id)??h),...n.filter(h=>!d.some(g=>g.id===h.id))].sort((h,g)=>h.createdAt.localeCompare(g.createdAt))}function ad(t){if(!t||typeof t!="object")return!1;const s=t;return typeof s.id=="string"&&(s.kind==="requestUserInput"||s.kind==="planDecision")&&typeof s.title=="string"&&typeof s.createdAt=="string"&&Array.isArray(s.questions)}function qr(t,s){var o,m;if(!t||t.kind!==s.kind)return s;const a=h=>{let g=h;const y=typeof s.sequence=="number"&&Number.isFinite(s.sequence)?s.sequence:typeof t.sequence=="number"&&Number.isFinite(t.sequence)?t.sequence:null;y!==null&&g.sequence!==y&&(g={...g,sequence:y});const A=typeof s.transcriptOrder=="number"&&Number.isFinite(s.transcriptOrder)?s.transcriptOrder:typeof t.transcriptOrder=="number"&&Number.isFinite(t.transcriptOrder)?t.transcriptOrder:null;return A!==null&&g.transcriptOrder!==A&&(g={...g,transcriptOrder:A}),g};if(t.kind==="agentMessage"&&s.kind==="agentMessage")return a(t.text.length>s.text.length?{...s,text:t.text,sequence:s.sequence??t.sequence??null}:s);const n=((o=t.detailText)==null?void 0:o.trim())||t.text.trim(),d=((m=s.detailText)==null?void 0:m.trim())||s.text.trim();return a(n.length>d.length?t:s)}function rd(t,s,a){if(!t||s&&s.turnId!==t.turnId)return s;const n=a.find(x=>x.id===t.turnId),d=new Map((n==null?void 0:n.items.map(x=>[x.id,x]))??[]),o=(n==null?void 0:n.items.filter(x=>x.kind==="agentMessage").map(x=>x.text.trim()).filter(Boolean))??[],m=x=>x.kind==="agentMessage"&&x.text.trim().length>0&&o.some(f=>f.includes(x.text.trim()));if(!s){const x=t.items.filter(f=>{const k=d.get(f.id);return k?k.kind!==f.kind||typeof f.sequence=="number"&&Number.isFinite(f.sequence)&&k.sequence!==f.sequence:!m(f)});return x.length===0?null:{...t,items:x}}const h=new Map(t.items.map(x=>[x.id,x])),g=new Map(s.items.map(x=>[x.id,x])),A=[...t.items.map(x=>x.id),...s.items.map(x=>x.id).filter(x=>!h.has(x))].map(x=>{const f=g.get(x),k=h.get(x);if(!f){const C=d.get(x);return!C&&k&&m(k)||C&&C.kind===(k==null?void 0:k.kind)&&!(k&&typeof k.sequence=="number"&&Number.isFinite(k.sequence)&&C.sequence!==k.sequence)?null:k??null}return qr(k,f)}).filter(x=>!!x);return A.length===0?null:{turnId:s.turnId,items:A,updatedAt:s.updatedAt.localeCompare(t.updatedAt)>=0?s.updatedAt:t.updatedAt}}function Ps(t,s){const a=t.filter(n=>n.id!==s.id);return[s,...a]}function od(t){return`${t.threadId}:${t.objective}:${t.createdAt}`}function ld(t,s){const a=Date.parse(t.updatedAt)||0,d=(Date.parse(s.updatedAt)||0)>=a?s:t,o=d===s?t:s;return{...d,localGoalId:d.localGoalId??o.localGoalId??null}}function zr(t){const s=new Map;for(const a of t){const n=od(a),d=s.get(n);s.set(n,d?ld(d,a):a)}return[...s.values()].sort((a,n)=>Date.parse(n.updatedAt)-Date.parse(a.updatedAt))}function cn(t,s){return zr([s,...t])}function id(t){const s=new Intl.NumberFormat(void 0,{notation:"compact",maximumFractionDigits:1});return t.tokenBudget===null?`${s.format(t.tokensUsed)} tok`:`${s.format(t.tokensUsed)}/${s.format(t.tokenBudget)} tok`}function dd(t){const s=Math.max(0,Math.floor(t/60)),a=Math.floor(s/60),n=s%60;return a>0?`${a}h ${n}m`:`${s}m`}function Qa(t,s){if(!s)return null;const a=t.find(n=>n.model===s);return a?a.supportedReasoningEfforts.length>1:null}function cd(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`client-${Date.now()}-${Math.random().toString(16).slice(2,10)}`}function Us(t,s){return(t==null?void 0:t.items.some(a=>a.kind==="userMessage"&&a.text.trim()===s))??!1}function er(t){return t.replace(/\s*\[PHOTO\s+[^\]]+\]\s*/g," ").replace(/\s+/g," ").trim()}function gn(t,s){const a=er(s);return a?(t==null?void 0:t.items.some(n=>n.kind==="userMessage"&&er(n.text)===a))??!1:!1}function Fn(t){return(t==null?void 0:t.items.some(s=>s.kind==="userMessage"&&/\[PHOTO\s+\.\/\.temp\/threads\/[^\]]+\]/.test(s.text)))??!1}function ud(t,s){return t.find(a=>Us(a,s))??(s.includes("[PHOTO ")?t.find(a=>gn(a,s))??null:null)}function md(t,s,a,n){let d=!1;const o=t.map(m=>m.id!==s?m:(d=!0,{...m,tokenUsage:a,priceEstimate:n}));return d?o:t}const hd=3e3,pd=6e4,fd=5e3,xd=2147e6,gd=["worker:read","worker:write","session:prompt","provider:turn:create","provider:turn:interrupt"];function bd(t){if(!t)return"no activity yet";const s=Date.parse(t);if(!Number.isFinite(s))return t;const a=Date.now()-s,n=Math.abs(a),d=a>=0?"ago":"from now",o=6e4,m=60*o,h=24*m;return n<o?"just now":n<m?`${Math.round(n/o)}m ${d}`:n<h?`${Math.round(n/m)}h ${d}`:`${Math.round(n/h)}d ${d}`}function vd({title:t,children:s}){const[a,n]=r.useState(!1);return e.jsxs("section",{className:"control-metadata-disclosure",children:[e.jsxs("button",{type:"button","aria-expanded":a,onClick:()=>n(d=>!d),className:"control-metadata-trigger",children:[e.jsx("span",{children:t}),e.jsx("span",{children:a?"Hide":"Show"})]}),a?s:null]})}function Ae({label:t,value:s}){const a=s&&s.trim()?s:"not assigned";return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsxs("dd",{children:[e.jsx("span",{children:a}),s?e.jsx("button",{type:"button",className:"control-copy-button",onClick:()=>{var n;(n=navigator.clipboard)==null||n.writeText(s)},children:"Copy"}):null]})]})}function jd(t){if(!t||typeof t!="object")return null;const s=t,a=Array.isArray(s.content)?s.content.filter(n=>typeof n=="string"):typeof s.content=="string"?[s.content]:[];return a.length===0?null:{content:a.join(`
|
|
5
|
+
`),format:typeof s.format=="string"?s.format:"text",name:typeof s.name=="string"?s.name:null}}function yd({selected:t,onClose:s}){const a=ca(),[n,d]=r.useState(t.kind==="artifact"?"preview":"logs"),[o,m]=r.useState(!0),h=t.kind==="artifact"?t.artifact:null,g=t.kind==="historyDetail"?t.detail:null,y=t.item,A=h?jd(h.payload):null,x=h?a.renderArtifact({artifact:h,expanded:o,onToggleExpanded:()=>m(k=>!k)}):null,f=[{id:"preview",label:"Preview"},{id:"source",label:"Source"},{id:"logs",label:"Logs"},{id:"metadata",label:"Metadata"}];return e.jsxs("aside",{className:"control-artifact-inspector","aria-label":"Thread inspector",children:[e.jsxs("header",{className:"control-artifact-inspector-header",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{children:(h==null?void 0:h.type)??y.kind}),e.jsx("h2",{children:(h==null?void 0:h.title)??(g==null?void 0:g.title)??y.text??"Timeline detail"})]}),e.jsx("button",{type:"button",onClick:s,"aria-label":"Close thread inspector",children:"x"})]}),e.jsx("div",{className:"control-artifact-tabs",role:"tablist","aria-label":"Thread details",children:f.map(k=>e.jsx("button",{type:"button",role:"tab","aria-selected":n===k.id,onClick:()=>d(k.id),children:k.label},k.id))}),e.jsxs("div",{className:"control-artifact-panel",children:[n==="preview"?t.kind!=="artifact"?e.jsx("div",{className:"control-artifact-empty",children:"Preview is available for artifacts. Open Logs for this item detail."}):x?e.jsx("div",{className:"control-artifact-preview",children:x}):e.jsx("div",{className:"control-artifact-empty",children:"No renderer is enabled for this artifact type."}):null,n==="source"?g?e.jsx("pre",{className:"control-artifact-source-raw",children:g.text}):A?e.jsxs("div",{className:"control-artifact-source",children:[e.jsxs("div",{children:[e.jsx("span",{children:A.format}),A.name?e.jsx("strong",{children:A.name}):null]}),e.jsx("pre",{children:A.content})]}):e.jsx("pre",{className:"control-artifact-source-raw",children:JSON.stringify(h==null?void 0:h.payload,null,2)}):null,n==="logs"?e.jsx("div",{className:"control-artifact-logs",children:g?e.jsx("pre",{children:g.text}):e.jsxs("dl",{className:"control-detail-list",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Timeline item"}),e.jsx("dd",{children:y.text||y.previewText||(h==null?void 0:h.summaryText)||"Artifact created"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Status"}),e.jsx("dd",{children:y.status??"completed"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Source turn"}),e.jsx("dd",{children:(h==null?void 0:h.sourceTurnId)??y.sourceTurnId??"not assigned"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Source item"}),e.jsx("dd",{children:(h==null?void 0:h.sourceItemId)??y.id})]})]})}):null,n==="metadata"?e.jsxs("dl",{className:"control-detail-list",children:[e.jsx(Ae,{label:"Timeline item id",value:y.id}),e.jsx(Ae,{label:"Timeline kind",value:y.kind}),h?e.jsxs(e.Fragment,{children:[e.jsx(Ae,{label:"Artifact id",value:h.id}),e.jsx(Ae,{label:"Plugin id",value:h.pluginId}),e.jsx(Ae,{label:"Artifact type",value:h.type}),e.jsx(Ae,{label:"Created",value:ps(h.createdAt)}),e.jsx(Ae,{label:"Source turn",value:h.sourceTurnId}),e.jsx(Ae,{label:"Source item",value:h.sourceItemId})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ae,{label:"Detail id",value:g==null?void 0:g.id}),e.jsx(Ae,{label:"Detail kind",value:g==null?void 0:g.kind})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Payload"}),e.jsx("dd",{children:e.jsx("pre",{children:JSON.stringify(h?h.payload:{item:y,detail:g},null,2)})})]})]}):null]})]})}const wd=[],Nd=[],Sd=[],kd={sessions:{list:!1,read:!0,resume:!0,importLocal:!1},turns:{start:!0,streamInput:!1,steer:!1,interrupt:!0,compact:!1},branching:{fork:!1,hardRollback:!1,resumeAt:!1,rewindFiles:!1},controls:{planMode:!1,permissionRequests:!1,sandboxMode:!1,performanceMode:!1,goals:!1},management:{models:!1,mcpStatus:!1,skills:!1,hooks:!1,hookTrust:!1,hostConfigFiles:!1,providerSettings:!1},usage:{contextWindow:!0,tokenUsage:!0,costUsd:!1}};function Cd(){const t=Qt();return t?{baseUrl:t.baseUrl,token:t.token}:null}function Vr(t){switch(t){case"idle":case"running":case"interrupted":case"failed":case"not_loaded":case"system_error":return t;case"active":return"idle";default:return"not_loaded"}}function tr(t,s,a){const n=a==null?void 0:a.thread;return{id:t.id,workspaceId:s.id,provider:t.provider,providerSessionId:t.workerSessionId??(n==null?void 0:n.providerSessionId)??null,source:"supervisor",title:t.title||(n==null?void 0:n.title)||"Remote session",model:(n==null?void 0:n.model)??null,reasoningEffort:(n==null?void 0:n.reasoningEffort)??null,fastMode:(n==null?void 0:n.fastMode)??!1,collaborationMode:(n==null?void 0:n.collaborationMode)??"default",approvalMode:(n==null?void 0:n.approvalMode)??"guarded",sandboxMode:(n==null?void 0:n.sandboxMode)??null,status:(n==null?void 0:n.status)??Vr(t.status),summaryText:(n==null?void 0:n.summaryText)??null,lastError:(n==null?void 0:n.lastError)??null,activeTurnId:(n==null?void 0:n.activeTurnId)??null,isLoaded:!!(n!=null&&n.isLoaded),isPinned:!1,createdAt:t.createdAt,updatedAt:(n==null?void 0:n.updatedAt)??t.updatedAt,lastTurnStartedAt:(n==null?void 0:n.lastTurnStartedAt)??t.lastActivityAt,lastTurnCompletedAt:(n==null?void 0:n.lastTurnCompletedAt)??null,...n!=null&&n.contextUsage?{contextUsage:n.contextUsage}:{}}}function Td(t,s,a){const n=new URL(`/api/sandboxes/${encodeURIComponent(t.sandboxId)}/api/threads/${encodeURIComponent(s)}/assets/image`,t.routerBaseUrl);return n.searchParams.set("path",a),n.toString()}const Id={status:"not_created",connectionButtonDisabled:!0,connectionButtonLabel:"Remote shell unavailable",shellInputEnabled:!1,isConnecting:!1,isCommandRunning:!1,promptLabel:"Remote shell adapter not connected",isMobileShell:!1,hasShell:!1,busy:!1,loading:!1,error:"Remote sandbox shell routing is not connected yet."};function Wn(t){return t instanceof re&&t.statusCode===401&&t.payload.code==="invalid_route_token"}function sr(t){return t instanceof re&&(t.statusCode===404||t.statusCode===409)}function Jr(t,s){return Object.is(t,s)?!0:JSON.stringify(t)===JSON.stringify(s)}function qn(t,s){let a=t.length!==s.length||t.some((o,m)=>{var h;return o.id!==((h=s[m])==null?void 0:h.id)});const n=new Map(t.map(o=>[o.id,o])),d=s.map(o=>{const m=n.get(o.id);return m&&Jr(m,o)?m:(a=!0,o)});return a?d:t}function un(t,s){return Jr(t,s)?t:s}function Ed(t,s){if(!t)return s;const a=qn(t.turns,zt(t.turns,s.turns)),n=qn(t.pendingRequests,ia(t.pendingRequests,s.pendingRequests,new Set)),d={...s,turns:a,pendingRequests:n,pendingSteers:qn(t.pendingSteers,s.pendingSteers)};return("answeredRequestNotes"in s||"answeredRequestNotes"in t)&&(d.answeredRequestNotes=un(t.answeredRequestNotes,s.answeredRequestNotes)??[]),("activityNotes"in s||"activityNotes"in t)&&(d.activityNotes=un(t.activityNotes,s.activityNotes)??[]),("livePlan"in s||"livePlan"in t)&&(d.livePlan=un(t.livePlan,s.livePlan)??null),("liveItems"in s||"liveItems"in t)&&(d.liveItems=un(t.liveItems,s.liveItems)??null),d}function Rd(){return e.jsx(Pd,{})}function Pd(){const{sessionId:t=""}=ur(),s=at(),a=Jt(),n=r.useMemo(Cd,[]),[d,o]=r.useState(null),[m,h]=r.useState(null),[g,y]=r.useState(null),[A,x]=r.useState([]),[f,k]=r.useState(null),[C,E]=r.useState(null),[v,J]=r.useState(null),[te,_]=r.useState({prompt:"",attachments:[]}),[R,X]=r.useState(!0),[c,D]=r.useState(!1),[Y,I]=r.useState(null),[q,B]=r.useState(0),[je,fe]=r.useState("chat"),[H,he]=r.useState(!0),[T,le]=r.useState(null),oe=r.useRef(!1),W=r.useRef(null),F=r.useRef(null),z=r.useCallback(se=>{J(ie=>{const ue=Ed(ie,se);return F.current=ue,ue})},[]),ce=r.useCallback(async se=>{if(!n)return null;const ie=await Ir(n,se.sandbox.id,{projectId:se.project.id,workspaceId:se.workspace.id,sessionId:se.session.id,scopes:gd});return E(ie),ie},[n]),xe=r.useCallback(async()=>!d||!m||!g||!f||d.state!=="running"?null:ce({sandbox:d,project:m,workspace:g,session:f}),[ce,m,d,f,g]),rt=r.useCallback(async()=>{if(!n)return s("/control-plane/login",{replace:!0}),null;X(!0),I(null);try{const se=await ha(n);if(o(se.sandbox),se.sandbox.state!=="running")return k(null),E(null),J(null),F.current=null,I("Sandbox is not running. Start the sandbox from the control plane before opening chat."),null;const ie=await Cr(n);for(const ue of ie.projects){const me=await aa(n,ue.id);for(const ke of me.workspaces){const V=await ra(n,ke.id),Xe=V.sessions.find(gt=>gt.id===t);if(!Xe)continue;const Le=await Tr(n,Xe.id),Qe=V.sessions.map(gt=>gt.id===Le.session.id?Le.session:gt),xt=await ce({sandbox:se.sandbox,project:ue,workspace:ke,session:Le.session});if(!xt)return I("Unable to issue a router token for this session."),null;if(h(ue),y(ke),x(Qe),k(Le.session),!Le.session.workerSessionId)return J(null),F.current=null,I("Session resumed, but the worker did not return a thread id."),null;const Dt=await us(xt,Le.session.workerSessionId);return z(Dt),B(gt=>gt+1),{session:Le.session,token:xt,detail:Dt}}}return I("Session was not found in any project workspace."),null}catch(se){return se instanceof re&&se.payload.code==="unauthorized"?(jn(),s("/control-plane/login",{replace:!0}),null):(I(se instanceof Error?se.message:"Unable to open control-plane session."),null)}finally{X(!1)}},[z,n,ce,s,t]);r.useEffect(()=>{rt()},[rt]),r.useEffect(()=>{le(null)},[t]),r.useEffect(()=>{if(W.current&&(window.clearTimeout(W.current),W.current=null),!C)return;const se=Date.parse(C.expiresAt);if(!Number.isFinite(se))return;const ie=Math.max(fd,Math.min(xd,se-Date.now()-pd));return W.current=window.setTimeout(()=>{xe().catch(ue=>{I(ue instanceof Error?ue.message:"Unable to refresh router token.")})},ie),()=>{W.current&&(window.clearTimeout(W.current),W.current=null)}},[xe,C]);const ct=r.useCallback(async(se={})=>{if(!(!C||!(f!=null&&f.workerSessionId))){se.silent||I(null);try{z(await us(C,f.workerSessionId))}catch(ie){if(Wn(ie))try{const ue=await xe();if(ue&&f.workerSessionId){z(await us(ue,f.workerSessionId));return}}catch(ue){I(ue instanceof Error?ue.message:"Unable to refresh worker thread.");return}if(sr(ie)&&!oe.current){oe.current=!0;try{await rt();return}finally{oe.current=!1}}I(ie instanceof Error?ie.message:"Unable to refresh worker thread.")}}},[z,rt,xe,C,f==null?void 0:f.workerSessionId]);r.useEffect(()=>{if(!((v==null?void 0:v.thread.status)==="running"||!!(v!=null&&v.thread.activeTurnId)||c)||!C||!(f!=null&&f.workerSessionId))return;const ie=window.setInterval(()=>{ct({silent:!0})},hd);return()=>window.clearInterval(ie)},[v==null?void 0:v.thread.activeTurnId,v==null?void 0:v.thread.status,ct,C,c,f==null?void 0:f.workerSessionId]);async function Ke(se){const ie=se.prompt.trim();if(!ie||!C||!(f!=null&&f.workerSessionId))return!1;D(!0),I(null);try{return await $n(C,f.workerSessionId,{prompt:ie}),_({prompt:"",attachments:[]}),await ct(),B(ue=>ue+1),!0}catch(ue){if(Wn(ue))try{const me=await xe();if(!me||!f.workerSessionId)throw ue;await $n(me,f.workerSessionId,{prompt:ie});const ke=await us(me,f.workerSessionId);return z(ke),_({prompt:"",attachments:[]}),B(V=>V+1),!0}catch(me){return I(me instanceof Error?me.message:"Unable to send prompt."),!1}if(sr(ue)&&!oe.current){oe.current=!0;try{const me=await rt();if(!(me!=null&&me.session.workerSessionId))throw ue;await $n(me.token,me.session.workerSessionId,{prompt:ie});const ke=await us(me.token,me.session.workerSessionId);return z(ke),_({prompt:"",attachments:[]}),B(V=>V+1),!0}catch(me){return I(me instanceof Error?me.message:"Unable to send prompt."),!1}finally{oe.current=!1}}return I(ue instanceof Error?ue.message:"Unable to send prompt."),!1}finally{D(!1)}}async function wt(){var se,ie;if(!(!C||!(f!=null&&f.workerSessionId))){D(!0),I(null);try{const ue=((se=F.current)==null?void 0:se.thread.activeTurnId)??void 0,me=await Ha(C,f.workerSessionId,ue?{turnId:ue}:{});J(ke=>ke&&{...ke,thread:me}),await ct({silent:!0})}catch(ue){if(Wn(ue))try{const me=await xe();if(!me||!f.workerSessionId)throw ue;const ke=((ie=F.current)==null?void 0:ie.thread.activeTurnId)??void 0,V=await Ha(me,f.workerSessionId,ke?{turnId:ke}:{});J(Xe=>Xe&&{...Xe,thread:V}),z(await us(me,f.workerSessionId));return}catch(me){I(me instanceof Error?me.message:"Unable to interrupt turn.");return}I(ue instanceof Error?ue.message:"Unable to interrupt turn.")}finally{D(!1)}}}const ze=C?f!=null&&f.workerSessionId?void 0:"Reconnect this session before sending a prompt.":"Waiting for a router token...",ut=g?A.map(se=>tr(se,g,se.id===(f==null?void 0:f.id)?v:null)):[],Be=f&&g?tr(f,g,v):null,mt=Be&&ut.every(se=>se.id!==Be.id)?[Be,...ut]:ut,Ye=(v==null?void 0:v.thread.status)??Vr(f==null?void 0:f.status),b=fr(Ye),j=(v==null?void 0:v.thread.lastTurnStartedAt)??(v==null?void 0:v.thread.updatedAt)??(f==null?void 0:f.lastActivityAt)??(f==null?void 0:f.updatedAt)??null,M=(f==null?void 0:f.provider)??(v==null?void 0:v.thread.provider)??"codex",Q=(v==null?void 0:v.thread.model)??"default model",be=(C==null?void 0:C.expiresAt)??null,$e=e.jsxs("div",{className:"control-session-meta",children:[e.jsxs("dl",{className:"control-detail-list compact summary two",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Status"}),e.jsx("dd",{children:b})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Provider"}),e.jsx("dd",{children:M})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Workspace"}),e.jsx("dd",{children:(g==null?void 0:g.name)??(v==null?void 0:v.workspace.label)??"Unavailable"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Project"}),e.jsx("dd",{children:(m==null?void 0:m.name)??"None"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Model"}),e.jsx("dd",{children:Q})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Last activity"}),e.jsx("dd",{children:bd(j)})]})]}),e.jsx(vd,{title:"Diagnostics",children:e.jsxs("dl",{className:"control-detail-list",children:[e.jsx(Ae,{label:"Control session id",value:(f==null?void 0:f.id)??t}),e.jsx(Ae,{label:"Worker thread id",value:f==null?void 0:f.workerSessionId}),e.jsx(Ae,{label:"Workspace path",value:(g==null?void 0:g.path)??(v==null?void 0:v.workspace.absPath)}),e.jsx(Ae,{label:"Workspace id",value:g==null?void 0:g.id}),e.jsx(Ae,{label:"Project id",value:m==null?void 0:m.id}),e.jsx(Ae,{label:"Sandbox id",value:d==null?void 0:d.id}),e.jsx(Ae,{label:"Router URL",value:(C==null?void 0:C.routerBaseUrl)??(d==null?void 0:d.routerBaseUrl)}),e.jsx(Ae,{label:"Image",value:d==null?void 0:d.image}),e.jsx(Ae,{label:"Worker service",value:d==null?void 0:d.workerServiceName}),e.jsx(Ae,{label:"Session updated",value:ps((f==null?void 0:f.updatedAt)??null)}),e.jsx(Ae,{label:"Route token expires",value:ps(be)})]})})]}),Ue=e.jsx("div",{className:"space-y-4 text-sm",children:e.jsxs("section",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs uppercase tracking-[0.2em] text-[var(--theme-fg-muted)]",children:"Remote Session"}),e.jsx("button",{type:"button",onClick:()=>void rt(),disabled:R,className:"block w-full rounded-xl border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-2 text-left text-sm text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:opacity-60",children:R?"Reconnecting...":"Reconnect session"}),e.jsx("button",{type:"button",onClick:()=>void ct(),disabled:!C,className:"block w-full rounded-xl border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-2 text-left text-sm text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:opacity-60",children:"Refresh worker thread"})]})}),Ze=r.useCallback(se=>{le({kind:"artifact",...se})},[]),ht=r.useCallback(se=>{le({kind:"historyDetail",...se})},[]),Ve=r.useCallback(async se=>{if(!C||!(f!=null&&f.workerSessionId))throw new Error("Reconnect this session before loading item details.");return ll(C,f.workerSessionId,se)},[C,f==null?void 0:f.workerSessionId]),pt=r.useMemo(()=>({scrollRequestKey:q,className:"thread-timeline-surface min-h-0 flex-1",onTailVisibilityChange:he,answeredRequestNotes:(v==null?void 0:v.answeredRequestNotes)??wd,activityNotes:(v==null?void 0:v.activityNotes)??Nd,pendingSteers:(v==null?void 0:v.pendingSteers)??Sd,onLoadHistoryItemDetail:Ve,onSelectArtifact:Ze,onSelectHistoryItemDetail:ht}),[v==null?void 0:v.activityNotes,v==null?void 0:v.answeredRequestNotes,v==null?void 0:v.pendingSteers,Ze,ht,Ve,q]),Me=v?{busy:c,error:Y,model:v.thread.model,reasoningEffort:v.thread.reasoningEffort,fastMode:v.thread.fastMode??!1,collaborationMode:v.thread.collaborationMode,contextUsage:v.thread.contextUsage,capabilities:kd,toolboxItems:[],followTail:H,threadConnected:v.thread.isLoaded,disabled:!!ze,...ze?{disabledPlaceholder:ze}:{},draftPrompt:te.prompt,draftAttachments:te.attachments,onDraftChange:_,canInterrupt:!!v.thread.activeTurnId,onInterrupt:wt,shellControlState:Id,onToggleView:()=>fe("shell"),onToggleFollow:()=>B(se=>se+1)}:null,Et=e.jsx("span",{className:"control-session-status-badge",children:b}),Lt=e.jsx("div",{className:"flex min-h-0 flex-1 items-center justify-center p-4 sm:p-6",children:e.jsxs("div",{className:"thread-empty-surface max-w-md rounded-[1.6rem] border px-6 py-8 text-center",children:[e.jsx("p",{className:"text-base font-medium text-[var(--theme-fg)]",children:"Remote shell transport unavailable"}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-[var(--theme-fg-muted)]",children:"The Terminal plugin is enabled, but this control-plane route does not yet provide the remote shell API adapter used by the main supervisor thread page."}),e.jsx("button",{type:"button",onClick:()=>fe("chat"),className:"mt-5 inline-flex h-9 items-center rounded-full border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-4 text-sm font-medium text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--theme-ring)] focus:ring-offset-2 focus:ring-offset-[var(--theme-surface)]",children:"Switch to chat"})]})}),Gt=r.useCallback(se=>C&&(f!=null&&f.workerSessionId)?Td(C,f.workerSessionId,se):"",[C,f==null?void 0:f.workerSessionId]),Kt=r.useMemo(()=>({openThread:se=>{s(`/control-plane/sessions/${se}`)},getThreadHref:se=>`/control-plane/sessions/${se}`,getNewThreadHref:()=>"/control-plane",sendPrompt:Ke,interrupt:wt,getImageAssetUrl:Gt,shell:null}),[Gt,s]);return e.jsxs("div",{className:"control-chat-workspace",children:[e.jsx(pr,{threads:mt,detail:v,status:null,loading:R,error:R?null:Y,adapter:Kt,currentWorkspaceId:(g==null?void 0:g.id)??null,currentWorkspaceLabel:(g==null?void 0:g.name)??(v==null?void 0:v.workspace.label)??null,metaContent:$e,settingsContent:Ue,surfaceActions:Et,appMenuButton:e.jsx(bo,{}),appNavigationMenu:e.jsx(go,{currentPath:`/control-plane/sessions/${t}`,items:[{label:"Control Plane",href:"/control-plane"},{label:"Workspaces",href:"/workspaces"}],onNavigate:s}),onCloseAppNavigation:(a==null?void 0:a.closeNav)??(()=>{}),activeView:je,timelineProps:pt,shellEffectiveTheme:(a==null?void 0:a.effectiveTheme)??"dark",shellThemeMode:(a==null?void 0:a.themeMode)??"system",...a!=null&&a.setThemeMode?{onShellThemeModeChange:a.setThemeMode}:{},shellUnavailableContent:Lt,shellDisconnectedContent:Lt,shellContent:Lt,loadingContent:e.jsx("div",{className:"flex flex-1 items-center justify-center px-6 py-12 text-center text-[var(--theme-fg-muted)]",children:"Opening worker thread..."}),emptyContent:e.jsx("div",{className:"flex flex-1 items-center justify-center px-6 py-12 text-center text-[var(--theme-fg-muted)]",children:"No worker thread is connected yet."}),...f?{currentThreadId:f.id}:{},...Me?{composerProps:Me}:{}}),T?e.jsx("div",{className:"control-artifact-inspector-overlay",children:e.jsx(yd,{selected:T,onClose:()=>le(null)})}):null]})}function Ad({onLogin:t}){const[s,a]=r.useState(""),[n,d]=r.useState(""),[o,m]=r.useState(null),[h,g]=r.useState(!1);async function y(A){A.preventDefault(),m(null),g(!0);try{await t({username:s,password:n})}catch(x){x instanceof re?m(x.payload.message):m("Unable to sign in.")}finally{g(!1)}}return e.jsx("main",{className:"flex min-h-screen items-center justify-center bg-[var(--app-bg)] px-4 py-8 text-[var(--app-fg)]",children:e.jsxs("section",{className:"w-full max-w-sm rounded-[1.35rem] border border-[var(--theme-border)] bg-[var(--theme-panel)] p-5 shadow-2xl shadow-[color-mix(in_oklch,var(--app-fg)_14%,transparent)] sm:p-6",children:[e.jsxs("div",{className:"mb-5",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-muted)]",children:"Supervisor Access"}),e.jsx("h1",{className:"mt-2 text-2xl font-semibold tracking-normal text-[var(--theme-fg)]",children:"Sign in"}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-[var(--theme-muted)]",children:"Use the admin credentials configured on this Remote Codex server."})]}),e.jsxs("form",{onSubmit:y,className:"space-y-4",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm font-medium text-[var(--theme-fg-soft)]",children:"Username"}),e.jsx("input",{autoComplete:"username",autoFocus:!0,className:"mt-2 h-11 w-full rounded-xl border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 text-sm text-[var(--theme-fg)] outline-none transition focus:border-[var(--theme-accent-solid)] focus:ring-2 focus:ring-[var(--theme-accent-border)]",disabled:h,name:"username",onChange:A=>a(A.target.value),value:s})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm font-medium text-[var(--theme-fg-soft)]",children:"Password"}),e.jsx("input",{autoComplete:"current-password",className:"mt-2 h-11 w-full rounded-xl border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 text-sm text-[var(--theme-fg)] outline-none transition focus:border-[var(--theme-accent-solid)] focus:ring-2 focus:ring-[var(--theme-accent-border)]",disabled:h,name:"password",onChange:A=>d(A.target.value),type:"password",value:n})]}),o&&e.jsx("p",{className:"rounded-xl border border-[var(--status-danger-border)] bg-[var(--status-danger-bg)] px-3 py-2 text-sm text-[var(--status-danger-fg)]",children:o}),e.jsx("button",{className:"h-11 w-full rounded-xl bg-[var(--theme-accent-solid)] px-4 text-sm font-semibold text-[var(--theme-accent-solid-fg)] transition hover:bg-[var(--theme-accent-solid-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--theme-accent-border)] disabled:cursor-not-allowed disabled:opacity-60",disabled:h||!s.trim()||!n,type:"submit",children:h?"Signing in...":"Sign in"})]})]})})}function zn(t,s){return t instanceof re?t.payload.message:t instanceof Error?t.message:s}function Ud(){var I;const[t,s]=r.useState(null),[a,n]=r.useState(""),[d,o]=r.useState(""),[m,h]=r.useState(""),[g,y]=r.useState(""),[A,x]=r.useState(!0),[f,k]=r.useState(!1),[C,E]=r.useState(!1),[v,J]=r.useState(null),[te,_]=r.useState(null),[R,X]=r.useState(!1);async function c(){var q;x(!0),_(null);try{xs();const B=await $s();s(B),n(((q=B.user)==null?void 0:q.username)??"")}catch(B){_(zn(B,"Unable to load account."))}finally{x(!1)}}r.useEffect(()=>{c()},[]);async function D(q){q.preventDefault(),k(!0),_(null),J(null);try{const B=await hl({username:a});s(je=>je!=null&&je.authenticated?{...je,user:B}:je),n(B.username),J("Account updated.")}catch(B){_(zn(B,"Unable to update account."))}finally{k(!1)}}async function Y(q){q.preventDefault(),E(!0),_(null),J(null);try{if(m!==g){_("New passwords do not match.");return}await pl({currentPassword:d,newPassword:m}),o(""),h(""),y(""),J("Password changed.")}catch(B){_(zn(B,"Unable to change password."))}finally{E(!1)}}return e.jsx("main",{className:"min-h-screen bg-[var(--app-bg)] px-4 py-6 text-[var(--app-fg)] sm:px-6",children:e.jsxs("div",{className:"mx-auto w-full max-w-4xl space-y-5 pr-12 sm:pr-0",children:[e.jsxs("header",{className:"border-b border-[var(--theme-border)] pb-5",children:[e.jsx(It,{className:"text-sm text-[var(--theme-accent-strong)]",to:"/workspaces",children:"Back to workspaces"}),e.jsx("p",{className:"mt-4 text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-fg-muted)]",children:"Relay Account"}),e.jsx("h1",{className:"mt-2 text-2xl font-semibold text-[var(--theme-fg)]",children:"Account settings"})]}),A?e.jsx("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4 text-sm text-[var(--theme-fg-muted)]",children:"Loading account..."}):t!=null&&t.authenticated?e.jsxs(e.Fragment,{children:[te?e.jsx(nr,{tone:"danger",children:te}):null,v?e.jsx(nr,{tone:"success",children:v}):null,e.jsxs("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:"Profile"}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"Username changes apply to future shares and login."})]}),e.jsxs("form",{className:"space-y-4",onSubmit:D,children:[e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Email",e.jsx("input",{className:"relay-input mt-2 w-full",disabled:!0,readOnly:!0,value:((I=t.user)==null?void 0:I.email)??""})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-end",children:[e.jsxs("label",{className:"block flex-1 text-sm text-[var(--theme-fg-soft)]",children:["Username",e.jsx("input",{className:"relay-input mt-2 w-full",onChange:q=>n(q.target.value),value:a})]}),e.jsxs("button",{className:"relay-button-primary inline-flex h-10 items-center justify-center gap-2",disabled:f||!a.trim(),type:"submit",children:[e.jsx(nt.Save,{className:"h-4 w-4"}),"Save"]})]}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-2",onClick:()=>X(!0),type:"button",children:[R?e.jsx(nt.CheckCircle2,{className:"h-4 w-4"}):e.jsx(nt.MailCheck,{className:"h-4 w-4"}),R?"Verification queued":"Verify email"]})]})]}),e.jsxs("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:"Password"}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"Use at least 8 characters."})]}),e.jsxs("form",{className:"grid gap-4 sm:grid-cols-3",onSubmit:Y,children:[e.jsx(Vn,{label:"Current password",value:d,onChange:o}),e.jsx(Vn,{label:"New password",value:m,onChange:h}),e.jsx(Vn,{label:"Confirm password",value:g,onChange:y}),e.jsxs("button",{className:"relay-button-primary inline-flex h-10 items-center justify-center gap-2 sm:col-span-3 sm:w-fit",disabled:C||!d||m.length<8||!g,type:"submit",children:[e.jsx(nt.Save,{className:"h-4 w-4"}),"Change password"]})]})]})]}):e.jsx("section",{className:"rounded-lg border border-[var(--status-danger-border)] bg-[var(--status-danger-bg)] p-4 text-sm text-[var(--status-danger-fg)]",children:"Relay login is required."})]})})}function Vn({label:t,value:s,onChange:a}){return e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:[t,e.jsx("input",{autoComplete:"new-password",className:"relay-input mt-2 w-full",onChange:n=>a(n.target.value),type:"password",value:s})]})}function nr({tone:t,children:s}){return e.jsx("div",{className:`rounded-lg border px-3 py-2 text-sm ${t==="danger"?"border-[var(--status-danger-border)] bg-[var(--status-danger-bg)] text-[var(--status-danger-fg)]":"border-[var(--status-success-border)] bg-[var(--status-success-bg)] text-[var(--status-success-fg)]"}`,children:s})}function Jn(t){return t instanceof re?t.payload.message:t instanceof Error?t.message:"Unable to update relay admin state."}function Od(){const[t,s]=r.useState(null),[a,n]=r.useState(!0),[d,o]=r.useState(null),[m,h]=r.useState(null);async function g(){n(!0),o(null);try{xs(),s(await gl())}catch(x){o(Jn(x))}finally{n(!1)}}r.useEffect(()=>{g()},[]);async function y(x){h("registration"),o(null);try{const f=await bl(x);s(k=>k&&{...k,registrationEnabled:f.registrationEnabled})}catch(f){o(Jn(f))}finally{h(null)}}async function A(x,f){h(x),o(null);try{const k=await vl(x,f);s(C=>C&&{...C,users:C.users.map(E=>E.id===k.id?k:E)})}catch(k){o(Jn(k))}finally{h(null)}}return e.jsxs("main",{className:"min-h-screen bg-[var(--app-bg)] px-4 py-6 text-[var(--app-fg)] sm:px-6",children:[e.jsx(ga,{}),e.jsxs("div",{className:"mx-auto flex w-full max-w-6xl flex-col gap-5",children:[e.jsxs("header",{className:"flex flex-col gap-3 border-b border-[var(--theme-border)] pb-5 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-fg-muted)]",children:"Relay Admin"}),e.jsx("h1",{className:"mt-2 text-2xl font-semibold text-[var(--theme-fg)]",children:"Users and devices"}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"Manage relay accounts, registration, and connected devices."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(It,{className:"relay-button-secondary",to:"/relay-portal",children:"Portal"}),e.jsx("button",{className:"relay-button-secondary",onClick:()=>void g(),type:"button",children:"Refresh"})]})]}),a?e.jsx("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4 text-sm text-[var(--theme-fg-muted)]",children:"Loading relay admin..."}):d?e.jsx("section",{className:"rounded-lg border border-[var(--status-danger-border)] bg-[var(--status-danger-bg)] p-4 text-sm text-[var(--status-danger-fg)]",children:d}):t?e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:"Registration"}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"New users can create relay accounts without email verification."})]}),e.jsx("button",{className:"relay-button-primary",disabled:m==="registration",onClick:()=>void y(!t.registrationEnabled),type:"button",children:t.registrationEnabled?"Disable":"Enable"})]})}),e.jsxs("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:"Users"}),e.jsx("div",{className:"mt-4 overflow-x-auto",children:e.jsxs("table",{className:"w-full min-w-[44rem] border-collapse text-left text-sm",children:[e.jsx("thead",{className:"text-xs uppercase tracking-[0.16em] text-[var(--theme-fg-muted)]",children:e.jsxs("tr",{children:[e.jsx("th",{className:"border-b border-[var(--theme-border)] py-2 pr-3",children:"User"}),e.jsx("th",{className:"border-b border-[var(--theme-border)] py-2 pr-3",children:"Email"}),e.jsx("th",{className:"border-b border-[var(--theme-border)] py-2 pr-3",children:"Role"}),e.jsx("th",{className:"border-b border-[var(--theme-border)] py-2 pr-3",children:"Status"}),e.jsx("th",{className:"border-b border-[var(--theme-border)] py-2 pr-3",children:"Actions"})]})}),e.jsx("tbody",{children:t.users.map(x=>e.jsxs("tr",{children:[e.jsx("td",{className:"border-b border-[var(--theme-border)] py-3 pr-3 font-medium text-[var(--theme-fg)]",children:x.username}),e.jsx("td",{className:"border-b border-[var(--theme-border)] py-3 pr-3 text-[var(--theme-fg-muted)]",children:x.email}),e.jsx("td",{className:"border-b border-[var(--theme-border)] py-3 pr-3 text-[var(--theme-fg-muted)]",children:x.role}),e.jsx("td",{className:"border-b border-[var(--theme-border)] py-3 pr-3 text-[var(--theme-fg-muted)]",children:x.enabled?"Enabled":"Disabled"}),e.jsx("td",{className:"border-b border-[var(--theme-border)] py-3 pr-3",children:e.jsx("button",{className:"relay-button-secondary",disabled:m===x.id||x.role==="admin",onClick:()=>void A(x.id,!x.enabled),type:"button",children:x.enabled?"Disable":"Enable"})})]},x.id))})]})})]}),e.jsxs("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:"Devices"}),e.jsx("div",{className:"mt-4 grid gap-3 lg:grid-cols-2",children:t.devices.map(x=>e.jsxs("article",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`h-2.5 w-2.5 rounded-full ${x.connected?"bg-emerald-500":"bg-[var(--theme-fg-muted)]"}`}),e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:x.name})]}),e.jsx("p",{className:"mt-2 font-mono text-xs text-[var(--theme-fg-muted)]",children:x.id}),e.jsxs("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:["Owner: ",x.ownerUserId]})]},x.id))})]})]}):null]})]})}function Gn(t,s){return t instanceof re?t.payload.message:t instanceof Error?t.message:s}function $d(){const t=at(),[s,a]=r.useState(null),[n,d]=r.useState(""),[o,m]=r.useState(null),[h,g]=r.useState(null),[y,A]=r.useState(!0),[x,f]=r.useState(null),[k,C]=r.useState(null);async function E(){A(!0),C(null);try{xs(),a(await Rr())}catch(R){C(Gn(R,"Unable to load devices."))}finally{A(!1)}}r.useEffect(()=>{E()},[]);async function v(R){R.preventDefault(),f("create"),C(null);try{const X=await Pr({name:n});m(X),d(""),await E()}catch(X){C(Gn(X,"Unable to create device."))}finally{f(null)}}async function J(R){f(R.id),C(null);try{await Ar(R.id),(o==null?void 0:o.device.id)===R.id&&m(null),await E()}catch(X){C(Gn(X,"Unable to delete device."))}finally{f(null)}}function te(R){bn(R.id),vn(null),t("/workspaces")}async function _(R){var c;const X=R.token;if(!X){C("This device token is not available. Create a new device token for devices created before token storage was enabled.");return}try{await((c=navigator.clipboard)==null?void 0:c.writeText(Gr(X))),g(R.id),window.setTimeout(()=>{g(D=>D===R.id?null:D)},1600)}catch{}}return e.jsx("main",{className:"min-h-screen bg-[var(--app-bg)] px-4 py-6 text-[var(--app-fg)] sm:px-6",children:e.jsxs("div",{className:"mx-auto w-full max-w-6xl space-y-5 pr-12 sm:pr-0",children:[e.jsxs("header",{className:"flex flex-col gap-3 border-b border-[var(--theme-border)] pb-5 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{children:[e.jsx(It,{className:"text-sm text-[var(--theme-accent-strong)]",to:"/workspaces",children:"Back to workspaces"}),e.jsx("p",{className:"mt-4 text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-fg-muted)]",children:"Relay Devices"}),e.jsx("h1",{className:"mt-2 text-2xl font-semibold text-[var(--theme-fg)]",children:"Device management"})]}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-2",onClick:()=>void E(),type:"button",children:[e.jsx(nt.RefreshCcw,{className:"h-4 w-4"}),"Refresh"]})]}),k?e.jsx(Dd,{tone:"danger",children:k}):null,o?e.jsx(Ld,{result:o}):null,e.jsxs("section",{className:"grid gap-4 lg:grid-cols-[minmax(20rem,0.8fr)_minmax(0,1.2fr)]",children:[e.jsxs("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsxs("div",{className:"mb-4 flex items-start gap-3",children:[e.jsx("span",{className:"inline-flex h-9 w-9 items-center justify-center rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] text-[var(--theme-fg)]",children:e.jsx(nt.Plus,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:"Add device"}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"Create a token for one private supervisor."})]})]}),e.jsxs("form",{className:"space-y-3",onSubmit:v,children:[e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Device name",e.jsx("input",{className:"relay-input mt-2 w-full",onChange:R=>d(R.target.value),placeholder:"MacBook Pro",value:n})]}),e.jsxs("button",{className:"relay-button-primary inline-flex h-10 w-full items-center justify-center gap-2",disabled:x==="create"||!n.trim(),type:"submit",children:[e.jsx(nt.MonitorSmartphone,{className:"h-4 w-4"}),"Create device token"]})]})]}),e.jsxs("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:"Devices"}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"Connect to an online device before opening workspaces."})]}),e.jsx("span",{className:"rounded-full border border-[var(--theme-border)] px-2 py-0.5 text-xs text-[var(--theme-fg-muted)]",children:(s==null?void 0:s.devices.length)??0})]}),y?e.jsx("p",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-4 text-sm text-[var(--theme-fg-muted)]",children:"Loading devices..."}):s!=null&&s.devices.length?e.jsx("div",{className:"space-y-3",children:s.devices.map(R=>e.jsx(Md,{busy:x===R.id,copiedSetup:h===R.id,device:R,onConnect:()=>te(R),onCopySetup:()=>void _(R),onDelete:()=>void J(R),setupTokenAvailable:!!R.token},R.id))}):e.jsx("div",{className:"rounded-lg border border-dashed border-[var(--theme-border)] bg-[var(--theme-surface)] p-5 text-sm text-[var(--theme-fg-muted)]",children:"No devices yet. Create a token, then start `remote-codex relay-supervisor` on your private machine."})]})]})]})})}function Md({device:t,busy:s,copiedSetup:a,onConnect:n,onCopySetup:d,onDelete:o,setupTokenAvailable:m}){return e.jsxs("article",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-3",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:`h-2.5 w-2.5 rounded-full ${t.connected?"bg-[var(--status-success-fg)]":"bg-[var(--theme-fg-muted)]"}`}),e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:t.name})]}),e.jsx("p",{className:"mt-1 font-mono text-xs text-[var(--theme-fg-muted)]",children:t.tokenPreview}),e.jsx("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:t.connected?`Online since ${or(t.connectedAt)}`:`Offline. Last heartbeat: ${or(t.lastHeartbeatAt)}`})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-2",onClick:d,title:m?"Copy relay supervisor setup command":"Device token is not available. Create a new device token for devices created before token storage was enabled.",disabled:!m,type:"button",children:[e.jsx(nt.Copy,{className:"h-4 w-4"}),a?"Copied":"Copy setup"]}),e.jsxs("button",{className:"relay-button-primary inline-flex items-center gap-2",disabled:!t.connected,onClick:n,type:"button",children:[e.jsx(nt.Plug,{className:"h-4 w-4"}),"Connect"]}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-2",disabled:s,onClick:o,type:"button",children:[e.jsx(nt.Trash2,{className:"h-4 w-4"}),"Delete"]})]})]}),m?null:e.jsx("p",{className:"mt-3 rounded-md border border-[var(--theme-border)] bg-[var(--theme-panel)] px-3 py-2 text-xs text-[var(--theme-fg-muted)]",children:"Token not available for this device. Create a new device token to copy a ready-to-run setup command."})]})}function Ld({result:t}){const s=Gr(t.token);return e.jsxs("section",{className:"rounded-lg border border-[var(--theme-accent-border)] bg-[var(--theme-accent-soft)] p-4",children:[e.jsxs("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:["Token created for ",t.device.name]}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"Store this token now. It will not be shown again."}),e.jsx(ar,{label:"Device token",value:t.token}),e.jsx(ar,{label:"Supervisor command",value:s})]})}function ar({label:t,value:s}){async function a(){var n;try{await((n=navigator.clipboard)==null?void 0:n.writeText(s))}catch{}}return e.jsxs("div",{className:"mt-3",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-[0.14em] text-[var(--theme-fg-muted)]",children:t}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-1 px-2 py-1 text-xs",onClick:()=>void a(),type:"button",children:[e.jsx(nt.Copy,{className:"h-3.5 w-3.5"}),"Copy"]})]}),e.jsx("code",{className:"block break-all rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] px-3 py-2 font-mono text-xs text-[var(--theme-fg)]",children:s})]})}function Dd({tone:t,children:s}){return e.jsx("div",{className:"rounded-lg border border-[var(--status-danger-border)] bg-[var(--status-danger-bg)] px-3 py-2 text-sm text-[var(--status-danger-fg)]",children:s})}function Gr(t){const s=Hd();return[`REMOTE_CODEX_RELAY_SERVER_URL=${rr(s)} \\`,`REMOTE_CODEX_RELAY_AGENT_TOKEN=${rr(t)} \\`,"remote-codex relay-supervisor"].join(`
|
|
6
|
+
`)}function rr(t){return/^[A-Za-z0-9_./:@%+=,~-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function Hd(){return typeof window>"u"?"wss://relay.example.com":window.location.origin.replace(/^https:\/\//,"wss://").replace(/^http:\/\//,"ws://")}function or(t){return t?new Date(t).toLocaleString():"never"}function kn(t,s){return t instanceof re?t.payload.message:t instanceof Error?t.message:s}function Kr(){var R,X;const t=at(),[s,a]=r.useState(null),[n,d]=r.useState(null),[o,m]=r.useState(!0),[h,g]=r.useState(null),[y,A]=r.useState(null);async function x(){m(!0),g(null);try{xs();const c=await $s();a(c),c.authenticated?d(await Rr()):d(null)}catch(c){g(kn(c,"Unable to load relay portal."))}finally{m(!1)}}r.useEffect(()=>{x()},[]);async function f(){A(null),await x()}async function k(c){const D=await Pr({name:c});A(D),await x()}async function C(c){await Ar(c),await x()}async function E(c){await fl(c),await x()}async function v(c){await xl(c),await x()}async function J(){await Er(),a(await $s()),d(null),A(null)}function te(c){bn(c),vn(null),t("/workspaces")}function _(c,D){bn(c),vn(D),t(`/threads/${encodeURIComponent(D)}`)}return o?e.jsx(Kn,{children:"Checking relay session..."}):s!=null&&s.authenticated?e.jsx(Kn,{children:e.jsxs("div",{className:"mx-auto flex w-full max-w-6xl flex-col gap-5",children:[e.jsxs("header",{className:"flex flex-col gap-3 border-b border-[var(--theme-border)] pb-5 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-fg-muted)]",children:"Relay Portal"}),e.jsx("h1",{className:"mt-2 text-2xl font-semibold text-[var(--theme-fg)]",children:(R=s.user)==null?void 0:R.username}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"Manage devices and shared Remote Codex sessions."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[((X=s.user)==null?void 0:X.role)==="admin"?e.jsx(It,{className:"relay-button-secondary",to:"/relay-admin",children:"Admin"}):null,e.jsx("button",{className:"relay-button-secondary",onClick:()=>void x(),type:"button",children:"Refresh"}),e.jsx("button",{className:"relay-button-secondary",onClick:()=>void J(),type:"button",children:"Sign out"})]})]}),h?e.jsx(da,{tone:"danger",children:h}):null,y?e.jsxs(da,{tone:"accent",children:["Device token for ",y.device.name,". Store it on the device as REMOTE_CODEX_RELAY_AGENT_TOKEN. It will not be shown again.",e.jsx("code",{className:"mt-2 block break-all rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] px-3 py-2 font-mono text-xs",children:y.token}),e.jsx("code",{className:"mt-2 block break-all rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] px-3 py-2 font-mono text-xs",children:Wd(y.token)})]}):null,e.jsxs("section",{className:"grid gap-4 lg:grid-cols-[minmax(0,1.2fr)_minmax(20rem,0.8fr)]",children:[e.jsxs(Yn,{title:"Devices",description:"Owned devices and sessions shared with you.",children:[e.jsx(Bd,{onCreate:k}),e.jsx("div",{className:"mt-4 divide-y divide-[var(--theme-border)] rounded-lg border border-[var(--theme-border)]",children:n!=null&&n.devices.length?n.devices.map(c=>e.jsxs("div",{className:"flex flex-col gap-3 p-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`h-2.5 w-2.5 rounded-full ${c.connected?"bg-emerald-500":"bg-[var(--theme-fg-muted)]"}`}),e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:c.name})]}),e.jsx("p",{className:"mt-1 font-mono text-xs text-[var(--theme-fg-muted)]",children:c.tokenPreview}),e.jsx("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:c.connected?`Online. Last heartbeat: ${lr(c.lastHeartbeatAt??c.connectedAt)}`:`Offline. Last online: ${lr(c.lastHeartbeatAt??c.connectedAt)}`})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{className:"relay-button-primary",disabled:!c.connected,onClick:()=>te(c.id),type:"button",children:"Open"}),e.jsx("button",{className:"relay-button-secondary",onClick:()=>void C(c.id),type:"button",children:"Delete"})]})]},c.id)):e.jsx("p",{className:"p-3 text-sm text-[var(--theme-fg-muted)]",children:"No devices yet."})}),e.jsxs("div",{className:"mt-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("h3",{className:"text-sm font-semibold text-[var(--theme-fg)]",children:"Shared"}),e.jsx("span",{className:"rounded-full border border-[var(--theme-border)] px-2 py-0.5 text-[11px] text-[var(--theme-fg-muted)]",children:(n==null?void 0:n.sharedWithMe.length)??0})]}),e.jsx("div",{className:"mt-3 space-y-3",children:n!=null&&n.sharedWithMe.length?n.sharedWithMe.map(c=>e.jsx("article",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-3",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:c.label||c.threadId}),e.jsxs("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:[c.ownerUsername," / ",c.deviceName]})]}),e.jsx("button",{className:"relay-button-primary",onClick:()=>_(c.deviceId,c.threadId),type:"button",children:"Continue"})]})},c.id)):e.jsx("p",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-3 text-sm text-[var(--theme-fg-muted)]",children:"No shared sessions."})})]})]}),e.jsx(Yn,{title:"Invite",description:"Share a single thread with another relay user.",children:e.jsx(Fd,{devices:(n==null?void 0:n.devices)??[],onShare:E})})]}),e.jsx("section",{children:e.jsx(Yn,{title:"Shared By Me",description:"Active invitations you created.",children:e.jsx("div",{className:"space-y-3",children:n!=null&&n.sharedByMe.length?n.sharedByMe.map(c=>e.jsxs("article",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-3",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:c.label||c.threadId}),e.jsxs("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:["Shared with ",c.targetUsername," on ",c.deviceName]}),e.jsx("button",{className:"relay-button-secondary mt-3",onClick:()=>void v(c.id),type:"button",children:"Revoke"})]},c.id)):e.jsx("p",{className:"text-sm text-[var(--theme-fg-muted)]",children:"No active shares."})})})})]})}):e.jsx(Kn,{children:e.jsx(_d,{registrationEnabled:(s==null?void 0:s.registrationEnabled)??!0,initialError:h,onAuthenticated:f})})}function _d({registrationEnabled:t,initialError:s,onAuthenticated:a}){const[n,d]=r.useState("login"),[o,m]=r.useState(""),[h,g]=r.useState(""),[y,A]=r.useState(""),[x,f]=r.useState(""),[k,C]=r.useState(""),[E,v]=r.useState(s),[J,te]=r.useState(!1);async function _(R){R.preventDefault(),te(!0),v(null);try{n==="login"?await ul({identifier:o,password:x}):await ml({email:h,username:y,password:x,registrationPassword:k}),await a()}catch(X){v(kn(X,"Unable to authenticate with relay."))}finally{te(!1)}}return e.jsxs("section",{className:"w-full max-w-sm rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-5 shadow-xl shadow-black/10",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-fg-muted)]",children:"Relay Access"}),e.jsx("h1",{className:"mt-2 text-2xl font-semibold text-[var(--theme-fg)]",children:n==="login"?"Sign in":"Create account"}),e.jsxs("form",{className:"mt-5 space-y-4",onSubmit:_,children:[n==="login"?e.jsx(Vt,{autoComplete:"username",label:"Email or username",onChange:m,value:o}):e.jsxs(e.Fragment,{children:[e.jsx(Vt,{autoComplete:"email",label:"Email",onChange:g,value:h}),e.jsx(Vt,{autoComplete:"username",label:"Username",onChange:A,value:y}),e.jsx(Vt,{autoComplete:"one-time-code",label:"Registration password",onChange:C,type:"password",value:k})]}),e.jsx(Vt,{autoComplete:n==="login"?"current-password":"new-password",label:"Password",onChange:f,type:"password",value:x}),E?e.jsx(da,{tone:"danger",children:E}):null,e.jsx("button",{className:"relay-button-primary h-11 w-full",disabled:J,type:"submit",children:J?"Working...":n==="login"?"Sign in":"Register"})]}),e.jsx("button",{className:"mt-4 text-sm text-[var(--theme-accent-strong)] disabled:text-[var(--theme-fg-muted)]",disabled:n==="login"?!t:!1,onClick:()=>d(n==="login"?"register":"login"),type:"button",children:n==="login"?t?"Create relay account":"Registration is disabled":"Use an existing account"})]})}function Bd({onCreate:t}){const[s,a]=r.useState(""),[n,d]=r.useState(!1),[o,m]=r.useState(null);async function h(g){g.preventDefault(),d(!0),m(null);try{await t(s),a("")}catch(y){m(kn(y,"Unable to create device."))}finally{d(!1)}}return e.jsxs("form",{className:"flex flex-col gap-2 sm:flex-row",onSubmit:h,children:[e.jsx("input",{className:"relay-input min-w-0 flex-1",onChange:g=>a(g.target.value),placeholder:"Device name",value:s}),e.jsx("button",{className:"relay-button-primary",disabled:n||!s.trim(),type:"submit",children:"Create"}),o?e.jsx("p",{className:"text-sm text-[var(--status-danger-fg)]",children:o}):null]})}function Fd({devices:t,onShare:s}){const a=r.useMemo(()=>{var v;return((v=t[0])==null?void 0:v.id)??""},[t]),[n,d]=r.useState(a),[o,m]=r.useState(""),[h,g]=r.useState(""),[y,A]=r.useState(""),[x,f]=r.useState(!1),[k,C]=r.useState(null);r.useEffect(()=>{!n&&a&&d(a)},[n,a]);async function E(v){v.preventDefault(),f(!0),C(null);try{await s({targetUsername:o,deviceId:n,threadId:h,...y.trim()?{label:y}:{}}),m(""),g(""),A(""),C("Invitation created.")}catch(J){C(kn(J,"Unable to create invitation."))}finally{f(!1)}}return e.jsxs("form",{className:"space-y-3",onSubmit:E,children:[e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Device",e.jsx("select",{className:"relay-input mt-2 w-full",onChange:v=>d(v.target.value),value:n,children:t.map(v=>e.jsx("option",{value:v.id,children:v.name},v.id))})]}),e.jsx(Vt,{label:"Username",onChange:m,value:o}),e.jsx(Vt,{label:"Thread ID",onChange:g,value:h}),e.jsx(Vt,{label:"Label",onChange:A,value:y}),k?e.jsx("p",{className:"text-sm text-[var(--theme-fg-muted)]",children:k}):null,e.jsx("button",{className:"relay-button-primary",disabled:x||!n||!o.trim()||!h.trim(),type:"submit",children:"Invite"})]})}function Kn({children:t}){return e.jsxs("main",{className:"min-h-screen bg-[var(--app-bg)] px-4 py-6 text-[var(--app-fg)] sm:px-6",children:[e.jsx(ga,{}),e.jsx("div",{className:"flex min-h-[calc(100vh-3rem)] items-center justify-center",children:t})]})}function Yn({title:t,description:s,children:a}){return e.jsxs("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:t}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:s})]}),a]})}function Vt({label:t,value:s,onChange:a,type:n="text",autoComplete:d}){return e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:[t,e.jsx("input",{autoComplete:d,className:"relay-input mt-2 w-full",onChange:o=>a(o.target.value),type:n,value:s})]})}function da({tone:t,children:s}){return e.jsx("div",{className:`rounded-lg border px-3 py-2 text-sm ${t==="danger"?"border-[var(--status-danger-border)] bg-[var(--status-danger-bg)] text-[var(--status-danger-fg)]":"border-[var(--theme-accent-border)] bg-[var(--theme-accent-soft)] text-[var(--theme-fg)]"}`,children:s})}function Wd(t){return`REMOTE_CODEX_RELAY_SERVER_URL=${qd()} REMOTE_CODEX_RELAY_AGENT_TOKEN=${t} remote-codex relay-supervisor`}function qd(){return typeof window>"u"?"wss://relay.example.com":window.location.origin.replace(/^https:\/\//,"wss://").replace(/^http:\/\//,"ws://")}function lr(t){return t??"never"}const ir=3,zd=10,Vd=1e3,Jd=2e3,Zn=5500,Gd=3e3,Xn=0,ms=1,mn=3,Kd=["read-only","workspace-write","danger-full-access"],Yd=[],Zd=[],Xd=[],Qd={workspace:!0,toolUsage:!1,guide:!1,threadGraph:!1,extensions:!1,defaultTab:"workspace"};function ec(){return e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-3.5 w-3.5 fill-current",children:e.jsx("path",{d:"M5.75 1.75c-.97 0-1.75.78-1.75 1.75v.25H3.5c-.97 0-1.75.78-1.75 1.75v6c0 .97.78 1.75 1.75 1.75h4.75c.97 0 1.75-.78 1.75-1.75v-.25h.5c.97 0 1.75-.78 1.75-1.75v-6c0-.97-.78-1.75-1.75-1.75h-4.75Zm-.5 2V3.5c0-.28.22-.5.5-.5h4.75c.28 0 .5.22.5.5v6a.5.5 0 0 1-.5.5H10v-4.5c0-.97-.78-1.75-1.75-1.75h-3Zm-1.75 1.25h4.75c.28 0 .5.22.5.5v6a.5.5 0 0 1-.5.5H3.5a.5.5 0 0 1-.5-.5v-6c0-.28.22-.5.5-.5Z"})})}function tc(){return e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-4 w-4 fill-none stroke-current",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M4.25 2.25h5.2l2.3 2.3v9.2h-7.5a2 2 0 0 1-2-2v-7.5a2 2 0 0 1 2-2Z"}),e.jsx("path",{d:"M9.25 2.5v2.25h2.25"}),e.jsx("path",{d:"M7 6.75v4"}),e.jsx("path",{d:"m5.45 9.35 1.55 1.55 1.55-1.55"})]})}function hn({status:t}){return e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-4.5 w-4.5 fill-none stroke-current",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M2.5 6.75A8.22 8.22 0 0 1 8 4.5c2.14 0 4.1.8 5.5 2.25"}),e.jsx("path",{d:"M4.75 9a4.95 4.95 0 0 1 6.5 0"}),e.jsx("path",{d:"M6.9 11.3a1.9 1.9 0 0 1 2.2 0"}),t==="connected"?e.jsx("path",{d:"m6.7 13.2.9.9 1.7-2"}):t==="offline"?e.jsx("path",{d:"M3 3l10 10"}):t==="detached"?null:e.jsxs(e.Fragment,{children:[e.jsx("path",{d:"M11.8 11.1a2.2 2.2 0 0 1-1.8 2.7"}),e.jsx("path",{d:"m10.7 11.35 1.3-.55-.55-1.3"})]})]})}function sc(t,s){if(!t)return"Thread disconnected";switch(s.status){case"connected":return"Realtime updates connected";case"reconnecting":return"Realtime updates reconnecting";case"offline":return"Browser offline";case"checking":return"Checking realtime connection"}}function nc(){var Ea;const{id:t=""}=ur(),s=at(),a=Jt(),n=ca(),d=r.useRef(""),o=r.useRef(null),m=r.useRef(null),h=r.useRef(null),g=r.useRef(!1),y=r.useRef(null),A=r.useRef(null),x=r.useRef(typeof navigator>"u"?!0:navigator.onLine),f=r.useRef(!1),k=r.useRef(null),C=r.useRef(null),E=r.useRef(0),v=r.useRef(0),J=r.useRef(null),te=r.useRef(null),_=r.useRef(null),R=r.useRef(null),X=r.useRef(new Set),[c,D]=r.useState(null),[Y,I]=r.useState([]),[q,B]=r.useState([]),[je,fe]=r.useState(null),[H,he]=r.useState(null),[T,le]=r.useState(null),[oe,W]=r.useState(""),[F,z]=r.useState(null),[ce,xe]=r.useState(null),[rt,ct]=r.useState(!0),[Ke,wt]=r.useState(0),[ze,ut]=r.useState(!0),[Be,mt]=r.useState(!1),[Ye,b]=r.useState(!1),[j,M]=r.useState("chat"),Q=n.getThreadPanels().some(l=>l.kind==="terminal"),be=r.useMemo(()=>({fetchState:ql,createShell:Jl,terminateShell:Gl,updateShell:Kl,connectSocket:xi}),[]),$e=r.useCallback(l=>`/threads/${l}`,[]),Ue=r.useCallback(l=>{s(`/threads/${l}`)},[s]),Ze=r.useCallback(l=>l?`/threads/new?workspaceId=${encodeURIComponent(l)}`:"/threads/new",[]),ht=r.useCallback(({threadId:l,path:i})=>`/api/threads/${l}/assets/image?path=${encodeURIComponent(i)}`,[]),[Ve,pt]=r.useState({prompt:"",attachments:[]}),[Me,Et]=r.useState(!1),[Lt,Gt]=r.useState(0),[Kt,se]=r.useState(0),[ie,ue]=r.useState(0),[me,ke]=r.useState(!1),[V,Xe]=r.useState(null),[Le,Qe]=r.useState(!1),[xt,Dt]=r.useState(!1),[gt,gs]=r.useState(!1),[bs,vs]=r.useState(null),[Nt,Yt]=r.useState("idle"),[bt,js]=r.useState({status:x.current?"checking":"offline",browserOnline:x.current,healthOk:!1,socketOpen:!1,lastHealthyAt:null}),[we,ot]=r.useState(null),[St,Rt]=r.useState([]),[ys,et]=r.useState({status:"idle",data:null,error:null}),[ft,Pt]=r.useState({status:"idle",data:null,error:null}),[Je,Ie]=r.useState({status:"idle",data:null,error:null}),[Ht,kt]=r.useState({status:"idle",data:null,error:null}),[Ce,ye]=r.useState({status:"idle",data:null,error:null}),[Ms,G]=r.useState(!1),[ee,ne]=r.useState(!1),[ws,ts]=r.useState(()=>new Set),[Ns,At]=r.useState(!1),[Ut,Ls]=r.useState(!1),[Ct,_t]=r.useState({status:"idle",data:null,error:null}),[vt,Bt]=r.useState(null),[Ss,Zt]=r.useState(!1),[Ds,de]=r.useState(null),Ot=((Ea=T==null?void 0:T.hostConfigFiles.find(l=>{var i;return(i=l.roles)==null?void 0:i.includes("mcp")}))==null?void 0:Ea.name)??null,ss=r.useCallback(()=>{const l=d.current;d.current="",o.current=null,l&&r.startTransition(()=>{W(i=>i+l)})},[]),ns=r.useCallback(l=>{d.current+=l,o.current===null&&(o.current=window.requestAnimationFrame(()=>{ss()}))},[ss]),ks=r.useCallback((l,i)=>{xe(p=>{const P=(p==null?void 0:p.turnId)===l?p.items:[],O=P.findIndex(Te=>Te.id===i.id),Z=qr(P[O],i),pe=O>=0?P.map((Te,L)=>L===O?Z:Te):[...P,Z];return{turnId:l,items:pe,updatedAt:new Date().toISOString()}})},[]),Hs=r.useCallback((l,i,p,P,O)=>{xe(Z=>{const pe=(Z==null?void 0:Z.turnId)===l?Z.items:[],Te=pe.find(Pe=>Pe.id===i),L=(Te==null?void 0:Te.kind)==="agentMessage"?{...Te,text:`${Te.text}${p}`,sequence:P??Te.sequence??null}:{id:i,createdAt:O??new Date().toISOString(),kind:"agentMessage",text:p,sequence:P},Fe=pe.findIndex(Pe=>Pe.id===i),it=Fe>=0?pe.map((Pe,ge)=>ge===Fe?L:Pe):[...pe,L];return{turnId:l,items:it,updatedAt:new Date().toISOString()}})},[]),lt=r.useCallback(()=>{d.current="",o.current!==null&&(window.cancelAnimationFrame(o.current),o.current=null)},[]);r.useEffect(()=>{et({status:"idle",data:null,error:null}),Pt({status:"idle",data:null,error:null}),Ie({status:"idle",data:null,error:null}),kt({status:"idle",data:null,error:null}),ye({status:"idle",data:null,error:null}),At(!1),_t({status:"idle",data:null,error:null})},[t]);const as=r.useCallback(async()=>{if(t){_t(l=>({status:"loading",data:l.data,error:null}));try{const l=await Bl(t);_t({status:"ready",data:l,error:null})}catch(l){const i=l instanceof re?l.payload.message:"Unable to load export turns.";_t(p=>({status:"failed",data:p.data,error:i}))}}},[t]);async function _s(l){if(t){de(null),Ls(!0);try{const{blob:i,filename:p}=await Wl(t,l),P=URL.createObjectURL(i),O=document.createElement("a");O.href=P,O.download=p,document.body.append(O),O.click(),O.remove(),window.setTimeout(()=>URL.revokeObjectURL(P),3e4),At(!1)}catch(i){const p=i instanceof re?i.payload.message:"Unable to export transcript.";de(p)}finally{Ls(!1)}}}async function Bs(){if(t){ye(l=>{var i;return{status:"loading",data:l.data??((i=_.current)==null?void 0:i.goal)??null,error:null}});try{const l=await ei(t);ye({status:"ready",data:l.goal,error:null}),D(i=>i&&(l.goal?{...i,goal:l.goal,goalHistory:cn(i.goalHistory??[],l.goal)}:{...i,goal:l.goal}))}catch(l){ye(i=>({status:"failed",data:i.data,error:l instanceof re?l.payload.message:"Unable to load goal."}))}}}async function Fs(l){if(t){ye(i=>{var p;return{status:"loading",data:i.data??((p=_.current)==null?void 0:p.goal)??null,error:null}});try{const i=await ti(t,l);ye({status:"ready",data:i.goal,error:null}),D(p=>p&&(i.goal?{...p,goal:i.goal,goalHistory:cn(p.goalHistory??[],i.goal)}:{...p,goal:i.goal}))}catch(i){throw ye(p=>({status:"failed",data:p.data,error:i instanceof re?i.payload.message:"Unable to update goal."})),i}}}async function Cn(){if(t){ye(l=>{var i;return{status:"loading",data:l.data??((i=_.current)==null?void 0:i.goal)??null,error:null}});try{const l=await si(t);ye({status:"ready",data:null,error:null}),D(i=>i&&(l.goalHistory?{...i,goal:null,goalHistory:l.goalHistory}:{...i,goal:null}))}catch(l){throw ye(i=>({status:"failed",data:i.data,error:l instanceof re?l.payload.message:"Unable to clear goal."})),l}}}async function Ws(l){ne(!0);try{await Fs({status:l})}finally{ne(!1)}}async function Tn(){ne(!0);try{await Cn()}finally{ne(!1)}}async function qs(){if(t){et(l=>({status:"loading",data:l.data,error:null}));try{const l=await ai(t);et({status:"ready",data:l,error:null})}catch(l){et(i=>({status:"failed",data:i.data,error:l instanceof re?l.payload.message:"Unable to load skills."}))}}}async function In(){if(t){Pt(l=>({status:"loading",data:l.data,error:null}));try{const l=await ri(t);Pt({status:"ready",data:l,error:null})}catch(l){Pt(i=>({status:"failed",data:i.data,error:l instanceof re?l.payload.message:"Unable to load MCP servers."}))}}}async function En(){if(t){Ie(l=>({status:"loading",data:l.data,error:null}));try{const l=await oi(t);Ie({status:"ready",data:l,error:null})}catch(l){Ie(i=>({status:"failed",data:i.data,error:l instanceof re?l.payload.message:"Unable to load hooks."}))}}}async function Rn(l){if(t){Ie(i=>({status:"loading",data:i.data,error:null}));try{const i=await li(t,l);Ie({status:"ready",data:i,error:null})}catch(i){throw Ie(p=>({status:"failed",data:p.data,error:i instanceof re?i.payload.message:"Unable to create hook."})),i}}}async function Ge(l){if(t){Ie(i=>({status:"loading",data:i.data,error:null}));try{const i=await ii(t,l);Ie({status:"ready",data:i,error:null})}catch(i){throw Ie(p=>({status:"failed",data:p.data,error:i instanceof re?i.payload.message:"Unable to update hook."})),i}}}async function Cs(l){if(t){Ie(i=>({status:"loading",data:i.data,error:null}));try{const i=await di(t,l);Ie({status:"ready",data:i,error:null})}catch(i){throw Ie(p=>({status:"failed",data:p.data,error:i instanceof re?i.payload.message:"Unable to trust hook."})),i}}}async function zs(l){if(t){Ie(i=>({status:"loading",data:i.data,error:null}));try{const i=await ci(t,l);Ie({status:"ready",data:i,error:null})}catch(i){throw Ie(p=>({status:"failed",data:p.data,error:i instanceof re?i.payload.message:"Unable to untrust hook."})),i}}}async function jt(){if(t){kt(l=>({status:"loading",data:l.data,error:null}));try{const l=await ni(t);kt({status:"ready",data:l,error:null})}catch(l){kt(i=>({status:"failed",data:i.data,error:l instanceof re?l.payload.message:"Unable to load turns for forking."}))}}}async function yt(){if(!t)return;const l=await qa(t,{mode:"latest"});I(i=>Ps(i,l.thread.thread)),s(`/threads/${l.thread.thread.id}`)}async function Pn(l){if(!t)return;const i=await qa(t,{mode:"turn",turnId:l});I(p=>Ps(p,i.thread.thread)),s(`/threads/${i.thread.thread.id}`)}const Vs=r.useCallback(l=>{const i=R.current,p=i&&Object.keys(i).length>0?{...l,thread:{...l.thread,...i}}:l,P=_.current;_.current=p,z(p.livePlan??null);const O=P?zt(P.turns,p.turns):p.turns;xe(L=>rd(L,p.liveItems??null,O)),ye(L=>L.status==="idle"?L:{...L,data:p.goal??null});const Z=p.thread.activeTurnId===null&&p.thread.status!=="running";D(L=>L&&!p.goalHistory?{...p,turns:zt(L.turns,p.turns),pendingRequests:ia(L.pendingRequests,p.pendingRequests,X.current),...L.goalHistory?{goalHistory:L.goalHistory}:{}}:L?{...p,turns:zt(L.turns,p.turns),pendingRequests:ia(L.pendingRequests,p.pendingRequests,X.current)}:p),I(L=>Ps(L,p.thread));const pe=new Map(p.turns.map(L=>[L.id,L])),Te=new Set((p.pendingSteers??[]).map(L=>L.clientRequestId).filter(L=>!!L));Rt(L=>L.filter(Fe=>{if(Te.has(Fe.clientRequestId))return!1;const it=pe.get(Fe.turnId);return!(!it||Us(it,Fe.prompt)||p.thread.activeTurnId!==Fe.turnId&&it.status!=="inProgress")})),ot(L=>{if(!L)return L;const Fe=L.serverTurnId??L.id,it=p.turns.some($=>$.id===Fe),Pe=pe.get(Fe)??null,ge=ud(p.turns,L.prompt),w=!!ge;if(ge&&!L.serverTurnId)return{...L,id:ge.id,serverTurnId:ge.id,status:L.status==="failed"?L.status:ge.status==="inProgress"?"inProgress":L.status};if(Pe&&L.serverTurnId)return Us(Pe,L.prompt)||L.prompt.includes("[PHOTO ")&&(gn(Pe,L.prompt)||Fn(Pe))?Pe.status==="inProgress"?{...L,id:Pe.id,serverTurnId:Pe.id,status:L.status==="failed"?L.status:"inProgress"}:null:{...L,id:Pe.id,serverTurnId:Pe.id,status:L.status==="failed"?L.status:"inProgress"};if(!L.serverTurnId&&L.prompt.includes("[PHOTO ")&&p.thread.activeTurnId&&p.thread.status==="running"){const $=pe.get(p.thread.activeTurnId);if($&&Fn($))return{...L,id:$.id,serverTurnId:$.id,status:L.status==="failed"?L.status:"inProgress"}}return it||Z&&w?null:L}),(Z||te.current&&p.turns.some(L=>L.id===te.current))&&(te.current=null,lt(),W(""),z(null),xe(null))},[lt]);r.useEffect(()=>{_.current=c},[c]);const Js=r.useCallback(async({seedThread:l}={})=>{var pe;const i=v.current+1;v.current=i;const p=(l==null?void 0:l.provider)??((pe=_.current)==null?void 0:pe.thread.provider)??"codex",[P,O,Z]=await Promise.allSettled([Mr(),Ur(p),oa(p)]);v.current===i&&(P.status==="fulfilled"?I(l?Ps(P.value,l):P.value):l&&I(Te=>Ps(Te,l)),O.status==="fulfilled"&&(J.current=p,fe(O.value.status),he(O.value.capabilities),le(O.value.managementSchema)),Z.status==="fulfilled"&&(J.current=p,B(Z.value)))},[]),Ft=r.useCallback(async({showLoading:l=!0,clearError:i=!0,reportError:p=!0,limit:P=ir}={})=>{const O=E.current+1;E.current=O,l&&ut(!0),i&&de(null);try{const Z=await Ba(t,{limit:P});if(E.current!==O)return;Vs(Z),J.current!==Z.thread.provider&&Js({seedThread:Z.thread})}catch(Z){if(E.current!==O||!p)return;de(Z instanceof Error?Z.message:"Unable to load thread detail.")}finally{E.current===O&&ut(!1)}},[Vs,t,Js]),He=r.useCallback(()=>{var Te;const l=((Te=m.current)==null?void 0:Te.readyState)??mn,i=l===ms,p=x.current,P=Date.now(),O=y.current!==null&&P-Date.parse(y.current)<=Zn,Z=A.current!==null&&P-A.current<=Zn;let pe;p?i&&Z?pe="connected":l===Xn||h.current!==null||O||Z||g.current?pe="reconnecting":pe="checking":pe="offline",js(L=>L.status===pe&&L.browserOnline===p&&L.healthOk===O&&L.socketOpen===i&&L.lastHealthyAt===y.current?L:{status:pe,browserOnline:p,healthOk:O,socketOpen:i,lastHealthyAt:y.current})},[]);r.useEffect(()=>{E.current+=1,v.current+=1,D(null),pt({prompt:"",attachments:[]}),mt(!1),Yt("idle"),ot(null),Rt([]),xe(null),R.current=null,te.current=null,X.current=new Set,y.current=null,A.current=null,f.current=!1,x.current=typeof navigator>"u"?!0:navigator.onLine,js({status:x.current?"checking":"offline",browserOnline:x.current,healthOk:!1,socketOpen:!1,lastHealthyAt:null})},[t]),r.useEffect(()=>{if(Nt==="idle")return;const l=window.setTimeout(()=>{Yt("idle")},Nt==="copied"?1200:1600);return()=>{window.clearTimeout(l)}},[Nt]),r.useEffect(()=>{if(typeof document>"u")return;const{documentElement:l,body:i}=document;return l.classList.add("thread-detail-scroll-locked"),i.classList.add("thread-detail-scroll-locked"),()=>{l.classList.remove("thread-detail-scroll-locked"),i.classList.remove("thread-detail-scroll-locked")}},[]),r.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const l=window.matchMedia("(max-width: 639px)"),i=()=>Et(l.matches);return i(),l.addEventListener("change",i),()=>{l.removeEventListener("change",i)}},[]),r.useEffect(()=>{var i,p;if(typeof window>"u")return;const l=()=>{const P=window.visualViewport,O=P?Math.max(0,Math.round(window.innerHeight-P.height-P.offsetTop)):0;ue(O),document.documentElement.style.setProperty("--thread-detail-keyboard-inset",`${O}px`)};return l(),(i=window.visualViewport)==null||i.addEventListener("resize",l),(p=window.visualViewport)==null||p.addEventListener("scroll",l),window.addEventListener("resize",l),()=>{var P,O;(P=window.visualViewport)==null||P.removeEventListener("resize",l),(O=window.visualViewport)==null||O.removeEventListener("scroll",l),window.removeEventListener("resize",l),document.documentElement.style.removeProperty("--thread-detail-keyboard-inset")}},[]),r.useEffect(()=>{if(typeof document>"u")return;const l=()=>{const i=document.activeElement,p=C.current,P=p==null?void 0:p.querySelector('[aria-label="Prompt"]');ke(!!(i&&P&&(i===P||P.contains(i))))};return l(),document.addEventListener("focusin",l),document.addEventListener("focusout",l),()=>{document.removeEventListener("focusin",l),document.removeEventListener("focusout",l)}},[j,c==null?void 0:c.thread.id,Me]),r.useEffect(()=>{const l=C.current;if(!l||typeof ResizeObserver>"u")return;const i=l.querySelector("form")??l,p=()=>{Gt(Math.max(l.getBoundingClientRect().height,i.getBoundingClientRect().height))};p();const P=new ResizeObserver(()=>{p()});return P.observe(i),()=>{P.disconnect()}},[j,Me]),r.useEffect(()=>{var P,O;const l=C.current;if(!l||!Me||j!=="chat"){se(0);return}const i=()=>{const Z=l.getBoundingClientRect();se(Math.max(0,Math.ceil(window.innerHeight-Z.top)))};i(),window.addEventListener("resize",i),(P=window.visualViewport)==null||P.addEventListener("resize",i),(O=window.visualViewport)==null||O.addEventListener("scroll",i);let p=null;return typeof ResizeObserver<"u"&&(p=new ResizeObserver(i),p.observe(l)),()=>{var Z,pe;window.removeEventListener("resize",i),(Z=window.visualViewport)==null||Z.removeEventListener("resize",i),(pe=window.visualViewport)==null||pe.removeEventListener("scroll",i),p==null||p.disconnect()}},[j,c==null?void 0:c.thread.id,Me,ie,me]),r.useEffect(()=>{Ft({showLoading:!0,limit:ir})},[Ft]),r.useEffect(()=>{let l=!1,i=null;const p=()=>{Ft({showLoading:!1,clearError:!1,reportError:!1})},P=()=>{h.current!==null&&(window.clearTimeout(h.current),h.current=null)},O=()=>{l||!x.current||h.current!==null||(h.current=window.setTimeout(()=>{h.current=null,!l&&L()},Vd),He())},Z=()=>{const w=m.current;if(m.current=null,w)try{w.close()}catch{}},pe=w=>{if(w.threadId===t){if(w.type==="thread.output.delta"&&typeof w.payload.delta=="string"){const $=typeof w.payload.turnId=="string"?w.payload.turnId:null,ae=typeof w.payload.itemId=="string"?w.payload.itemId:null,Ee=typeof w.payload.sequence=="number"&&Number.isFinite(w.payload.sequence)?w.payload.sequence:null;$&&ae?Hs($,ae,w.payload.delta,Ee,w.payload.createdAt??w.timestamp):ns(w.payload.delta),$&&ot(ve=>ve&&(ve.serverTurnId===null||ve.serverTurnId===$)?{...ve,serverTurnId:$,id:$,status:ve.status==="failed"?ve.status:"inProgress",tokenUsage:ve.tokenUsage}:ve)}if(w.type==="thread.context.updated"){const $=w.payload.contextUsage&&typeof w.payload.contextUsage=="object"?w.payload.contextUsage:null;if($){const ae=$;D(Ee=>Ee&&{...Ee,thread:{...Ee.thread,contextUsage:ae}}),I(Ee=>Ee.map(ve=>ve.id===t?{...ve,contextUsage:ae}:ve))}}if(w.type==="thread.turn.token.updated"&&typeof w.payload.turnId=="string"&&w.payload.tokenUsage&&typeof w.payload.tokenUsage=="object"){const $=w.payload.turnId,ae=w.payload.tokenUsage,Ee=w.payload.priceEstimate&&typeof w.payload.priceEstimate=="object"?w.payload.priceEstimate:null;D(ve=>{if(!ve)return ve;const tt=md(ve.turns,$,ae,Ee);return tt===ve.turns?ve:{...ve,turns:tt}}),ot(ve=>ve&&(ve.serverTurnId===$||ve.id===$)?{...ve,tokenUsage:ae,priceEstimate:Ee}:ve)}if(w.type==="thread.turn.started"||w.type==="thread.turn.completed"||w.type==="thread.turn.failed"||w.type==="thread.updated"||w.type==="thread.goal.updated"||w.type==="thread.goal.cleared"||w.type==="thread.request.created"||w.type==="thread.request.resolved"){if(w.type==="thread.goal.updated"){const $=w.payload.goal&&typeof w.payload.goal=="object"?w.payload.goal:null,ae=Array.isArray(w.payload.goalHistory)?w.payload.goalHistory:null;ye({status:"ready",data:$,error:null}),D(Ee=>Ee&&(ae?{...Ee,goal:$,goalHistory:ae}:$?{...Ee,goal:$,goalHistory:cn(Ee.goalHistory??[],$)}:{...Ee,goal:$}))}if(w.type==="thread.goal.cleared"){const $=Array.isArray(w.payload.goalHistory)?w.payload.goalHistory:null;ye({status:"ready",data:null,error:null}),D(ae=>ae&&($?{...ae,goal:null,goalHistory:$}:{...ae,goal:null}))}if(p(),w.type==="thread.turn.started"){lt(),W(""),xe(null),te.current=null;const $=typeof w.payload.turnId=="string"?w.payload.turnId:null;$&&ot(ae=>ae&&{...ae,serverTurnId:$,id:$,status:ae.status==="failed"?ae.status:"inProgress",error:null,tokenUsage:ae.tokenUsage})}if(w.type==="thread.turn.completed"||w.type==="thread.turn.failed"){lt(),W("");const $=typeof w.payload.turnId=="string"?w.payload.turnId:null;$&&(te.current=$,w.type==="thread.turn.failed"&&ot(ae=>ae&&(ae.serverTurnId===$||ae.id===$)?{...ae,status:"failed",error:typeof w.payload.error=="string"?w.payload.error:"Unable to complete the turn.",tokenUsage:ae.tokenUsage}:ae))}}if(w.type==="thread.request.created"&&ad(w.payload.request)&&(X.current.delete(w.payload.request.id),D($=>$&&sd($,w.payload.request))),w.type==="thread.request.resolved"&&typeof w.payload.requestId=="string"){const $=w.payload.requestId;X.current.add($),D(ae=>ae&&nd(ae,$))}if((w.type==="thread.item.started"||w.type==="thread.item.completed")&&w.payload.item&&typeof w.payload.item=="object"&&typeof w.payload.turnId=="string"){const $=w.payload.turnId,ae=w.payload.item;typeof ae.id=="string"&&typeof ae.text=="string"&&ks($,ae)}w.type==="thread.plan.updated"&&Array.isArray(w.payload.plan)&&z({turnId:String(w.payload.turnId??""),explanation:typeof w.payload.explanation=="string"?w.payload.explanation:null,plan:w.payload.plan})}},Te=()=>{const w=m.current;if(!(!w||w.readyState!==ms))try{w.send(JSON.stringify({type:"supervisor.ping",timestamp:new Date().toISOString()}))}catch{f.current=!0,Z(),O(),He()}},L=()=>{var ae;if(l||!x.current){He();return}const w=((ae=m.current)==null?void 0:ae.readyState)??mn;if(w===Xn||w===ms){He();return}const $=Hr(pe);m.current=$,He(),$.addEventListener("message",Ee=>{if(m.current===$)try{const ve=JSON.parse(Ee.data);(ve.type==="supervisor.connected"||ve.type==="supervisor.pong")&&(A.current=Date.now(),He())}catch{}}),$.addEventListener("open",()=>{m.current===$&&(f.current=!0,p(),Te(),He())}),$.addEventListener("close",()=>{m.current===$&&(m.current=null),f.current=!0,O(),He()}),$.addEventListener("error",()=>{m.current===$&&(m.current=null),f.current=!0,O(),He()})},Fe=async()=>{var w;if(!(l||!x.current||g.current)){g.current=!0,He();try{await El();const $=f.current;y.current=new Date().toISOString(),$&&(f.current=!1,p()),(((w=m.current)==null?void 0:w.readyState)??mn)!==ms&&L()}catch{y.current=null,f.current=!0,O()}finally{g.current=!1,He()}}},it=()=>{x.current=!0,f.current=!0,He(),L(),Fe()},Pe=()=>{x.current=!1,y.current=null,A.current=null,f.current=!0,P(),Z(),He()},ge=()=>{var ae;if(l||!x.current){He();return}const w=((ae=m.current)==null?void 0:ae.readyState)??mn,$=A.current===null?null:Date.now()-A.current;w===ms&&$!==null&&$>Zn?(f.current=!0,Z(),O()):w===ms?Te():w!==Xn&&L(),Fe(),He()};return window.addEventListener("online",it),window.addEventListener("offline",Pe),L(),Fe(),i=window.setInterval(ge,Jd),()=>{l=!0,window.removeEventListener("online",it),window.removeEventListener("offline",Pe),P(),i!==null&&window.clearInterval(i),lt(),Z()}},[Hs,lt,t,Ft,ns,He,ks]),r.useEffect(()=>{if(!((c==null?void 0:c.thread.activeTurnId)!==null||(c==null?void 0:c.thread.status)==="running"||we!==null||St.length>0||oe.length>0||F!==null||ce!==null))return;const i=window.setInterval(()=>{Ft({showLoading:!1,clearError:!1,reportError:!1})},Gd);return()=>{window.clearInterval(i)}},[c==null?void 0:c.thread.activeTurnId,c==null?void 0:c.thread.status,oe.length,ce,F,Ft,St.length,we]);const Gs=r.useCallback(async()=>{var l;if(!(!c||c.turns.length===0||Be)){mt(!0),de(null);try{const i=(l=c.turns[0])==null?void 0:l.id,p=await Ba(t,{limit:zd,...i?{beforeTurnId:i}:{}});D(P=>P?{...p,turns:td(P.turns,p.turns)}:p),I(P=>P.map(O=>O.id===p.thread.id?p.thread:O))}catch(i){de(i instanceof Error?i.message:"Unable to load earlier turns.")}finally{mt(!1)}}},[c,t,Be]);async function Ks(l){var Fe,it,Pe;if(j==="shell"){if((c==null?void 0:c.thread.isLoaded)===!1)return await Wt({attachShell:!0}),!1;let ge=!1;if((V==null?void 0:V.shellInputEnabled)!==!0&&((V==null?void 0:V.loading)===!1&&(V==null?void 0:V.isConnecting)!==!0&&(V==null?void 0:V.status)!=="creating"&&(V==null?void 0:V.status)!=="workspace_missing"&&(await((Fe=k.current)==null?void 0:Fe.toggleConnection()),ge=!0),(V==null?void 0:V.isConnecting)===!0))return de("Connecting to the shell. Try again after it attaches."),!1;if(((it=k.current)==null?void 0:it.sendCommand(l.prompt))??!1)de(null);else return de(ge?"Shell is still attaching. Try again after it connects.":"Connect the shell before sending commands."),!1;return!0}b(!0),de(null),wt(ge=>ge+1);const i=_.current,p=i?{...i.thread,...R.current??{}}:null,P=(p==null?void 0:p.model)??null,O=(p==null?void 0:p.reasoningEffort)??null,Z=cd(),pe=`optimistic-${Date.now()}`,Te=`optimistic-steer-${Z}`,L=new Date().toISOString();try{let ge=_.current;if(ge&&!ge.thread.isLoaded){const Re={...ge.thread,...R.current??{}},dt=await Fa(t,{...ge.thread.model?{model:ge.thread.model}:{},...ge.thread.sandboxMode?{sandboxMode:ge.thread.sandboxMode}:{}}),st={...dt,thread:{...dt.thread,model:Re.model??dt.thread.model,reasoningEffort:Re.reasoningEffort??dt.thread.reasoningEffort,collaborationMode:Re.collaborationMode??dt.thread.collaborationMode,sandboxMode:Re.sandboxMode??dt.thread.sandboxMode??null}};ge=st,_.current=st,D(an=>an?{...st,turns:zt(an.turns,st.turns)}:st),I(an=>an.map(Ra=>Ra.id===st.thread.id?st.thread:Ra))}const w=ge?{...ge.thread,...R.current??{}}:null,$=(w==null?void 0:w.status)==="running"?w.activeTurnId:null,ae=j==="chat"&&!!$;ae&&$?Rt(Re=>[...Re,{id:Te,clientRequestId:Z,turnId:$,prompt:l.prompt,createdAt:L,status:"steering"}]):(lt(),W(""),ot({id:pe,serverTurnId:null,startedAt:L,status:"sending",error:null,prompt:l.prompt,model:P,reasoningEffort:O,reasoningEffortAvailable:Qa(q,P),tokenUsage:null,priceEstimate:null}));const Ee={prompt:l.prompt,clientRequestId:Z,...w!=null&&w.model?{model:w.model}:{},...w!=null&&w.reasoningEffort?{reasoningEffort:w.reasoningEffort}:{},...w!=null&&w.collaborationMode?{collaborationMode:w.collaborationMode}:{},...w!=null&&w.sandboxMode?{sandboxMode:w.sandboxMode}:{},...(Pe=l.attachments)!=null&&Pe.length?{attachments:l.attachments}:{}},ve=await Zl(t,Ee),tt=R.current&&Object.keys(R.current).length>0?{...ve,...R.current}:ve;D(Re=>Re&&{...Re,thread:tt}),I(Re=>Re.map(dt=>dt.id===tt.id?tt:dt)),ae&&$?tt.activeTurnId!==null&&tt.activeTurnId!==$&&tt.lastTurnStartedAt!==(w==null?void 0:w.lastTurnStartedAt)?(lt(),W(""),z(null),Rt(dt=>dt.filter(st=>st.id!==Te)),ot({id:pe,serverTurnId:tt.activeTurnId,startedAt:tt.lastTurnStartedAt??L,status:"inProgress",error:null,prompt:l.prompt,model:P,reasoningEffort:O,reasoningEffortAvailable:Qa(q,P),tokenUsage:null,priceEstimate:null})):Rt(dt=>dt.map(st=>st.id===Te?{...st,turnId:tt.activeTurnId??st.turnId,status:"accepted"}:st)):(ot(Re=>Re&&Re.id===pe?{...Re,id:tt.activeTurnId??Re.id,serverTurnId:tt.activeTurnId??Re.serverTurnId,status:"inProgress",error:null,tokenUsage:Re.tokenUsage,priceEstimate:Re.priceEstimate}:Re),z(null)),pt({prompt:"",attachments:[]})}catch(ge){const w=ge instanceof re?ge.payload.message:ge instanceof Error?ge.message:"Unable to send prompt.";ge instanceof re?de(ge.payload.message):de(w),Rt($=>$.filter(ae=>ae.clientRequestId!==Z)),ot($=>$&&$.id===pe?{...$,status:"failed",error:w}:$)}finally{b(!1)}}async function An(){const l=c==null?void 0:c.thread.providerSessionId;if(l)try{await navigator.clipboard.writeText(l),Yt("copied")}catch{Yt("failed")}}async function Wt(l){if(c){b(!0),de(null),lt(),W("");try{if(c.thread.isLoaded){const p=await Yl(t);D(P=>P?{...p,turns:zt(P.turns,p.turns)}:p),Xe(null),I(P=>P.map(O=>O.id===p.thread.id?p.thread:O)),Qe(!1);return}const i=await Fa(t,{...c.thread.model?{model:c.thread.model}:{},...c.thread.sandboxMode?{sandboxMode:c.thread.sandboxMode}:{}});D(p=>p?{...i,turns:zt(p.turns,i.turns)}:i),I(p=>p.map(P=>P.id===i.thread.id?i.thread:P)),l!=null&&l.attachShell&&j==="shell"&&Qe(!0)}catch(i){de(i instanceof Error?i.message:"Unable to change connection state.")}finally{b(!1)}}}async function rs(){var l;if(j==="shell"){const i=((l=k.current)==null?void 0:l.sendControl("ctrl_c"))??!1;de(i?null:"Connect the shell before sending Ctrl-C.");return}b(!0),de(null);try{const i=c!=null&&c.thread.activeTurnId?await Wa(t,{turnId:c.thread.activeTurnId}):await Wa(t);D(p=>p&&{...p,thread:i}),I(p=>p.map(P=>P.id===i.id?i:P)),lt(),W("")}catch(i){de(i instanceof Error?i.message:"Unable to interrupt turn.")}finally{b(!1)}}async function os(l){if(!c)return;const i=c,p={...R.current??{},...l.model!==void 0?{model:l.model}:{},...l.reasoningEffort!==void 0?{reasoningEffort:l.reasoningEffort}:{},...l.fastMode!==void 0?{fastMode:l.fastMode}:{},...l.collaborationMode!==void 0?{collaborationMode:l.collaborationMode}:{},...l.sandboxMode!==void 0?{sandboxMode:l.sandboxMode}:{}},P={...c.thread,...p};Dt(!0),R.current=p,_.current={...c,thread:P},D(O=>O&&{...O,thread:P}),I(O=>O.map(Z=>Z.id===P.id?{...Z,...P}:Z));try{const O=await Xl(t,{...l.model!==void 0?{model:l.model}:{},...l.reasoningEffort!==void 0?{reasoningEffort:l.reasoningEffort}:{},...l.fastMode!==void 0?{fastMode:l.fastMode}:{},...l.collaborationMode!==void 0?{collaborationMode:l.collaborationMode}:{},...l.sandboxMode!==void 0?{sandboxMode:l.sandboxMode}:{}});R.current=null,_.current=i?{...i,thread:O}:null,D(Z=>Z&&{...Z,thread:O}),I(Z=>Z.map(pe=>pe.id===O.id?O:pe))}catch(O){R.current=null,_.current=i,D(i),I(Z=>Z.map(pe=>pe.id===i.thread.id?i.thread:pe)),de(O instanceof Error?O.message:"Unable to update thread settings.")}finally{Dt(!1)}}const ls=r.useCallback(async(l,i)=>{vs(l),de(null);try{const p=await ui(t,l,i);D(P=>P?{...p,turns:zt(P.turns,p.turns)}:p),z(p.livePlan??null),xe(p.liveItems??null)}catch(p){de(p instanceof Error?p.message:"Unable to answer this request.")}finally{vs(null)}},[t]),Ys=r.useCallback(l=>Ml(t,l),[t]);async function Xt(){if(c){gs(!0),de(null);try{const l=await Ql(t);D(i=>i&&{...i,thread:l}),I(i=>i.map(p=>p.id===l.id?l:p))}catch(l){de(l instanceof Error?l.message:"Unable to compact this thread context.")}finally{gs(!1)}}}async function Zs(l,i){try{const p=await Lr(l,{title:i});I(P=>P.map(O=>O.id===p.id?{...O,title:p.title,updatedAt:p.updatedAt}:O)),D(P=>P&&P.thread.id===p.id?{...P,thread:{...P.thread,title:p.title,updatedAt:p.updatedAt}}:P)}catch(p){throw de(p instanceof Error?p.message:"Unable to rename thread."),p}}async function Xs(){if(vt){Zt(!0),de(null);try{await Dr(vt.id),I(i=>i.filter(p=>p.id!==vt.id));const l=vt.id===(c==null?void 0:c.thread.id);if(Bt(null),l){const i=Y.find(p=>p.id!==vt.id&&p.workspaceId===(c==null?void 0:c.thread.workspaceId))??Y.find(p=>p.id!==vt.id);s(i?`/threads/${i.id}`:"/threads")}}catch(l){de(l instanceof Error?l.message:"Unable to delete thread.")}finally{Zt(!1)}}}function is(){M(l=>l==="chat"?(c!=null&&c.thread.isLoaded&&Qe(!0),"shell"):"chat")}async function qt(){var i;const l=await((i=k.current)==null?void 0:i.copyLastCommandOutput());de(l?null:"Unable to copy the last shell command output.")}function ds(l){var p,P;const i=l==="clear"?((p=k.current)==null?void 0:p.sendCommand("clear"))??!1:((P=k.current)==null?void 0:P.sendControl(l))??!1;de(i?null:"Connect the shell before sending control input.")}r.useEffect(()=>{if(!(!Le||j!=="shell"||!k.current||(c==null?void 0:c.thread.isLoaded)===!1||(V==null?void 0:V.loading)!==!1)){if((V==null?void 0:V.status)==="attached"){Qe(!1);return}Qe(!1),k.current.toggleConnection()}},[j,c==null?void 0:c.thread.isLoaded,Le,V==null?void 0:V.loading,V==null?void 0:V.status]),r.useEffect(()=>{if(j!=="shell")return;const l=window.requestAnimationFrame(()=>{var i;(i=k.current)==null||i.refreshLayout({syncBackendSize:!1})});return()=>{window.cancelAnimationFrame(l)}},[j]);const Ts=c&&c.workspacePathStatus==="missing"?"Restore this workspace path on the current machine before continuing.":null,Is=Me&&j==="chat",Qs=Is&&me?ie:0,en=Math.max(Lt,144),Un=Math.max(Kt,en+Qs),tn=Is?Un+12:0,sn=c?e.jsxs("dl",{className:"space-y-4 text-sm",children:[e.jsxs("div",{className:"relative pr-9",children:[e.jsx("dt",{className:"text-[var(--theme-fg-muted)]",children:"Session ID"}),e.jsx("dd",{className:"mt-1 break-all text-[var(--theme-fg)]",children:c.thread.providerSessionId??"Unavailable"}),c.thread.providerSessionId&&e.jsx("button",{type:"button","aria-label":"Copy session ID",title:Nt==="copied"?"Copied":Nt==="failed"?"Copy failed":"Copy session ID",onClick:()=>void An(),className:`thread-mobile-hit-target absolute bottom-0 right-0 inline-flex h-5 w-5 items-center justify-center rounded-full border shadow-sm shadow-stone-950/25 backdrop-blur transition ${Nt==="copied"?"ui-status-info":Nt==="failed"?"ui-status-danger":"border-[var(--theme-border)] bg-[var(--theme-surface-strong)] text-[var(--theme-fg-soft)] hover:bg-[var(--theme-hover)] hover:text-[var(--theme-fg)]"}`,children:e.jsx("span",{className:"scale-[0.72]",children:e.jsx(ec,{})})})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[var(--theme-fg-muted)]",children:"Source"}),e.jsx("dd",{className:"mt-1 text-[var(--theme-fg)]",children:c.thread.source==="local_codex_import"?`Imported local ${c.thread.provider} session`:`${c.thread.provider} supervisor thread`})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[var(--theme-fg-muted)]",children:"Status"}),e.jsx("dd",{className:"mt-1 text-[var(--theme-fg)]",children:fr(c.thread.status)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[var(--theme-fg-muted)]",children:"Created"}),e.jsx("dd",{className:"mt-1 text-[var(--theme-fg)]",children:ps(c.thread.createdAt)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[var(--theme-fg-muted)]",children:"Workspace"}),e.jsx("dd",{className:"mt-1 break-words text-[var(--theme-fg)]",children:c.workspace.absPath})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[var(--theme-fg-muted)]",children:"Workspace path"}),e.jsx("dd",{className:"mt-1 text-[var(--theme-fg)]",children:c.workspacePathStatus==="present"?"Present":"Missing on this machine"})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[var(--theme-fg-muted)]",children:"Active turn"}),e.jsx("dd",{className:"mt-1 text-[var(--theme-fg)]",children:c.thread.activeTurnId??"None"})]})]}):null,nn=c&&(H!=null&&H.controls.sandboxMode)?e.jsx("div",{className:"space-y-3",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-[0.2em] text-[var(--theme-fg-muted)]",children:"Sandbox Mode"}),e.jsx("div",{className:"mt-2 space-y-1.5",children:Kd.map(l=>{const i=ed(c.thread)===l;return e.jsx("button",{type:"button",disabled:xt,onClick:()=>void os({sandboxMode:l}),className:`block w-full rounded-xl border px-3 py-2 text-left text-sm transition ${i?"ui-status-warning":"border-[var(--theme-border)] bg-[var(--theme-surface-strong)] text-[var(--theme-fg-soft)] hover:bg-[var(--theme-hover)] hover:text-[var(--theme-fg)]"} disabled:cursor-not-allowed disabled:opacity-60`,children:l},l)})})]})}):null,u=(we==null?void 0:we.serverTurnId)??null,N=we&&c?c.turns.find(l=>(Us(l,we.prompt)||we.prompt.includes("[PHOTO ")&&(gn(l,we.prompt)||Fn(l)))&&(u&&l.id===u||l.id===we.id||Us(l,we.prompt)||we.prompt.includes("[PHOTO ")&&gn(l,we.prompt)))??null:null,S=r.useMemo(()=>we&&!N?{id:we.id,startedAt:we.startedAt,status:we.status,error:we.error,model:we.model,reasoningEffort:we.reasoningEffort,reasoningEffortAvailable:we.reasoningEffortAvailable,tokenUsage:we.tokenUsage,priceEstimate:we.priceEstimate,items:[{id:`${we.id}-user-message`,kind:"userMessage",text:we.prompt}]}:null,[N,we]),K=(c==null?void 0:c.thread.isLoaded)??!1,De=K?bt.status==="connected"?"ui-action-success shadow-lg shadow-stone-950/20":bt.status==="reconnecting"?"thread-live-connection-reconnecting ui-status-success shadow-lg shadow-stone-950/20":bt.status==="offline"?"ui-status-danger shadow-lg shadow-stone-950/20":"ui-status-warning shadow-lg shadow-stone-950/20":"host-icon-button border shadow-lg shadow-black/10",_e=sc(K,bt),$t=[_e,K?null:"Tap to connect this thread",bt.lastHealthyAt?`Last healthy ${ps(bt.lastHealthyAt)}`:null].filter(Boolean).join(" · "),On=K?e.jsx("div",{role:"status","aria-live":"polite","aria-label":_e,title:$t,className:`inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition ${De}`,children:e.jsx(hn,{status:bt.status})}):e.jsx("button",{type:"button",onClick:()=>void Wt(),disabled:Ye||!c,"aria-label":Ye?"Connecting thread":"Connect thread",title:Ye?"Connecting thread":$t,className:`inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition ${De}`,children:e.jsx(hn,{status:"detached"})}),so=K?e.jsx("div",{title:$t,className:`hidden lg:inline-flex h-9 w-9 items-center justify-center rounded-full transition ${De}`,children:e.jsx(hn,{status:bt.status})}):e.jsx("button",{type:"button",onClick:()=>void Wt(),disabled:Ye||!c,title:Ye?"Connecting thread":$t,className:`hidden lg:inline-flex h-9 w-9 items-center justify-center rounded-full transition ${De}`,children:e.jsx(hn,{status:"detached"})}),va=Ce.data??(c==null?void 0:c.goal)??null,ja=(c==null?void 0:c.goalHistory)??[],ya=va?cn(ja,va):zr(ja),wa=(H==null?void 0:H.controls.goals)??!1,no=e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-4 w-4 fill-none stroke-current",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("circle",{cx:"8",cy:"8",r:"5.5"}),e.jsx("circle",{cx:"8",cy:"8",r:"2"}),e.jsx("path",{d:"M8 1.7v2M8 12.3v2M1.7 8h2M12.3 8h2"})]}),ao=Ms&&wa?e.jsxs("div",{className:"host-dialog w-96 max-w-[calc(100vw-1.5rem)] rounded-3xl border p-3 text-left shadow-2xl shadow-black/20 backdrop-blur-xl",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"host-page-title text-sm font-semibold",children:"Goal monitor"}),e.jsx("p",{className:"host-muted text-xs",children:"Current thread only"})]}),e.jsx("button",{type:"button",onClick:()=>G(!1),className:"host-secondary-button rounded-full border px-2.5 py-1 text-xs transition",children:"Close"})]}),Ce.error?e.jsx("p",{className:"host-error mt-3 rounded-2xl border px-3 py-2 text-xs",children:Ce.error}):null,e.jsx("div",{className:"mt-3 max-h-[28rem] space-y-2 overflow-auto pr-1",children:ya.length===0?e.jsx("p",{className:"host-empty-state rounded-2xl border px-3 py-3 text-sm",children:"No goals in this thread yet."}):ya.map(l=>{const i=`${l.threadId}:${l.objective}:${l.createdAt}`,p=ws.has(i),P=["active","paused","budgetLimited"].includes(l.status);return e.jsxs("div",{className:`rounded-2xl border px-3 py-3 ${P?"ui-status-info":"host-surface-strong"}`,children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("button",{type:"button",onClick:()=>ts(O=>{const Z=new Set(O);return Z.has(i)?Z.delete(i):Z.add(i),Z}),className:"min-w-0 flex-1 text-left",children:e.jsx("p",{className:`text-sm font-medium leading-5 ${p?"":"line-clamp-2"}`,children:l.objective})}),e.jsx("span",{className:"host-muted shrink-0 rounded-full border border-[var(--theme-border)] px-2 py-1 text-[10px] uppercase tracking-[0.14em]",children:l.status})]}),e.jsxs("div",{className:"host-muted mt-2 flex flex-wrap gap-2 text-[11px]",children:[e.jsx("span",{children:dd(l.timeUsedSeconds)}),e.jsx("span",{children:id(l)}),e.jsxs("span",{title:ps(l.updatedAt),children:["Updated ",new Date(l.updatedAt).toLocaleTimeString()]})]}),P?e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",disabled:ee||l.status==="active",onClick:()=>void Ws("active"),className:"ui-status-info rounded-full px-3 py-1.5 text-xs transition disabled:cursor-not-allowed disabled:opacity-50",children:"Continue"}),e.jsx("button",{type:"button",disabled:ee||l.status==="paused",onClick:()=>void Ws("paused"),className:"host-secondary-button rounded-full border px-3 py-1.5 text-xs transition disabled:cursor-not-allowed disabled:opacity-50",children:"Pause"}),e.jsx("button",{type:"button",disabled:ee,onClick:()=>void Tn(),className:"rounded-full border border-[var(--status-danger-border)] px-3 py-1.5 text-xs text-[var(--status-danger-fg)] transition hover:bg-[var(--status-danger-bg)] disabled:cursor-not-allowed disabled:opacity-50",children:"Terminate"})]}):null]},i)})})]}):null,Na=wa?e.jsx("button",{type:"button","aria-label":"Open goal monitor",title:"Open goal monitor",onClick:()=>{G(l=>!l),Bs()},className:"ui-status-info inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full shadow-lg shadow-stone-950/20 transition lg:h-9 lg:w-9",children:no}):null,Sa=e.jsx("button",{type:"button","aria-label":"Export transcript",title:"Export transcript",onClick:()=>At(!0),disabled:!c,className:"host-icon-button inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full border shadow-lg shadow-black/10 transition disabled:cursor-not-allowed disabled:opacity-50 lg:h-9 lg:w-9",children:e.jsx(tc,{})}),ro=e.jsxs("div",{className:"relative flex items-center justify-end gap-1.5",children:[Sa,Na,On]}),oo=e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[Sa,Na,so]}),lo=r.useMemo(()=>({livePlan:F,liveItems:ce,respondingRequestId:bs,onRespondToRequest:ls,scrollRequestKey:Ke,bottomSpacer:tn,className:"thread-timeline-surface min-h-0 flex-1",onTailVisibilityChange:ct,loadingEarlier:Be,onLoadEarlier:Gs,onOpenThread:Ue,answeredRequestNotes:(c==null?void 0:c.answeredRequestNotes)??Yd,activityNotes:(c==null?void 0:c.activityNotes)??Zd,pendingSteers:(c==null?void 0:c.pendingSteers)??Xd,optimisticSteers:St,optimisticTurn:S}),[c==null?void 0:c.answeredRequestNotes,c==null?void 0:c.activityNotes,c==null?void 0:c.pendingSteers,Gs,ls,ce,F,Be,Ue,St,bs,Ke,tn,S]),ka=c?{busy:j==="chat"?Ye:!1,settingsBusy:xt,error:null,model:c.thread.model,reasoningEffort:c.thread.reasoningEffort,fastMode:c.thread.fastMode??!1,collaborationMode:c.thread.collaborationMode,modelOptions:q,contextUsage:c.thread.contextUsage,capabilities:H,toolboxItems:(T==null?void 0:T.toolboxItems)??[],hookCommandTemplates:(T==null?void 0:T.hookCommandTemplates)??[],mcpConfigFormat:(T==null?void 0:T.mcpConfigFormat)??"none",followTail:rt,threadConnected:c.thread.isLoaded,shellAvailable:Q,disabled:!!Ts,...Ts?{disabledPlaceholder:Ts}:{},shellControlState:V,draftPrompt:Ve.prompt,draftAttachments:Ve.attachments,onDraftChange:pt,canInterrupt:!!c.thread.activeTurnId,onInterrupt:rs,onCompact:Xt,onOpenForkTurns:jt,onForkLatest:yt,onForkTurn:Pn,onOpenSkills:qs,onOpenMcp:In,onOpenHooks:En,onCreateHook:Rn,onUpdateHook:Ge,onTrustHook:Cs,onUntrustHook:zs,goalState:Ce,onOpenGoal:Bs,onUpdateGoal:Fs,...Ot?{onReadProviderConfig:()=>Or(c.thread.provider,Ot),onWriteProviderConfig:l=>$r(c.thread.provider,Ot,{content:l})}:{},onToggleFollow:()=>wt(l=>l+1),onUpdateSettings:os,onToggleView:is,onShellCopy:qt,onShellControl:ds,compactBusy:gt,skillsState:ys,mcpState:ft,hooksState:Je,forkTurnOptionsState:Ht}:null,Ca=c?{busy:Ye,settingsBusy:!1,error:c.thread.isLoaded?(V==null?void 0:V.error)??null:null,followTail:!1,capabilities:H,toolboxItems:(T==null?void 0:T.toolboxItems)??[],hookCommandTemplates:(T==null?void 0:T.hookCommandTemplates)??[],mcpConfigFormat:(T==null?void 0:T.mcpConfigFormat)??"none",threadConnected:c.thread.isLoaded,shellAvailable:Q,shellControlState:V,canInterrupt:!!(c.thread.isLoaded&&(V!=null&&V.isCommandRunning)),onInterrupt:rs,onToggleView:is,onShellCopy:qt,onShellControl:ds}:null,Ta=r.useCallback(l=>c?ht({threadId:c.thread.id,path:l}):"",[c==null?void 0:c.thread.id,ht]),Ia=r.useMemo(()=>{const l=(c==null?void 0:c.workspace.id)??null;return l?{listTree:()=>Rl(l),readFile:i=>Pl(l,{path:i.path,...i.offset!==void 0?{offset:i.offset}:{},...i.limit!==void 0?{limit:i.limit}:{}}),getRawFileUrl:i=>Al(l,{path:i.path}),uploadFile:i=>Ol(l,{file:i.file}),writeFile:async i=>{await $l(l,{path:i.path,content:i.content})},downloadNode:async i=>{de(null);try{const p=await Ul(l,{path:i.path}),P=URL.createObjectURL(p.blob),O=document.createElement("a");O.href=P,O.download=p.filename,document.body.append(O),O.click(),O.remove(),URL.revokeObjectURL(P)}catch(p){de(p instanceof re?p.payload.message:p instanceof Error?p.message:"Workspace download failed.")}}}:null},[c==null?void 0:c.workspace.id]),io=r.useMemo(()=>({openThread:Ue,getThreadHref:$e,getNewThreadHref:Ze,renameThread:Zs,deleteThread:Bt,sendPrompt:Ks,interrupt:rs,compact:Xt,updateSettings:os,loadHistoryItemDetail:Ys,getImageAssetUrl:Ta,workspace:Ia,shell:be}),[Ta,Ze,$e,Xt,rs,Ys,Ks,Zs,os,be,Ue,Ia]),co=c!=null&&c.thread.workspaceId?`/threads?workspaceId=${encodeURIComponent(c.thread.workspaceId)}`:"/workspaces",uo=e.jsxs(e.Fragment,{children:[e.jsx(vo,{open:Ns,busy:Ut,turnsState:Ct,onCancel:()=>{Ut||At(!1)},onLoadTurns:as,onExport:_s}),e.jsx(wn,{open:vt!==null,title:"Delete Thread",description:vt?`Delete ${Oo(vt.title)} from supervisor. The backend session id will no longer appear in this workspace list.`:"",confirmLabel:"Delete Thread",busy:Ss,onCancel:()=>{Ss||Bt(null)},onConfirm:()=>void Xs()})]});return e.jsx(pr,{threads:Y,detail:c,status:je,loading:ze,error:ze?null:Ds,plugins:n,adapter:io,metaContent:sn,settingsContent:nn,globalSettingsContent:e.jsx(xa,{embedded:!0}),mobileHeaderAction:ro,workspaceReturnHref:co,onCloseAppNavigation:(a==null?void 0:a.closeNav)??(()=>{}),surfaceActions:oo,floatingPanel:ao,workspaceFeatures:Qd,activeView:j,liveOutput:oe,timelineProps:lo,timelineComponent:yo,useFloatingMobileComposer:Is,floatingMobileComposerBottomOffset:Qs,composerHostRef:C,shellPanelRef:k,shellPanelComponent:jo,shellEffectiveTheme:(a==null?void 0:a.effectiveTheme)??"dark",shellThemeMode:(a==null?void 0:a.themeMode)??"system",...a!=null&&a.setThemeMode?{onShellThemeModeChange:a.setThemeMode}:{},onShellStateChange:Xe,loadingContent:e.jsx("div",{className:"host-muted flex flex-1 items-center justify-center px-6 py-12 text-center",children:"Loading thread detail..."}),emptyContent:e.jsx("div",{className:"host-muted flex flex-1 items-center justify-center px-6 py-12 text-center",children:"Unable to resolve this thread."}),dialogs:uo,...ka?{composerProps:ka}:{},...Ca?{shellComposerProps:Ca}:{}})}function ac(){const t=at(),[s,a]=r.useState(""),[n,d]=r.useState(Tt),[o,m]=r.useState([]),[h,g]=r.useState(!0),[y,A]=r.useState(!1),[x,f]=r.useState(null);r.useEffect(()=>{let E=!1;return g(!0),pa().then(v=>{var te,_;if(E)return;m(v);const J=((te=v.find(R=>R.isDefault&&R.enabled))==null?void 0:te.provider)??((_=v.find(R=>R.enabled))==null?void 0:_.provider)??Tt;d(J)}).catch(()=>{E||m([])}).finally(()=>{E||g(!1)}),()=>{E=!0}},[]);const k=r.useMemo(()=>o.length>0?o:[{provider:Tt,displayName:Pa[Tt].displayName,enabled:!0}],[o]);async function C(E){E.preventDefault();const v=s.trim();if(!v){f("Session ID is required.");return}A(!0),f(null);try{const J=await Vl({sessionId:v,provider:n});t(`/threads/${J.thread.id}`)}catch(J){J instanceof re?f(J.payload.message):f(J instanceof Error?J.message:"Unable to import session.")}finally{A(!1)}}return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("p",{className:"host-page-eyebrow text-xs uppercase tracking-[0.3em]",children:"Import Session"}),e.jsx("h2",{className:"host-page-title mt-2 text-3xl font-semibold",children:"Bring in a local backend session"}),e.jsx("p",{className:"host-page-description mt-3 max-w-3xl text-sm leading-6",children:"Select the backend and paste a session ID from this machine. Supervisor will recover the workspace path, reuse an existing workspace when possible, or create one with the last folder name as the default label."}),e.jsx("p",{className:"host-muted mt-2 max-w-3xl text-sm leading-6",children:"Imported history appears immediately, but sending a new prompt still requires a manual Resume / Connect."})]}),e.jsxs("form",{onSubmit:C,className:"host-panel space-y-5 rounded-3xl border p-6",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"backend-provider",className:"host-form-label text-sm font-medium",children:"Backend"}),e.jsx("select",{id:"backend-provider",value:n,onChange:E=>d(E.target.value),disabled:y||h,className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition",children:k.map(E=>e.jsxs("option",{value:E.provider,children:[E.displayName||Pa[E.provider].displayName,E.enabled?"":" (not ready)"]},E.provider))})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"session-id",className:"host-form-label text-sm font-medium",children:"Session ID"}),e.jsx("input",{id:"session-id",value:s,onChange:E=>a(E.target.value),placeholder:"019d6fb7-7033-7a30-a2c7-74d0919e87d4",className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition"})]}),x&&e.jsx("div",{className:"host-error rounded-2xl border px-4 py-3 text-sm",children:x}),e.jsx("div",{className:"flex flex-wrap items-center gap-3",children:e.jsx("button",{type:"submit",disabled:y,className:"ui-action-primary rounded-full px-5 py-3 font-medium transition disabled:cursor-not-allowed",children:y?"Importing...":"Import Session"})})]})]})}function yn(t){return t.enabled&&t.capabilities.sessions.resume&&t.capabilities.turns.start}function rc(t,s){var n;const a=t.find(d=>d.provider===s);return a&&yn(a)?a.provider:((n=t.find(yn))==null?void 0:n.provider)??Tt}function oc(){const t=at(),s=Jt(),[a]=mr(),[n,d]=r.useState([]),[o,m]=r.useState([]),[h,g]=r.useState([]),[y,A]=r.useState((s==null?void 0:s.defaultBackend)??Tt),[x,f]=r.useState(""),[k,C]=r.useState(""),E=a.get("title"),[v,J]=r.useState(()=>E??""),[te,_]=r.useState("yolo"),[R,X]=r.useState(!0),[c,D]=r.useState(!1),[Y,I]=r.useState(null),q=a.get("workspaceId"),B=(s==null?void 0:s.defaultBackend)??Tt;r.useEffect(()=>{let H=!1;return Promise.all([fa(),pa()]).then(async([he,T])=>{var F,z,ce;if(H)return;const le=rc(T,B);A(le),m(T);const oe=await oa(le);if(H)return;d(he),g(oe);const W=he.some(xe=>xe.id===q)?q:((F=he[0])==null?void 0:F.id)??"";f(W),C(((z=oe.find(xe=>xe.isDefault))==null?void 0:z.model)??((ce=oe[0])==null?void 0:ce.model)??"")}).catch(he=>{H||I(he instanceof Error?he.message:"Unable to load creation form data.")}).finally(()=>{H||X(!1)}),()=>{H=!0}},[B,q]),r.useEffect(()=>{if(!y)return;let H=!1;return g([]),C(""),I(null),oa(y).then(he=>{var T,le;H||(g(he),C(((T=he.find(oe=>oe.isDefault))==null?void 0:T.model)??((le=he[0])==null?void 0:le.model)??""))}).catch(he=>{H||(g([]),C(""),I(he instanceof Error?he.message:"Unable to load backend models."))}),()=>{H=!0}},[y]);function je(){if(window.history.length>1){t(-1);return}if(q){t(`/threads?workspaceId=${encodeURIComponent(q)}`);return}t("/workspaces")}async function fe(H){H.preventDefault(),D(!0),I(null);try{const he=await zl(v.trim()?{workspaceId:x,provider:y,model:k,approvalMode:te,title:v.trim()}:{workspaceId:x,provider:y,model:k,approvalMode:te});t(`/threads/${he.id}`)}catch(he){he instanceof re?I(he.payload.message):I(he instanceof Error?he.message:"Unable to create thread.")}finally{D(!1)}}return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("p",{className:"host-page-eyebrow text-xs uppercase tracking-[0.3em]",children:"New Thread"}),e.jsx("h2",{className:"host-page-title mt-2 text-3xl font-semibold",children:"Start a backend session"}),e.jsx("p",{className:"host-page-description mt-3 max-w-2xl text-sm leading-6",children:"Choose the workspace, model, and approval mode that should back the new thread."})]}),R?e.jsx("div",{className:"host-empty-state rounded-3xl border px-6 py-12 text-center",children:"Loading creation form..."}):e.jsxs("form",{onSubmit:fe,className:"host-panel space-y-5 rounded-3xl border p-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"host-form-label text-sm font-medium",htmlFor:"thread-backend",children:"Backend"}),e.jsx("select",{id:"thread-backend",value:y,onChange:H=>{const he=H.target.value;A(he)},className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition",children:o.map(H=>e.jsxs("option",{value:H.provider,disabled:!yn(H),children:[H.displayName,yn(H)?"":" (not available)"]},H.provider))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"host-form-label text-sm font-medium",htmlFor:"thread-workspace",children:"Workspace"}),e.jsx("select",{id:"thread-workspace",value:x,onChange:H=>f(H.target.value),className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition",children:n.map(H=>e.jsxs("option",{value:H.id,children:[H.label," · ",H.absPath]},H.id))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"host-form-label text-sm font-medium",htmlFor:"thread-model",children:"Model"}),e.jsxs("select",{id:"thread-model",value:k,onChange:H=>C(H.target.value),disabled:h.length===0,className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition",children:[h.length===0?e.jsx("option",{value:"",children:"No models available"}):null,h.map(H=>e.jsxs("option",{value:H.model,children:[H.displayName," · ",H.model]},H.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"host-form-label text-sm font-medium",htmlFor:"thread-title",children:"Title"}),e.jsx("input",{id:"thread-title",value:v,onChange:H=>J(H.target.value),placeholder:"Optional. Falls back to first prompt.",className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"host-form-label text-sm font-medium",htmlFor:"thread-approval-mode",children:"Approval mode"}),e.jsxs("select",{id:"thread-approval-mode",value:te,onChange:H=>_(H.target.value),className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition",children:[e.jsx("option",{value:"yolo",children:"yolo"}),e.jsx("option",{value:"guarded",children:"guarded"})]})]}),Y&&e.jsx("div",{className:"host-error rounded-2xl border px-4 py-3 text-sm",children:Y}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("button",{type:"submit",disabled:c||!x||!k,className:"ui-action-primary rounded-full px-5 py-3 font-medium transition disabled:cursor-not-allowed",children:c?"Creating...":"Create Thread"}),e.jsx("button",{type:"button",onClick:je,disabled:c,className:"host-secondary-button rounded-full border px-5 py-3 font-medium transition disabled:cursor-not-allowed disabled:opacity-60",children:"Cancel"})]})]})]})}function lc(t){return t?`/threads/new?workspaceId=${encodeURIComponent(t)}`:"/threads/new"}function ic({getThreadHref:t,onOpenThread:s,getNewThreadHref:a,renderThreadLink:n,onCloseAppNavigation:d,...o}){const m=at(),h=Jt(),g=d??(h==null?void 0:h.closeNav),y=o.effectiveTheme??(h==null?void 0:h.effectiveTheme),A=o.themeMode??(h==null?void 0:h.themeMode),x=o.onThemeModeChange??(h==null?void 0:h.setThemeMode);return e.jsx(wo,{...o,workspaceReturnHref:o.workspaceReturnHref??"/workspaces",globalSettingsContent:o.globalSettingsContent??e.jsx(xa,{embedded:!0}),...y?{effectiveTheme:y}:{},...A?{themeMode:A}:{},...x?{onThemeModeChange:x}:{},getThreadHref:t??(f=>`/threads/${f}`),onOpenThread:s??(f=>m(`/threads/${f}`)),getNewThreadHref:a??lc,renderThreadLink:n??(({thread:f,children:k,className:C,onClick:E})=>e.jsx(It,{to:`/threads/${f.id}`,className:C,onClick:E,children:k})),...g?{onCloseAppNavigation:g}:{}})}function Yr({open:t,title:s,label:a,value:n,busy:d=!1,onChange:o,onCancel:m,onSubmit:h}){if(r.useEffect(()=>{if(!t)return;function y(A){A.key==="Escape"&&!d&&m()}return window.addEventListener("keydown",y),()=>{window.removeEventListener("keydown",y)}},[d,m,t]),!t)return null;function g(y){y.preventDefault(),h()}return mo.createPortal(e.jsxs("div",{className:"fixed inset-0 z-[95] flex items-center justify-center p-4 sm:p-6",children:[e.jsx("button",{type:"button","aria-label":"Close rename dialog",onClick:m,disabled:d,className:"ui-overlay-scrim absolute inset-0 backdrop-blur-sm disabled:cursor-not-allowed"}),e.jsxs("form",{role:"dialog","aria-modal":"true","aria-label":s,onSubmit:g,className:"host-dialog relative z-[1] w-full max-w-md rounded-[1.6rem] border p-5 shadow-2xl shadow-black/20 sm:p-6",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"host-page-title text-sm font-medium",children:s}),e.jsx("p",{className:"host-muted mt-1 text-sm",children:"Changes are saved only after confirmation."})]}),e.jsx("button",{type:"button","aria-label":"Close dialog",onClick:m,disabled:d,className:"host-icon-button inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-full border transition disabled:cursor-not-allowed disabled:opacity-60",children:e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-4 w-4 fill-current",children:e.jsx("path",{d:"M3.22 2.47 8 7.25l4.78-4.78 1.06 1.06L9.06 8.31l4.78 4.78-1.06 1.06L8 9.37l-4.78 4.78-1.06-1.06 4.78-4.78-4.78-4.78 1.06-1.06Z"})})})]}),e.jsxs("div",{className:"mt-5",children:[e.jsx("label",{htmlFor:"rename-dialog-input",className:"host-form-label text-sm font-medium",children:a}),e.jsx("input",{id:"rename-dialog-input","aria-label":a,autoFocus:!0,value:n,onChange:y=>o(y.target.value),className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition"})]}),e.jsxs("div",{className:"mt-5 flex items-center justify-end gap-2",children:[e.jsx("button",{type:"button",onClick:m,disabled:d,className:"host-secondary-button rounded-full border px-4 py-2 text-sm font-medium transition disabled:cursor-not-allowed disabled:opacity-60",children:"Cancel"}),e.jsx("button",{type:"submit",disabled:d||!n.trim(),className:"ui-action-success rounded-full px-4 py-2 text-sm font-medium transition disabled:cursor-not-allowed",children:"Save"})]})]})]}),document.body)}function dc(){const[t]=mr(),s=at(),a=Jt(),n=t.get("workspaceId"),[d,o]=r.useState([]),[m,h]=r.useState([]),[g,y]=r.useState(null),[A,x]=r.useState(!0),[f,k]=r.useState(null),[C,E]=r.useState(null),[v,J]=r.useState(""),[te,_]=r.useState(null),[R,X]=r.useState(null),[c,D]=r.useState(!1),Y=(a==null?void 0:a.defaultBackend)??Tt,I=r.useCallback(async()=>{x(!0),k(null);try{const[W,F,z]=await Promise.all([Ur(Y).then(ce=>ce.status),Mr(),fa()]);y(W),o(F),h(z)}catch(W){k(W instanceof Error?W.message:"Unable to load threads.")}finally{x(!1)}},[Y]);r.useEffect(()=>{if(n===null)return;I();const W=Hr(F=>{o(z=>z.map(ce=>ce.id===F.threadId?{...ce,status:F.type==="thread.updated"&&typeof F.payload.status=="string"?F.payload.status:ce.status,lastError:(F.type==="thread.turn.failed"||F.type==="thread.turn.completed")&&typeof F.payload.error=="string"?F.payload.error:ce.lastError,title:F.type==="thread.updated"&&typeof F.payload.title=="string"?F.payload.title:ce.title}:ce))});return()=>{W.close()}},[I,n]);const q=Object.fromEntries(m.map(W=>[W.id,W.label])),B=m.find(W=>W.id===n)??null,je=r.useMemo(()=>n?d.filter(W=>W.workspaceId===n):[],[n,d]),fe=je.filter(W=>W.status==="running").length,H=n?`/threads/new?workspaceId=${encodeURIComponent(n)}`:"/threads/new";if(n===null)return e.jsx(Os,{to:"/workspaces",replace:!0});function he(){switch(g==null?void 0:g.state){case"ready":return"bg-emerald-400 shadow-[0_0_0_3px_rgba(52,211,153,0.14)]";case"starting":return"bg-amber-300 shadow-[0_0_0_3px_rgba(252,211,77,0.12)]";case"degraded":case"failed":return"bg-rose-400 shadow-[0_0_0_3px_rgba(251,113,133,0.14)]";default:return"bg-stone-500 shadow-[0_0_0_3px_rgba(120,113,108,0.14)]"}}async function T(W,F){try{const z=await Lr(W,{title:F});o(ce=>ce.map(xe=>xe.id===z.id?{...xe,title:z.title,updatedAt:z.updatedAt}:xe))}catch(z){throw k(z instanceof Error?z.message:"Unable to rename thread."),z}}async function le(){if(!C)return;const W=v.trim();if(W){_(C);try{await T(C,W),E(null),J("")}finally{_(null)}}}async function oe(){if(R){D(!0);try{await Dr(R.id),o(W=>W.filter(F=>F.id!==R.id)),X(null)}catch(W){k(W instanceof Error?W.message:"Unable to delete thread.")}finally{D(!1)}}}return e.jsx(ic,{threads:d,workspaceLabels:q,status:g,loading:A,error:f,viewportConstrained:n!==null,showMobileAppMenu:!0,showMobileThreadNavToggle:!1,showMobileNewThreadShortcut:!1,currentWorkspaceId:n,currentWorkspaceLabel:(B==null?void 0:B.label)??null,onRenameThread:T,onDeleteThread:X,children:e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"host-panel flex min-h-0 flex-1 flex-col overflow-hidden rounded-[2rem] border shadow-2xl shadow-black/10",children:[e.jsx("div",{className:"border-b border-[var(--theme-border)] px-4 py-3 sm:px-6 sm:py-4",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("h2",{className:"host-page-title min-w-0 truncate text-base font-semibold sm:text-lg",title:B?`${B.label} threads`:"All threads",children:B?B.label:"All Threads"}),e.jsx(It,{to:H,className:"ui-action-primary inline-flex h-9 shrink-0 items-center rounded-full px-3.5 text-xs font-medium uppercase tracking-[0.18em] transition",children:"New Thread"})]})}),e.jsx("div",{className:"px-4 py-3 sm:px-6 sm:py-4",children:e.jsxs("article",{className:"host-surface-strong inline-flex min-w-[12rem] max-w-full items-center gap-3 rounded-[1.25rem] border px-3.5 py-2.5",children:[e.jsx("span",{"aria-hidden":"true",className:`h-2.5 w-2.5 shrink-0 rounded-full ${he()}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"host-muted truncate text-[11px] uppercase tracking-[0.22em]",children:"Supervisor"}),e.jsx("p",{className:"host-soft truncate text-sm",children:(g==null?void 0:g.lastError)??((g==null?void 0:g.state)==="ready"?"Ready":(g==null?void 0:g.state)??"Checking")})]})]})}),!A&&!f&&je.length>0&&e.jsxs("div",{className:"flex min-h-0 flex-1 flex-col border-t border-[var(--theme-border)] px-4 py-4 sm:px-6 sm:py-5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"host-muted text-xs uppercase tracking-[0.28em]",children:"Recent Threads"}),e.jsxs("span",{className:"host-warning-pill rounded-full border px-2 py-0.5 text-[11px] font-medium uppercase tracking-[0.18em]",children:[je.length," total"]}),fe>0&&e.jsxs("span",{className:"host-muted text-xs",children:["· ",fe," running"]})]}),e.jsx("div",{className:"mt-3 min-h-0 flex-1",children:e.jsx(No,{threads:je,currentWorkspaceId:n,workspaceLabels:q,onOpenThread:W=>s(`/threads/${W}`),onBeginRenameThread:W=>{E(W.id),J(W.title)},onDeleteThread:W=>X(W),scrollable:!0,maxHeightClassName:"max-h-full",showDeleteButton:!0,showSessionCopyButton:!0})})]}),!A&&!f&&je.length===0&&e.jsx("div",{className:"host-muted border-t border-[var(--theme-border)] px-4 py-6 text-sm sm:px-6",children:"No threads available in this workspace."})]}),e.jsx(Yr,{open:C!==null,title:"Rename Thread",label:"Thread Title",value:v,busy:te!==null,onChange:J,onCancel:()=>{E(null),J("")},onSubmit:()=>void le()}),e.jsx(wn,{open:R!==null,title:"Delete Thread",description:R?`Delete ${Po(R.title)} from supervisor. The backend session id will no longer appear in this workspace list.`:"",confirmLabel:"Delete Thread",busy:c,onCancel:()=>{c||X(null)},onConfirm:()=>void oe()})]})})}function dr(t){const s=t.trim(),a=s.replace(/[\\/]+$/,"");if(!a)return"";if(Zr(s)){const d=(a.split(/[?#]/)[0]??a).split(/[/:]/).filter(Boolean).at(-1)??"";return d.endsWith(".git")?d.slice(0,-4):d}return a.split(/[\\/]/).filter(Boolean).at(-1)??""}function Zr(t){const s=t.trim();return/^https?:\/\/.+/i.test(s)||/^ssh:\/\/.+/i.test(s)||/^git@[^:]+:.+/.test(s)}function cc({initialPath:t="",initialLabel:s="",submitLabel:a="Save Workspace",error:n,busy:d=!1,onSubmit:o}){const m=dr(t),[h,g]=r.useState(t),[y,A]=r.useState(s||m),[x,f]=r.useState(null),k=r.useRef(m);r.useEffect(()=>{const E=dr(h);A(v=>!v.trim()||v===k.current?E:v),k.current=E},[h]);async function C(E){E.preventDefault();const v=h.trim();if(!v){f("Workspace path or Git URL is required.");return}f(null);const J=y.trim(),te=Zr(v)?"gitUrl":"absPath";await o(J?{[te]:v,label:J}:{[te]:v})}return e.jsxs("form",{onSubmit:C,className:"host-panel space-y-5 rounded-3xl border p-6",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"workspace-path",className:"host-form-label text-sm font-medium",children:"Path or Git URL"}),e.jsx("input",{id:"workspace-path",name:"absPath",value:h,onChange:E=>g(E.target.value),placeholder:"/Users/name/project or https://github.com/owner/repo.git",className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition"}),e.jsx("p",{className:"host-muted mt-2 text-xs",children:"Absolute paths register local directories. Git URLs clone into the configured dev home."})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"workspace-label",className:"host-form-label text-sm font-medium",children:"Display label"}),e.jsx("input",{id:"workspace-label",name:"label",value:y,onChange:E=>A(E.target.value),placeholder:"Optional override",className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition"}),e.jsx("p",{className:"host-muted mt-2 text-xs",children:"Defaults to the last folder name. You can override it."})]}),(x||n)&&e.jsx("div",{className:"host-error rounded-2xl border px-4 py-3 text-sm",children:x??n}),e.jsx("button",{type:"submit",disabled:d,className:"ui-action-primary rounded-full px-5 py-3 font-medium transition disabled:cursor-not-allowed",children:d?"Saving...":a})]})}function uc(){const t=at(),[s,a]=r.useState(null),[n,d]=r.useState(!1);async function o(m){d(!0),a(null);try{const h=await mi(m);t(`/threads?workspaceId=${encodeURIComponent(h.id)}`)}catch(h){h instanceof re?a(h.payload.message):a(h instanceof Error?h.message:"Unable to create workspace.")}finally{d(!1)}}return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("p",{className:"host-page-eyebrow text-xs uppercase tracking-[0.3em]",children:"Add Workspace"}),e.jsx("h2",{className:"host-page-title mt-2 text-3xl font-semibold",children:"Create a workspace"}),e.jsx("p",{className:"host-page-description mt-3 max-w-2xl text-sm leading-6",children:"Register an existing local directory, create one missing child directory under dev home, or clone a Git repository into dev home."})]}),e.jsx(cc,{busy:n,error:s,submitLabel:"Create Workspace",onSubmit:o})]})}function cr(t){return Date.parse(t.lastOpenedAt??t.createdAt)}function mc(t,s){return t.isFavorite!==s.isFavorite?t.isFavorite?-1:1:cr(s)-cr(t)}function hc(t){return t?new Date(t).toLocaleString():"Never opened"}function pc(t,s=28){return t.length<=s?t:`...${t.slice(-(s-3))}`}function fc({active:t}){return e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:`h-3.5 w-3.5 fill-current ${t?"rotate-[18deg]":"rotate-[8deg]"}`,children:e.jsx("path",{d:"M10.7 1.75c.34 0 .62.28.62.63v1.24l1.43 1.42c.24.24.24.62 0 .86l-1.1 1.1v2.02c0 .17-.07.33-.19.45l-1.5 1.5v2.28c0 .28-.18.53-.44.6a.62.62 0 0 1-.69-.24L7.2 12.4l-2.83 2.83a.625.625 0 1 1-.88-.88l2.83-2.83-2.2-1.62a.62.62 0 0 1-.24-.69c.08-.26.32-.44.6-.44h2.28l1.5-1.5a.64.64 0 0 1 .45-.18h2.02l1.1-1.11-1.42-1.42H9.07a.63.63 0 0 1-.62-.63c0-.34.28-.62.62-.62h1.63Z"})})}function xc(){return e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-3.5 w-3.5 fill-current",children:e.jsx("path",{d:"M6.1 1.75h3.8c.75 0 1.4.52 1.57 1.25h2.03c.35 0 .63.28.63.63 0 .34-.28.62-.63.62h-.66l-.62 8.03c-.08 1.09-.99 1.97-2.08 1.97H5.86c-1.09 0-2-.88-2.08-1.97l-.62-8.03H2.5a.62.62 0 1 1 0-1.25h2.03c.17-.73.82-1.25 1.57-1.25Zm0 1.25c-.07 0-.14.03-.19.08A.26.26 0 0 0 5.84 3h4.32a.26.26 0 0 0-.07-.17.26.26 0 0 0-.19-.08H6.1Zm-1.07 1.25.61 7.93c.03.44.4.79.84.79h3.04c.44 0 .81-.35.84-.79l.61-7.93H5.03Zm1.53 1.32c.35 0 .62.28.62.62v4.19a.62.62 0 1 1-1.24 0V6.19c0-.34.28-.62.62-.62Zm2.82 0c.34 0 .62.28.62.62v4.19a.62.62 0 1 1-1.24 0V6.19c0-.34.28-.62.62-.62Z"})})}function gc(){const t=at(),[s,a]=r.useState([]),[n,d]=r.useState(!0),[o,m]=r.useState(null),[h,g]=r.useState(null),[y,A]=r.useState(null),[x,f]=r.useState(null),[k,C]=r.useState(""),[E,v]=r.useState(null),[J,te]=r.useState(null),[_,R]=r.useState(null),[X,c]=r.useState(!1);async function D(){d(!0),A(null);try{a(await fa())}catch(T){A(T instanceof Error?T.message:"Unable to load workspaces.")}finally{d(!1)}}r.useEffect(()=>{D(),il().then(T=>{m(T),g(null)}).catch(T=>{g(T instanceof Error?T.message:"Unable to load supervisor config.")})},[]);async function Y(T){const le={...T,isFavorite:!T.isFavorite};a(oe=>oe.map(W=>W.id===T.id?le:W));try{const oe=await fi(T.id,{isFavorite:!T.isFavorite});a(W=>W.map(F=>F.id===oe.id?oe:F))}catch(oe){a(W=>W.map(F=>F.id===T.id?T:F)),A(oe instanceof Error?oe.message:"Unable to update workspace.")}}async function I(T){const le=k.trim();if(le){v(T);try{const oe=await hi(T,{label:le});a(W=>W.map(F=>F.id===oe.id?oe:F)),f(null),C("")}catch(oe){A(oe instanceof Error?oe.message:"Unable to rename workspace.")}finally{v(null)}}}function q(T){f(T.id),C(T.label)}function B(){f(null),C("")}function je(T){t(`/threads?workspaceId=${encodeURIComponent(T)}`)}async function fe(){if(_){c(!0);try{await pi(_.id),a(T=>T.filter(le=>le.id!==_.id)),R(null)}catch(T){A(T instanceof Error?T.message:"Unable to delete workspace.")}finally{c(!1)}}}function H(T,le){(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),je(le))}const he=r.useMemo(()=>[...s].sort(mc),[s]);return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"host-topbar sticky top-[env(safe-area-inset-top)] z-20 -mx-4 border-b px-2.5 py-2 backdrop-blur sm:mx-0 sm:rounded-[1.4rem] sm:border sm:px-4",children:e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 sm:gap-2",children:[e.jsx(Fr,{}),e.jsx(It,{to:"/threads/import",className:"host-info-pill inline-flex h-8 shrink-0 items-center rounded-full border px-2.5 text-[11px] font-medium uppercase tracking-[0.14em] transition sm:px-3 sm:text-xs sm:tracking-[0.18em]",children:"Import"}),e.jsx(It,{to:"/workspaces/new",className:"ui-action-primary inline-flex h-8 shrink-0 items-center rounded-full px-2.5 text-[11px] font-medium uppercase tracking-[0.14em] transition sm:px-3 sm:text-xs sm:tracking-[0.18em]",children:"Create"}),e.jsx("div",{className:"min-w-0 flex-1 text-right",children:e.jsx("p",{className:"host-page-eyebrow truncate text-[11px] uppercase tracking-[0.24em]",children:"Workspaces"})})]}),e.jsx(Wr,{className:"absolute left-0 top-[calc(100%+0.5rem)] z-30 w-[min(22rem,calc(100vw-1rem))]"})]})}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1fr)_20rem]",children:[e.jsxs("section",{className:"min-w-0 space-y-4",children:[n&&e.jsx("div",{className:"host-empty-state rounded-[1.6rem] border px-6 py-12 text-center",children:"Loading workspace registry..."}),y&&e.jsx("div",{className:"host-error rounded-[1.4rem] border px-4 py-4",children:y}),!n&&!y&&s.length===0&&e.jsxs("div",{className:"host-empty-state rounded-[1.6rem] border border-dashed px-6 py-12 text-center",children:[e.jsx("p",{className:"host-page-title text-lg font-medium",children:"No workspaces yet"}),e.jsx("p",{className:"host-muted mt-2 text-sm",children:"Add a local directory inside the configured workspace root to start building the registry."})]}),!n&&he.length>0&&e.jsx("div",{className:"space-y-2 overflow-x-hidden",children:he.map(T=>e.jsxs("article",{role:"link",tabIndex:0,onClick:()=>je(T.id),onKeyDown:le=>H(le,T.id),className:"host-card relative overflow-hidden rounded-[1.35rem] border px-4 py-3 transition",children:[e.jsxs("div",{className:"absolute right-2.5 top-2.5 flex items-center gap-1.5",children:[e.jsx("button",{type:"button","aria-label":`Delete workspace ${T.label}`,title:"Delete workspace",onClick:le=>{le.stopPropagation(),R(T)},className:"inline-flex h-7 w-7 items-center justify-center rounded-full border border-[var(--status-danger-border)] bg-[var(--status-danger-bg)] text-[var(--status-danger-fg)] transition hover:bg-[var(--status-danger-border)]",children:e.jsx(xc,{})}),e.jsx("button",{type:"button","aria-label":T.isFavorite?`Unpin workspace ${T.label}`:`Pin workspace ${T.label}`,title:T.isFavorite?"Unpin workspace":"Pin workspace",onClick:le=>{le.stopPropagation(),Y(T)},className:`inline-flex h-7 w-7 items-center justify-center rounded-full border transition ${T.isFavorite?"host-warning-pill":"host-icon-button"}`,children:e.jsx(fc,{active:T.isFavorite})})]}),e.jsx("div",{className:"flex min-w-0 items-start gap-3 pr-[4.6rem]",children:e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1",children:[e.jsx("p",{className:"host-page-title min-w-0 max-w-full truncate text-base font-semibold sm:text-lg",title:T.label,children:T.label}),e.jsx("button",{type:"button",onClick:le=>{le.stopPropagation(),q(T)},"aria-label":`Rename workspace ${T.label}`,className:"host-muted inline-flex h-4 w-4 shrink-0 items-center justify-center transition hover:text-[var(--theme-fg)]",children:e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-3 w-3 fill-current",children:e.jsx("path",{d:"m11.9 1.6 2.5 2.5-8.2 8.2-3.3.7.7-3.3 8.3-8.1Zm-7.3 8.7-.3 1.3 1.3-.3 6.9-6.9-1-1-6.9 6.9Zm8.8-7.8-1-1-1 1 1 1 1-1Z"})})})]}),e.jsx("button",{type:"button","aria-label":T.absPath,title:T.absPath,onClick:le=>{le.stopPropagation(),te(T.absPath)},className:"host-muted mt-1 inline-block max-w-full overflow-hidden whitespace-nowrap text-left text-[9px] leading-4 transition hover:text-[var(--theme-fg-soft)]",children:pc(T.absPath)}),e.jsx("div",{className:"host-muted mt-2 flex flex-wrap items-center gap-2 text-xs",children:e.jsxs("span",{className:"min-w-0 truncate",children:["Last opened: ",hc(T.lastOpenedAt)]})})]})})]},T.id))})]}),e.jsx(bc,{config:o,error:h,workspaceCount:s.length})]}),e.jsx(Yr,{open:x!==null,title:"Rename Workspace",label:"Workspace Label",value:k,busy:E!==null,onChange:C,onCancel:B,onSubmit:()=>x?I(x):void 0}),e.jsx(So,{open:J!==null,title:"Workspace Path",text:J??"",onClose:()=>te(null)}),e.jsx(wn,{open:_!==null,title:"Delete Workspace",description:_?`Delete ${_.label} from supervisor. This also removes its threads and local supervisor metadata.`:"",confirmLabel:"Delete Workspace",busy:X,onCancel:()=>{X||R(null)},onConfirm:()=>void fe()})]})}function bc({config:t,error:s,workspaceCount:a}){return e.jsxs("aside",{className:"space-y-3 xl:sticky xl:top-[calc(env(safe-area-inset-top)+4.25rem)] xl:self-start",children:[e.jsxs("section",{className:"rounded-[1.2rem] border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.18em] text-[var(--theme-fg-muted)]",children:"Supervisor"}),e.jsxs("dl",{className:"mt-4 space-y-3",children:[e.jsx(pn,{label:"Workspace root",value:(t==null?void 0:t.workspaceRoot)??"Loading..."}),e.jsx(pn,{label:"Environment",value:t?`${t.environment} · ${t.host}:${t.port}`:s??"Loading..."}),e.jsx(pn,{label:"Version",value:t?`${t.appName} ${t.appVersion}`:"Loading..."}),e.jsx(pn,{label:"Workspaces",value:String(a)})]})]}),s?e.jsx("section",{className:"rounded-[1.2rem] border border-[var(--status-warning-border)] bg-[var(--status-warning-bg)] p-4 text-sm text-[var(--status-warning-fg)]",children:"Runtime metadata is unavailable. Workspace actions may still work if a relay device is connected."}):null]})}function pn({label:t,value:s}){return e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-[var(--theme-fg-muted)]",children:t}),e.jsx("dd",{className:"mt-1 break-words font-mono text-xs leading-5 text-[var(--theme-fg)]",children:s})]})}const Xr="remote-codex-theme-mode",Qr="remote-codex-default-backend",eo="remote-codex-auto-collapse-completed-turns";function to(){return!1}function vc(){return to()?e.jsx(Os,{to:"/control-plane",replace:!0}):e.jsx(Os,{to:"/workspaces",replace:!0})}function jc({children:t}){const s=es(),a=s.pathname.startsWith("/control-plane")||s.pathname==="/"&&to(),n=r.useMemo(()=>a?{}:{fetchPlugins:Ll,importPlugin:Dl,updatePlugin:Hl,deletePlugin:_l},[a]);return e.jsx(ko,{adapter:n,children:t})}function yc(){if(typeof window>"u")return"system";const t=window.localStorage.getItem(Xr);return t==="light"||t==="dark"||t==="system"?t:"system"}function wc(){if(typeof window>"u")return Tt;const t=window.localStorage.getItem(Qr);return Eo(t)??Tt}function Nc(){return typeof window>"u"?!0:window.localStorage.getItem(eo)!=="false"}function Sc(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function kc({themeMode:t,setThemeMode:s,effectiveTheme:a}){const[n,d]=r.useState(!1),[o,m]=r.useState(!1),[h,g]=r.useState(wc),[y,A]=r.useState(Nc),x=es(),f=/^\/threads\/[^/]+$/.test(x.pathname),k=/^\/control-plane\/sessions\/[^/]+$/.test(x.pathname),C=x.pathname==="/threads",E=f||k||C,v=C||f||k,J=f||k,te=x.pathname==="/workspaces",_=x.pathname.startsWith("/control-plane"),R=te||C||_;r.useEffect(()=>{d(!1)},[x.pathname,x.search]);function X(Y){g(Y),window.localStorage.setItem(Qr,Y)}function c(Y){A(Y),window.localStorage.setItem(eo,Y?"true":"false")}const D={navOpen:n,openNav:()=>d(!0),toggleNav:()=>d(Y=>!Y),closeNav:()=>d(!1),settingsOpen:o,openSettings:()=>{d(!1),m(!0)},closeSettings:()=>m(!1),themeMode:t,setThemeMode:s,effectiveTheme:a,defaultBackend:h,setDefaultBackend:X,autoCollapseCompletedTurns:y,setAutoCollapseCompletedTurns:c};return e.jsxs(Co.Provider,{value:D,children:[e.jsxs("div",{className:`bg-[var(--app-bg)] text-[var(--app-fg)] ${E?"fixed inset-0 overflow-hidden overscroll-none":"min-h-screen"}`,children:[te?e.jsx(ga,{}):null,!R&&!J&&e.jsxs("div",{className:"fixed left-4 top-4 z-50",children:[e.jsx(Fr,{}),e.jsx(Wr,{className:"mt-3 w-[min(22rem,calc(100vw-2rem))]"})]}),e.jsx("main",{className:`mx-auto w-full ${v?"max-w-none":"max-w-[1600px]"} ${E?"absolute inset-0 pb-0 sm:pb-4":"pb-4"} ${v?f||k?"pt-0":C?"pt-[env(safe-area-inset-top)] sm:pt-4":"pt-[calc(env(safe-area-inset-top)+4rem)] sm:pt-4":te||_?"pt-[env(safe-area-inset-top)] sm:pt-4":"pt-4"} ${E?f||k?"overflow-hidden overscroll-none px-0":"overflow-hidden overscroll-none px-0 sm:px-6":"px-4 sm:px-6"}`,children:e.jsx("section",{className:`min-w-0 ${E?f||k?"h-full min-h-0 overflow-hidden overscroll-none":"h-full overflow-hidden overscroll-none":""}`,children:e.jsx(po,{})})})]}),e.jsx(xa,{})]})}function Cc({children:t}){const[s,a]=r.useState({status:"checking"});async function n(m){try{const h=await dl();if(m!=null&&m())return;a(!h.authRequired||h.authenticated?{status:"authenticated"}:{status:"loginRequired",session:h,error:null})}catch(h){if(m!=null&&m())return;if(h instanceof re&&h.statusCode===401){a({status:"loginRequired",session:{authenticated:!1,username:null,expiresAt:null,mode:"server",authRequired:!0},error:null});return}a({status:"unavailable",error:h instanceof Error?h.message:"Unable to check supervisor access."})}}r.useEffect(()=>{let m=!1;return n(()=>m),()=>{m=!0}},[]);async function d(m){await cl(m),a({status:"authenticated"})}function o(){a({status:"checking"}),n()}return s.status==="checking"?e.jsx("main",{className:"flex min-h-screen items-center justify-center bg-[var(--app-bg)] px-4 text-sm text-[var(--theme-muted)]",children:"Checking supervisor access..."}):s.status==="unavailable"?e.jsx("main",{className:"flex min-h-screen items-center justify-center bg-[var(--app-bg)] px-4 text-[var(--app-fg)]",children:e.jsxs("section",{className:"w-full max-w-md rounded-[1.35rem] border border-[var(--theme-border)] bg-[var(--theme-panel)] p-5 shadow-2xl shadow-[color-mix(in_oklch,var(--app-fg)_14%,transparent)] sm:p-6",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-muted)]",children:"Supervisor Access"}),e.jsx("h1",{className:"mt-2 text-2xl font-semibold tracking-normal text-[var(--theme-fg)]",children:"Unable to reach supervisor"}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-[var(--theme-muted)]",children:s.error}),e.jsx("button",{className:"mt-5 h-11 rounded-xl bg-[var(--theme-accent-solid)] px-4 text-sm font-semibold text-[var(--theme-accent-solid-fg)] transition hover:bg-[var(--theme-accent-solid-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--theme-accent-border)]",onClick:o,type:"button",children:"Retry"})]})}):s.status==="loginRequired"?e.jsxs(e.Fragment,{children:[s.error&&e.jsx("div",{className:"fixed left-1/2 top-4 z-50 w-[min(28rem,calc(100vw-2rem))] -translate-x-1/2 rounded-xl border border-[var(--status-warning-border)] bg-[var(--status-warning-bg)] px-3 py-2 text-sm text-[var(--status-warning-fg)]",children:s.error}),e.jsx(Ad,{onLogin:d})]}):t}function Tc({children:t}){const[s,a]=r.useState({status:"checking"});return r.useEffect(()=>{let n=!1;return $s().then(d=>{n||a(d.authenticated?{status:"authenticated",session:d}:{status:"loginRequired"})}).catch(()=>{n||a({status:"loginRequired"})}),()=>{n=!0}},[]),s.status==="checking"?e.jsx("main",{className:"flex min-h-screen items-center justify-center bg-[var(--app-bg)] px-4 text-sm text-[var(--theme-muted)]",children:"Checking relay access..."}):s.status==="loginRequired"?e.jsx(Kr,{}):t}function Ic({children:t}){return es().pathname.startsWith("/control-plane")?t:na()?e.jsx(Tc,{children:t}):e.jsx(Cc,{children:t})}function Ec({themeMode:t,setThemeMode:s,effectiveTheme:a}){return e.jsxs(hr,{children:[e.jsx(qe,{path:"/",element:e.jsx(Os,{to:"/workspaces",replace:!0})}),e.jsxs(qe,{element:e.jsx(kc,{themeMode:t,setThemeMode:s,effectiveTheme:a}),children:[e.jsx(qe,{path:"/workspaces",element:e.jsx(gc,{})}),e.jsx(qe,{path:"/workspaces/new",element:e.jsx(uc,{})}),e.jsx(qe,{path:"/relay-account",element:e.jsx(Ud,{})}),e.jsx(qe,{path:"/relay-devices",element:e.jsx($d,{})}),e.jsx(qe,{path:"/control-plane/login",element:e.jsx(Qi,{})}),e.jsx(qe,{path:"/control-plane",element:e.jsx(Xa,{children:e.jsx(Ki,{})})}),e.jsx(qe,{path:"/control-plane/sessions/:sessionId",element:e.jsx(Xa,{children:e.jsx(Rd,{})})}),e.jsx(qe,{path:"/threads",element:e.jsx(dc,{})}),e.jsx(qe,{path:"/threads/import",element:e.jsx(ac,{})}),e.jsx(qe,{path:"/threads/new",element:e.jsx(oc,{})}),e.jsx(qe,{path:"/threads/:id",element:e.jsx(nc,{})})]})]})}function Rc(){const[t,s]=r.useState(()=>yc()),[a,n]=r.useState(()=>Sc()),d=t==="system"?a:t;return r.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const o=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{n(o.matches?"dark":"light")};return m(),typeof o.addEventListener=="function"?o.addEventListener("change",m):o.addListener(m),()=>{typeof o.removeEventListener=="function"?o.removeEventListener("change",m):o.removeListener(m)}},[]),r.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(Xr,t)},[t]),r.useEffect(()=>{const o=document.documentElement;o.dataset.themeMode=t,o.dataset.themeEffective=d,o.style.colorScheme=d},[d,t]),e.jsx("div",{className:"theme-shell theme-scrollbar",children:e.jsx(ho,{children:e.jsx(jc,{children:e.jsxs(hr,{children:[e.jsx(qe,{path:"/",element:e.jsx(vc,{})}),e.jsx(qe,{path:"/relay-portal",element:e.jsx(Kr,{})}),e.jsx(qe,{path:"/relay-admin",element:e.jsx(Od,{})}),e.jsx(qe,{path:"/*",element:e.jsx(Ic,{children:e.jsx(Ec,{themeMode:t,setThemeMode:s,effectiveTheme:d})})})]})})})})}fo.createRoot(document.getElementById("root")).render(e.jsx(xo.StrictMode,{children:e.jsx(Rc,{})}));
|