remote-codex 0.11.12 → 0.11.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +0,0 @@
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 uo,B as mo,h as hr,i as We,O as ho,k as po,c as fo}from"./react-vendor-CgLzZcV4.js";import{u as Jt,a as ca,C as wn,f as ps,T as pr,A as xo,b as go,t as fr,E as bo,c as vo,d as yo,e as jo,g as wo,L as No,P as So,h as ko}from"./thread-ui-DldLSgqC.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 Co=["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 To(t){return typeof t=="string"&&Co.includes(t)}function Io(t){return To(t)?t:null}var Aa=15;function Eo(t){return t.replace(/\s+/g," ").trim()}function Ro(t){const s=Eo(t);if(!s)return"";const a=Array.from(s);return a.length<=Aa?s:`${a.slice(0,Aa).join("")}...`}const Po=["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 Ao(t){return t.replace(/\s+/g," ").trim()}function Uo(t){const s=Ao(t);if(!s)return"";const a=Array.from(s);return a.length<=Ua?s:`${a.slice(0,Ua).join("")}...`}class ae 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 Oo(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(Qn,t);return}window.localStorage.removeItem(Qn)}}function yr(){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 jr(){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 $o(){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=jr();return s?`/relay/devices/${encodeURIComponent(s)}${t}`:`/relay${t}`}return t}function Mo(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 Lo(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)??Mo(t.status),message:n,...d?{details:d}:{}}}async function Nr(t){var d,o;const s=Lo(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
- ${m}`}:null,s)}catch{try{return await n()}catch{return cs(t,null,s)}}}async function O(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 ae(n.status,d)}return await n.json()}function Do(t){const s=String(t);return s.includes("/exports/pdf")?s.includes("format=html")?"remote-codex-transcript.html":"remote-codex-transcript.pdf":"download"}function Ho(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 ae(a.status,d)}const n=Ho(a.headers.get("content-disposition"))??Do(t);return{blob:await a.blob(),filename:n}}function kr(t={}){const s=new Headers(t.headers),a=yr(),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 _o(t,s){return`${t.baseUrl.replace(/\/+$/,"")}${s}`}function Bo(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 O(_o(t,s),{...a,headers:Bo(t,a)})}function ma(t,s){return`${t.replace(/\/+$/,"")}${s}`}function Fo(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 Wo(t,s){return O(ma(t,"/api/auth/password/register"),{method:"POST",body:JSON.stringify(s)})}function qo(t,s){return O(ma(t,"/api/auth/password/login"),{method:"POST",body:JSON.stringify(s)})}function ha(t){return Se(t,"/api/me",{cache:"no-store"})}function zo(t,s=10){const a=new URLSearchParams({limit:String(s)});return Se(t,`/api/usage/events?${a.toString()}`,{cache:"no-store"})}function Vo(t){return Se(t,"/api/usage/harness/summary",{cache:"no-store"})}function Jo(t,s=10){const a=new URLSearchParams({limit:String(s)});return Se(t,`/api/usage/harness/events?${a.toString()}`,{cache:"no-store"})}function Go(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 Ko(t,s){return Se(t,"/api/projects",{method:"POST",body:JSON.stringify(s)})}function Yo(t,s,a){return Se(t,`/api/projects/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(a)})}function Zo(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 Xo(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 Qo(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 el(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 tl(t){return Se(t,"/api/sandbox/start",{method:"POST"})}function sl(t){return Se(t,"/api/sandbox/stop",{method:"POST"})}function nl(t){return Se(t,"/api/sandbox/restart",{method:"POST"})}function Ma(t){return Se(t,"/api/sandbox/health",{cache:"no-store"})}function al(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 rl(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 O(Nn(t,`/api/threads/${encodeURIComponent(s)}`,a),{cache:"no-store",headers:Sn(t)})}function ol(t,s,a){return O(Nn(t,`/api/threads/${encodeURIComponent(s)}/items/${encodeURIComponent(a)}/detail`),{cache:"no-store",headers:Sn(t)})}function $n(t,s,a){return O(Nn(t,`/api/threads/${encodeURIComponent(s)}/prompt`),{method:"POST",body:JSON.stringify(a),headers:Sn(t)})}function Ha(t,s,a={}){return O(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 ll(){return O("/api/config/runtime")}function il(){return O("/api/auth/session",{cache:"no-store"})}async function dl(t){const s=await O("/api/auth/login",{method:"POST",body:JSON.stringify(t)});return Oo(s.token??null),s}function $s(){return O("/relay/auth/session",{credentials:"same-origin"})}async function cl(t){xs();const s=await O("/relay/auth/login",{method:"POST",body:JSON.stringify(t)});return ua(s.token),s}async function ul(t){xs();const s=await O("/relay/auth/register",{method:"POST",body:JSON.stringify(t)});return ua(s.token),s}async function Er(){const t=await O("/relay/auth/logout",{method:"POST"});return ua(null),bn(null),vn(null),t}function Rr(){return O("/relay/portal")}function Pr(t){return O("/relay/devices",{method:"POST",body:JSON.stringify(t)})}function Ar(t){return O(`/relay/devices/${encodeURIComponent(t)}`,{method:"DELETE"})}function ml(t){return O("/relay/account",{method:"PATCH",body:JSON.stringify(t)})}function hl(t){return O("/relay/account/password",{method:"PATCH",body:JSON.stringify(t)})}function pl(t){return O("/relay/shares",{method:"POST",body:JSON.stringify(t)})}function fl(t){return O(`/relay/shares/${encodeURIComponent(t)}`,{method:"DELETE"})}function xl(){return O("/relay/admin")}function gl(t){return O("/relay/admin/settings/registration",{method:"PATCH",body:JSON.stringify({enabled:t})})}function bl(t,s){return O(`/relay/admin/users/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({enabled:s})})}function vl(){return O("/api/config/workspace-settings",{cache:"no-store"})}function yl(t){return O("/api/config/workspace-settings",{method:"PATCH",body:JSON.stringify(t)})}function pa(){return O("/api/agent-runtimes",{cache:"no-store"})}function Ur(t){return O(`/api/agent-runtimes/${encodeURIComponent(t)}/status`,{cache:"no-store"})}function jl(t){return O(`/api/agent-runtimes/${encodeURIComponent(t)}/restart`,{method:"POST"})}function wl(t,s){return O(`/api/agent-runtimes/${encodeURIComponent(t)}/install`,{method:"POST",body:JSON.stringify({action:s})})}function oa(t){return O(`/api/agent-runtimes/${encodeURIComponent(t)}/models`,{cache:"no-store"})}function Or(t,s){return O(`/api/config/providers/${encodeURIComponent(t)}/files/${encodeURIComponent(s)}`,{cache:"no-store"})}function $r(t,s,a){return O(`/api/config/providers/${encodeURIComponent(t)}/files/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(a)})}function Nl(t){return O(`/api/config/providers/${encodeURIComponent(t)}/archives`,{cache:"no-store"})}function Sl(t,s={}){return O(`/api/config/providers/${encodeURIComponent(t)}/archives`,{method:"POST",body:JSON.stringify(s)})}function kl(t,s,a){return O(`/api/config/providers/${encodeURIComponent(t)}/archives/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(a)})}function Cl(t,s){return O(`/api/config/providers/${encodeURIComponent(t)}/archives/${encodeURIComponent(s)}/apply`,{method:"POST"})}function Tl(){return O("/api/service/build-restart",{method:"POST"})}function Il(){return O("/healthz",{cache:"no-store"})}function fa(){return O("/api/workspaces")}function El(t){return O(`/api/workspaces/${encodeURIComponent(t)}/files/tree`,{cache:"no-store"})}function Rl(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)),O(`/api/workspaces/${encodeURIComponent(t)}/files/preview?${a.toString()}`,{cache:"no-store"})}function Pl(t,s){const a=new URLSearchParams({path:s.path});return`/api/workspaces/${encodeURIComponent(t)}/files/raw?${a.toString()}`}function Al(t,s){const a=new URLSearchParams({path:s.path});return Sr(`/api/workspaces/${encodeURIComponent(t)}/files/download?${a.toString()}`,{cache:"no-store"})}function Ul(t,s){const a=new FormData;return a.append("file",s.file,s.file.name),O(`/api/workspaces/${encodeURIComponent(t)}/files/upload`,{method:"POST",body:a})}function Ol(t,s){return O(`/api/workspaces/${encodeURIComponent(t)}/files`,{method:"PUT",body:JSON.stringify(s)})}function Mr(){return O("/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),O(`/api/threads/${t}${a.size>0?`?${a.toString()}`:""}`)}function $l(t,s){return O(`/api/threads/${t}/items/${encodeURIComponent(s)}/detail`)}function Ml(){return O("/api/plugins",{cache:"no-store"})}function Ll(t){return O("/api/plugins/import",{method:"POST",body:JSON.stringify(t)})}function Dl(t,s){return O(`/api/plugins/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(s)})}function Hl(t){return O(`/api/plugins/${encodeURIComponent(t)}`,{method:"DELETE"})}function _l(t){return O(`/api/threads/${t}/export-turns`,{cache:"no-store"})}function Bl(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 Fl(t,s){return Sr(Bl(t,s),{cache:"no-store"})}function Wl(t){return O(`/api/threads/${t}/shell`)}function ql(t){return O("/api/threads/start",{method:"POST",body:JSON.stringify(t)})}function zl(t){return O("/api/threads/import",{method:"POST",body:JSON.stringify(typeof t=="string"?{sessionId:t}:t)})}function Vl(t,s={}){return O(`/api/threads/${t}/shell`,{method:"POST",...Object.keys(s).length>0?{body:JSON.stringify(s)}:{}})}function Jl(t){return O(`/api/shells/${t}/terminate`,{method:"POST"})}function Gl(t,s){return O(`/api/shells/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Fa(t,s={}){return O(`/api/threads/${t}/resume`,{method:"POST",...Object.keys(s).length>0?{body:JSON.stringify(s)}:{}})}function Kl(t){return O(`/api/threads/${t}/disconnect`,{method:"POST"})}function Yl(t,s){const a=s.attachments??[];if(a.length===0)return O(`/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 O(`/api/threads/${t}/prompt`,{method:"POST",body:n})}function Wa(t,s={}){return O(`/api/threads/${t}/interrupt`,{method:"POST",body:JSON.stringify(s)})}function Lr(t,s){return O(`/api/threads/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Dr(t){return O(`/api/threads/${t}`,{method:"DELETE"})}function Zl(t,s){return O(`/api/threads/${t}/settings`,{method:"PATCH",body:JSON.stringify(s)})}function Xl(t){return O(`/api/threads/${t}/compact`,{method:"POST"})}function Ql(t){return O(`/api/threads/${t}/goal`,{cache:"no-store"})}function ei(t,s){return O(`/api/threads/${t}/goal`,{method:"PATCH",body:JSON.stringify(s)})}function ti(t){return O(`/api/threads/${t}/goal`,{method:"DELETE"})}function si(t){return O(`/api/threads/${t}/fork-turns`,{cache:"no-store"})}function qa(t,s){return O(`/api/threads/${t}/fork`,{method:"POST",body:JSON.stringify(s)})}function ni(t){return O(`/api/threads/${t}/skills`,{cache:"no-store"})}function ai(t){return O(`/api/threads/${t}/mcp-servers`,{cache:"no-store"})}function ri(t){return O(`/api/threads/${t}/hooks`,{cache:"no-store"})}function oi(t,s){return O(`/api/threads/${t}/hooks`,{method:"POST",body:JSON.stringify(s)})}function li(t,s){return O(`/api/threads/${t}/hooks`,{method:"PUT",body:JSON.stringify(s)})}function ii(t,s){return O(`/api/threads/${t}/hooks/trust`,{method:"POST",body:JSON.stringify(s)})}function di(t,s){return O(`/api/threads/${t}/hooks/untrust`,{method:"POST",body:JSON.stringify(s)})}function ci(t,s,a){return O(`/api/threads/${t}/requests/${encodeURIComponent(s)}/respond`,{method:"POST",body:JSON.stringify(a)})}function ui(t){return O("/api/workspaces",{method:"POST",body:JSON.stringify(t)})}function mi(t,s){return O(`/api/workspaces/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function hi(t){return O(`/api/workspaces/${t}`,{method:"DELETE"})}function pi(t,s){return O(`/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);xi(d)&&t(d)}catch{}}),a}function fi(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}gi(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=jr();s.pathname=o?`/relay/devices/${encodeURIComponent(o)}/ws`:"/relay/ws"}const a=vr(),n=yr(),d=$o();return fs()&&n&&s.searchParams.set("relaySession",n),fs()&&d&&s.searchParams.set("threadId",d),a&&s.searchParams.set("token",a),s.toString()}function xi(t){return"threadId"in t&&t.type.startsWith("thread.")&&typeof t.payload=="object"&&t.payload!==null}function gi(t){return"shellId"in t&&t.type.startsWith("shell.")&&typeof t.payload=="object"&&t.payload!==null}function bi(){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 vi=[{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 ji(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=[...Po.map(t=>ji(t,gr[t].displayName))];function wi(t){var s;return((s=hs.find(a=>a.provider===t))==null?void 0:s.managementSchema)??Br}function Ni(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 Si(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(bi,{})}):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(v){const R=v.target;if(!R)return;const x=d.current;x!=null&&x.contains(R)||R instanceof Element&&R.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),[v,R]=r.useState(null),[x,f]=r.useState({}),k=v?x[v]:null,[C,P]=r.useState({busy:!1,message:null,error:null}),[b,z]=r.useState([]),[se,F]=r.useState(hs),[E,J]=r.useState({loading:!1,saving:!1,error:null,operatingProvider:null,operatingAction:null,message:null}),[c,_]=r.useState(null),[re,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}),ge=(s==null?void 0:s.themeMode)??"system",pe=t||!!(s!=null&&s.settingsOpen);async function H(){const y=n.trim();if(!(!y||o.busy)){m({busy:!0,message:null,error:null});try{await a.importPluginManifest({manifestJson:y,enabled:!0}),d(""),m({busy:!1,message:"Plugin manifest imported.",error:null})}catch(w){m({busy:!1,message:null,error:w instanceof Error?w.message:"Unable to import plugin manifest."})}}}const he=(s==null?void 0:s.effectiveTheme)??"dark",T=(s==null?void 0:s.defaultBackend)??xr,le=a.plugins.filter(y=>y.enabled).length,oe=a.loading?"Loading...":`${le}/${a.plugins.length} enabled`,M=se.find(y=>y.provider===T)??hs.find(y=>y.provider===T)??hs[0],Y=M.managementSchema??wi(M.provider),W=Y.hostConfigFiles;r.useEffect(()=>{if(!pe||t||!s||!Y.configArchives)return;const y=s;function w(A){A.key==="Escape"&&y.closeSettings()}return window.addEventListener("keydown",w),()=>{window.removeEventListener("keydown",w)}},[Y.configArchives,t,pe,s]),r.useEffect(()=>{if(!pe)return;let y=!1;return J(w=>({...w,loading:!0,error:null})),pa().then(w=>{if(y)return;const A=[...w.map(Ln),...hs.filter(X=>!w.some(ve=>ve.provider===X.provider))];F(A),J(X=>({...X,loading:!1}))}).catch(w=>{y||(F(hs),J(A=>({...A,loading:!1,error:w instanceof ae?w.message:"Unable to load backend settings."})))}),()=>{y=!0}},[pe]),r.useEffect(()=>{if(!pe)return;let y=!1;return I(w=>({...w,loading:!0,message:null,error:null})),vl().then(w=>{y||(_(w),I(A=>({...A,devHomeDraft:w.devHome,loading:!1})))}).catch(w=>{y||I(A=>({...A,loading:!1,error:w instanceof ae?w.message:"Unable to load workspace settings."}))}),()=>{y=!0}},[pe]),r.useEffect(()=>{if(!pe||!M.capabilities.management.hostConfigFiles)return;let y=!1;async function w(){f(X=>{const ve={...X};for(const Pe of W)ve[Pe.name]={...Es(Pe.name),...X[Pe.name],loading:!0,saving:!1,error:null,saveMessage:null};return ve});const A=await Promise.allSettled(W.map(async X=>({name:X.name,result:await Or(M.provider,X.name)})));y||f(X=>{var Pe,ht;const ve={...X};for(const Ae of A){if(Ae.status==="fulfilled"){const{name:ot,result:Ke}=Ae.value;ve[ot]={path:Ke.path,exists:Ke.exists,originalContent:Ke.content,draftContent:Ke.content,loading:!1,saving:!1,error:null,saveMessage:null};continue}const wt=Ae.reason instanceof ae?Ae.reason.message:"Unable to load the file.",Ge=((Pe=W[A.indexOf(Ae)])==null?void 0:Pe.name)??((ht=W[0])==null?void 0:ht.name);Ge&&(ve[Ge]={...Es(Ge),...ve[Ge],loading:!1,saving:!1,error:wt,saveMessage:null})}return ve})}return w(),()=>{y=!0}},[M.capabilities.management.hostConfigFiles,M.provider,W,pe]),r.useEffect(()=>{if(!pe)return;let y=!1;async function w(){B(A=>({...A,loading:!0,error:null,message:null}));try{const A=await Nl(M.provider);if(y)return;z(A),B(X=>({...X,loading:!1}))}catch(A){if(y)return;B(X=>({...X,loading:!1,error:A instanceof ae?A.message:"Unable to load config archives."}))}}return w(),()=>{y=!0}},[M.provider,Y.configArchives,pe]);async function be(){if(!(C.busy||E.saving)){P({busy:!0,message:null,error:null});try{const y=await jl(M.provider),w=Ln(y);P({busy:!1,message:w.status.state==="ready"?`${w.displayName} backend restarted.`:`${w.displayName} backend state: ${w.status.state}`,error:null}),F(A=>A.map(X=>X.provider===w.provider?w:X))}catch(y){P({busy:!1,message:null,error:y instanceof ae?y.message:"Unable to restart the app server."})}}}async function fe(y,w){if(C.busy||E.saving)return;const A=se.find(X=>X.provider===y);J(X=>({...X,saving:!0,operatingProvider:y,operatingAction:w,message:null,error:null}));try{const X=await wl(y,w),ve=Ln(X);F(Pe=>Pe.map(ht=>ht.provider===ve.provider?ve:ht)),J(Pe=>({...Pe,saving:!1,operatingProvider:null,operatingAction:null,message:ve.installation.lastError?`${ve.displayName} ${w==="install"?"installed":"updated"}, but requires attention:
4
- ${ve.installation.lastError}`:`${ve.displayName} ${w==="install"?"installed":"updated"}.`,error:null}))}catch(X){J(ve=>({...ve,saving:!1,operatingProvider:null,operatingAction:null,message:null,error:X instanceof ae?Si(X):`Unable to ${w} ${(A==null?void 0:A.displayName)??y}.`}))}}async function rt(){if(!(C.busy||E.saving)){P({busy:!0,message:null,error:null});try{await Tl(),P({busy:!1,message:"Build and restart launched. The page may disconnect briefly.",error:null})}catch(y){P({busy:!1,message:null,error:y instanceof ae?y.message:"Unable to launch build and restart."})}}}async function ct(){const y=re.devHomeDraft.trim();if(!(!y||re.saving)){I(w=>({...w,saving:!0,message:null,error:null}));try{const w=await yl({devHome:y});_(w),I(A=>({...A,devHomeDraft:w.devHome,saving:!1,message:"Workspace defaults saved."}))}catch(w){I(A=>({...A,saving:!1,error:w instanceof ae?w.message:"Unable to save workspace settings."}))}}}async function Ye(y){const w=x[y];if(!(!w||w.saving)){f(A=>({...A,[y]:{...Es(y),...A[y],saving:!0,error:null,saveMessage:null}}));try{const A=await $r(M.provider,y,{content:w.draftContent});f(X=>({...X,[y]:{path:A.path,exists:A.exists,originalContent:A.content,draftContent:A.content,loading:!1,saving:!1,error:null,saveMessage:"Saved"}}))}catch(A){f(X=>({...X,[y]:{...Es(y),...X[y],saving:!1,error:A instanceof ae?A.message:"Unable to save the file.",saveMessage:null}}))}}}async function jt(){if(!q.creating){B(y=>({...y,creating:!0,message:null,error:null}));try{const y=await Sl(M.provider);z(w=>[y,...w]),B(w=>({...w,creating:!1,message:"Backup created."}))}catch(y){B(w=>({...w,creating:!1,error:y instanceof ae?y.message:"Unable to create a config backup."}))}}}async function qe(y){if(!q.applyingId){B(w=>({...w,applyingId:y.id,message:null,error:null}));try{const w=await Cl(M.provider,y.id);B(A=>({...A,applyingId:null,message:w.status.state==="ready"?`Applied "${w.archive.label}" and restarted ${M.displayName}.`:`Applied "${w.archive.label}". ${M.displayName} state: ${w.status.state}.`}))}catch(w){B(A=>({...A,applyingId:null,error:w instanceof ae?w.message:"Unable to apply the config archive."}))}}}async function ut(y){const w=q.renameDraft.trim();if(!(!w||q.renamingId!==y.id)){B(A=>({...A,message:null,error:null}));try{const A=await kl(M.provider,y.id,{label:w});z(X=>X.map(ve=>ve.id===y.id?A:ve)),B(X=>({...X,renamingId:null,renameDraft:"",message:"Backup renamed."}))}catch(A){B(X=>({...X,error:A instanceof ae?A.message:"Unable to rename the config backup."}))}}}if(!pe)return null;const Le=e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-3 grid gap-2",children:[a.plugins.map(y=>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:y.name}),e.jsx("span",{className:"mt-1 block text-xs leading-5 text-[var(--theme-fg-muted)]",children:y.description}),e.jsx("span",{className:"mt-2 block text-[10px] uppercase tracking-[0.16em] text-[var(--theme-fg-muted)]",children:[...y.capabilities.artifactTypes.map(w=>w.type),...y.capabilities.threadPanels.map(w=>w.kind??w.id)].join(", ")||"utility"}),e.jsx("span",{className:"mt-1 block text-[10px] uppercase tracking-[0.16em] text-[var(--theme-fg-muted)]",children:y.source==="imported"?"Imported manifest":"Built-in module"})]}),e.jsx("input",{type:"checkbox",checked:y.enabled,onChange:w=>void a.setPluginEnabled(y.id,w.currentTarget.checked),className:"mt-1 h-4 w-4 shrink-0 accent-[var(--theme-accent-solid)]"})]},y.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:y=>{d(y.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})]}),mt=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:vi.map(y=>{const w=ge===y.value;return e.jsxs("button",{type:"button",onClick:()=>s==null?void 0:s.setThemeMode(y.value),className:`block rounded-[1rem] border px-3 py-2.5 text-left transition ${w?"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:y.label}),w?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:y.description})]},y.value)})})]}),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:oe}),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"})]}):Le]}),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:re.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:re.devHomeDraft,onChange:y=>I(w=>({...w,devHomeDraft:y.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 ct(),disabled:re.loading||re.saving||!re.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:re.saving?"Saving...":"Save"})]})]})]}),re.error?e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:re.error}):re.message?e.jsx("p",{className:"mt-2 text-xs text-emerald-300",children:re.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 be(),disabled:C.busy||E.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 rt(),disabled:C.busy||E.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:se.map(y=>{const w=y.installation,A=!w.installed&&!!w.installCommand,X=w.installed&&!!w.updateCommand,ve=E.saving&&E.operatingProvider===y.provider,Pe=A?"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:y.displayName}),e.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${y.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:y.enabled?"Ready":w.installed?y.status.state:"Not installed"})]}),e.jsxs("p",{className:"mt-1 truncate text-xs text-[var(--theme-fg-muted)]",children:["Version:"," ",w.installedVersion??(w.installed?"Installed":"Unavailable"),w.latestVersion?` · Latest: ${w.latestVersion}`:""]}),w.lastError?e.jsx("p",{className:"mt-1 line-clamp-2 text-xs text-rose-300",children:w.lastError}):null]}),A||X?e.jsx("button",{type:"button","aria-label":`${A?"Install":"Update"} ${y.displayName}`,onClick:()=>void fe(y.provider,A?"install":"update"),disabled:C.busy||E.saving||!A&&!X,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:ve?E.operatingAction==="install"?"Installing...":"Updating...":Pe}):null]},y.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}):E.message?e.jsx("p",{className:`mt-2 whitespace-pre-line text-xs ${E.message.includes("requires attention")?"text-amber-300":"text-emerald-300"}`,children:E.message}):E.error?e.jsx("p",{className:"mt-2 whitespace-pre-line text-xs text-rose-300",children:E.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:[M.displayName," exposes these editable files through its backend schema."]})]})}),e.jsxs("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:[W.map(y=>{const w=x[y.name]??{path:y.name,exists:!1,originalContent:"",draftContent:"",loading:!1},A=w.draftContent!==w.originalContent;return e.jsx("button",{type:"button",onClick:()=>R(y.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:y.label}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:y.description})]}),e.jsx("div",{className:"shrink-0",children:w.loading?e.jsx("span",{className:"text-[11px] uppercase tracking-[0.2em] text-[var(--theme-fg-muted)]",children:"Loading"}):A?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"}):w.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"})})]})},y.name)}),W.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]})]}),Y.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 jt(),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..."}):b.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."}):b.map(y=>{const w=q.renamingId===y.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:[w?e.jsxs("div",{className:"flex max-w-xl gap-2",children:[e.jsx("input",{"aria-label":`Rename ${y.label}`,value:q.renameDraft,onChange:A=>B(X=>({...X,renameDraft:A.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 ${y.label}`,onClick:()=>void ut(y),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(A=>({...A,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:y.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 ",Ni(y.createdAt)]}),W.map(A=>{var X;return e.jsxs("span",{className:"rounded-full border border-[var(--theme-border)] bg-[var(--theme-panel)] px-2 py-0.5 font-mono",children:[A.name,":"," ",(X=y.files[A.name])!=null&&X.exists?"saved":"missing"]},A.name)})]})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2",children:[e.jsx("button",{type:"button",onClick:()=>B(A=>({...A,renamingId:y.id,renameDraft:y.label,message:null,error:null})),disabled:w,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 qe(y),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===y.id?"Applying...":"Apply"})]})]})},y.id)})})]}):null]})})]});return t?e.jsxs("div",{className:"flex min-h-0 flex-col overflow-hidden",children:[mt,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:oe})]}),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:Le})]})]}):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:mt}),v&&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:v}),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 ${v}`,onClick:()=>void Ye(v),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:()=>R(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 ${v}`,value:k.draftContent,onChange:y=>f(w=>({...w,[v]:{...Es(v),...w[v],draftContent:y.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 ${v} here`})})]})}):null]})}function ki(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 v=!1;return $s().then(R=>{v||n(R.authenticated?R:null)}).catch(()=>{v||n(null)}),()=>{v=!0}},[s.pathname]),r.useEffect(()=>{o(!1)},[s.pathname]);const m=(a==null?void 0:a.user)??null,h=r.useMemo(()=>ki(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(v=>!v),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 Ci="http://127.0.0.1:8790",ba="remote-codex-control-plane-auth";function Ti(t){const s=t.baseUrl||Ci;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=Ti(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 yn(){window.localStorage.removeItem(ba)}function Ii(){return!!Qt()}function Ei({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 Ri({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 Pi({children:t}){return e.jsx("aside",{className:"control-explorer-panel",children:t})}function Ai({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 Ui=6e4,Oi=5e3,$i=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 Mi(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 Li(){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 Di(){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 Hi(){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 _i(){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 Bi(){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 Fi(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 Wi(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 qi(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 zi(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 Vi(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 Fe({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 Ji({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(_i,{})}),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(Bi,{})})]})}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 Gi(){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),[v,R]=r.useState(null),[x,f]=r.useState(null),[k,C]=r.useState([]),[P,b]=r.useState(null),[z,se]=r.useState([]),[F,E]=r.useState([]),[J,c]=r.useState([]),[_,re]=r.useState([]),[I,q]=r.useState(""),[B,ge]=r.useState(""),[pe,H]=r.useState(""),[he,T]=r.useState(null),[le,oe]=r.useState(null),[M,Y]=r.useState(null),[W,be]=r.useState(null),[fe,rt]=r.useState("farmaco"),[ct,Ye]=r.useState(null),[jt,qe]=r.useState(null),[ut,Le]=r.useState(null),[mt,y]=r.useState("Computational chemistry"),[w,A]=r.useState("Molecule study"),[X,ve]=r.useState("Plan calculation"),[Pe,ht]=r.useState("codex"),[Ae,wt]=r.useState(null),[Ge,ot]=r.useState(""),[Ke,Ze]=r.useState(null),[Et,Lt]=r.useState(null),[Gt,Kt]=r.useState(null),[ee,ie]=r.useState(null),[ue,me]=r.useState(!1),[ke,V]=r.useState(null),[Xe,$e]=r.useState(!1),[Qe,ft]=r.useState("summary"),[Dt,xt]=r.useState(()=>{var u;return((u=Qt())==null?void 0:u.displayName)??""}),[gs,bs]=r.useState(null),[vs,Nt]=r.useState(null),[Yt,gt]=r.useState(null),[ys,we]=r.useState(null),[lt,St]=r.useState(null),[Rt,js]=r.useState(null),[et,pt]=r.useState({projects:!1,workspaces:!1,sessions:!1,usageEvents:!1,harness:!1}),[Pt,ze]=r.useState("idle"),Te=r.useRef(null),Ht=r.useRef(null),kt=!!(s&&n),Ce=(o==null?void 0:o.state)==="running",ye=qi(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(()=>F.find(u=>u.id===I)??null,[F,I]),Q=r.useMemo(()=>J.find(u=>u.id===B)??null,[B,J]),te=r.useMemo(()=>_.find(u=>u.id===pe)??null,[pe,_]),ws=kt&&!!G,ts=kt&&!!Q&&Ce,Ns=zi(o),At=G?void 0:"Select a project before creating a workspace.",Ut=Q?Ce?void 0:"Start the sandbox before creating a session.":"Select a workspace before creating a session.",Ls=te?Ce?void 0:"Start the sandbox before connecting a session.":"Select a session before connecting.",Ct=Q?"session":G?"workspace":"project",_t=Ct==="project"?"Project":Ct==="workspace"?"Workspace":"Session",bt=ke==="project"?"Create project":ke==="workspace"?`Create workspace in ${(G==null?void 0:G.name)??"project"}`:ke==="session"?`Create session in ${(Q==null?void 0:Q.name)??"workspace"}`:"",Bt=ke==="workspace"?At:ke==="session"?Ut:void 0,Ss=[G==null?void 0:G.name,Q==null?void 0:Q.name,te==null?void 0:te.title].filter(Boolean).join(" / "),Zt=Vi(W,ut),Ds=W!=null&&W.modules.length?W.modules:["farmaco","quntur","estructural"],de=Ka(ct),Ot=Ka(jt),ss=Ga(ct),ns=Ga(jt),ks=((n==null?void 0:n.displayName)??(n==null?void 0:n.email)??"U").trim().charAt(0).toUpperCase()||"U",Hs=((v==null?void 0:v.inputTokens)??0)+((v==null?void 0:v.outputTokens)??0),it=(x==null?void 0:x.totalCostUsd)??Number((v==null?void 0:v.costUsd)??0)+Number((P==null?void 0:P.costUsd)??0),as=_.filter(u=>u.status==="active").length,_s=_.filter(u=>!u.workerSessionId).length,Bs=_.filter(u=>u.status==="failed"||u.status==="closed").length,Fs=[{label:"All",value:_.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=(te==null?void 0:te.lastActivityAt)??(te==null?void 0:te.updatedAt)??null,Tn=(o==null?void 0:o.lastSeenAt)??(o==null?void 0:o.updatedAt)??null,qs=Fi(o),In=Wi(o),En=(Q==null?void 0:Q.name)??(G==null?void 0:G.name)??"Control Plane",Rn=Ss||"Choose a project and workspace to manage sessions";async function Ve(u,N){Lt(u),Kt(null),ie(null),bs(null),Nt(null),gt(null),we(null),St(null),js(null);try{return await N()}catch(S){if(S instanceof ae&&S.payload.code==="gateway_unavailable"&&bs(S.message),S instanceof ae&&S.payload.code==="quota_exceeded"){const K=S.payload.details??{},Me=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(Me!==null&&He!==null?`${$t} quota exhausted (${He}/${Me}).`:"Quota exceeded.")}return S instanceof ae&&S.payload.code==="account_inactive"&&gt(S.message),S instanceof ae&&(S.statusCode===401||S.payload.code==="unauthorized")&&(we(S.message),yn()),S instanceof ae&&S.payload.code==="forbidden"&&js(S.message),Kt(S instanceof Error?S.message:`${u} failed.`),null}finally{Lt(null)}}async function Cs(u=s){if(u){pt(N=>({...N,projects:!0,usageEvents:!0}));try{const N=await ha(u),[S,K,Me,He]=await Promise.all([Cr(u),zo(u,10),Vo(u),Jo(u,10)]);d(N.user),m(N.sandbox),R(N.usage),f(N.billing??null),C(K.events),b(Me.usage),se(He.events),E(S.projects),xt(N.user.displayName??""),q($t=>S.projects.some(On=>On.id===$t)?$t:"")}finally{pt(N=>({...N,projects:!1,usageEvents:!1}))}}}async function zs(u=s,N=fe){if(!u||!Ce){be(null),Ye(null),qe(null),Le(null);return}pt(S=>({...S,harness:!0})),Le(null);try{const S=await al(u);be(S);const K=S.modules.includes(N)?N:S.modules[0]??N;if(rt(K),S.enabled&&S.keyPresent&&S.chemistryToolsEnabled){const[Me,He]=await Promise.all([La(u,K),Da(u,K)]);Ye(Me),qe(He)}else Ye(null),qe(null)}catch(S){be(null),Ye(null),qe(null),Le(S instanceof Error?S.message:"Harness status refresh failed.")}finally{pt(S=>({...S,harness:!1}))}}r.useEffect(()=>{s&&Ve("Load control plane",async()=>{await Cs(s),ie("Control plane session is ready.")})},[]),r.useEffect(()=>{if(!s||!B){re([]),H("");return}H(""),pt(u=>({...u,sessions:!0})),Ve("Load sessions",async()=>{try{const u=await ra(s,B);re(u.sessions)}finally{pt(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.")})},$i);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){be(null),Ye(null),qe(null),Le(null);return}zs(s,fe)},[s,Ce,o==null?void 0:o.updatedAt]),r.useEffect(()=>{if(!s||!I){c([]),ge(""),re([]),H("");return}ge(""),re([]),H(""),pt(u=>({...u,workspaces:!0})),Ve("Load workspaces",async()=>{try{const u=await aa(s,I);c(u.workspaces)}finally{pt(u=>({...u,workspaces:!1}))}})},[s,I]),r.useEffect(()=>()=>{Te.current&&clearTimeout(Te.current),vt()},[]),r.useEffect(()=>{function u(N){N.key==="Escape"&&(me(!1),V(null),T(null),$e(!1))}return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[]);function vt(){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"){vt();const S=Pn(u);Y(S),St(null),ze(N);const K=new WebSocket(S);Ht.current=K,K.addEventListener("open",()=>{Ht.current===K&&ze("ready")}),K.addEventListener("error",()=>{Ht.current===K&&(St("Sandbox route connection failed."),ze("idle"))}),K.addEventListener("close",Me=>{Ht.current===K&&(St(Me.reason||"Sandbox route closed before the session could stay connected."),ze("idle"))})}function Js(u){if(yt(),!u)return;const N=Date.parse(u.expiresAt);if(!Number.isFinite(N))return;const S=Math.max(Oi,N-Date.now()-Ui);Te.current=setTimeout(()=>{Ys()},S)}async function Ft(){yn(),a(null),d(null),m(null),g(null),R(null),C([]),js(null),E([]),c([]),re([]),b(null),se([]),oe(null),me(!1),V(null),yt(),ze("idle"),ie("Signed out locally.")}async function De(u){u.preventDefault(),s&&await Ve("Update profile",async()=>{const N=await Go(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 Ve("Create project",async()=>{const N=await Ko(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 Ve("Create workspace",async()=>{const N=await Xo(s,{projectId:G.id,name:w,slug:Dn(w)}),S=await aa(s,G.id);c(S.workspaces),ge(""),re([]),H(""),V(null),ie(`Workspace "${N.workspace.name}" created. Select it before creating a session.`)})}async function An(u){u.preventDefault(),!(!s||!Q||!Ce)&&await Ve("Create session",async()=>{const N=await Qo(s,Q.id,{provider:Pe,title:X}),S=await ra(s,Q.id);re(S.sessions),H(""),V(null),ie(`Session "${N.session.title}" created. Select it before connecting.`)})}async function Wt(u){s&&await Ve(`${u} sandbox`,async()=>{if(u==="start")m((await tl(s)).sandbox);else if(u==="stop")m((await sl(s)).sandbox),oe(null),Y(null),vt(),yt(),ze("idle");else if(u==="restart")m((await nl(s)).sandbox),oe(null),Y(null),vt(),yt(),ze("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)){pt(N=>({...N,harness:!0})),Le(null);try{const[N,S]=await Promise.all([La(s,u),Da(s,u)]);Ye(N),qe(S)}catch(N){Ye(null),qe(null),Le(N instanceof Error?N.message:"Harness module refresh failed.")}finally{pt(N=>({...N,harness:!1}))}}}async function os(){!s||!o||await Ve("Inspect sandbox",async()=>{const u=await rl(s,o.id);g(u),ie("Sandbox detail loaded.")})}async function ls(u="connecting",N=pe){return!s||!o||!Ce?null:Ve("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"||!pe)return;ze("reconnecting"),await ls("reconnecting",pe)||ze("idle")}function Xt(u){T(null),H(u.id),oe(null),Y(null),vt(),yt(),ze("idle"),ft("summary"),$e(!0)}function Zs(u){Xt(u),$e(!0)}function Xs(u,N){var S;N&&(T(null),(S=navigator.clipboard)==null||S.writeText(N),ie(`${u} copied.`))}function is(u,N){wt(u),ot(N),T(null)}function qt(){wt(null),ot("")}async function ds(u){if(u.preventDefault(),!s||!Ae)return;const N=Ge.trim();if(!N){Kt("Name is required.");return}const S=Ae;await Ve(`Rename ${S.type}`,async()=>{if(S.type==="project"){const K=await Yo(s,S.id,{name:N,slug:Dn(N)});E(Me=>Me.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(Me=>Me.map(He=>He.id===K.workspace.id?K.workspace:He))}else{const K=await $a(s,S.id,{title:N});re(Me=>Me.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=F.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=J.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=_.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||!Ke)return;const u=Ke;await Ve(`Delete ${u.type}`,async()=>{if(u.type==="project"){const N=await Zo(s,u.id);E(S=>S.filter(K=>K.id!==N.project.id)),I===N.project.id&&(q(""),ge(""),H(""),c([]),re([]))}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&&(ge(""),H(""),re([]))}else{const N=await $a(s,u.id,{status:"deleted"});re(S=>S.filter(K=>K.id!==N.session.id)),pe===N.session.id&&H("")}Ae&&Rs(Ae)===Rs(u)&&qt(),Ze(null),oe(null),Y(null),vt(),yt(),ze("idle"),ie(`${Ne(u.type)} deleted.`)})}async function Qs(u){!s||!Ce||await Ve("Close session",async()=>{const N=await el(s,u.id);re(S=>S.map(K=>K.id===N.session.id?N.session:K)),H(N.session.id),oe(null),Y(null),vt(),yt(),ze("idle"),ie("Session finalized and disconnected.")})}async function en(u){!s||!Ce||await Ve("Resume session",async()=>{const N=await Tr(s,u.id);re(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(Ai,{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:()=>$e(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:De,className:"control-inline-form",children:[e.jsx(dn,{label:"Display name",value:Dt,onChange:xt}),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:(v==null?void 0:v.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:(P==null?void 0:P.eventCount)??0})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Compute"}),e.jsx("strong",{children:Number((P==null?void 0:P.computeUnits)??0).toFixed(1)})]}),e.jsxs("div",{children:[e.jsx("span",{children:"LLM cost"}),e.jsxs("strong",{children:["$",Number((v==null?void 0:v.costUsd)??0).toFixed(2)]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Harness cost"}),e.jsxs("strong",{children:["$",Number((P==null?void 0:P.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(Fe,{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..."}):z.length===0?e.jsx("p",{className:"control-empty",children:"No Harness usage events yet."}):z.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,ee?e.jsx("div",{className:"control-alert success",children:ee}):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,ys?e.jsxs("div",{className:"control-alert warning",children:["Session expired: ",ys]}):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(Ke);return e.jsxs(e.Fragment,{children:[e.jsxs(Ri,{topBar:Un,alerts:tn,sidebar:null,main:null,inspector:null,inspectorOpen:Xe,children:[e.jsxs(Pi,{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:bt}),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:y}),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:w,onChange:A}),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:X,onChange:ve}),e.jsxs("label",{className:"control-field",children:[e.jsx("span",{children:"Provider"}),e.jsxs("select",{value:Pe,onChange:u=>ht(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:(Q==null?void 0:Q.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:(Q==null?void 0:Q.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:_.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:()=>{ft("summary"),$e(!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:["$",it.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..."}):F.length===0?e.jsx("p",{className:"control-empty",children:"No projects yet."}):F.map(u=>e.jsxs("div",{className:"control-tree-group",children:[Rs(Ae)===`project:${u.id}`?e.jsx(Bn,{label:"Project name",value:Ge,onChange:ot,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),ge(""),re([]),H(""),oe(null),Y(null),vt(),yt(),ze("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(Li,{})}),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:()=>Ze({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..."}):J.length===0?e.jsx("p",{className:"control-empty",children:"No workspaces in this project."}):J.map(N=>e.jsxs("div",{className:"control-tree-group",children:[Rs(Ae)===`workspace:${N.id}`?e.jsx(Bn,{label:"Workspace name",value:Ge,onChange:ot,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:()=>{ge(N.id),H(""),oe(null),Y(null),vt(),yt(),ze("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(Di,{})}),e.jsx("strong",{children:N.name}),e.jsx("small",{children:Mi(N)})]}),e.jsx(_n,{label:`workspace ${N.name}`,onEdit:()=>is({type:"workspace",id:N.id},N.name),onDelete:()=>Ze({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..."}):_.length===0?e.jsx("p",{className:"control-empty",children:"No sessions for this workspace."}):_.map(S=>e.jsx("div",{className:"control-tree-group",children:Rs(Ae)===`session:${S.id}`?e.jsx(Bn,{label:"Session title",value:Ge,onChange:ot,onCancel:qt,onSubmit:ds}):e.jsxs("div",{className:`control-tree-item ${pe===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(Hi,{})}),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:()=>Ze({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:(Q==null?void 0:Q.name)??(G==null?void 0:G.name)??"Select a workspace"}),e.jsx("p",{children:Q?`${(G==null?void 0:G.name)??"Project"} · ${As(Q.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:F.length})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Workspaces"}),e.jsx("strong",{children:J.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:Q?`${_.length} in workspace`:"Select workspace"})]}),Q?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..."}):_.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:_.map(u=>e.jsxs("article",{role:"listitem",className:`control-session-row ${pe===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(Ji,{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:te?"Selected session":Q?"Workspace context":G?"Project context":"Selection"}),e.jsx("span",{children:te?Ne(te.status):Q?As(Q.sourceType):G?Ne(G.status):"Root"})]}),te?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:te.title})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Provider"}),e.jsx("dd",{children:ln(te.provider)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Status"}),e.jsx("dd",{children:e.jsx("span",{className:`control-status-pill compact ${Mt(te.status)}`,children:Ne(te.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(te)})]})]}),e.jsxs("div",{className:"control-action-row start",children:[e.jsx(Oe,{onClick:()=>void en(te),disabled:!s||!Ce,title:Ce?void 0:"Start the sandbox before opening this session.",ariaLabel:`${te.workerSessionId?"Resume":"Start"} session ${te.title} from detail`,children:te.workerSessionId?"Resume":"Start sandbox session"}),e.jsx(Oe,{onClick:()=>{ft("metadata"),$e(!0)},children:"Details"})]})]}):Q?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:Q.name})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Project"}),e.jsx("dd",{children:(G==null?void 0:G.name)??Q.projectId})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Source"}),e.jsx("dd",{children:As(Q.sourceType)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Sessions"}),e.jsx("dd",{children:_.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:J.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:()=>$e(!1)}):null,e.jsxs(Ei,{eyebrow:te?"Session":Q?"Workspace":G?"Project":"Sandbox",hidden:!Xe,onClose:()=>$e(!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:()=>ft(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,te||Q||G?e.jsxs("div",{className:"control-inspector-section",children:[e.jsxs("div",{className:"control-panel-heading compact",children:[e.jsx("h2",{children:te?"Session":Q?"Workspace":"Project"}),e.jsx("span",{children:te?Ne(te.status):Q?As(Q.sourceType):Ne(G==null?void 0:G.status)})]}),e.jsx("dl",{className:"control-detail-list compact summary",children:te?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Title"}),e.jsx("dd",{children:te.title})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Provider"}),e.jsx("dd",{children:ln(te.provider)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Runtime"}),e.jsx("dd",{children:Hn(te)})]})]}):Q?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Workspace"}),e.jsx("dd",{children:Q.name})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Sessions"}),e.jsx("dd",{children:_.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:J.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,fe),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:W!=null&&W.keyPresent?"Present":"Not present"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Chemistry"}),e.jsx("dd",{children:W!=null&&W.chemistryToolsEnabled?"Enabled":"Disabled"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Health"}),e.jsx("dd",{children:W!=null&&W.health?"OK":"Not available"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Module"}),e.jsx("dd",{children:rn[fe]})]}),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:[te?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(Fe,{label:"Session ID",value:te.id}),e.jsx(Fe,{label:"Worker session",value:te.workerSessionId}),e.jsx(Fe,{label:"Workspace ID",value:te.workspaceId}),e.jsx(Fe,{label:"Sandbox ID",value:te.sandboxId}),e.jsxs("div",{children:[e.jsx("dt",{children:"Created"}),e.jsx("dd",{children:te.createdAt})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Updated"}),e.jsx("dd",{children:te.updatedAt})]})]})]}):null,Q?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(Fe,{label:"Workspace ID",value:Q.id}),e.jsx(Fe,{label:"Project ID",value:Q.projectId}),e.jsx(Fe,{label:"Path",value:Q.path}),e.jsxs("div",{children:[e.jsx("dt",{children:"Slug"}),e.jsx("dd",{children:Q.slug})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Created"}),e.jsx("dd",{children:Q.createdAt})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Updated"}),e.jsx("dd",{children:Q.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(Fe,{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(Fe,{label:"Sandbox ID",value:o.id}),e.jsx(Fe,{label:"Image",value:o.image}),e.jsx(Fe,{label:"Worker ID",value:o.workerServiceName}),e.jsx(Fe,{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",pe),disabled:!Ce||!te,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:(te==null?void 0:te.title)??pe})]}),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:te?`Selected session: ${te.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(Fe,{label:"Router URL",value:le.routerBaseUrl}),e.jsx(Fe,{label:"WebSocket URL",value:le.wsBaseUrl}),e.jsx(Fe,{label:"Worker socket",value:M}),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":fe===u,className:fe===u?"selected":"",onClick:()=>void rs(u),disabled:et.harness||!(W!=null&&W.enabled)||!W.keyPresent,children:rn[u]},u))}),e.jsxs("dl",{className:"control-detail-list",children:[e.jsx(Fe,{label:"Base URL",value:W==null?void 0:W.baseUrl}),e.jsxs("div",{children:[e.jsx("dt",{children:"Enabled"}),e.jsx("dd",{children:W!=null&&W.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[fe]," 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"})]},`${fe}-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"})]},`${fe}-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:!!Ke,title:sn.title,description:sn.description,confirmLabel:"Delete",busy:!!(Et!=null&&Et.startsWith("Delete ")),onCancel:()=>Ze(null),onConfirm:Is})]})}const Ki="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(Ii())}),()=>{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 Yi(t){return{baseUrl:t.baseUrl,token:t.token}}function Zi(){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 Xi(){var re;const t=at(),s=es(),a=Qt(),[n,d]=r.useState("login"),[o,m]=r.useState((a==null?void 0:a.baseUrl)??Ki),[h,g]=r.useState((a==null?void 0:a.email)??"dev@example.com"),[v,R]=r.useState((a==null?void 0:a.displayName)??"Developer"),[x,f]=r.useState(""),[k,C]=r.useState(!1),[P,b]=r.useState(null),[z,se]=r.useState(null),F=s.state,E=((re=F==null?void 0:F.from)==null?void 0:re.pathname)??"/control-plane",J=r.useMemo(()=>{if(typeof window>"u")return;const I=new URL(window.location.href);return I.search="",I.toString()},[]);r.useEffect(()=>{const I=Zi();if(!I)return;if(I.error){se(`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(Yi(q)).then(B=>{xn({...q,email:B.user.email,displayName:B.user.displayName}),t("/control-plane",{replace:!0})}).catch(B=>{yn(),se(B instanceof Error?B.message:"Unable to finish OAuth sign in.")})},[t]);async function c(I){I.preventDefault(),C(!0),se(null),b(null);try{const q=n==="register"?await Wo(o,{email:h,password:x,displayName:v||null}):await qo(o,{email:h,password:x});xn({baseUrl:o,token:q.session.token,expiresAt:q.session.expiresAt,email:q.user.email,displayName:q.user.displayName}),b("Account session is ready."),t(E,{replace:!0})}catch(q){q instanceof ae&&q.payload.code==="conflict"?se("An account already exists for this email. Use sign in instead."):se(q instanceof Error?q.message:"Unable to authenticate.")}finally{C(!1)}}function _(I){window.location.assign(Fo(o,I,J))}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:()=>_("google"),children:"Continue with Google"}),e.jsx("button",{type:"button",onClick:()=>_("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:v,onChange:I=>R(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)})]}),z?e.jsx("p",{className:"control-auth-error",children:z}):null,P?e.jsx("p",{className:"control-auth-message",children:P}):null,e.jsx("button",{type:"submit",className:"control-primary-button",disabled:k,children:k?"Working...":n==="register"?"Create account":"Sign in"})]})]})})}function Qi(t){return t.sandboxMode??(t.approvalMode==="guarded"?"workspace-write":"danger-full-access")}function ed(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 td(t,s){return{...t,pendingRequests:[...t.pendingRequests.filter(a=>a.id!==s.id),s]}}function sd(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 nd(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 v=typeof s.sequence=="number"&&Number.isFinite(s.sequence)?s.sequence:typeof t.sequence=="number"&&Number.isFinite(t.sequence)?t.sequence:null;v!==null&&g.sequence!==v&&(g={...g,sequence:v});const R=typeof s.transcriptOrder=="number"&&Number.isFinite(s.transcriptOrder)?s.transcriptOrder:typeof t.transcriptOrder=="number"&&Number.isFinite(t.transcriptOrder)?t.transcriptOrder:null;return R!==null&&g.transcriptOrder!==R&&(g={...g,transcriptOrder:R}),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 ad(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])),R=[...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 R.length===0?null:{turnId:s.turnId,items:R,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 rd(t){return`${t.threadId}:${t.objective}:${t.createdAt}`}function od(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=rd(a),d=s.get(n);s.set(n,d?od(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 ld(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 id(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 dd(){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 cd(t,s){return t.find(a=>Us(a,s))??(s.includes("[PHOTO ")?t.find(a=>gn(a,s))??null:null)}function ud(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 md=3e3,hd=6e4,pd=5e3,fd=2147e6,xd=["worker:read","worker:write","session:prompt","provider:turn:create","provider:turn:interrupt"];function gd(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 bd({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 vd(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,v=t.item,R=h?vd(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)??v.kind}),e.jsx("h2",{children:(h==null?void 0:h.title)??(g==null?void 0:g.title)??v.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}):R?e.jsxs("div",{className:"control-artifact-source",children:[e.jsxs("div",{children:[e.jsx("span",{children:R.format}),R.name?e.jsx("strong",{children:R.name}):null]}),e.jsx("pre",{children:R.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:v.text||v.previewText||(h==null?void 0:h.summaryText)||"Artifact created"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Status"}),e.jsx("dd",{children:v.status??"completed"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Source turn"}),e.jsx("dd",{children:(h==null?void 0:h.sourceTurnId)??v.sourceTurnId??"not assigned"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Source item"}),e.jsx("dd",{children:(h==null?void 0:h.sourceItemId)??v.id})]})]})}):null,n==="metadata"?e.jsxs("dl",{className:"control-detail-list",children:[e.jsx(Re,{label:"Timeline item id",value:v.id}),e.jsx(Re,{label:"Timeline kind",value:v.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:v,detail:g},null,2)})})]})]}):null]})]})}const jd=[],wd=[],Nd=[],Sd={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 kd(){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 Cd(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 Td={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 ae&&t.statusCode===401&&t.payload.code==="invalid_route_token"}function sr(t){return t instanceof ae&&(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 Id(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 Ed(){return e.jsx(Rd,{})}function Rd(){const{sessionId:t=""}=ur(),s=at(),a=Jt(),n=r.useMemo(kd,[]),[d,o]=r.useState(null),[m,h]=r.useState(null),[g,v]=r.useState(null),[R,x]=r.useState([]),[f,k]=r.useState(null),[C,P]=r.useState(null),[b,z]=r.useState(null),[se,F]=r.useState({prompt:"",attachments:[]}),[E,J]=r.useState(!0),[c,_]=r.useState(!1),[re,I]=r.useState(null),[q,B]=r.useState(0),[ge,pe]=r.useState("chat"),[H,he]=r.useState(!0),[T,le]=r.useState(null),oe=r.useRef(!1),M=r.useRef(null),Y=r.useRef(null),W=r.useCallback(ee=>{z(ie=>{const ue=Id(ie,ee);return Y.current=ue,ue})},[]),be=r.useCallback(async ee=>{if(!n)return null;const ie=await Ir(n,ee.sandbox.id,{projectId:ee.project.id,workspaceId:ee.workspace.id,sessionId:ee.session.id,scopes:xd});return P(ie),ie},[n]),fe=r.useCallback(async()=>!d||!m||!g||!f||d.state!=="running"?null:be({sandbox:d,project:m,workspace:g,session:f}),[be,m,d,f,g]),rt=r.useCallback(async()=>{if(!n)return s("/control-plane/login",{replace:!0}),null;J(!0),I(null);try{const ee=await ha(n);if(o(ee.sandbox),ee.sandbox.state!=="running")return k(null),P(null),z(null),Y.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(xt=>xt.id===t);if(!Xe)continue;const $e=await Tr(n,Xe.id),Qe=V.sessions.map(xt=>xt.id===$e.session.id?$e.session:xt),ft=await be({sandbox:ee.sandbox,project:ue,workspace:ke,session:$e.session});if(!ft)return I("Unable to issue a router token for this session."),null;if(h(ue),v(ke),x(Qe),k($e.session),!$e.session.workerSessionId)return z(null),Y.current=null,I("Session resumed, but the worker did not return a thread id."),null;const Dt=await us(ft,$e.session.workerSessionId);return W(Dt),B(xt=>xt+1),{session:$e.session,token:ft,detail:Dt}}}return I("Session was not found in any project workspace."),null}catch(ee){return ee instanceof ae&&ee.payload.code==="unauthorized"?(yn(),s("/control-plane/login",{replace:!0}),null):(I(ee instanceof Error?ee.message:"Unable to open control-plane session."),null)}finally{J(!1)}},[W,n,be,s,t]);r.useEffect(()=>{rt()},[rt]),r.useEffect(()=>{le(null)},[t]),r.useEffect(()=>{if(M.current&&(window.clearTimeout(M.current),M.current=null),!C)return;const ee=Date.parse(C.expiresAt);if(!Number.isFinite(ee))return;const ie=Math.max(pd,Math.min(fd,ee-Date.now()-hd));return M.current=window.setTimeout(()=>{fe().catch(ue=>{I(ue instanceof Error?ue.message:"Unable to refresh router token.")})},ie),()=>{M.current&&(window.clearTimeout(M.current),M.current=null)}},[fe,C]);const ct=r.useCallback(async(ee={})=>{if(!(!C||!(f!=null&&f.workerSessionId))){ee.silent||I(null);try{W(await us(C,f.workerSessionId))}catch(ie){if(Wn(ie))try{const ue=await fe();if(ue&&f.workerSessionId){W(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.")}}},[W,rt,fe,C,f==null?void 0:f.workerSessionId]);r.useEffect(()=>{if(!((b==null?void 0:b.thread.status)==="running"||!!(b!=null&&b.thread.activeTurnId)||c)||!C||!(f!=null&&f.workerSessionId))return;const ie=window.setInterval(()=>{ct({silent:!0})},md);return()=>window.clearInterval(ie)},[b==null?void 0:b.thread.activeTurnId,b==null?void 0:b.thread.status,ct,C,c,f==null?void 0:f.workerSessionId]);async function Ye(ee){const ie=ee.prompt.trim();if(!ie||!C||!(f!=null&&f.workerSessionId))return!1;_(!0),I(null);try{return await $n(C,f.workerSessionId,{prompt:ie}),F({prompt:"",attachments:[]}),await ct(),B(ue=>ue+1),!0}catch(ue){if(Wn(ue))try{const me=await fe();if(!me||!f.workerSessionId)throw ue;await $n(me,f.workerSessionId,{prompt:ie});const ke=await us(me,f.workerSessionId);return W(ke),F({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 W(ke),F({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{_(!1)}}async function jt(){var ee,ie;if(!(!C||!(f!=null&&f.workerSessionId))){_(!0),I(null);try{const ue=((ee=Y.current)==null?void 0:ee.thread.activeTurnId)??void 0,me=await Ha(C,f.workerSessionId,ue?{turnId:ue}:{});z(ke=>ke&&{...ke,thread:me}),await ct({silent:!0})}catch(ue){if(Wn(ue))try{const me=await fe();if(!me||!f.workerSessionId)throw ue;const ke=((ie=Y.current)==null?void 0:ie.thread.activeTurnId)??void 0,V=await Ha(me,f.workerSessionId,ke?{turnId:ke}:{});z(Xe=>Xe&&{...Xe,thread:V}),W(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{_(!1)}}}const qe=C?f!=null&&f.workerSessionId?void 0:"Reconnect this session before sending a prompt.":"Waiting for a router token...",ut=g?R.map(ee=>tr(ee,g,ee.id===(f==null?void 0:f.id)?b:null)):[],Le=f&&g?tr(f,g,b):null,mt=Le&&ut.every(ee=>ee.id!==Le.id)?[Le,...ut]:ut,y=(b==null?void 0:b.thread.status)??Vr(f==null?void 0:f.status),w=fr(y),A=(b==null?void 0:b.thread.lastTurnStartedAt)??(b==null?void 0:b.thread.updatedAt)??(f==null?void 0:f.lastActivityAt)??(f==null?void 0:f.updatedAt)??null,X=(f==null?void 0:f.provider)??(b==null?void 0:b.thread.provider)??"codex",ve=(b==null?void 0:b.thread.model)??"default model",Pe=(C==null?void 0:C.expiresAt)??null,ht=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:w})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Provider"}),e.jsx("dd",{children:X})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Workspace"}),e.jsx("dd",{children:(g==null?void 0:g.name)??(b==null?void 0:b.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:ve})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Last activity"}),e.jsx("dd",{children:gd(A)})]})]}),e.jsx(bd,{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)??(b==null?void 0:b.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(Pe)})]})})]}),Ae=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:E,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:E?"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"})]})}),wt=r.useCallback(ee=>{le({kind:"artifact",...ee})},[]),Ge=r.useCallback(ee=>{le({kind:"historyDetail",...ee})},[]),ot=r.useCallback(async ee=>{if(!C||!(f!=null&&f.workerSessionId))throw new Error("Reconnect this session before loading item details.");return ol(C,f.workerSessionId,ee)},[C,f==null?void 0:f.workerSessionId]),Ke=r.useMemo(()=>({scrollRequestKey:q,className:"thread-timeline-surface min-h-0 flex-1",onTailVisibilityChange:he,answeredRequestNotes:(b==null?void 0:b.answeredRequestNotes)??jd,activityNotes:(b==null?void 0:b.activityNotes)??wd,pendingSteers:(b==null?void 0:b.pendingSteers)??Nd,onLoadHistoryItemDetail:ot,onSelectArtifact:wt,onSelectHistoryItemDetail:Ge}),[b==null?void 0:b.activityNotes,b==null?void 0:b.answeredRequestNotes,b==null?void 0:b.pendingSteers,wt,Ge,ot,q]),Ze=b?{busy:c,error:re,model:b.thread.model,reasoningEffort:b.thread.reasoningEffort,fastMode:b.thread.fastMode??!1,collaborationMode:b.thread.collaborationMode,contextUsage:b.thread.contextUsage,capabilities:Sd,toolboxItems:[],followTail:H,threadConnected:b.thread.isLoaded,disabled:!!qe,...qe?{disabledPlaceholder:qe}:{},draftPrompt:se.prompt,draftAttachments:se.attachments,onDraftChange:F,canInterrupt:!!b.thread.activeTurnId,onInterrupt:jt,shellControlState:Td,onToggleView:()=>pe("shell"),onToggleFollow:()=>B(ee=>ee+1)}:null,Et=e.jsx("span",{className:"control-session-status-badge",children:w}),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:()=>pe("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(ee=>C&&(f!=null&&f.workerSessionId)?Cd(C,f.workerSessionId,ee):"",[C,f==null?void 0:f.workerSessionId]),Kt=r.useMemo(()=>({openThread:ee=>{s(`/control-plane/sessions/${ee}`)},getThreadHref:ee=>`/control-plane/sessions/${ee}`,getNewThreadHref:()=>"/control-plane",sendPrompt:Ye,interrupt:jt,getImageAssetUrl:Gt,shell:null}),[Gt,s]);return e.jsxs("div",{className:"control-chat-workspace",children:[e.jsx(pr,{threads:mt,detail:b,status:null,loading:E,error:E?null:re,adapter:Kt,currentWorkspaceId:(g==null?void 0:g.id)??null,currentWorkspaceLabel:(g==null?void 0:g.name)??(b==null?void 0:b.workspace.label)??null,metaContent:ht,settingsContent:Ae,surfaceActions:Et,appMenuButton:e.jsx(go,{}),appNavigationMenu:e.jsx(xo,{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:ge,timelineProps:Ke,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}:{},...Ze?{composerProps:Ze}:{}}),T?e.jsx("div",{className:"control-artifact-inspector-overlay",children:e.jsx(yd,{selected:T,onClose:()=>le(null)})}):null]})}function Pd({onLogin:t}){const[s,a]=r.useState(""),[n,d]=r.useState(""),[o,m]=r.useState(null),[h,g]=r.useState(!1);async function v(R){R.preventDefault(),m(null),g(!0);try{await t({username:s,password:n})}catch(x){x instanceof ae?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:v,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:R=>a(R.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:R=>d(R.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 ae?t.payload.message:t instanceof Error?t.message:s}function Ad(){var I;const[t,s]=r.useState(null),[a,n]=r.useState(""),[d,o]=r.useState(""),[m,h]=r.useState(""),[g,v]=r.useState(""),[R,x]=r.useState(!0),[f,k]=r.useState(!1),[C,P]=r.useState(!1),[b,z]=r.useState(null),[se,F]=r.useState(null),[E,J]=r.useState(!1);async function c(){var q;x(!0),F(null);try{xs();const B=await $s();s(B),n(((q=B.user)==null?void 0:q.username)??"")}catch(B){F(zn(B,"Unable to load account."))}finally{x(!1)}}r.useEffect(()=>{c()},[]);async function _(q){q.preventDefault(),k(!0),F(null),z(null);try{const B=await ml({username:a});s(ge=>ge!=null&&ge.authenticated?{...ge,user:B}:ge),n(B.username),z("Account updated.")}catch(B){F(zn(B,"Unable to update account."))}finally{k(!1)}}async function re(q){q.preventDefault(),P(!0),F(null),z(null);try{if(m!==g){F("New passwords do not match.");return}await hl({currentPassword:d,newPassword:m}),o(""),h(""),v(""),z("Password changed.")}catch(B){F(zn(B,"Unable to change password."))}finally{P(!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"})]}),R?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:[se?e.jsx(nr,{tone:"danger",children:se}):null,b?e.jsx(nr,{tone:"success",children:b}):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:_,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:()=>J(!0),type:"button",children:[E?e.jsx(nt.CheckCircle2,{className:"h-4 w-4"}):e.jsx(nt.MailCheck,{className:"h-4 w-4"}),E?"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:re,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:v}),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 ae?t.payload.message:t instanceof Error?t.message:"Unable to update relay admin state."}function Ud(){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 xl())}catch(x){o(Jn(x))}finally{n(!1)}}r.useEffect(()=>{g()},[]);async function v(x){h("registration"),o(null);try{const f=await gl(x);s(k=>k&&{...k,registrationEnabled:f.registrationEnabled})}catch(f){o(Jn(f))}finally{h(null)}}async function R(x,f){h(x),o(null);try{const k=await bl(x,f);s(C=>C&&{...C,users:C.users.map(P=>P.id===k.id?k:P)})}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 v(!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 R(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 ae?t.payload.message:t instanceof Error?t.message:s}function Od(){const t=at(),[s,a]=r.useState(null),[n,d]=r.useState(""),[o,m]=r.useState(null),[h,g]=r.useState(null),[v,R]=r.useState(!0),[x,f]=r.useState(null),[k,C]=r.useState(null);async function P(){R(!0),C(null);try{xs(),a(await Rr())}catch(E){C(Gn(E,"Unable to load devices."))}finally{R(!1)}}r.useEffect(()=>{P()},[]);async function b(E){E.preventDefault(),f("create"),C(null);try{const J=await Pr({name:n});m(J),d(""),await P()}catch(J){C(Gn(J,"Unable to create device."))}finally{f(null)}}async function z(E){f(E.id),C(null);try{await Ar(E.id),(o==null?void 0:o.device.id)===E.id&&m(null),await P()}catch(J){C(Gn(J,"Unable to delete device."))}finally{f(null)}}function se(E){bn(E.id),vn(null),t("/workspaces")}async function F(E){var c;const J=(o==null?void 0:o.device.id)===E.id?o.token:null;try{await((c=navigator.clipboard)==null?void 0:c.writeText(Gr(J))),g(E.id),window.setTimeout(()=>{g(_=>_===E.id?null:_)},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 P(),type:"button",children:[e.jsx(nt.RefreshCcw,{className:"h-4 w-4"}),"Refresh"]})]}),k?e.jsx(Ld,{tone:"danger",children:k}):null,o?e.jsx(Md,{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:b,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:E=>d(E.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})]}),v?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(E=>e.jsx($d,{busy:x===E.id,copiedSetup:h===E.id,device:E,onConnect:()=>se(E),onCopySetup:()=>void F(E),onDelete:()=>void z(E),setupTokenAvailable:(o==null?void 0:o.device.id)===E.id},E.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 $d({device:t,busy:s,copiedSetup:a,onConnect:n,onCopySetup:d,onDelete:o,setupTokenAvailable:m}){return 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.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":"Copy setup command with a token placeholder. Existing device tokens are not shown again.",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"]})]})]})})}function Md({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 Ld({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=Dd();return[`REMOTE_CODEX_RELAY_SERVER_URL=${rr(s)} \\`,`REMOTE_CODEX_RELAY_AGENT_TOKEN=${rr(t??"<device-token>")} \\`,"remote-codex relay-supervisor"].join(`
6
- `)}function rr(t){return/^[A-Za-z0-9_./:@%+=,~-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function Dd(){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 ae?t.payload.message:t instanceof Error?t.message:s}function Kr(){var E,J;const t=at(),[s,a]=r.useState(null),[n,d]=r.useState(null),[o,m]=r.useState(!0),[h,g]=r.useState(null),[v,R]=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(){R(null),await x()}async function k(c){const _=await Pr({name:c});R(_),await x()}async function C(c){await Ar(c),await x()}async function P(c){await pl(c),await x()}async function b(c){await fl(c),await x()}async function z(){await Er(),a(await $s()),d(null),R(null)}function se(c){bn(c),vn(null),t("/workspaces")}function F(c,_){bn(c),vn(_),t(`/threads/${encodeURIComponent(_)}`)}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:(E=s.user)==null?void 0:E.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:[((J=s.user)==null?void 0:J.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 z(),type:"button",children:"Sign out"})]})]}),h?e.jsx(da,{tone:"danger",children:h}):null,v?e.jsxs(da,{tone:"accent",children:["Device token for ",v.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:v.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:Fd(v.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(_d,{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:()=>se(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:()=>F(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(Bd,{devices:(n==null?void 0:n.devices)??[],onShare:P})})]}),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 b(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(Hd,{registrationEnabled:(s==null?void 0:s.registrationEnabled)??!0,initialError:h,onAuthenticated:f})})}function Hd({registrationEnabled:t,initialError:s,onAuthenticated:a}){const[n,d]=r.useState("login"),[o,m]=r.useState(""),[h,g]=r.useState(""),[v,R]=r.useState(""),[x,f]=r.useState(""),[k,C]=r.useState(""),[P,b]=r.useState(s),[z,se]=r.useState(!1);async function F(E){E.preventDefault(),se(!0),b(null);try{n==="login"?await cl({identifier:o,password:x}):await ul({email:h,username:v,password:x,registrationPassword:k}),await a()}catch(J){b(kn(J,"Unable to authenticate with relay."))}finally{se(!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:F,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:R,value:v}),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}),P?e.jsx(da,{tone:"danger",children:P}):null,e.jsx("button",{className:"relay-button-primary h-11 w-full",disabled:z,type:"submit",children:z?"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 _d({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(v){m(kn(v,"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 Bd({devices:t,onShare:s}){const a=r.useMemo(()=>{var b;return((b=t[0])==null?void 0:b.id)??""},[t]),[n,d]=r.useState(a),[o,m]=r.useState(""),[h,g]=r.useState(""),[v,R]=r.useState(""),[x,f]=r.useState(!1),[k,C]=r.useState(null);r.useEffect(()=>{!n&&a&&d(a)},[n,a]);async function P(b){b.preventDefault(),f(!0),C(null);try{await s({targetUsername:o,deviceId:n,threadId:h,...v.trim()?{label:v}:{}}),m(""),g(""),R(""),C("Invitation created.")}catch(z){C(kn(z,"Unable to create invitation."))}finally{f(!1)}}return e.jsxs("form",{className:"space-y-3",onSubmit:P,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:b=>d(b.target.value),value:n,children:t.map(b=>e.jsx("option",{value:b.id,children:b.name},b.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:R,value:v}),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 Fd(t){return`REMOTE_CODEX_RELAY_SERVER_URL=${Wd()} REMOTE_CODEX_RELAY_AGENT_TOKEN=${t} remote-codex relay-supervisor`}function Wd(){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,qd=10,zd=1e3,Vd=2e3,Zn=5500,Jd=3e3,Xn=0,ms=1,mn=3,Gd=["read-only","workspace-write","danger-full-access"],Kd=[],Yd=[],Zd=[],Xd={workspace:!0,toolUsage:!1,guide:!1,threadGraph:!1,extensions:!1,defaultTab:"workspace"};function Qd(){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 ec(){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 tc(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 sc(){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),v=r.useRef(null),R=r.useRef(null),x=r.useRef(typeof navigator>"u"?!0:navigator.onLine),f=r.useRef(!1),k=r.useRef(null),C=r.useRef(null),P=r.useRef(0),b=r.useRef(0),z=r.useRef(null),se=r.useRef(null),F=r.useRef(null),E=r.useRef(null),J=r.useRef(new Set),[c,_]=r.useState(null),[re,I]=r.useState([]),[q,B]=r.useState([]),[ge,pe]=r.useState(null),[H,he]=r.useState(null),[T,le]=r.useState(null),[oe,M]=r.useState(""),[Y,W]=r.useState(null),[be,fe]=r.useState(null),[rt,ct]=r.useState(!0),[Ye,jt]=r.useState(0),[qe,ut]=r.useState(!0),[Le,mt]=r.useState(!1),[y,w]=r.useState(!1),[A,X]=r.useState("chat"),ve=n.getThreadPanels().some(l=>l.kind==="terminal"),Pe=r.useMemo(()=>({fetchState:Wl,createShell:Vl,terminateShell:Jl,updateShell:Gl,connectSocket:fi}),[]),ht=r.useCallback(l=>`/threads/${l}`,[]),Ae=r.useCallback(l=>{s(`/threads/${l}`)},[s]),wt=r.useCallback(l=>l?`/threads/new?workspaceId=${encodeURIComponent(l)}`:"/threads/new",[]),Ge=r.useCallback(({threadId:l,path:i})=>`/api/threads/${l}/assets/image?path=${encodeURIComponent(i)}`,[]),[ot,Ke]=r.useState({prompt:"",attachments:[]}),[Ze,Et]=r.useState(!1),[Lt,Gt]=r.useState(0),[Kt,ee]=r.useState(0),[ie,ue]=r.useState(0),[me,ke]=r.useState(!1),[V,Xe]=r.useState(null),[$e,Qe]=r.useState(!1),[ft,Dt]=r.useState(!1),[xt,gs]=r.useState(!1),[bs,vs]=r.useState(null),[Nt,Yt]=r.useState("idle"),[gt,ys]=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([]),[js,et]=r.useState({status:"idle",data:null,error:null}),[pt,Pt]=r.useState({status:"idle",data:null,error:null}),[ze,Te]=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),[Q,te]=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}),[bt,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(()=>{M(i=>i+l)})},[]),ns=r.useCallback(l=>{d.current+=l,o.current===null&&(o.current=window.requestAnimationFrame(()=>{ss()}))},[ss]),ks=r.useCallback((l,i)=>{fe(p=>{const U=(p==null?void 0:p.turnId)===l?p.items:[],$=U.findIndex(Ue=>Ue.id===i.id),Z=qr(U[$],i),ce=$>=0?U.map((Ue,D)=>D===$?Z:Ue):[...U,Z];return{turnId:l,items:ce,updatedAt:new Date().toISOString()}})},[]),Hs=r.useCallback((l,i,p,U)=>{fe($=>{const Z=($==null?void 0:$.turnId)===l?$.items:[],ce=Z.find(_e=>_e.id===i),Ue=(ce==null?void 0:ce.kind)==="agentMessage"?{...ce,text:`${ce.text}${p}`,sequence:U??ce.sequence??null}:{id:i,kind:"agentMessage",text:p,sequence:U},D=Z.findIndex(_e=>_e.id===i),Je=D>=0?Z.map((_e,Be)=>Be===D?Ue:_e):[...Z,Ue];return{turnId:l,items:Je,updatedAt:new Date().toISOString()}})},[]),it=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}),Te({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 _l(t);_t({status:"ready",data:l,error:null})}catch(l){const i=l instanceof ae?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 Fl(t,l),U=URL.createObjectURL(i),$=document.createElement("a");$.href=U,$.download=p,document.body.append($),$.click(),$.remove(),window.setTimeout(()=>URL.revokeObjectURL(U),3e4),At(!1)}catch(i){const p=i instanceof ae?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=F.current)==null?void 0:i.goal)??null,error:null}});try{const l=await Ql(t);ye({status:"ready",data:l.goal,error:null}),_(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 ae?l.payload.message:"Unable to load goal."}))}}}async function Fs(l){if(t){ye(i=>{var p;return{status:"loading",data:i.data??((p=F.current)==null?void 0:p.goal)??null,error:null}});try{const i=await ei(t,l);ye({status:"ready",data:i.goal,error:null}),_(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 ae?i.payload.message:"Unable to update goal."})),i}}}async function Cn(){if(t){ye(l=>{var i;return{status:"loading",data:l.data??((i=F.current)==null?void 0:i.goal)??null,error:null}});try{const l=await ti(t);ye({status:"ready",data:null,error:null}),_(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 ae?l.payload.message:"Unable to clear goal."})),l}}}async function Ws(l){te(!0);try{await Fs({status:l})}finally{te(!1)}}async function Tn(){te(!0);try{await Cn()}finally{te(!1)}}async function qs(){if(t){et(l=>({status:"loading",data:l.data,error:null}));try{const l=await ni(t);et({status:"ready",data:l,error:null})}catch(l){et(i=>({status:"failed",data:i.data,error:l instanceof ae?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 ai(t);Pt({status:"ready",data:l,error:null})}catch(l){Pt(i=>({status:"failed",data:i.data,error:l instanceof ae?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 ri(t);Te({status:"ready",data:l,error:null})}catch(l){Te(i=>({status:"failed",data:i.data,error:l instanceof ae?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 oi(t,l);Te({status:"ready",data:i,error:null})}catch(i){throw Te(p=>({status:"failed",data:p.data,error:i instanceof ae?i.payload.message:"Unable to create hook."})),i}}}async function Ve(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 ae?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 ii(t,l);Te({status:"ready",data:i,error:null})}catch(i){throw Te(p=>({status:"failed",data:p.data,error:i instanceof ae?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 di(t,l);Te({status:"ready",data:i,error:null})}catch(i){throw Te(p=>({status:"failed",data:p.data,error:i instanceof ae?i.payload.message:"Unable to untrust hook."})),i}}}async function vt(){if(t){kt(l=>({status:"loading",data:l.data,error:null}));try{const l=await si(t);kt({status:"ready",data:l,error:null})}catch(l){kt(i=>({status:"failed",data:i.data,error:l instanceof ae?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=E.current,p=i&&Object.keys(i).length>0?{...l,thread:{...l.thread,...i}}:l,U=F.current;F.current=p,W(p.livePlan??null);const $=U?zt(U.turns,p.turns):p.turns;fe(D=>ad(D,p.liveItems??null,$)),ye(D=>D.status==="idle"?D:{...D,data:p.goal??null});const Z=p.thread.activeTurnId===null&&p.thread.status!=="running";_(D=>D&&!p.goalHistory?{...p,turns:zt(D.turns,p.turns),pendingRequests:ia(D.pendingRequests,p.pendingRequests,J.current),...D.goalHistory?{goalHistory:D.goalHistory}:{}}:D?{...p,turns:zt(D.turns,p.turns),pendingRequests:ia(D.pendingRequests,p.pendingRequests,J.current)}:p),I(D=>Ps(D,p.thread));const ce=new Map(p.turns.map(D=>[D.id,D])),Ue=new Set((p.pendingSteers??[]).map(D=>D.clientRequestId).filter(D=>!!D));Rt(D=>D.filter(Je=>{if(Ue.has(Je.clientRequestId))return!1;const _e=ce.get(Je.turnId);return!(!_e||Us(_e,Je.prompt)||p.thread.activeTurnId!==Je.turnId&&_e.status!=="inProgress")})),lt(D=>{if(!D)return D;const Je=D.serverTurnId??D.id,_e=p.turns.some(L=>L.id===Je),Be=ce.get(Je)??null,je=cd(p.turns,D.prompt),j=!!je;if(je&&!D.serverTurnId)return{...D,id:je.id,serverTurnId:je.id,status:D.status==="failed"?D.status:je.status==="inProgress"?"inProgress":D.status};if(Be&&D.serverTurnId)return Us(Be,D.prompt)||D.prompt.includes("[PHOTO ")&&(gn(Be,D.prompt)||Fn(Be))?Be.status==="inProgress"?{...D,id:Be.id,serverTurnId:Be.id,status:D.status==="failed"?D.status:"inProgress"}:null:{...D,id:Be.id,serverTurnId:Be.id,status:D.status==="failed"?D.status:"inProgress"};if(!D.serverTurnId&&D.prompt.includes("[PHOTO ")&&p.thread.activeTurnId&&p.thread.status==="running"){const L=ce.get(p.thread.activeTurnId);if(L&&Fn(L))return{...D,id:L.id,serverTurnId:L.id,status:D.status==="failed"?D.status:"inProgress"}}return _e||Z&&j?null:D}),(Z||se.current&&p.turns.some(D=>D.id===se.current))&&(se.current=null,it(),M(""),W(null),fe(null))},[it]);r.useEffect(()=>{F.current=c},[c]);const Js=r.useCallback(async({seedThread:l}={})=>{var ce;const i=b.current+1;b.current=i;const p=(l==null?void 0:l.provider)??((ce=F.current)==null?void 0:ce.thread.provider)??"codex",[U,$,Z]=await Promise.allSettled([Mr(),Ur(p),oa(p)]);b.current===i&&(U.status==="fulfilled"?I(l?Ps(U.value,l):U.value):l&&I(Ue=>Ps(Ue,l)),$.status==="fulfilled"&&(z.current=p,pe($.value.status),he($.value.capabilities),le($.value.managementSchema)),Z.status==="fulfilled"&&(z.current=p,B(Z.value)))},[]),Ft=r.useCallback(async({showLoading:l=!0,clearError:i=!0,reportError:p=!0,limit:U=ir}={})=>{const $=P.current+1;P.current=$,l&&ut(!0),i&&de(null);try{const Z=await Ba(t,{limit:U});if(P.current!==$)return;Vs(Z),z.current!==Z.thread.provider&&Js({seedThread:Z.thread})}catch(Z){if(P.current!==$||!p)return;de(Z instanceof Error?Z.message:"Unable to load thread detail.")}finally{P.current===$&&ut(!1)}},[Vs,t,Js]),De=r.useCallback(()=>{var Ue;const l=((Ue=m.current)==null?void 0:Ue.readyState)??mn,i=l===ms,p=x.current,U=Date.now(),$=v.current!==null&&U-Date.parse(v.current)<=Zn,Z=R.current!==null&&U-R.current<=Zn;let ce;p?i&&Z?ce="connected":l===Xn||h.current!==null||$||Z||g.current?ce="reconnecting":ce="checking":ce="offline",ys(D=>D.status===ce&&D.browserOnline===p&&D.healthOk===$&&D.socketOpen===i&&D.lastHealthyAt===v.current?D:{status:ce,browserOnline:p,healthOk:$,socketOpen:i,lastHealthyAt:v.current})},[]);r.useEffect(()=>{P.current+=1,b.current+=1,_(null),Ke({prompt:"",attachments:[]}),mt(!1),Yt("idle"),lt(null),Rt([]),fe(null),E.current=null,se.current=null,J.current=new Set,v.current=null,R.current=null,f.current=!1,x.current=typeof navigator>"u"?!0:navigator.onLine,ys({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 U=window.visualViewport,$=U?Math.max(0,Math.round(window.innerHeight-U.height-U.offsetTop)):0;ue($),document.documentElement.style.setProperty("--thread-detail-keyboard-inset",`${$}px`)};return l(),(i=window.visualViewport)==null||i.addEventListener("resize",l),(p=window.visualViewport)==null||p.addEventListener("scroll",l),window.addEventListener("resize",l),()=>{var U,$;(U=window.visualViewport)==null||U.removeEventListener("resize",l),($=window.visualViewport)==null||$.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,U=p==null?void 0:p.querySelector('[aria-label="Prompt"]');ke(!!(i&&U&&(i===U||U.contains(i))))};return l(),document.addEventListener("focusin",l),document.addEventListener("focusout",l),()=>{document.removeEventListener("focusin",l),document.removeEventListener("focusout",l)}},[A,c==null?void 0:c.thread.id,Ze]),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 U=new ResizeObserver(()=>{p()});return U.observe(i),()=>{U.disconnect()}},[A,Ze]),r.useEffect(()=>{var U,$;const l=C.current;if(!l||!Ze||A!=="chat"){ee(0);return}const i=()=>{const Z=l.getBoundingClientRect();ee(Math.max(0,Math.ceil(window.innerHeight-Z.top)))};i(),window.addEventListener("resize",i),(U=window.visualViewport)==null||U.addEventListener("resize",i),($=window.visualViewport)==null||$.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()}},[A,c==null?void 0:c.thread.id,Ze,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})},U=()=>{h.current!==null&&(window.clearTimeout(h.current),h.current=null)},$=()=>{l||!x.current||h.current!==null||(h.current=window.setTimeout(()=>{h.current=null,!l&&D()},zd),De())},Z=()=>{const j=m.current;if(m.current=null,j)try{j.close()}catch{}},ce=j=>{if(j.threadId===t){if(j.type==="thread.output.delta"&&typeof j.payload.delta=="string"){const L=typeof j.payload.turnId=="string"?j.payload.turnId:null,ne=typeof j.payload.itemId=="string"?j.payload.itemId:null,Ie=typeof j.payload.sequence=="number"&&Number.isFinite(j.payload.sequence)?j.payload.sequence:null;L&&ne?Hs(L,ne,j.payload.delta,Ie):ns(j.payload.delta),L&&lt(xe=>xe&&(xe.serverTurnId===null||xe.serverTurnId===L)?{...xe,serverTurnId:L,id:L,status:xe.status==="failed"?xe.status:"inProgress",tokenUsage:xe.tokenUsage}:xe)}if(j.type==="thread.context.updated"){const L=j.payload.contextUsage&&typeof j.payload.contextUsage=="object"?j.payload.contextUsage:null;if(L){const ne=L;_(Ie=>Ie&&{...Ie,thread:{...Ie.thread,contextUsage:ne}}),I(Ie=>Ie.map(xe=>xe.id===t?{...xe,contextUsage:ne}:xe))}}if(j.type==="thread.turn.token.updated"&&typeof j.payload.turnId=="string"&&j.payload.tokenUsage&&typeof j.payload.tokenUsage=="object"){const L=j.payload.turnId,ne=j.payload.tokenUsage,Ie=j.payload.priceEstimate&&typeof j.payload.priceEstimate=="object"?j.payload.priceEstimate:null;_(xe=>{if(!xe)return xe;const tt=ud(xe.turns,L,ne,Ie);return tt===xe.turns?xe:{...xe,turns:tt}}),lt(xe=>xe&&(xe.serverTurnId===L||xe.id===L)?{...xe,tokenUsage:ne,priceEstimate:Ie}:xe)}if(j.type==="thread.turn.started"||j.type==="thread.turn.completed"||j.type==="thread.turn.failed"||j.type==="thread.updated"||j.type==="thread.goal.updated"||j.type==="thread.goal.cleared"||j.type==="thread.request.created"||j.type==="thread.request.resolved"){if(j.type==="thread.goal.updated"){const L=j.payload.goal&&typeof j.payload.goal=="object"?j.payload.goal:null,ne=Array.isArray(j.payload.goalHistory)?j.payload.goalHistory:null;ye({status:"ready",data:L,error:null}),_(Ie=>Ie&&(ne?{...Ie,goal:L,goalHistory:ne}:L?{...Ie,goal:L,goalHistory:cn(Ie.goalHistory??[],L)}:{...Ie,goal:L}))}if(j.type==="thread.goal.cleared"){const L=Array.isArray(j.payload.goalHistory)?j.payload.goalHistory:null;ye({status:"ready",data:null,error:null}),_(ne=>ne&&(L?{...ne,goal:null,goalHistory:L}:{...ne,goal:null}))}if(p(),j.type==="thread.turn.started"){it(),M(""),fe(null),se.current=null;const L=typeof j.payload.turnId=="string"?j.payload.turnId:null;L&&lt(ne=>ne&&{...ne,serverTurnId:L,id:L,status:ne.status==="failed"?ne.status:"inProgress",error:null,tokenUsage:ne.tokenUsage})}if(j.type==="thread.turn.completed"||j.type==="thread.turn.failed"){it(),M("");const L=typeof j.payload.turnId=="string"?j.payload.turnId:null;L&&(se.current=L,j.type==="thread.turn.failed"&&lt(ne=>ne&&(ne.serverTurnId===L||ne.id===L)?{...ne,status:"failed",error:typeof j.payload.error=="string"?j.payload.error:"Unable to complete the turn.",tokenUsage:ne.tokenUsage}:ne))}}if(j.type==="thread.request.created"&&nd(j.payload.request)&&(J.current.delete(j.payload.request.id),_(L=>L&&td(L,j.payload.request))),j.type==="thread.request.resolved"&&typeof j.payload.requestId=="string"){const L=j.payload.requestId;J.current.add(L),_(ne=>ne&&sd(ne,L))}if((j.type==="thread.item.started"||j.type==="thread.item.completed")&&j.payload.item&&typeof j.payload.item=="object"&&typeof j.payload.turnId=="string"){const L=j.payload.turnId,ne=j.payload.item;typeof ne.id=="string"&&typeof ne.text=="string"&&ks(L,ne)}j.type==="thread.plan.updated"&&Array.isArray(j.payload.plan)&&W({turnId:String(j.payload.turnId??""),explanation:typeof j.payload.explanation=="string"?j.payload.explanation:null,plan:j.payload.plan})}},Ue=()=>{const j=m.current;if(!(!j||j.readyState!==ms))try{j.send(JSON.stringify({type:"supervisor.ping",timestamp:new Date().toISOString()}))}catch{f.current=!0,Z(),$(),De()}},D=()=>{var ne;if(l||!x.current){De();return}const j=((ne=m.current)==null?void 0:ne.readyState)??mn;if(j===Xn||j===ms){De();return}const L=Hr(ce);m.current=L,De(),L.addEventListener("message",Ie=>{if(m.current===L)try{const xe=JSON.parse(Ie.data);(xe.type==="supervisor.connected"||xe.type==="supervisor.pong")&&(R.current=Date.now(),De())}catch{}}),L.addEventListener("open",()=>{m.current===L&&(f.current=!0,p(),Ue(),De())}),L.addEventListener("close",()=>{m.current===L&&(m.current=null),f.current=!0,$(),De()}),L.addEventListener("error",()=>{m.current===L&&(m.current=null),f.current=!0,$(),De()})},Je=async()=>{var j;if(!(l||!x.current||g.current)){g.current=!0,De();try{await Il();const L=f.current;v.current=new Date().toISOString(),L&&(f.current=!1,p()),(((j=m.current)==null?void 0:j.readyState)??mn)!==ms&&D()}catch{v.current=null,f.current=!0,$()}finally{g.current=!1,De()}}},_e=()=>{x.current=!0,f.current=!0,De(),D(),Je()},Be=()=>{x.current=!1,v.current=null,R.current=null,f.current=!0,U(),Z(),De()},je=()=>{var ne;if(l||!x.current){De();return}const j=((ne=m.current)==null?void 0:ne.readyState)??mn,L=R.current===null?null:Date.now()-R.current;j===ms&&L!==null&&L>Zn?(f.current=!0,Z(),$()):j===ms?Ue():j!==Xn&&D(),Je(),De()};return window.addEventListener("online",_e),window.addEventListener("offline",Be),D(),Je(),i=window.setInterval(je,Vd),()=>{l=!0,window.removeEventListener("online",_e),window.removeEventListener("offline",Be),U(),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||Y!==null||be!==null))return;const i=window.setInterval(()=>{Ft({showLoading:!1,clearError:!1,reportError:!1})},Jd);return()=>{window.clearInterval(i)}},[c==null?void 0:c.thread.activeTurnId,c==null?void 0:c.thread.status,oe.length,be,Y,Ft,St.length,we]);const Gs=r.useCallback(async()=>{var l;if(!(!c||c.turns.length===0||Le)){mt(!0),de(null);try{const i=(l=c.turns[0])==null?void 0:l.id,p=await Ba(t,{limit:qd,...i?{beforeTurnId:i}:{}});_(U=>U?{...p,turns:ed(U.turns,p.turns)}:p),I(U=>U.map($=>$.id===p.thread.id?p.thread:$))}catch(i){de(i instanceof Error?i.message:"Unable to load earlier turns.")}finally{mt(!1)}}},[c,t,Le]);async function Ks(l){var Je,_e,Be;if(A==="shell"){if((c==null?void 0:c.thread.isLoaded)===!1)return await Wt({attachShell:!0}),!1;let je=!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((Je=k.current)==null?void 0:Je.toggleConnection()),je=!0),(V==null?void 0:V.isConnecting)===!0))return de("Connecting to the shell. Try again after it attaches."),!1;if(((_e=k.current)==null?void 0:_e.sendCommand(l.prompt))??!1)de(null);else return de(je?"Shell is still attaching. Try again after it connects.":"Connect the shell before sending commands."),!1;return!0}w(!0),de(null),jt(je=>je+1);const i=F.current,p=i?{...i.thread,...E.current??{}}:null,U=(p==null?void 0:p.model)??null,$=(p==null?void 0:p.reasoningEffort)??null,Z=dd(),ce=`optimistic-${Date.now()}`,Ue=`optimistic-steer-${Z}`,D=new Date().toISOString();try{let je=F.current;if(je&&!je.thread.isLoaded){const Ee={...je.thread,...E.current??{}},dt=await Fa(t,{...je.thread.model?{model:je.thread.model}:{},...je.thread.sandboxMode?{sandboxMode:je.thread.sandboxMode}:{}}),st={...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}};je=st,F.current=st,_(an=>an?{...st,turns:zt(an.turns,st.turns)}:st),I(an=>an.map(Ra=>Ra.id===st.thread.id?st.thread:Ra))}const j=je?{...je.thread,...E.current??{}}:null,L=(j==null?void 0:j.status)==="running"?j.activeTurnId:null,ne=A==="chat"&&!!L;ne&&L?Rt(Ee=>[...Ee,{id:Ue,clientRequestId:Z,turnId:L,prompt:l.prompt,createdAt:D,status:"steering"}]):(it(),M(""),lt({id:ce,serverTurnId:null,startedAt:D,status:"sending",error:null,prompt:l.prompt,model:U,reasoningEffort:$,reasoningEffortAvailable:Qa(q,U),tokenUsage:null,priceEstimate:null}));const Ie={prompt:l.prompt,clientRequestId:Z,...j!=null&&j.model?{model:j.model}:{},...j!=null&&j.reasoningEffort?{reasoningEffort:j.reasoningEffort}:{},...j!=null&&j.collaborationMode?{collaborationMode:j.collaborationMode}:{},...j!=null&&j.sandboxMode?{sandboxMode:j.sandboxMode}:{},...(Be=l.attachments)!=null&&Be.length?{attachments:l.attachments}:{}},xe=await Yl(t,Ie),tt=E.current&&Object.keys(E.current).length>0?{...xe,...E.current}:xe;_(Ee=>Ee&&{...Ee,thread:tt}),I(Ee=>Ee.map(dt=>dt.id===tt.id?tt:dt)),ne&&L?tt.activeTurnId!==null&&tt.activeTurnId!==L&&tt.lastTurnStartedAt!==(j==null?void 0:j.lastTurnStartedAt)?(it(),M(""),W(null),Rt(dt=>dt.filter(st=>st.id!==Ue)),lt({id:ce,serverTurnId:tt.activeTurnId,startedAt:tt.lastTurnStartedAt??D,status:"inProgress",error:null,prompt:l.prompt,model:U,reasoningEffort:$,reasoningEffortAvailable:Qa(q,U),tokenUsage:null,priceEstimate:null})):Rt(dt=>dt.map(st=>st.id===Ue?{...st,turnId:tt.activeTurnId??st.turnId,status:"accepted"}:st)):(lt(Ee=>Ee&&Ee.id===ce?{...Ee,id:tt.activeTurnId??Ee.id,serverTurnId:tt.activeTurnId??Ee.serverTurnId,status:"inProgress",error:null,tokenUsage:Ee.tokenUsage,priceEstimate:Ee.priceEstimate}:Ee),W(null)),Ke({prompt:"",attachments:[]})}catch(je){const j=je instanceof ae?je.payload.message:je instanceof Error?je.message:"Unable to send prompt.";je instanceof ae?de(je.payload.message):de(j),Rt(L=>L.filter(ne=>ne.clientRequestId!==Z)),lt(L=>L&&L.id===ce?{...L,status:"failed",error:j}:L)}finally{w(!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){w(!0),de(null),it(),M("");try{if(c.thread.isLoaded){const p=await Kl(t);_(U=>U?{...p,turns:zt(U.turns,p.turns)}:p),Xe(null),I(U=>U.map($=>$.id===p.thread.id?p.thread:$)),Qe(!1);return}const i=await Fa(t,{...c.thread.model?{model:c.thread.model}:{},...c.thread.sandboxMode?{sandboxMode:c.thread.sandboxMode}:{}});_(p=>p?{...i,turns:zt(p.turns,i.turns)}:i),I(p=>p.map(U=>U.id===i.thread.id?i.thread:U)),l!=null&&l.attachShell&&A==="shell"&&Qe(!0)}catch(i){de(i instanceof Error?i.message:"Unable to change connection state.")}finally{w(!1)}}}async function rs(){var l;if(A==="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}w(!0),de(null);try{const i=c!=null&&c.thread.activeTurnId?await Wa(t,{turnId:c.thread.activeTurnId}):await Wa(t);_(p=>p&&{...p,thread:i}),I(p=>p.map(U=>U.id===i.id?i:U)),it(),M("")}catch(i){de(i instanceof Error?i.message:"Unable to interrupt turn.")}finally{w(!1)}}async function os(l){if(!c)return;const i=c,p={...E.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}:{}},U={...c.thread,...p};Dt(!0),E.current=p,F.current={...c,thread:U},_($=>$&&{...$,thread:U}),I($=>$.map(Z=>Z.id===U.id?{...Z,...U}:Z));try{const $=await Zl(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}:{}});E.current=null,F.current=i?{...i,thread:$}:null,_(Z=>Z&&{...Z,thread:$}),I(Z=>Z.map(ce=>ce.id===$.id?$:ce))}catch($){E.current=null,F.current=i,_(i),I(Z=>Z.map(ce=>ce.id===i.thread.id?i.thread:ce)),de($ instanceof Error?$.message:"Unable to update thread settings.")}finally{Dt(!1)}}const ls=r.useCallback(async(l,i)=>{vs(l),de(null);try{const p=await ci(t,l,i);_(U=>U?{...p,turns:zt(U.turns,p.turns)}:p),W(p.livePlan??null),fe(p.liveItems??null)}catch(p){de(p instanceof Error?p.message:"Unable to answer this request.")}finally{vs(null)}},[t]),Ys=r.useCallback(l=>$l(t,l),[t]);async function Xt(){if(c){gs(!0),de(null);try{const l=await Xl(t);_(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(U=>U.map($=>$.id===p.id?{...$,title:p.title,updatedAt:p.updatedAt}:$)),_(U=>U&&U.thread.id===p.id?{...U,thread:{...U.thread,title:p.title,updatedAt:p.updatedAt}}:U)}catch(p){throw de(p instanceof Error?p.message:"Unable to rename thread."),p}}async function Xs(){if(bt){Zt(!0),de(null);try{await Dr(bt.id),I(i=>i.filter(p=>p.id!==bt.id));const l=bt.id===(c==null?void 0:c.thread.id);if(Bt(null),l){const i=re.find(p=>p.id!==bt.id&&p.workspaceId===(c==null?void 0:c.thread.workspaceId))??re.find(p=>p.id!==bt.id);s(i?`/threads/${i.id}`:"/threads")}}catch(l){de(l instanceof Error?l.message:"Unable to delete thread.")}finally{Zt(!1)}}}function is(){X(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,U;const i=l==="clear"?((p=k.current)==null?void 0:p.sendCommand("clear"))??!1:((U=k.current)==null?void 0:U.sendControl(l))??!1;de(i?null:"Connect the shell before sending control input.")}r.useEffect(()=>{if(!(!$e||A!=="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()}},[A,c==null?void 0:c.thread.isLoaded,$e,V==null?void 0:V.loading,V==null?void 0:V.status]),r.useEffect(()=>{if(A!=="shell")return;const l=window.requestAnimationFrame(()=>{var i;(i=k.current)==null||i.refreshLayout({syncBackendSize:!1})});return()=>{window.cancelAnimationFrame(l)}},[A]);const Ts=c&&c.workspacePathStatus==="missing"?"Restore this workspace path on the current machine before continuing.":null,Is=Ze&&A==="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(Qd,{})})})]}),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:Gd.map(l=>{const i=Qi(c.thread)===l;return e.jsx("button",{type:"button",disabled:ft,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,Me=K?gt.status==="connected"?"ui-action-success shadow-lg shadow-stone-950/20":gt.status==="reconnecting"?"thread-live-connection-reconnecting ui-status-success shadow-lg shadow-stone-950/20":gt.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=tc(K,gt),$t=[He,K?null:"Tap to connect this thread",gt.lastHealthyAt?`Last healthy ${ps(gt.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 ${Me}`,children:e.jsx(hn,{status:gt.status})}):e.jsx("button",{type:"button",onClick:()=>void Wt(),disabled:y||!c,"aria-label":y?"Connecting thread":"Connect thread",title:y?"Connecting thread":$t,className:`inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition ${Me}`,children:e.jsx(hn,{status:"detached"})}),to=K?e.jsx("div",{title:$t,className:`hidden lg:inline-flex h-9 w-9 items-center justify-center rounded-full transition ${Me}`,children:e.jsx(hn,{status:gt.status})}):e.jsx("button",{type:"button",onClick:()=>void Wt(),disabled:y||!c,title:y?"Connecting thread":$t,className:`hidden lg:inline-flex h-9 w-9 items-center justify-center rounded-full transition ${Me}`,children:e.jsx(hn,{status:"detached"})}),va=Ce.data??(c==null?void 0:c.goal)??null,ya=(c==null?void 0:c.goalHistory)??[],ja=va?cn(ya,va):zr(ya),wa=(H==null?void 0:H.controls.goals)??!1,so=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"})]}),no=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:ja.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."}):ja.map(l=>{const i=`${l.threadId}:${l.objective}:${l.createdAt}`,p=ws.has(i),U=["active","paused","budgetLimited"].includes(l.status);return e.jsxs("div",{className:`rounded-2xl border px-3 py-3 ${U?"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($=>{const Z=new Set($);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:id(l.timeUsedSeconds)}),e.jsx("span",{children:ld(l)}),e.jsxs("span",{title:ps(l.updatedAt),children:["Updated ",new Date(l.updatedAt).toLocaleTimeString()]})]}),U?e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",disabled:Q||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:Q||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:Q,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:so}):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(ec,{})}),ao=e.jsxs("div",{className:"relative flex items-center justify-end gap-1.5",children:[Sa,Na,On]}),ro=e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[Sa,Na,to]}),oo=r.useMemo(()=>({livePlan:Y,liveItems:be,respondingRequestId:bs,onRespondToRequest:ls,scrollRequestKey:Ye,bottomSpacer:tn,className:"thread-timeline-surface min-h-0 flex-1",onTailVisibilityChange:ct,loadingEarlier:Le,onLoadEarlier:Gs,onOpenThread:Ae,answeredRequestNotes:(c==null?void 0:c.answeredRequestNotes)??Kd,activityNotes:(c==null?void 0:c.activityNotes)??Yd,pendingSteers:(c==null?void 0:c.pendingSteers)??Zd,optimisticSteers:St,optimisticTurn:S}),[c==null?void 0:c.answeredRequestNotes,c==null?void 0:c.activityNotes,c==null?void 0:c.pendingSteers,Gs,ls,be,Y,Le,Ae,St,bs,Ye,tn,S]),ka=c?{busy:A==="chat"?y:!1,settingsBusy:ft,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:ve,disabled:!!Ts,...Ts?{disabledPlaceholder:Ts}:{},shellControlState:V,draftPrompt:ot.prompt,draftAttachments:ot.attachments,onDraftChange:Ke,canInterrupt:!!c.thread.activeTurnId,onInterrupt:rs,onCompact:Xt,onOpenForkTurns:vt,onForkLatest:yt,onForkTurn:Pn,onOpenSkills:qs,onOpenMcp:In,onOpenHooks:En,onCreateHook:Rn,onUpdateHook:Ve,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:()=>jt(l=>l+1),onUpdateSettings:os,onToggleView:is,onShellCopy:qt,onShellControl:ds,compactBusy:xt,skillsState:js,mcpState:pt,hooksState:ze,forkTurnOptionsState:Ht}:null,Ca=c?{busy:y,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:ve,shellControlState:V,canInterrupt:!!(c.thread.isLoaded&&(V!=null&&V.isCommandRunning)),onInterrupt:rs,onToggleView:is,onShellCopy:qt,onShellControl:ds}:null,Ta=r.useCallback(l=>c?Ge({threadId:c.thread.id,path:l}):"",[c==null?void 0:c.thread.id,Ge]),Ia=r.useMemo(()=>{const l=(c==null?void 0:c.workspace.id)??null;return l?{listTree:()=>El(l),readFile:i=>Rl(l,{path:i.path,...i.offset!==void 0?{offset:i.offset}:{},...i.limit!==void 0?{limit:i.limit}:{}}),getRawFileUrl:i=>Pl(l,{path:i.path}),uploadFile:i=>Ul(l,{file:i.file}),writeFile:async i=>{await Ol(l,{path:i.path,content:i.content})},downloadNode:async i=>{de(null);try{const p=await Al(l,{path:i.path}),U=URL.createObjectURL(p.blob),$=document.createElement("a");$.href=U,$.download=p.filename,document.body.append($),$.click(),$.remove(),URL.revokeObjectURL(U)}catch(p){de(p instanceof ae?p.payload.message:p instanceof Error?p.message:"Workspace download failed.")}}}:null},[c==null?void 0:c.workspace.id]),lo=r.useMemo(()=>({openThread:Ae,getThreadHref:ht,getNewThreadHref:wt,renameThread:Zs,deleteThread:Bt,sendPrompt:Ks,interrupt:rs,compact:Xt,updateSettings:os,loadHistoryItemDetail:Ys,getImageAssetUrl:Ta,workspace:Ia,shell:Pe}),[Ta,wt,ht,Xt,rs,Ys,Ks,Zs,os,Pe,Ae,Ia]),io=c!=null&&c.thread.workspaceId?`/threads?workspaceId=${encodeURIComponent(c.thread.workspaceId)}`:"/workspaces",co=e.jsxs(e.Fragment,{children:[e.jsx(bo,{open:Ns,busy:Ut,turnsState:Ct,onCancel:()=>{Ut||At(!1)},onLoadTurns:as,onExport:_s}),e.jsx(wn,{open:bt!==null,title:"Delete Thread",description:bt?`Delete ${Uo(bt.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:re,detail:c,status:ge,loading:qe,error:qe?null:Ds,plugins:n,adapter:lo,metaContent:sn,settingsContent:nn,globalSettingsContent:e.jsx(xa,{embedded:!0}),mobileHeaderAction:ao,workspaceReturnHref:io,onCloseAppNavigation:(a==null?void 0:a.closeNav)??(()=>{}),surfaceActions:ro,floatingPanel:no,workspaceFeatures:Xd,activeView:A,liveOutput:oe,timelineProps:oo,timelineComponent:yo,useFloatingMobileComposer:Is,floatingMobileComposerBottomOffset:Qs,composerHostRef:C,shellPanelRef:k,shellPanelComponent:vo,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:co,...ka?{composerProps:ka}:{},...Ca?{shellComposerProps:Ca}:{}})}function nc(){const t=at(),[s,a]=r.useState(""),[n,d]=r.useState(Tt),[o,m]=r.useState([]),[h,g]=r.useState(!0),[v,R]=r.useState(!1),[x,f]=r.useState(null);r.useEffect(()=>{let P=!1;return g(!0),pa().then(b=>{var se,F;if(P)return;m(b);const z=((se=b.find(E=>E.isDefault&&E.enabled))==null?void 0:se.provider)??((F=b.find(E=>E.enabled))==null?void 0:F.provider)??Tt;d(z)}).catch(()=>{P||m([])}).finally(()=>{P||g(!1)}),()=>{P=!0}},[]);const k=r.useMemo(()=>o.length>0?o:[{provider:Tt,displayName:Pa[Tt].displayName,enabled:!0}],[o]);async function C(P){P.preventDefault();const b=s.trim();if(!b){f("Session ID is required.");return}R(!0),f(null);try{const z=await zl({sessionId:b,provider:n});t(`/threads/${z.thread.id}`)}catch(z){z instanceof ae?f(z.payload.message):f(z instanceof Error?z.message:"Unable to import session.")}finally{R(!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:P=>d(P.target.value),disabled:v||h,className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition",children:k.map(P=>e.jsxs("option",{value:P.provider,children:[P.displayName||Pa[P.provider].displayName,P.enabled?"":" (not ready)"]},P.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:P=>a(P.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:v,className:"ui-action-primary rounded-full px-5 py-3 font-medium transition disabled:cursor-not-allowed",children:v?"Importing...":"Import Session"})})]})]})}function jn(t){return t.enabled&&t.capabilities.sessions.resume&&t.capabilities.turns.start}function ac(t,s){var n;const a=t.find(d=>d.provider===s);return a&&jn(a)?a.provider:((n=t.find(jn))==null?void 0:n.provider)??Tt}function rc(){const t=at(),s=Jt(),[a]=mr(),[n,d]=r.useState([]),[o,m]=r.useState([]),[h,g]=r.useState([]),[v,R]=r.useState((s==null?void 0:s.defaultBackend)??Tt),[x,f]=r.useState(""),[k,C]=r.useState(""),P=a.get("title"),[b,z]=r.useState(()=>P??""),[se,F]=r.useState("yolo"),[E,J]=r.useState(!0),[c,_]=r.useState(!1),[re,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 Y,W,be;if(H)return;const le=ac(T,B);R(le),m(T);const oe=await oa(le);if(H)return;d(he),g(oe);const M=he.some(fe=>fe.id===q)?q:((Y=he[0])==null?void 0:Y.id)??"";f(M),C(((W=oe.find(fe=>fe.isDefault))==null?void 0:W.model)??((be=oe[0])==null?void 0:be.model)??"")}).catch(he=>{H||I(he instanceof Error?he.message:"Unable to load creation form data.")}).finally(()=>{H||J(!1)}),()=>{H=!0}},[B,q]),r.useEffect(()=>{if(!v)return;let H=!1;return g([]),C(""),I(null),oa(v).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}},[v]);function ge(){if(window.history.length>1){t(-1);return}if(q){t(`/threads?workspaceId=${encodeURIComponent(q)}`);return}t("/workspaces")}async function pe(H){H.preventDefault(),_(!0),I(null);try{const he=await ql(b.trim()?{workspaceId:x,provider:v,model:k,approvalMode:se,title:b.trim()}:{workspaceId:x,provider:v,model:k,approvalMode:se});t(`/threads/${he.id}`)}catch(he){he instanceof ae?I(he.payload.message):I(he instanceof Error?he.message:"Unable to create thread.")}finally{_(!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."})]}),E?e.jsx("div",{className:"host-empty-state rounded-3xl border px-6 py-12 text-center",children:"Loading creation form..."}):e.jsxs("form",{onSubmit:pe,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:v,onChange:H=>{const he=H.target.value;R(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:!jn(H),children:[H.displayName,jn(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:b,onChange:H=>z(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:se,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:[e.jsx("option",{value:"yolo",children:"yolo"}),e.jsx("option",{value:"guarded",children:"guarded"})]})]}),re&&e.jsx("div",{className:"host-error rounded-2xl border px-4 py-3 text-sm",children:re}),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:ge,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 oc(t){return t?`/threads/new?workspaceId=${encodeURIComponent(t)}`:"/threads/new"}function lc({getThreadHref:t,onOpenThread:s,getNewThreadHref:a,renderThreadLink:n,onCloseAppNavigation:d,...o}){const m=at(),h=Jt(),g=d??(h==null?void 0:h.closeNav),v=o.effectiveTheme??(h==null?void 0:h.effectiveTheme),R=o.themeMode??(h==null?void 0:h.themeMode),x=o.onThemeModeChange??(h==null?void 0:h.setThemeMode);return e.jsx(jo,{...o,workspaceReturnHref:o.workspaceReturnHref??"/workspaces",globalSettingsContent:o.globalSettingsContent??e.jsx(xa,{embedded:!0}),...v?{effectiveTheme:v}:{},...R?{themeMode:R}:{},...x?{onThemeModeChange:x}:{},getThreadHref:t??(f=>`/threads/${f}`),onOpenThread:s??(f=>m(`/threads/${f}`)),getNewThreadHref:a??oc,renderThreadLink:n??(({thread:f,children:k,className:C,onClick:P})=>e.jsx(It,{to:`/threads/${f.id}`,className:C,onClick:P,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 v(R){R.key==="Escape"&&!d&&m()}return window.addEventListener("keydown",v),()=>{window.removeEventListener("keydown",v)}},[d,m,t]),!t)return null;function g(v){v.preventDefault(),h()}return uo.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:v=>o(v.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 ic(){const[t]=mr(),s=at(),a=Jt(),n=t.get("workspaceId"),[d,o]=r.useState([]),[m,h]=r.useState([]),[g,v]=r.useState(null),[R,x]=r.useState(!0),[f,k]=r.useState(null),[C,P]=r.useState(null),[b,z]=r.useState(""),[se,F]=r.useState(null),[E,J]=r.useState(null),[c,_]=r.useState(!1),re=(a==null?void 0:a.defaultBackend)??Tt,I=r.useCallback(async()=>{x(!0),k(null);try{const[M,Y,W]=await Promise.all([Ur(re).then(be=>be.status),Mr(),fa()]);v(M),o(Y),h(W)}catch(M){k(M instanceof Error?M.message:"Unable to load threads.")}finally{x(!1)}},[re]);r.useEffect(()=>{if(n===null)return;I();const M=Hr(Y=>{o(W=>W.map(be=>be.id===Y.threadId?{...be,status:Y.type==="thread.updated"&&typeof Y.payload.status=="string"?Y.payload.status:be.status,lastError:(Y.type==="thread.turn.failed"||Y.type==="thread.turn.completed")&&typeof Y.payload.error=="string"?Y.payload.error:be.lastError,title:Y.type==="thread.updated"&&typeof Y.payload.title=="string"?Y.payload.title:be.title}:be))});return()=>{M.close()}},[I,n]);const q=Object.fromEntries(m.map(M=>[M.id,M.label])),B=m.find(M=>M.id===n)??null,ge=r.useMemo(()=>n?d.filter(M=>M.workspaceId===n):[],[n,d]),pe=ge.filter(M=>M.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(M,Y){try{const W=await Lr(M,{title:Y});o(be=>be.map(fe=>fe.id===W.id?{...fe,title:W.title,updatedAt:W.updatedAt}:fe))}catch(W){throw k(W instanceof Error?W.message:"Unable to rename thread."),W}}async function le(){if(!C)return;const M=b.trim();if(M){F(C);try{await T(C,M),P(null),z("")}finally{F(null)}}}async function oe(){if(E){_(!0);try{await Dr(E.id),o(M=>M.filter(Y=>Y.id!==E.id)),J(null)}catch(M){k(M instanceof Error?M.message:"Unable to delete thread.")}finally{_(!1)}}}return e.jsx(lc,{threads:d,workspaceLabels:q,status:g,loading:R,error:f,viewportConstrained:n!==null,showMobileAppMenu:!0,showMobileThreadNavToggle:!1,showMobileNewThreadShortcut:!1,currentWorkspaceId:n,currentWorkspaceLabel:(B==null?void 0:B.label)??null,onRenameThread:T,onDeleteThread:J,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")})]})]})}),!R&&!f&&ge.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:[ge.length," total"]}),pe>0&&e.jsxs("span",{className:"host-muted text-xs",children:["· ",pe," running"]})]}),e.jsx("div",{className:"mt-3 min-h-0 flex-1",children:e.jsx(wo,{threads:ge,currentWorkspaceId:n,workspaceLabels:q,onOpenThread:M=>s(`/threads/${M}`),onBeginRenameThread:M=>{P(M.id),z(M.title)},onDeleteThread:M=>J(M),scrollable:!0,maxHeightClassName:"max-h-full",showDeleteButton:!0,showSessionCopyButton:!0})})]}),!R&&!f&&ge.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:b,busy:se!==null,onChange:z,onCancel:()=>{P(null),z("")},onSubmit:()=>void le()}),e.jsx(wn,{open:E!==null,title:"Delete Thread",description:E?`Delete ${Ro(E.title)} from supervisor. The backend session id will no longer appear in this workspace list.`:"",confirmLabel:"Delete Thread",busy:c,onCancel:()=>{c||J(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 dc({initialPath:t="",initialLabel:s="",submitLabel:a="Save Workspace",error:n,busy:d=!1,onSubmit:o}){const m=dr(t),[h,g]=r.useState(t),[v,R]=r.useState(s||m),[x,f]=r.useState(null),k=r.useRef(m);r.useEffect(()=>{const P=dr(h);R(b=>!b.trim()||b===k.current?P:b),k.current=P},[h]);async function C(P){P.preventDefault();const b=h.trim();if(!b){f("Workspace path or Git URL is required.");return}f(null);const z=v.trim(),se=Zr(b)?"gitUrl":"absPath";await o(z?{[se]:b,label:z}:{[se]:b})}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:P=>g(P.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:v,onChange:P=>R(P.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 cc(){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 ui(m);t(`/threads?workspaceId=${encodeURIComponent(h.id)}`)}catch(h){h instanceof ae?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(dc,{busy:n,error:s,submitLabel:"Create Workspace",onSubmit:o})]})}function cr(t){return Date.parse(t.lastOpenedAt??t.createdAt)}function uc(t,s){return t.isFavorite!==s.isFavorite?t.isFavorite?-1:1:cr(s)-cr(t)}function mc(t){return t?new Date(t).toLocaleString():"Never opened"}function hc(t,s=28){return t.length<=s?t:`...${t.slice(-(s-3))}`}function pc({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 fc(){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 xc(){const t=at(),[s,a]=r.useState([]),[n,d]=r.useState(!0),[o,m]=r.useState(null),[h,g]=r.useState(null),[v,R]=r.useState(null),[x,f]=r.useState(null),[k,C]=r.useState(""),[P,b]=r.useState(null),[z,se]=r.useState(null),[F,E]=r.useState(null),[J,c]=r.useState(!1);async function _(){d(!0),R(null);try{a(await fa())}catch(T){R(T instanceof Error?T.message:"Unable to load workspaces.")}finally{d(!1)}}r.useEffect(()=>{_(),ll().then(T=>{m(T),g(null)}).catch(T=>{g(T instanceof Error?T.message:"Unable to load supervisor config.")})},[]);async function re(T){const le={...T,isFavorite:!T.isFavorite};a(oe=>oe.map(M=>M.id===T.id?le:M));try{const oe=await pi(T.id,{isFavorite:!T.isFavorite});a(M=>M.map(Y=>Y.id===oe.id?oe:Y))}catch(oe){a(M=>M.map(Y=>Y.id===T.id?T:Y)),R(oe instanceof Error?oe.message:"Unable to update workspace.")}}async function I(T){const le=k.trim();if(le){b(T);try{const oe=await mi(T,{label:le});a(M=>M.map(Y=>Y.id===oe.id?oe:Y)),f(null),C("")}catch(oe){R(oe instanceof Error?oe.message:"Unable to rename workspace.")}finally{b(null)}}}function q(T){f(T.id),C(T.label)}function B(){f(null),C("")}function ge(T){t(`/threads?workspaceId=${encodeURIComponent(T)}`)}async function pe(){if(F){c(!0);try{await hi(F.id),a(T=>T.filter(le=>le.id!==F.id)),E(null)}catch(T){R(T instanceof Error?T.message:"Unable to delete workspace.")}finally{c(!1)}}}function H(T,le){(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),ge(le))}const he=r.useMemo(()=>[...s].sort(uc),[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..."}),v&&e.jsx("div",{className:"host-error rounded-[1.4rem] border px-4 py-4",children:v}),!n&&!v&&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:()=>ge(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(),E(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(fc,{})}),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(),re(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(pc,{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(),se(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:hc(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: ",mc(T.lastOpenedAt)]})})]})})]},T.id))})]}),e.jsx(gc,{config:o,error:h,workspaceCount:s.length})]}),e.jsx(Yr,{open:x!==null,title:"Rename Workspace",label:"Workspace Label",value:k,busy:P!==null,onChange:C,onCancel:B,onSubmit:()=>x?I(x):void 0}),e.jsx(No,{open:z!==null,title:"Workspace Path",text:z??"",onClose:()=>se(null)}),e.jsx(wn,{open:F!==null,title:"Delete Workspace",description:F?`Delete ${F.label} from supervisor. This also removes its threads and local supervisor metadata.`:"",confirmLabel:"Delete Workspace",busy:J,onCancel:()=>{J||E(null)},onConfirm:()=>void pe()})]})}function gc({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";function eo(){return!1}function bc(){return eo()?e.jsx(Os,{to:"/control-plane",replace:!0}):e.jsx(Os,{to:"/workspaces",replace:!0})}function vc({children:t}){const s=es(),a=s.pathname.startsWith("/control-plane")||s.pathname==="/"&&eo(),n=r.useMemo(()=>a?{}:{fetchPlugins:Ml,importPlugin:Ll,updatePlugin:Dl,deletePlugin:Hl},[a]);return e.jsx(So,{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 jc(){if(typeof window>"u")return Tt;const t=window.localStorage.getItem(Qr);return Io(t)??Tt}function wc(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function Nc({themeMode:t,setThemeMode:s,effectiveTheme:a}){const[n,d]=r.useState(!1),[o,m]=r.useState(!1),[h,g]=r.useState(jc),v=es(),R=/^\/threads\/[^/]+$/.test(v.pathname),x=/^\/control-plane\/sessions\/[^/]+$/.test(v.pathname),f=v.pathname==="/threads",k=R||x||f,C=f||R||x,P=R||x,b=v.pathname==="/workspaces",z=v.pathname.startsWith("/control-plane"),se=b||f||z;r.useEffect(()=>{d(!1)},[v.pathname,v.search]);function F(J){g(J),window.localStorage.setItem(Qr,J)}const E={navOpen:n,openNav:()=>d(!0),toggleNav:()=>d(J=>!J),closeNav:()=>d(!1),settingsOpen:o,openSettings:()=>{d(!1),m(!0)},closeSettings:()=>m(!1),themeMode:t,setThemeMode:s,effectiveTheme:a,defaultBackend:h,setDefaultBackend:F};return e.jsxs(ko.Provider,{value:E,children:[e.jsxs("div",{className:`bg-[var(--app-bg)] text-[var(--app-fg)] ${k?"fixed inset-0 overflow-hidden overscroll-none":"min-h-screen"}`,children:[b?e.jsx(ga,{}):null,!se&&!P&&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 ${C?"max-w-none":"max-w-[1600px]"} ${k?"absolute inset-0 pb-0 sm:pb-4":"pb-4"} ${C?R||x?"pt-0":f?"pt-[env(safe-area-inset-top)] sm:pt-4":"pt-[calc(env(safe-area-inset-top)+4rem)] sm:pt-4":b||z?"pt-[env(safe-area-inset-top)] sm:pt-4":"pt-4"} ${k?R||x?"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 ${k?R||x?"h-full min-h-0 overflow-hidden overscroll-none":"h-full overflow-hidden overscroll-none":""}`,children:e.jsx(ho,{})})})]}),e.jsx(xa,{})]})}function Sc({children:t}){const[s,a]=r.useState({status:"checking"});async function n(m){try{const h=await il();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 ae&&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 dl(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(Pd,{onLogin:d})]}):t}function kc({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 Cc({children:t}){return es().pathname.startsWith("/control-plane")?t:na()?e.jsx(kc,{children:t}):e.jsx(Sc,{children:t})}function Tc({themeMode:t,setThemeMode:s,effectiveTheme:a}){return e.jsxs(hr,{children:[e.jsx(We,{path:"/",element:e.jsx(Os,{to:"/workspaces",replace:!0})}),e.jsxs(We,{element:e.jsx(Nc,{themeMode:t,setThemeMode:s,effectiveTheme:a}),children:[e.jsx(We,{path:"/workspaces",element:e.jsx(xc,{})}),e.jsx(We,{path:"/workspaces/new",element:e.jsx(cc,{})}),e.jsx(We,{path:"/relay-account",element:e.jsx(Ad,{})}),e.jsx(We,{path:"/relay-devices",element:e.jsx(Od,{})}),e.jsx(We,{path:"/control-plane/login",element:e.jsx(Xi,{})}),e.jsx(We,{path:"/control-plane",element:e.jsx(Xa,{children:e.jsx(Gi,{})})}),e.jsx(We,{path:"/control-plane/sessions/:sessionId",element:e.jsx(Xa,{children:e.jsx(Ed,{})})}),e.jsx(We,{path:"/threads",element:e.jsx(ic,{})}),e.jsx(We,{path:"/threads/import",element:e.jsx(nc,{})}),e.jsx(We,{path:"/threads/new",element:e.jsx(rc,{})}),e.jsx(We,{path:"/threads/:id",element:e.jsx(sc,{})})]})]})}function Ic(){const[t,s]=r.useState(()=>yc()),[a,n]=r.useState(()=>wc()),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(mo,{children:e.jsx(vc,{children:e.jsxs(hr,{children:[e.jsx(We,{path:"/",element:e.jsx(bc,{})}),e.jsx(We,{path:"/relay-portal",element:e.jsx(Kr,{})}),e.jsx(We,{path:"/relay-admin",element:e.jsx(Ud,{})}),e.jsx(We,{path:"/*",element:e.jsx(Cc,{children:e.jsx(Tc,{themeMode:t,setThemeMode:s,effectiveTheme:d})})})]})})})})}po.createRoot(document.getElementById("root")).render(e.jsx(fo.StrictMode,{children:e.jsx(Ic,{})}));