remote-codex 0.11.8 → 0.11.10

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.
Files changed (22) hide show
  1. package/apps/relay-server/dist/index.js +93 -10
  2. package/apps/supervisor-api/dist/{chunk-ELPP22TZ.js → chunk-HMFJNQDI.js} +11 -4
  3. package/apps/supervisor-api/dist/index.js +1 -1
  4. package/apps/supervisor-api/dist/worker-index.js +1 -1
  5. package/apps/supervisor-web/dist/assets/{core-DIQen2lE.js → core-oEok_Crl.js} +1 -1
  6. package/apps/supervisor-web/dist/assets/{graph-vendor-CGzY-MFv.js → graph-vendor-DVPtkh3h.js} +1 -1
  7. package/apps/supervisor-web/dist/assets/index-Cp9GkemI.css +1 -0
  8. package/apps/supervisor-web/dist/assets/index-M5xKhovw.js +5 -0
  9. package/apps/supervisor-web/dist/assets/{markdown-vendor-hBDTCSB-.js → markdown-vendor-BQJfKm05.js} +1 -1
  10. package/apps/supervisor-web/dist/assets/{react-vendor-o1Xrx7m4.js → react-vendor-CgLzZcV4.js} +1 -1
  11. package/apps/supervisor-web/dist/assets/{terminal-vendor-CLGgN91S.js → terminal-vendor-B365Go3Z.js} +1 -1
  12. package/apps/supervisor-web/dist/assets/thread-ui-DldLSgqC.js +3604 -0
  13. package/apps/supervisor-web/dist/assets/ui-vendor-CeKGesq3.js +50 -0
  14. package/apps/supervisor-web/dist/index.html +8 -8
  15. package/bin/remote-codex.mjs +255 -40
  16. package/package.json +2 -2
  17. package/packages/shared/src/index.ts +1 -0
  18. package/apps/supervisor-api/dist/chunk-ZWZQVPDT.js +0 -27893
  19. package/apps/supervisor-web/dist/assets/index-CXq73NcP.js +0 -5
  20. package/apps/supervisor-web/dist/assets/index-Di1JBevU.css +0 -1
  21. package/apps/supervisor-web/dist/assets/thread-ui-ICfwCbte.js +0 -3604
  22. package/apps/supervisor-web/dist/assets/ui-vendor-D1uxdi-d.js +0 -430
@@ -1,5 +0,0 @@
1
- import{j as e,u as Ps,d as ht,r as a,N as rr,e as na,L as qt,f as ra,a as Xa,B as Qa,h as aa,i as Ke,O as eo,k as to,c as so}from"./react-vendor-o1Xrx7m4.js";import{u as zt,a as ar,C as fn,f as ms,T as oa,A as no,b as ro,t as la,E as ao,c as oo,d as lo,e as io,g as co,L as uo,P as mo,h as ho}from"./thread-ui-ICfwCbte.js";import"./ui-vendor-D1uxdi-d.js";import"./graph-vendor-CGzY-MFv.js";import"./terminal-vendor-CLGgN91S.js";import"./markdown-vendor-hBDTCSB-.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const c of document.querySelectorAll('link[rel="modulepreload"]'))n(c);new MutationObserver(c=>{for(const o of c)if(o.type==="childList")for(const p of o.addedNodes)p.tagName==="LINK"&&p.rel==="modulepreload"&&n(p)}).observe(document,{childList:!0,subtree:!0});function r(c){const o={};return c.integrity&&(o.integrity=c.integrity),c.referrerPolicy&&(o.referrerPolicy=c.referrerPolicy),c.crossOrigin==="use-credentials"?o.credentials="include":c.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(c){if(c.ep)return;c.ep=!0;const o=r(c);fetch(c.href,o)}})();var po=["codex","claude","opencode"],Ct="codex",Cr={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 fo(t){return typeof t=="string"&&po.includes(t)}function xo(t){return fo(t)?t:null}var Tr=15;function go(t){return t.replace(/\s+/g," ").trim()}function bo(t){const s=go(t);if(!s)return"";const r=Array.from(s);return r.length<=Tr?s:`${r.slice(0,Tr).join("")}...`}const vo=["codex","claude","opencode"],ia="codex",da={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"}},Ir=15;function jo(t){return t.replace(/\s+/g," ").trim()}function yo(t){const s=jo(t);if(!s)return"";const r=Array.from(s);return r.length<=Ir?s:`${r.slice(0,Ir).join("")}...`}class ae extends Error{constructor(s,r){super(r.message),this.statusCode=s,this.payload=r}}const zn="remote-codex-auth-token",Jn="remote-codex-relay-token",ca="remote-codex-relay-mode",Vn="remote-codex-relay-device-id",Gn="remote-codex-relay-thread-id";function ua(){return typeof window>"u"?null:window.localStorage.getItem(zn)}function wo(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(zn,t);return}window.localStorage.removeItem(zn)}}function ma(){return typeof window>"u"?null:window.localStorage.getItem(Jn)}function or(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(Jn,t);return}window.localStorage.removeItem(Jn)}}function hs(){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(ca)==="true"}function xn(){typeof window>"u"||window.localStorage.setItem(ca,"true")}function ha(){return hs()}function pa(){return typeof window>"u"?null:window.localStorage.getItem(Vn)}function Kn(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(Vn,t);return}window.localStorage.removeItem(Vn)}}function No(){return typeof window>"u"?null:window.localStorage.getItem(Gn)}function Yn(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(Gn,t);return}window.localStorage.removeItem(Gn)}}function fa(t){if(!hs())return t;if(t.startsWith("/api/")){const s=pa();return s?`/relay/devices/${encodeURIComponent(s)}${t}`:`/relay${t}`}return t}function So(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 ko(t,s){const r=s==null?void 0:s.trim(),n=r?`${t} ${r}`:`${t}`;return t===429?`Too many requests (${n}).`:t===503?`Upstream service unavailable (${n}).`:`Request failed (${n}).`}function is(t,s,r){const n=typeof(s==null?void 0:s.message)=="string"&&s.message.trim()?s.message.trim():r,c=s!=null&&s.details&&typeof s.details=="object"?s.details:void 0;return{code:(s==null?void 0:s.code)??So(t.status),message:n,...c?{details:c}:{}}}async function xa(t){var c,o;const s=ko(t.status,t.statusText),r=((o=(c=t.headers)==null?void 0:c.get)==null?void 0:o.call(c,"content-type"))??"",n=async()=>is(t,await t.json(),s);if(r.includes("application/json"))try{return await n()}catch{return is(t,null,s)}try{if(typeof t.text!="function")try{return await n()}catch{return is(t,null,s)}const p=(await t.text()).trim();if(p.startsWith("{"))try{return is(t,JSON.parse(p),s)}catch{}return is(t,p?{message:`${s}
2
- ${p}`}:null,s)}catch{try{return await n()}catch{return is(t,null,s)}}}async function U(t,s){const r=new Headers(s==null?void 0:s.headers);(s==null?void 0:s.body)!==void 0&&!(s.body instanceof FormData)&&!r.has("Content-Type")&&r.set("Content-Type","application/json");const n=await fetch(fa(String(t)),ba({...s,headers:r}));if(!n.ok){const c=await xa(n);throw new ae(n.status,c)}return await n.json()}function Co(t){const s=String(t);return s.includes("/exports/pdf")?s.includes("format=html")?"remote-codex-transcript.html":"remote-codex-transcript.pdf":"download"}function To(t){var c;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 r=t.match(/filename="([^"]+)"/i);if(r!=null&&r[1])return r[1].trim();const n=t.match(/filename=([^;]+)/i);return((c=n==null?void 0:n[1])==null?void 0:c.trim())??null}async function ga(t,s){const r=await fetch(fa(String(t)),ba(s));if(!r.ok){const c=await xa(r);throw new ae(r.status,c)}const n=To(r.headers.get("content-disposition"))??Co(t);return{blob:await r.blob(),filename:n}}function ba(t={}){const s=new Headers(t.headers),r=ma(),n=ua();return hs()&&r&&!s.has("Authorization")?s.set("Authorization",`Bearer ${r}`):n&&!s.has("Authorization")&&s.set("Authorization",`Bearer ${n}`),{...t,credentials:t.credentials??"same-origin",headers:s}}function Io(t,s){return`${t.baseUrl.replace(/\/+$/,"")}${s}`}function Eo(t,s){const r=new Headers(s==null?void 0:s.headers);return r.set("Authorization",`Bearer ${t.token}`),r}async function Ne(t,s,r){return U(Io(t,s),{...r,headers:Eo(t,r)})}function lr(t,s){return`${t.replace(/\/+$/,"")}${s}`}function Ro(t,s,r=typeof window>"u"?void 0:window.location.href){const n=new URL(lr(t,`/api/auth/oauth/${s}/start`));return r&&n.searchParams.set("returnTo",r),n.toString()}function Po(t,s){return U(lr(t,"/api/auth/password/register"),{method:"POST",body:JSON.stringify(s)})}function Ao(t,s){return U(lr(t,"/api/auth/password/login"),{method:"POST",body:JSON.stringify(s)})}function ir(t){return Ne(t,"/api/me",{cache:"no-store"})}function Uo(t,s=10){const r=new URLSearchParams({limit:String(s)});return Ne(t,`/api/usage/events?${r.toString()}`,{cache:"no-store"})}function Oo(t){return Ne(t,"/api/usage/harness/summary",{cache:"no-store"})}function Mo(t,s=10){const r=new URLSearchParams({limit:String(s)});return Ne(t,`/api/usage/harness/events?${r.toString()}`,{cache:"no-store"})}function $o(t,s){return Ne(t,"/api/me",{method:"PATCH",body:JSON.stringify(s)})}function va(t){return Ne(t,"/api/projects",{cache:"no-store"})}function Lo(t,s){return Ne(t,"/api/projects",{method:"POST",body:JSON.stringify(s)})}function Do(t,s,r){return Ne(t,`/api/projects/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(r)})}function Ho(t,s){return Ne(t,`/api/projects/${encodeURIComponent(s)}`,{method:"DELETE"})}function Zn(t,s){const r=s?`?projectId=${encodeURIComponent(s)}`:"";return Ne(t,`/api/workspaces${r}`,{cache:"no-store"})}function Bo(t,s){const r=s.projectId?`/api/projects/${encodeURIComponent(s.projectId)}/workspaces`:"/api/workspaces",n=s.projectId?{name:s.name,slug:s.slug}:s;return Ne(t,r,{method:"POST",body:JSON.stringify(n)})}function Er(t,s,r){return Ne(t,`/api/workspaces/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(r)})}function Xn(t,s){return Ne(t,`/api/workspaces/${encodeURIComponent(s)}/sessions`,{cache:"no-store"})}function _o(t,s,r){return Ne(t,`/api/workspaces/${encodeURIComponent(s)}/sessions`,{method:"POST",body:JSON.stringify(r)})}function Rr(t,s,r){return Ne(t,`/api/sessions/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(r)})}function Fo(t,s){return Ne(t,`/api/sessions/${encodeURIComponent(s)}/close`,{method:"POST"})}function ja(t,s){return Ne(t,`/api/sessions/${encodeURIComponent(s)}/resume`,{method:"POST"})}function Wo(t){return Ne(t,"/api/sandbox/start",{method:"POST"})}function qo(t){return Ne(t,"/api/sandbox/stop",{method:"POST"})}function zo(t){return Ne(t,"/api/sandbox/restart",{method:"POST"})}function Pr(t){return Ne(t,"/api/sandbox/health",{cache:"no-store"})}function Jo(t){return Ne(t,"/api/sandbox/harness/status",{cache:"no-store"})}function Ar(t,s){return Ne(t,`/api/sandbox/harness/modules/${encodeURIComponent(s)}/tools`,{cache:"no-store"})}function Ur(t,s){return Ne(t,`/api/sandbox/harness/modules/${encodeURIComponent(s)}/runs`,{cache:"no-store"})}function Vo(t,s){return Ne(t,`/api/admin/sandboxes/${encodeURIComponent(s)}`,{cache:"no-store"})}function ya(t,s,r){return Ne(t,`/api/sandboxes/${encodeURIComponent(s)}/route-token`,{method:"POST",body:JSON.stringify(r)})}function gn(t,s,r){const n=s.replace(/^\/+/,""),c=new URL(`/api/sandboxes/${encodeURIComponent(t.sandboxId)}/${n}`,t.routerBaseUrl);for(const[o,p]of Object.entries(r??{}))p!=null&&c.searchParams.set(o,String(p));return c.toString()}function bn(t,s){const r=new Headers(s==null?void 0:s.headers);return r.set("Authorization",`Bearer ${t.token}`),r}function ds(t,s,r={}){return U(gn(t,`/api/threads/${encodeURIComponent(s)}`,r),{cache:"no-store",headers:bn(t)})}function Go(t,s,r){return U(gn(t,`/api/threads/${encodeURIComponent(s)}/items/${encodeURIComponent(r)}/detail`),{cache:"no-store",headers:bn(t)})}function En(t,s,r){return U(gn(t,`/api/threads/${encodeURIComponent(s)}/prompt`),{method:"POST",body:JSON.stringify(r),headers:bn(t)})}function Or(t,s,r={}){return U(gn(t,`/api/threads/${encodeURIComponent(s)}/interrupt`),{method:"POST",body:JSON.stringify(r),headers:bn(t)})}function Mr(t,s){const r=t.originalName.trim();if(r)return r;const n=t.file.name.trim();return n||(t.kind==="photo"?`photo-${s+1}.jpg`:`file-${s+1}`)}function Ko(){return U("/api/config/runtime")}function Yo(){return U("/api/auth/session",{cache:"no-store"})}async function Zo(t){const s=await U("/api/auth/login",{method:"POST",body:JSON.stringify(t)});return wo(s.token??null),s}function Qn(){return U("/relay/auth/session",{credentials:"same-origin"})}async function Xo(t){xn();const s=await U("/relay/auth/login",{method:"POST",body:JSON.stringify(t)});return or(s.token),s}async function Qo(t){xn();const s=await U("/relay/auth/register",{method:"POST",body:JSON.stringify(t)});return or(s.token),s}async function el(){const t=await U("/relay/auth/logout",{method:"POST"});return or(null),Kn(null),Yn(null),t}function tl(){return U("/relay/portal")}function sl(t){return U("/relay/devices",{method:"POST",body:JSON.stringify(t)})}function nl(t){return U(`/relay/devices/${encodeURIComponent(t)}`,{method:"DELETE"})}function rl(t){return U("/relay/shares",{method:"POST",body:JSON.stringify(t)})}function al(t){return U(`/relay/shares/${encodeURIComponent(t)}`,{method:"DELETE"})}function ol(){return U("/relay/admin")}function ll(t){return U("/relay/admin/settings/registration",{method:"PATCH",body:JSON.stringify({enabled:t})})}function il(t,s){return U(`/relay/admin/users/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({enabled:s})})}function dl(){return U("/api/config/workspace-settings",{cache:"no-store"})}function cl(t){return U("/api/config/workspace-settings",{method:"PATCH",body:JSON.stringify(t)})}function dr(){return U("/api/agent-runtimes",{cache:"no-store"})}function wa(t){return U(`/api/agent-runtimes/${encodeURIComponent(t)}/status`,{cache:"no-store"})}function ul(t){return U(`/api/agent-runtimes/${encodeURIComponent(t)}/restart`,{method:"POST"})}function ml(t,s){return U(`/api/agent-runtimes/${encodeURIComponent(t)}/install`,{method:"POST",body:JSON.stringify({action:s})})}function er(t){return U(`/api/agent-runtimes/${encodeURIComponent(t)}/models`,{cache:"no-store"})}function Na(t,s){return U(`/api/config/providers/${encodeURIComponent(t)}/files/${encodeURIComponent(s)}`,{cache:"no-store"})}function Sa(t,s,r){return U(`/api/config/providers/${encodeURIComponent(t)}/files/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(r)})}function hl(t){return U(`/api/config/providers/${encodeURIComponent(t)}/archives`,{cache:"no-store"})}function pl(t,s={}){return U(`/api/config/providers/${encodeURIComponent(t)}/archives`,{method:"POST",body:JSON.stringify(s)})}function fl(t,s,r){return U(`/api/config/providers/${encodeURIComponent(t)}/archives/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(r)})}function xl(t,s){return U(`/api/config/providers/${encodeURIComponent(t)}/archives/${encodeURIComponent(s)}/apply`,{method:"POST"})}function gl(){return U("/api/service/build-restart",{method:"POST"})}function bl(){return U("/healthz",{cache:"no-store"})}function cr(){return U("/api/workspaces")}function vl(t){return U(`/api/workspaces/${encodeURIComponent(t)}/files/tree`,{cache:"no-store"})}function jl(t,s){const r=new URLSearchParams({path:s.path});return s.offset!==void 0&&r.set("offset",String(s.offset)),s.limit!==void 0&&r.set("limit",String(s.limit)),U(`/api/workspaces/${encodeURIComponent(t)}/files/preview?${r.toString()}`,{cache:"no-store"})}function yl(t,s){const r=new URLSearchParams({path:s.path});return`/api/workspaces/${encodeURIComponent(t)}/files/raw?${r.toString()}`}function wl(t,s){const r=new URLSearchParams({path:s.path});return ga(`/api/workspaces/${encodeURIComponent(t)}/files/download?${r.toString()}`,{cache:"no-store"})}function Nl(t,s){const r=new FormData;return r.append("file",s.file,s.file.name),U(`/api/workspaces/${encodeURIComponent(t)}/files/upload`,{method:"POST",body:r})}function ka(){return U("/api/threads")}function $r(t,s={}){const r=new URLSearchParams;return s.limit!==void 0&&r.set("limit",String(s.limit)),s.beforeTurnId&&r.set("beforeTurnId",s.beforeTurnId),U(`/api/threads/${t}${r.size>0?`?${r.toString()}`:""}`)}function Sl(t,s){return U(`/api/threads/${t}/items/${encodeURIComponent(s)}/detail`)}function kl(){return U("/api/plugins",{cache:"no-store"})}function Cl(t){return U("/api/plugins/import",{method:"POST",body:JSON.stringify(t)})}function Tl(t,s){return U(`/api/plugins/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(s)})}function Il(t){return U(`/api/plugins/${encodeURIComponent(t)}`,{method:"DELETE"})}function El(t){return U(`/api/threads/${t}/export-turns`,{cache:"no-store"})}function Rl(t,s){var n,c,o;const r=new URLSearchParams;return s.format!==void 0&&r.set("format",s.format),r.set("mode",s.mode),s.limit!==void 0&&r.set("limit",String(s.limit)),s.turnIds!==void 0&&r.set("turnIds",s.turnIds.join(",")),s.profile!==void 0&&r.set("profile",s.profile),((n=s.options)==null?void 0:n.includeTokenAndPrice)!==void 0&&r.set("includeTokenAndPrice",String(s.options.includeTokenAndPrice)),((c=s.options)==null?void 0:c.includeCommandOutput)!==void 0&&r.set("includeCommandOutput",String(s.options.includeCommandOutput)),((o=s.options)==null?void 0:o.includeAbsolutePaths)!==void 0&&r.set("includeAbsolutePaths",String(s.options.includeAbsolutePaths)),`/api/threads/${encodeURIComponent(t)}/exports/pdf?${r.toString()}`}function Pl(t,s){return ga(Rl(t,s),{cache:"no-store"})}function Al(t){return U(`/api/threads/${t}/shell`)}function Ul(t){return U("/api/threads/start",{method:"POST",body:JSON.stringify(t)})}function Ol(t){return U("/api/threads/import",{method:"POST",body:JSON.stringify(typeof t=="string"?{sessionId:t}:t)})}function Ml(t,s={}){return U(`/api/threads/${t}/shell`,{method:"POST",...Object.keys(s).length>0?{body:JSON.stringify(s)}:{}})}function $l(t){return U(`/api/shells/${t}/terminate`,{method:"POST"})}function Ll(t,s){return U(`/api/shells/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Lr(t,s={}){return U(`/api/threads/${t}/resume`,{method:"POST",...Object.keys(s).length>0?{body:JSON.stringify(s)}:{}})}function Dl(t){return U(`/api/threads/${t}/disconnect`,{method:"POST"})}function Hl(t,s){const r=s.attachments??[];if(r.length===0)return U(`/api/threads/${t}/prompt`,{method:"POST",body:JSON.stringify(s)});const n=new FormData;n.append("prompt",s.prompt),s.clientRequestId!==void 0&&n.append("clientRequestId",s.clientRequestId),s.model!==void 0&&n.append("model",s.model),s.reasoningEffort!==void 0&&s.reasoningEffort!==null&&n.append("reasoningEffort",s.reasoningEffort),s.collaborationMode!==void 0&&n.append("collaborationMode",s.collaborationMode),s.sandboxMode!==void 0&&s.sandboxMode!==null&&n.append("sandboxMode",s.sandboxMode);const c=r.map((o,p)=>({clientId:o.clientId,kind:o.kind,originalName:Mr(o,p),placeholder:o.placeholder}));n.append("attachmentManifest",JSON.stringify(c));for(const[o,p]of r.entries())n.append("attachments",p.file,Mr(p,o));return U(`/api/threads/${t}/prompt`,{method:"POST",body:n})}function Dr(t,s={}){return U(`/api/threads/${t}/interrupt`,{method:"POST",body:JSON.stringify(s)})}function Ca(t,s){return U(`/api/threads/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Ta(t){return U(`/api/threads/${t}`,{method:"DELETE"})}function Bl(t,s){return U(`/api/threads/${t}/settings`,{method:"PATCH",body:JSON.stringify(s)})}function _l(t){return U(`/api/threads/${t}/compact`,{method:"POST"})}function Fl(t){return U(`/api/threads/${t}/goal`,{cache:"no-store"})}function Wl(t,s){return U(`/api/threads/${t}/goal`,{method:"PATCH",body:JSON.stringify(s)})}function ql(t){return U(`/api/threads/${t}/goal`,{method:"DELETE"})}function zl(t){return U(`/api/threads/${t}/fork-turns`,{cache:"no-store"})}function Hr(t,s){return U(`/api/threads/${t}/fork`,{method:"POST",body:JSON.stringify(s)})}function Jl(t){return U(`/api/threads/${t}/skills`,{cache:"no-store"})}function Vl(t){return U(`/api/threads/${t}/mcp-servers`,{cache:"no-store"})}function Gl(t){return U(`/api/threads/${t}/hooks`,{cache:"no-store"})}function Kl(t,s){return U(`/api/threads/${t}/hooks`,{method:"POST",body:JSON.stringify(s)})}function Yl(t,s){return U(`/api/threads/${t}/hooks`,{method:"PUT",body:JSON.stringify(s)})}function Zl(t,s){return U(`/api/threads/${t}/hooks/trust`,{method:"POST",body:JSON.stringify(s)})}function Xl(t,s){return U(`/api/threads/${t}/hooks/untrust`,{method:"POST",body:JSON.stringify(s)})}function Ql(t,s,r){return U(`/api/threads/${t}/requests/${encodeURIComponent(s)}/respond`,{method:"POST",body:JSON.stringify(r)})}function ei(t){return U("/api/workspaces",{method:"POST",body:JSON.stringify(t)})}function ti(t,s){return U(`/api/workspaces/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function si(t){return U(`/api/workspaces/${t}`,{method:"DELETE"})}function ni(t,s){return U(`/api/workspaces/${t}/favorite`,{method:"POST",body:JSON.stringify(s)})}function Ia(t){const s=window.location.protocol==="https:"?"wss:":"ws:",r=new WebSocket(Ea(s));return r.addEventListener("message",n=>{try{const c=JSON.parse(n.data);ai(c)&&t(c)}catch{}}),r}function ri(t={}){const s=window.location.protocol==="https:"?"wss:":"ws:",r=new WebSocket(Ea(s));return r.addEventListener("message",n=>{var c,o;try{const p=JSON.parse(n.data);if(p.type==="supervisor.connected"){(c=t.onConnected)==null||c.call(t,p);return}oi(p)&&((o=t.onShellEvent)==null||o.call(t,p))}catch{}}),{socket:r,send(n){r.send(JSON.stringify(n))}}}function Ea(t){const s=new URL(`${t}//${window.location.host}/ws`);if(hs()){const o=pa();s.pathname=o?`/relay/devices/${encodeURIComponent(o)}/ws`:"/relay/ws"}const r=ua(),n=ma(),c=No();return hs()&&n&&s.searchParams.set("relaySession",n),hs()&&c&&s.searchParams.set("threadId",c),r&&s.searchParams.set("token",r),s.toString()}function ai(t){return"threadId"in t&&t.type.startsWith("thread.")&&typeof t.payload=="object"&&t.payload!==null}function oi(t){return"shellId"in t&&t.type.startsWith("shell.")&&typeof t.payload=="object"&&t.payload!==null}function li(){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 cn(){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 Rn(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 ii=[{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."}],Ra={hostConfigFiles:[],toolboxItems:[],hookCommandTemplates:[],providerConfigFormat:"none",mcpConfigFormat:"none",configArchives:!1,buildRestart:!1},di={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 tr(t){const s=di[t];return{packageName:s.packageName,installed:t==="codex",installedVersion:null,latestVersion:null,installCommand:s.installCommand,updateCommand:s.updateCommand,busy:!1,lastError:null}}function ci(t,s){return{provider:t,displayName:s,description:`${s} backend descriptor is not available.`,enabled:!1,isDefault:t===ia,status:{state:"stopped",transport:da[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:Ra,installation:tr(t)}}function Pn(t){const s=t.installation??tr(t.provider);return{...t,installation:{...tr(t.provider),...s}}}const us=[...vo.map(t=>ci(t,da[t].displayName))];function ui(t){var s;return((s=us.find(r=>r.provider===t))==null?void 0:s.managementSchema)??Ra}function mi(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 hi(t){const s=t.payload.details,r=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 r?`${t.message}
3
- ${r}`:t.message}function Cs(t){return{path:t,exists:!1,originalContent:"",draftContent:"",loading:!1,saving:!1,error:null,saveMessage:null}}function Pa({className:t=""}){const s=zt();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(cn,{}):e.jsx(li,{})}):null}function Aa({className:t=""}){const s=zt(),r=Ps(),n=ht(),c=a.useRef(null),o=r.pathname==="/workspaces",p=r.pathname==="/threads/import";return a.useEffect(()=>{if(!(s!=null&&s.navOpen))return;const m=s;function g(w){const P=w.target;if(!P)return;const x=c.current;x!=null&&x.contains(P)||P instanceof Element&&P.closest('[aria-controls="app-shell-navigation-menu"]')||m.closeNav()}return document.addEventListener("pointerdown",g),()=>{document.removeEventListener("pointerdown",g)}},[s]),s!=null&&s.navOpen?e.jsxs("div",{ref:c,id:"app-shell-navigation-menu",onPointerDown:m=>{m.stopPropagation()},onMouseDown:m=>{m.stopPropagation()},onTouchStart:m=>{m.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:Rn(o),children:"Workspaces"}),e.jsx("button",{type:"button",disabled:p,onClick:()=>{p||(s.closeNav(),n("/threads/import"))},className:Rn(p),children:"Import Session"}),e.jsx("button",{type:"button",onClick:()=>{s.openSettings()},className:Rn(),children:"Settings"})]})]}):null}function ur({embedded:t=!1}={}){const s=zt(),r=ar(),[n,c]=a.useState(""),[o,p]=a.useState({busy:!1,message:null,error:null}),[m,g]=a.useState(!1),[w,P]=a.useState(null),[x,f]=a.useState({}),k=w?x[w]:null,[C,R]=a.useState({busy:!1,message:null,error:null}),[v,Q]=a.useState([]),[oe,ee]=a.useState(us),[_,le]=a.useState({loading:!1,saving:!1,error:null,operatingProvider:null,operatingAction:null,message:null}),[u,B]=a.useState(null),[ne,T]=a.useState({devHomeDraft:"",loading:!1,saving:!1,message:null,error:null}),[K,z]=a.useState({loading:!1,creating:!1,applyingId:null,renamingId:null,renameDraft:"",message:null,error:null}),L=(s==null?void 0:s.themeMode)??"system",Z=t||!!(s!=null&&s.settingsOpen);async function A(){const b=n.trim();if(!(!b||o.busy)){p({busy:!0,message:null,error:null});try{await r.importPluginManifest({manifestJson:b,enabled:!0}),c(""),p({busy:!1,message:"Plugin manifest imported.",error:null})}catch(y){p({busy:!1,message:null,error:y instanceof Error?y.message:"Unable to import plugin manifest."})}}}const ie=(s==null?void 0:s.effectiveTheme)??"dark",Y=(s==null?void 0:s.defaultBackend)??ia,Ce=r.plugins.filter(b=>b.enabled).length,fe=r.loading?"Loading...":`${Ce}/${r.plugins.length} enabled`,D=oe.find(b=>b.provider===Y)??us.find(b=>b.provider===Y)??us[0],re=D.managementSchema??ui(D.provider),H=re.hostConfigFiles;a.useEffect(()=>{if(!Z||t||!s||!re.configArchives)return;const b=s;function y(I){I.key==="Escape"&&b.closeSettings()}return window.addEventListener("keydown",y),()=>{window.removeEventListener("keydown",y)}},[re.configArchives,t,Z,s]),a.useEffect(()=>{if(!Z)return;let b=!1;return le(y=>({...y,loading:!0,error:null})),dr().then(y=>{if(b)return;const I=[...y.map(Pn),...us.filter(V=>!y.some(be=>be.provider===V.provider))];ee(I),le(V=>({...V,loading:!1}))}).catch(y=>{b||(ee(us),le(I=>({...I,loading:!1,error:y instanceof ae?y.message:"Unable to load backend settings."})))}),()=>{b=!0}},[Z]),a.useEffect(()=>{if(!Z)return;let b=!1;return T(y=>({...y,loading:!0,message:null,error:null})),dl().then(y=>{b||(B(y),T(I=>({...I,devHomeDraft:y.devHome,loading:!1})))}).catch(y=>{b||T(I=>({...I,loading:!1,error:y instanceof ae?y.message:"Unable to load workspace settings."}))}),()=>{b=!0}},[Z]),a.useEffect(()=>{if(!Z||!D.capabilities.management.hostConfigFiles)return;let b=!1;async function y(){f(V=>{const be={...V};for(const Pe of H)be[Pe.name]={...Cs(Pe.name),...V[Pe.name],loading:!0,saving:!1,error:null,saveMessage:null};return be});const I=await Promise.allSettled(H.map(async V=>({name:V.name,result:await Na(D.provider,V.name)})));b||f(V=>{var Pe,ut;const be={...V};for(const Ae of I){if(Ae.status==="fulfilled"){const{name:rt,result:Ge}=Ae.value;be[rt]={path:Ge.path,exists:Ge.exists,originalContent:Ge.content,draftContent:Ge.content,loading:!1,saving:!1,error:null,saveMessage:null};continue}const yt=Ae.reason instanceof ae?Ae.reason.message:"Unable to load the file.",Ve=((Pe=H[I.indexOf(Ae)])==null?void 0:Pe.name)??((ut=H[0])==null?void 0:ut.name);Ve&&(be[Ve]={...Cs(Ve),...be[Ve],loading:!1,saving:!1,error:yt,saveMessage:null})}return be})}return y(),()=>{b=!0}},[D.capabilities.management.hostConfigFiles,D.provider,H,Z]),a.useEffect(()=>{if(!Z)return;let b=!1;async function y(){z(I=>({...I,loading:!0,error:null,message:null}));try{const I=await hl(D.provider);if(b)return;Q(I),z(V=>({...V,loading:!1}))}catch(I){if(b)return;z(V=>({...V,loading:!1,error:I instanceof ae?I.message:"Unable to load config archives."}))}}return y(),()=>{b=!0}},[D.provider,re.configArchives,Z]);async function ge(){if(!(C.busy||_.saving)){R({busy:!0,message:null,error:null});try{const b=await ul(D.provider),y=Pn(b);R({busy:!1,message:y.status.state==="ready"?`${y.displayName} backend restarted.`:`${y.displayName} backend state: ${y.status.state}`,error:null}),ee(I=>I.map(V=>V.provider===y.provider?y:V))}catch(b){R({busy:!1,message:null,error:b instanceof ae?b.message:"Unable to restart the app server."})}}}async function pe(b,y){if(C.busy||_.saving)return;const I=oe.find(V=>V.provider===b);le(V=>({...V,saving:!0,operatingProvider:b,operatingAction:y,message:null,error:null}));try{const V=await ml(b,y),be=Pn(V);ee(Pe=>Pe.map(ut=>ut.provider===be.provider?be:ut)),le(Pe=>({...Pe,saving:!1,operatingProvider:null,operatingAction:null,message:be.installation.lastError?`${be.displayName} ${y==="install"?"installed":"updated"}, but requires attention:
4
- ${be.installation.lastError}`:`${be.displayName} ${y==="install"?"installed":"updated"}.`,error:null}))}catch(V){le(be=>({...be,saving:!1,operatingProvider:null,operatingAction:null,message:null,error:V instanceof ae?hi(V):`Unable to ${y} ${(I==null?void 0:I.displayName)??b}.`}))}}async function nt(){if(!(C.busy||_.saving)){R({busy:!0,message:null,error:null});try{await gl(),R({busy:!1,message:"Build and restart launched. The page may disconnect briefly.",error:null})}catch(b){R({busy:!1,message:null,error:b instanceof ae?b.message:"Unable to launch build and restart."})}}}async function it(){const b=ne.devHomeDraft.trim();if(!(!b||ne.saving)){T(y=>({...y,saving:!0,message:null,error:null}));try{const y=await cl({devHome:b});B(y),T(I=>({...I,devHomeDraft:y.devHome,saving:!1,message:"Workspace defaults saved."}))}catch(y){T(I=>({...I,saving:!1,error:y instanceof ae?y.message:"Unable to save workspace settings."}))}}}async function Ye(b){const y=x[b];if(!(!y||y.saving)){f(I=>({...I,[b]:{...Cs(b),...I[b],saving:!0,error:null,saveMessage:null}}));try{const I=await Sa(D.provider,b,{content:y.draftContent});f(V=>({...V,[b]:{path:I.path,exists:I.exists,originalContent:I.content,draftContent:I.content,loading:!1,saving:!1,error:null,saveMessage:"Saved"}}))}catch(I){f(V=>({...V,[b]:{...Cs(b),...V[b],saving:!1,error:I instanceof ae?I.message:"Unable to save the file.",saveMessage:null}}))}}}async function jt(){if(!K.creating){z(b=>({...b,creating:!0,message:null,error:null}));try{const b=await pl(D.provider);Q(y=>[b,...y]),z(y=>({...y,creating:!1,message:"Backup created."}))}catch(b){z(y=>({...y,creating:!1,error:b instanceof ae?b.message:"Unable to create a config backup."}))}}}async function We(b){if(!K.applyingId){z(y=>({...y,applyingId:b.id,message:null,error:null}));try{const y=await xl(D.provider,b.id);z(I=>({...I,applyingId:null,message:y.status.state==="ready"?`Applied "${y.archive.label}" and restarted ${D.displayName}.`:`Applied "${y.archive.label}". ${D.displayName} state: ${y.status.state}.`}))}catch(y){z(I=>({...I,applyingId:null,error:y instanceof ae?y.message:"Unable to apply the config archive."}))}}}async function dt(b){const y=K.renameDraft.trim();if(!(!y||K.renamingId!==b.id)){z(I=>({...I,message:null,error:null}));try{const I=await fl(D.provider,b.id,{label:y});Q(V=>V.map(be=>be.id===b.id?I:be)),z(V=>({...V,renamingId:null,renameDraft:"",message:"Backup renamed."}))}catch(I){z(V=>({...V,error:I instanceof ae?I.message:"Unable to rename the config backup."}))}}}if(!Z)return null;const Le=e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-3 grid gap-2",children:[r.plugins.map(b=>e.jsxs("label",{className:"flex items-start justify-between gap-3 rounded-[1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-2.5",children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-sm font-medium text-[var(--theme-fg)]",children:b.name}),e.jsx("span",{className:"mt-1 block text-xs leading-5 text-[var(--theme-fg-muted)]",children:b.description}),e.jsx("span",{className:"mt-2 block text-[10px] uppercase tracking-[0.16em] text-[var(--theme-fg-muted)]",children:[...b.capabilities.artifactTypes.map(y=>y.type),...b.capabilities.threadPanels.map(y=>y.kind??y.id)].join(", ")||"utility"}),e.jsx("span",{className:"mt-1 block text-[10px] uppercase tracking-[0.16em] text-[var(--theme-fg-muted)]",children:b.source==="imported"?"Imported manifest":"Built-in module"})]}),e.jsx("input",{type:"checkbox",checked:b.enabled,onChange:y=>void r.setPluginEnabled(b.id,y.currentTarget.checked),className:"mt-1 h-4 w-4 shrink-0 accent-[var(--theme-accent-solid)]"})]},b.id)),r.plugins.length===0&&e.jsx("p",{className:"rounded-[1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-3 text-xs text-[var(--theme-fg-muted)]",children:"No plugins are registered."})]}),e.jsxs("div",{className:"mt-3 border-t border-[var(--theme-border)] pt-3",children:[e.jsx("label",{className:"block text-xs font-medium text-[var(--theme-fg)]",children:"Import manifest JSON"}),e.jsx("textarea",{value:n,onChange:b=>{c(b.currentTarget.value),(o.message||o.error)&&p({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 A(),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})]}),r.error&&e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:r.error})]}),ct=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(cn,{})})]})}),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:"," ",ie,"."]})]})}),e.jsx("div",{className:"mt-3 grid gap-2 sm:grid-cols-3",children:ii.map(b=>{const y=L===b.value;return e.jsxs("button",{type:"button",onClick:()=>s==null?void 0:s.setThemeMode(b.value),className:`block rounded-[1rem] border px-3 py-2.5 text-left transition ${y?"border-[var(--theme-accent-border)] bg-[var(--theme-accent-soft)]":"border-[var(--theme-border)] bg-[var(--theme-surface-strong)] hover:bg-[var(--theme-hover)]"}`,children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-sm font-medium text-[var(--theme-fg)]",children:b.label}),y?e.jsx("span",{className:"rounded-full border border-[var(--theme-accent-border)] bg-[var(--theme-accent-soft)] px-2 py-0.5 text-[10px] uppercase tracking-[0.18em] text-[var(--theme-accent-strong)]",children:"Active"}):null]}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:b.description})]},b.value)})})]}),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 r.refresh(),disabled:r.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:r.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:fe}),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:(u==null?void 0:u.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:ne.loading&&!u?"Loading...":(u==null?void 0:u.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:ne.devHomeDraft,onChange:b=>T(y=>({...y,devHomeDraft:b.target.value,message:null,error:null})),placeholder:"/Users/name/dev",className:"min-w-0 flex-1 rounded-full border border-[var(--theme-border)] bg-[var(--theme-panel)] px-3 py-2 text-sm text-[var(--theme-fg)] outline-none focus:border-[var(--theme-accent-border)]"}),e.jsx("button",{type:"button","aria-label":"Save workspace defaults",onClick:()=>void it(),disabled:ne.loading||ne.saving||!ne.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:ne.saving?"Saving...":"Save"})]})]})]}),ne.error?e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:ne.error}):ne.message?e.jsx("p",{className:"mt-2 text-xs text-emerald-300",children:ne.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 ge(),disabled:C.busy||_.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 nt(),disabled:C.busy||_.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:oe.map(b=>{const y=b.installation,I=!y.installed&&!!y.installCommand,V=y.installed&&!!y.updateCommand,be=_.saving&&_.operatingProvider===b.provider,Pe=I?"Install":"Update";return e.jsxs("div",{className:"flex flex-col gap-2 rounded-[0.95rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-2 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-[var(--theme-fg)]",children:b.displayName}),e.jsx("span",{className:`rounded-full border px-2 py-0.5 text-[10px] uppercase tracking-[0.16em] ${b.enabled?"border-emerald-400/35 bg-emerald-400/10 text-emerald-400":"border-[var(--theme-border)] bg-[var(--theme-muted)] text-[var(--theme-fg-muted)]"}`,children:b.enabled?"Ready":y.installed?b.status.state:"Not installed"})]}),e.jsxs("p",{className:"mt-1 truncate text-xs text-[var(--theme-fg-muted)]",children:["Version:"," ",y.installedVersion??(y.installed?"Installed":"Unavailable"),y.latestVersion?` · Latest: ${y.latestVersion}`:""]}),y.lastError?e.jsx("p",{className:"mt-1 line-clamp-2 text-xs text-rose-300",children:y.lastError}):null]}),I||V?e.jsx("button",{type:"button","aria-label":`${I?"Install":"Update"} ${b.displayName}`,onClick:()=>void pe(b.provider,I?"install":"update"),disabled:C.busy||_.saving||!I&&!V,className:"shrink-0 rounded-full border border-[var(--theme-border-strong)] bg-[var(--theme-panel)] px-3 py-1.5 text-xs font-medium text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:bg-[var(--theme-muted)] disabled:text-[var(--theme-fg-muted)]",children:be?_.operatingAction==="install"?"Installing...":"Updating...":Pe}):null]},b.provider)})}),C.error?e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:C.error}):C.message?e.jsx("p",{className:"mt-2 text-xs text-emerald-300",children:C.message}):_.message?e.jsx("p",{className:`mt-2 whitespace-pre-line text-xs ${_.message.includes("requires attention")?"text-amber-300":"text-emerald-300"}`,children:_.message}):_.error?e.jsx("p",{className:"mt-2 whitespace-pre-line text-xs text-rose-300",children:_.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:[D.displayName," exposes these editable files through its backend schema."]})]})}),e.jsxs("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:[H.map(b=>{const y=x[b.name]??{path:b.name,exists:!1,originalContent:"",draftContent:"",loading:!1},I=y.draftContent!==y.originalContent;return e.jsx("button",{type:"button",onClick:()=>P(b.name),className:"block rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-3 text-left transition hover:bg-[var(--theme-hover)]",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:b.label}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:b.description})]}),e.jsx("div",{className:"shrink-0",children:y.loading?e.jsx("span",{className:"text-[11px] uppercase tracking-[0.2em] text-[var(--theme-fg-muted)]",children:"Loading"}):I?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"}):y.exists?e.jsx("span",{className:"rounded-full border border-emerald-400/25 bg-emerald-400/10 px-2 py-0.5 text-[10px] uppercase tracking-[0.18em] text-emerald-600 dark:text-emerald-100",children:"Ready"}):e.jsx("span",{className:"rounded-full border border-sky-300/25 bg-sky-300/10 px-2 py-0.5 text-[10px] uppercase tracking-[0.18em] text-sky-600 dark:text-sky-100",children:"New"})})]})},b.name)}),H.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]})]}),re.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:K.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:K.creating?"Creating...":"Create backup"})]}),K.error?e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:K.error}):K.message?e.jsx("p",{className:"mt-2 text-xs text-emerald-300",children:K.message}):null,e.jsx("div",{className:"mt-3 space-y-2",children:K.loading?e.jsx("p",{className:"rounded-[1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-3 text-xs text-[var(--theme-fg-muted)]",children:"Loading backups..."}):v.length===0?e.jsx("p",{className:"rounded-[1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-3 text-xs text-[var(--theme-fg-muted)]",children:"No config backups yet."}):v.map(b=>{const y=K.renamingId===b.id;return e.jsx("div",{className:"rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-3",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[y?e.jsxs("div",{className:"flex max-w-xl gap-2",children:[e.jsx("input",{"aria-label":`Rename ${b.label}`,value:K.renameDraft,onChange:I=>z(V=>({...V,renameDraft:I.target.value,error:null,message:null})),className:"min-w-0 flex-1 rounded-full border border-[var(--theme-border)] bg-[var(--theme-panel)] px-3 py-1.5 text-sm text-[var(--theme-fg)] outline-none focus:border-[var(--theme-accent-border)]"}),e.jsx("button",{type:"button","aria-label":`Save archive name ${b.label}`,onClick:()=>void dt(b),className:"rounded-full bg-[var(--theme-accent-solid)] px-3 py-1.5 text-xs font-medium text-[var(--theme-accent-solid-fg)] transition hover:bg-[var(--theme-accent-solid-hover)]",children:"Save"}),e.jsx("button",{type:"button",onClick:()=>z(I=>({...I,renamingId:null,renameDraft:""})),className:"rounded-full border border-[var(--theme-border)] bg-[var(--theme-panel)] px-3 py-1.5 text-xs font-medium text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)]",children:"Cancel"})]}):e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:b.label}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-2 text-[11px] text-[var(--theme-fg-muted)]",children:[e.jsxs("span",{children:["Created ",mi(b.createdAt)]}),H.map(I=>{var V;return e.jsxs("span",{className:"rounded-full border border-[var(--theme-border)] bg-[var(--theme-panel)] px-2 py-0.5 font-mono",children:[I.name,":"," ",(V=b.files[I.name])!=null&&V.exists?"saved":"missing"]},I.name)})]})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2",children:[e.jsx("button",{type:"button",onClick:()=>z(I=>({...I,renamingId:b.id,renameDraft:b.label,message:null,error:null})),disabled:y,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 We(b),disabled:K.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:K.applyingId===b.id?"Applying...":"Apply"})]})]})},b.id)})})]}):null]})})]});return t?e.jsxs("div",{className:"flex min-h-0 flex-col overflow-hidden",children:[ct,m?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:fe})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx("button",{type:"button",onClick:()=>void r.refresh(),disabled:r.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:r.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(cn,{})})]})]}),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:ct}),w&&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:w}),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 ${w}`,onClick:()=>void Ye(w),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:()=>P(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(cn,{})})]})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto p-4 sm:p-5",children:e.jsx("textarea",{"aria-label":`Edit ${w}`,value:k.draftContent,onChange:b=>f(y=>({...y,[w]:{...Cs(w),...y[w],draftContent:b.target.value,error:null,saveMessage:null}})),spellCheck:!1,className:"min-h-[28rem] w-full rounded-[1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-3 font-mono text-[13px] leading-6 text-[var(--theme-fg)] outline-none transition focus:border-[var(--theme-accent-border)]",placeholder:k.loading?"Loading...":`Edit ${w} here`})})]})}):null]})}const pi="http://127.0.0.1:8790",mr="remote-codex-control-plane-auth";function fi(t){const s=t.baseUrl||pi;if(t.token){const r={baseUrl:s,token:t.token};return t.email!==void 0&&(r.email=t.email),t.displayName!==void 0&&(r.displayName=t.displayName),t.expiresAt!==void 0&&(r.expiresAt=t.expiresAt),r}if(t.subject){const r={baseUrl:s,token:`dev:${t.subject}`};return t.email!==void 0&&(r.email=t.email),t.displayName!==void 0&&(r.displayName=t.displayName),r}return null}function Zt(){if(typeof window>"u")return null;const t=window.localStorage.getItem(mr);if(!t)return null;try{const s=fi(JSON.parse(t));return!(s!=null&&s.baseUrl)||!s.token||s.expiresAt&&Date.parse(s.expiresAt)<=Date.now()?null:s}catch{return null}}function un(t){window.localStorage.setItem(mr,JSON.stringify(t))}function hn(){window.localStorage.removeItem(mr)}function xi(){return!!Zt()}function gi({eyebrow:t,hidden:s,onClose:r,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:r,"aria-label":"Close details inspector",children:"x"})]}),n]})})}function bi({topBar:t,alerts:s,children:r,sidebar:n,main:c,inspector:o,inspectorOpen:p}){const m=r??e.jsxs(e.Fragment,{children:[n,e.jsx("main",{className:"control-main-column",children:c}),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 ${p?"inspector-open":"inspector-collapsed"}`,children:m})]})}function vi({children:t}){return e.jsx("aside",{className:"control-explorer-panel",children:t})}function ji({title:t,subtitle:s,actions:r}){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:r})]})}const yi=6e4,wi=5e3,Ni=3e3,tn={estructural:"Estructural",quntur:"Quntur",farmaco:"Farmaco"};function sn(t){if(!t)return"no activity yet";const s=Date.parse(t);if(!Number.isFinite(s))return t;const r=Date.now()-s,n=Math.abs(r),c=r>=0?"ago":"from now",o=6e4,p=60*o,m=24*p;return n<o?"just now":n<p?`${Math.round(n/o)}m ${c}`:n<m?`${Math.round(n/p)}h ${c}`:`${Math.round(n/m)}d ${c}`}function An(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function Ot(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 we(t){return t?t.split(/[_\s-]+/).filter(Boolean).map(s=>`${s.charAt(0).toUpperCase()}${s.slice(1)}`).join(" "):"Unknown"}function Es(t){switch(t){case"empty":return"Local workspace";case"git":return"Git workspace";default:return we(t)}}function Si(t){return Es(t.sourceType)}function Un(t){return t.workerSessionId?"Runtime ready":"Not started"}function Ts(t){return t?`${t.type}:${t.id}`:""}function nn(t){switch(t){case"codex":return"Codex";case"claude":return"Claude";case"opencode":return"OpenCode";default:return we(t)}}function Br({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 ki(){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 Ci(){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 Ti(){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 Ii(){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 Ei(){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 _r(t){switch(t){case"connecting":return"Connecting";case"ready":return"Ready";case"reconnecting":return"Reconnecting";default:return"Idle"}}function Ri(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":we(t.state)}function Pi(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 Ai(t,s){const r="Sign in before managing the sandbox.";if(!t)return{start:{label:"Start",disabled:!0,title:r},stop:{label:"Stop",disabled:!0,title:r},restart:{label:"Restart",disabled:!0,title:r},health:{label:"Health",disabled:!0,title:r},inspect:{label:"Inspect",disabled:!0,title:r}};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,c=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:!c,title:c?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 Ui(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 Oi(t,s){return s?"unavailable":t?!t.enabled||!t.chemistryToolsEnabled?"not configured":t.keyPresent?t.health?"ready":"degraded":"missing key":"idle"}function Fr(t){switch(t){case"ready":return Ot("running");case"unavailable":case"missing key":return Ot("failed");case"not configured":case"idle":return Ot("stopped");default:return Ot("starting")}}function Wr(t){return t?typeof t.text=="string"?t.text.trim():t.payload===void 0?"":JSON.stringify(t.payload,null,2):""}function qr(t){const s=t==null?void 0:t.payload;if(Array.isArray(s))return s;if(s&&typeof s=="object")for(const r of["tools","runs","items","artifacts"]){const n=s[r];if(Array.isArray(n))return n}return[]}function zr(t,s){if(!t||typeof t!="object")return String(t??s);const r=t;for(const n of["name","tool","run_id","id","title","path"]){const c=r[n];if(typeof c=="string"&&c.trim())return c}return s}function Jr(t){if(!t||typeof t!="object")return"";const s=t;return["status","type","module","execution_mode"].map(r=>{const n=s[r];return typeof n=="string"&&n.trim()?n:null}).filter(Boolean).join(" / ")}function rn({label:t,value:s,onChange:r,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:c=>r(c.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:r=!1,type:n="button",title:c,ariaLabel:o}){return e.jsx("button",{type:n,"aria-label":o,onClick:s,disabled:r,title:c,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 r=s&&s.trim()?s:"not assigned";return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsxs("dd",{children:[e.jsx("span",{children:r}),s?e.jsx("button",{type:"button",className:"control-copy-button",onClick:()=>{var n;(n=navigator.clipboard)==null||n.writeText(s)},children:"Copy"}):null]})]})}function Mi({status:t}){return e.jsx("span",{className:`control-status-pill compact ${Ot(t)}`,children:we(t)})}function On({label:t,onEdit:s,onDelete:r}){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(Ii,{})}),e.jsx("button",{type:"button",className:"control-tree-action-button danger",onClick:n=>{n.stopPropagation(),r()},"aria-label":`Delete ${t}`,title:`Delete ${t}`,children:e.jsx(Ei,{})})]})}function Mn({label:t,value:s,onChange:r,onCancel:n,onSubmit:c}){return e.jsxs("form",{className:"control-tree-edit-form",onSubmit:c,children:[e.jsxs("label",{children:[e.jsx("span",{children:t}),e.jsx("input",{value:s,onChange:o=>r(o.currentTarget.value),autoFocus:!0})]}),e.jsx("button",{type:"submit",children:"Save"}),e.jsx("button",{type:"button",onClick:n,children:"Cancel"})]})}function $i(){var Qs;const t=ht(),[s,r]=a.useState(()=>{const d=Zt();return d?{baseUrl:d.baseUrl,token:d.token}:null}),[n,c]=a.useState(null),[o,p]=a.useState(null),[m,g]=a.useState(null),[w,P]=a.useState(null),[x,f]=a.useState(null),[k,C]=a.useState([]),[R,v]=a.useState(null),[Q,oe]=a.useState([]),[ee,_]=a.useState([]),[le,u]=a.useState([]),[B,ne]=a.useState([]),[T,K]=a.useState(""),[z,L]=a.useState(""),[Z,A]=a.useState(""),[ie,Y]=a.useState(null),[Ce,fe]=a.useState(null),[D,re]=a.useState(null),[H,ge]=a.useState(null),[pe,nt]=a.useState("farmaco"),[it,Ye]=a.useState(null),[jt,We]=a.useState(null),[dt,Le]=a.useState(null),[ct,b]=a.useState("Computational chemistry"),[y,I]=a.useState("Molecule study"),[V,be]=a.useState("Plan calculation"),[Pe,ut]=a.useState("codex"),[Ae,yt]=a.useState(null),[Ve,rt]=a.useState(""),[Ge,Ze]=a.useState(null),[Tt,Mt]=a.useState(null),[Jt,Vt]=a.useState(null),[X,de]=a.useState(null),[ue,me]=a.useState(!1),[Se,F]=a.useState(null),[Xe,Me]=a.useState(!1),[Qe,pt]=a.useState("summary"),[$t,ft]=a.useState(()=>{var d;return((d=Zt())==null?void 0:d.displayName)??""}),[ps,fs]=a.useState(null),[xs,wt]=a.useState(null),[Gt,xt]=a.useState(null),[gs,ye]=a.useState(null),[at,Nt]=a.useState(null),[It,bs]=a.useState(null),[et,mt]=a.useState({projects:!1,workspaces:!1,sessions:!1,usageEvents:!1,harness:!1}),[Et,qe]=a.useState("idle"),Te=a.useRef(null),Lt=a.useRef(null),St=!!(s&&n),ke=(o==null?void 0:o.state)==="running",ve=Ai(St,o),As=(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,W=a.useMemo(()=>ee.find(d=>d.id===T)??null,[ee,T]),G=a.useMemo(()=>le.find(d=>d.id===z)??null,[z,le]),te=a.useMemo(()=>B.find(d=>d.id===Z)??null,[Z,B]),vs=St&&!!W,Qt=St&&!!G&&ke,js=Ui(o),Rt=W?void 0:"Select a project before creating a workspace.",Pt=G?ke?void 0:"Start the sandbox before creating a session.":"Select a workspace before creating a session.",Us=te?ke?void 0:"Start the sandbox before connecting a session.":"Select a session before connecting.",kt=G?"session":W?"workspace":"project",Dt=kt==="project"?"Project":kt==="workspace"?"Workspace":"Session",gt=Se==="project"?"Create project":Se==="workspace"?`Create workspace in ${(W==null?void 0:W.name)??"project"}`:Se==="session"?`Create session in ${(G==null?void 0:G.name)??"workspace"}`:"",Ht=Se==="workspace"?Rt:Se==="session"?Pt:void 0,ys=[W==null?void 0:W.name,G==null?void 0:G.name,te==null?void 0:te.title].filter(Boolean).join(" / "),Kt=Oi(H,dt),Os=H!=null&&H.modules.length?H.modules:["farmaco","quntur","estructural"],he=qr(it),At=qr(jt),es=Wr(it),ts=Wr(jt),ws=((n==null?void 0:n.displayName)??(n==null?void 0:n.email)??"U").trim().charAt(0).toUpperCase()||"U",Ms=((w==null?void 0:w.inputTokens)??0)+((w==null?void 0:w.outputTokens)??0),ot=(x==null?void 0:x.totalCostUsd)??Number((w==null?void 0:w.costUsd)??0)+Number((R==null?void 0:R.costUsd)??0),ss=B.filter(d=>d.status==="active").length,$s=B.filter(d=>!d.workerSessionId).length,Ls=B.filter(d=>d.status==="failed"||d.status==="closed").length,Ds=[{label:"All",value:B.length},{label:"Active",value:ss},{label:"Needs runtime",value:$s},{label:"Closed",value:Ls}],jn=(s==null?void 0:s.baseUrl)??((Qs=Zt())==null?void 0:Qs.baseUrl)??"not connected",Hs=(te==null?void 0:te.lastActivityAt)??(te==null?void 0:te.updatedAt)??null,yn=(o==null?void 0:o.lastSeenAt)??(o==null?void 0:o.updatedAt)??null,Bs=Ri(o),wn=Pi(o),Nn=(G==null?void 0:G.name)??(W==null?void 0:W.name)??"Control Plane",Sn=ys||"Choose a project and workspace to manage sessions";async function ze(d,N){Mt(d),Vt(null),de(null),fs(null),wt(null),xt(null),ye(null),Nt(null),bs(null);try{return await N()}catch(S){if(S instanceof ae&&S.payload.code==="gateway_unavailable"&&fs(S.message),S instanceof ae&&S.payload.code==="quota_exceeded"){const q=S.payload.details??{},$e=typeof q.limit=="number"?q.limit:null,He=typeof q.used=="number"?q.used:null,Ut=typeof q.quotaProfile=="string"?q.quotaProfile:(n==null?void 0:n.quotaProfile)??"current";wt($e!==null&&He!==null?`${Ut} quota exhausted (${He}/${$e}).`:"Quota exceeded.")}return S instanceof ae&&S.payload.code==="account_inactive"&&xt(S.message),S instanceof ae&&(S.statusCode===401||S.payload.code==="unauthorized")&&(ye(S.message),hn()),S instanceof ae&&S.payload.code==="forbidden"&&bs(S.message),Vt(S instanceof Error?S.message:`${d} failed.`),null}finally{Mt(null)}}async function Ns(d=s){if(d){mt(N=>({...N,projects:!0,usageEvents:!0}));try{const N=await ir(d),[S,q,$e,He]=await Promise.all([va(d),Uo(d,10),Oo(d),Mo(d,10)]);c(N.user),p(N.sandbox),P(N.usage),f(N.billing??null),C(q.events),v($e.usage),oe(He.events),_(S.projects),ft(N.user.displayName??""),K(Ut=>S.projects.some(In=>In.id===Ut)?Ut:"")}finally{mt(N=>({...N,projects:!1,usageEvents:!1}))}}}async function _s(d=s,N=pe){if(!d||!ke){ge(null),Ye(null),We(null),Le(null);return}mt(S=>({...S,harness:!0})),Le(null);try{const S=await Jo(d);ge(S);const q=S.modules.includes(N)?N:S.modules[0]??N;if(nt(q),S.enabled&&S.keyPresent&&S.chemistryToolsEnabled){const[$e,He]=await Promise.all([Ar(d,q),Ur(d,q)]);Ye($e),We(He)}else Ye(null),We(null)}catch(S){ge(null),Ye(null),We(null),Le(S instanceof Error?S.message:"Harness status refresh failed.")}finally{mt(S=>({...S,harness:!1}))}}a.useEffect(()=>{s&&ze("Load control plane",async()=>{await Ns(s),de("Control plane session is ready.")})},[]),a.useEffect(()=>{if(!s||!z){ne([]),A("");return}A(""),mt(d=>({...d,sessions:!0})),ze("Load sessions",async()=>{try{const d=await Xn(s,z);ne(d.sessions)}finally{mt(d=>({...d,sessions:!1}))}})},[s,z]),a.useEffect(()=>{if(!s||!o||!As)return;let d=!1;const N=setTimeout(()=>{Pr(s).then(S=>{d||p(S.sandbox)}).catch(S=>{d||Nt(S instanceof Error?S.message:"Sandbox health refresh failed.")})},Ni);return()=>{d=!0,clearTimeout(N)}},[s,o==null?void 0:o.state,o==null?void 0:o.startupProgress,o==null?void 0:o.updatedAt,As]),a.useEffect(()=>{if(!s||!ke){ge(null),Ye(null),We(null),Le(null);return}_s(s,pe)},[s,ke,o==null?void 0:o.updatedAt]),a.useEffect(()=>{if(!s||!T){u([]),L(""),ne([]),A("");return}L(""),ne([]),A(""),mt(d=>({...d,workspaces:!0})),ze("Load workspaces",async()=>{try{const d=await Zn(s,T);u(d.workspaces)}finally{mt(d=>({...d,workspaces:!1}))}})},[s,T]),a.useEffect(()=>()=>{Te.current&&clearTimeout(Te.current),bt()},[]),a.useEffect(()=>{function d(N){N.key==="Escape"&&(me(!1),F(null),Y(null),Me(!1))}return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[]);function bt(){const d=Lt.current;Lt.current=null,d&&d.readyState!==WebSocket.CLOSED&&d.close()}function vt(){Te.current&&(clearTimeout(Te.current),Te.current=null)}function kn(d){return`${d.wsBaseUrl.replace(/\/+$/,"")}/api/sandboxes/${encodeURIComponent(d.sandboxId)}/ws?token=${encodeURIComponent(d.token)}`}function Fs(d,N="connecting"){bt();const S=kn(d);re(S),Nt(null),qe(N);const q=new WebSocket(S);Lt.current=q,q.addEventListener("open",()=>{Lt.current===q&&qe("ready")}),q.addEventListener("error",()=>{Lt.current===q&&(Nt("Sandbox route connection failed."),qe("idle"))}),q.addEventListener("close",$e=>{Lt.current===q&&(Nt($e.reason||"Sandbox route closed before the session could stay connected."),qe("idle"))})}function Ws(d){if(vt(),!d)return;const N=Date.parse(d.expiresAt);if(!Number.isFinite(N))return;const S=Math.max(wi,N-Date.now()-yi);Te.current=setTimeout(()=>{Js()},S)}async function Bt(){hn(),r(null),c(null),p(null),g(null),P(null),C([]),bs(null),_([]),u([]),ne([]),v(null),oe([]),fe(null),me(!1),F(null),vt(),qe("idle"),de("Signed out locally.")}async function De(d){d.preventDefault(),s&&await ze("Update profile",async()=>{const N=await $o(s,{displayName:$t});c(N.user);const S=Zt();S&&un({...S,email:N.user.email,displayName:N.user.displayName}),de("Profile updated.")})}async function qs(d){d.preventDefault(),s&&await ze("Create project",async()=>{const N=await Lo(s,{name:ct,slug:An(ct)});await Ns(s),F(null),de(`Project "${N.project.name}" created. Select it before creating a workspace.`)})}async function zs(d){d.preventDefault(),!(!s||!W)&&await ze("Create workspace",async()=>{const N=await Bo(s,{projectId:W.id,name:y,slug:An(y)}),S=await Zn(s,W.id);u(S.workspaces),L(""),ne([]),A(""),F(null),de(`Workspace "${N.workspace.name}" created. Select it before creating a session.`)})}async function Cn(d){d.preventDefault(),!(!s||!G||!ke)&&await ze("Create session",async()=>{const N=await _o(s,G.id,{provider:Pe,title:V}),S=await Xn(s,G.id);ne(S.sessions),A(""),F(null),de(`Session "${N.session.title}" created. Select it before connecting.`)})}async function _t(d){s&&await ze(`${d} sandbox`,async()=>{if(d==="start")p((await Wo(s)).sandbox);else if(d==="stop")p((await qo(s)).sandbox),fe(null),re(null),bt(),vt(),qe("idle");else if(d==="restart")p((await zo(s)).sandbox),fe(null),re(null),bt(),vt(),qe("idle");else{const N=await Pr(s);p(N.sandbox),de(`Sandbox health is ${we(N.status.state)}.`)}})}async function ns(d){if(nt(d),!(!s||!ke)){mt(N=>({...N,harness:!0})),Le(null);try{const[N,S]=await Promise.all([Ar(s,d),Ur(s,d)]);Ye(N),We(S)}catch(N){Ye(null),We(null),Le(N instanceof Error?N.message:"Harness module refresh failed.")}finally{mt(N=>({...N,harness:!1}))}}}async function rs(){!s||!o||await ze("Inspect sandbox",async()=>{const d=await Vo(s,o.id);g(d),de("Sandbox detail loaded.")})}async function as(d="connecting",N=Z){return!s||!o||!ke?null:ze("Create route token",async()=>{const S={scopes:["worker:read","worker:write","session:prompt","provider:turn:create"]};W!=null&&W.id&&(S.projectId=W.id),z&&(S.workspaceId=z),N&&(S.sessionId=N);const q=await ya(s,o.id,S);return fe(q),Ws(q),Fs(q,d),de("Route token is available in memory."),q})}async function Js(){if(!s||!o||o.state!=="running"||!Z)return;qe("reconnecting"),await as("reconnecting",Z)||qe("idle")}function Yt(d){Y(null),A(d.id),fe(null),re(null),bt(),vt(),qe("idle"),pt("summary"),Me(!0)}function Vs(d){Yt(d),Me(!0)}function Gs(d,N){var S;N&&(Y(null),(S=navigator.clipboard)==null||S.writeText(N),de(`${d} copied.`))}function os(d,N){yt(d),rt(N),Y(null)}function Ft(){yt(null),rt("")}async function ls(d){if(d.preventDefault(),!s||!Ae)return;const N=Ve.trim();if(!N){Vt("Name is required.");return}const S=Ae;await ze(`Rename ${S.type}`,async()=>{if(S.type==="project"){const q=await Do(s,S.id,{name:N,slug:An(N)});_($e=>$e.map(He=>He.id===q.project.id?q.project:He))}else if(S.type==="workspace"){const q=await Er(s,S.id,{name:N});u($e=>$e.map(He=>He.id===q.workspace.id?q.workspace:He))}else{const q=await Rr(s,S.id,{title:N});ne($e=>$e.map(He=>He.id===q.session.id?q.session:He))}Ft(),de(`${we(S.type)} renamed.`)})}function Ss(d){if(!d)return{title:"Delete item",description:"This item will be removed from the active control plane view."};if(d.type==="project"){const S=ee.find(q=>q.id===d.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(d.type==="workspace"){const S=le.find(q=>q.id===d.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=B.find(S=>S.id===d.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 ks(){if(!s||!Ge)return;const d=Ge;await ze(`Delete ${d.type}`,async()=>{if(d.type==="project"){const N=await Ho(s,d.id);_(S=>S.filter(q=>q.id!==N.project.id)),T===N.project.id&&(K(""),L(""),A(""),u([]),ne([]))}else if(d.type==="workspace"){const N=await Er(s,d.id,{status:"deleted"});u(S=>S.filter(q=>q.id!==N.workspace.id)),z===N.workspace.id&&(L(""),A(""),ne([]))}else{const N=await Rr(s,d.id,{status:"deleted"});ne(S=>S.filter(q=>q.id!==N.session.id)),Z===N.session.id&&A("")}Ae&&Ts(Ae)===Ts(d)&&Ft(),Ze(null),fe(null),re(null),bt(),vt(),qe("idle"),de(`${we(d.type)} deleted.`)})}async function Ks(d){!s||!ke||await ze("Close session",async()=>{const N=await Fo(s,d.id);ne(S=>S.map(q=>q.id===N.session.id?N.session:q)),A(N.session.id),fe(null),re(null),bt(),vt(),qe("idle"),de("Session finalized and disconnected.")})}async function Ys(d){!s||!ke||await ze("Resume session",async()=>{const N=await ja(s,d.id);ne(S=>S.map(q=>q.id===N.session.id?N.session:q)),A(N.session.id),await as("connecting",N.session.id),de("Session resumed."),t(`/control-plane/sessions/${encodeURIComponent(N.session.id)}`)})}const Tn=e.jsx(ji,{title:Nn,subtitle:Sn,actions:e.jsxs(e.Fragment,{children:[o?e.jsx("span",{className:`control-status-pill ${Ot(o.state)}`,children:we(o.state)}):null,e.jsx(Oe,{onClick:()=>void Ns(s),disabled:!s||Tt==="Load control plane",children:"Refresh"}),e.jsx(Oe,{onClick:()=>Me(d=>!d),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(d=>!d),"aria-haspopup":"menu","aria-expanded":ue,"aria-label":"Open account menu",children:ws}),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:ws}),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:we((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(rn,{label:"Display name",value:$t,onChange:ft}),e.jsx(Oe,{type:"submit",disabled:!s||Tt==="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:(w==null?void 0:w.requestCount)??0})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Tokens"}),e.jsx("strong",{children:Ms})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Total cost"}),e.jsxs("strong",{children:["$",ot.toFixed(2)]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Harness"}),e.jsx("strong",{children:(R==null?void 0:R.eventCount)??0})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Compute"}),e.jsx("strong",{children:Number((R==null?void 0:R.computeUnits)??0).toFixed(1)})]}),e.jsxs("div",{children:[e.jsx("span",{children:"LLM cost"}),e.jsxs("strong",{children:["$",Number((w==null?void 0:w.costUsd)??0).toFixed(2)]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Harness cost"}),e.jsxs("strong",{children:["$",Number((R==null?void 0:R.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:jn})})]}),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(d=>e.jsxs("div",{children:[e.jsx("strong",{children:d.model}),e.jsxs("span",{children:[d.provider,", ",d.inputTokens+d.outputTokens," tokens, $",Number(d.costUsd).toFixed(2)]}),e.jsx("small",{children:d.occurredAt})]},d.id))}),e.jsx("div",{className:"control-usage-events compact",children:et.usageEvents?e.jsx("p",{className:"control-empty",children:"Loading Harness usage..."}):Q.length===0?e.jsx("p",{className:"control-empty",children:"No Harness usage events yet."}):Q.slice(0,4).map(d=>e.jsxs("div",{children:[e.jsx("strong",{children:d.tool??d.module}),e.jsxs("span",{children:[d.module,", ",d.status,", $",Number(d.costUsd).toFixed(2)]}),e.jsx("small",{children:d.occurredAt})]},d.id))})]}),e.jsx(Oe,{onClick:Bt,children:"Sign out"})]}):null]})]})}),Zs=e.jsxs(e.Fragment,{children:[Jt?e.jsx("div",{className:"control-alert danger",children:Jt}):null,X?e.jsx("div",{className:"control-alert success",children:X}):null,ps?e.jsxs("div",{className:"control-alert warning",children:["LLM gateway unavailable: ",ps]}):null,xs?e.jsxs("div",{className:"control-alert danger",children:["LLM quota exceeded: ",xs]}):null,Gt?e.jsxs("div",{className:"control-alert danger",children:["Account disabled: ",Gt]}):null,gs?e.jsxs("div",{className:"control-alert warning",children:["Session expired: ",gs]}):null,It?e.jsxs("div",{className:"control-alert warning",children:["Admin access denied: ",It]}):null,Et==="reconnecting"?e.jsx("div",{className:"control-alert warning",children:"Reconnecting sandbox route."}):null,Et==="connecting"?e.jsx("div",{className:"control-alert neutral",children:"Connecting sandbox route."}):null,at?e.jsxs("div",{className:"control-alert danger",children:["Sandbox offline: ",at]}):null,js?e.jsx("div",{className:`control-alert ${js.tone}`,children:js.text}):null]}),Xs=Ss(Ge);return e.jsxs(e.Fragment,{children:[e.jsxs(bi,{topBar:Tn,alerts:Zs,sidebar:null,main:null,inspector:null,inspectorOpen:Xe,children:[e.jsxs(vi,{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:()=>F(kt),"aria-label":`Open create panel for ${Dt.toLowerCase()}`,title:`Create ${Dt.toLowerCase()}`,children:"+"})]}),Se?e.jsxs("div",{className:"control-create-popover",children:[e.jsxs("div",{className:"control-panel-heading",children:[e.jsx("h2",{children:gt}),e.jsx("button",{type:"button",className:"control-icon-button quiet",onClick:()=>F(null),"aria-label":"Close create panel",children:"x"})]}),Se==="project"?e.jsxs("form",{onSubmit:qs,className:"control-create-form",children:[e.jsx(rn,{label:"Project name",value:ct,onChange:b}),e.jsx(Oe,{type:"submit",disabled:!St,children:"Create project"})]}):Se==="workspace"?e.jsxs("form",{onSubmit:zs,className:"control-create-form",children:[e.jsx(rn,{label:"Workspace name",value:y,onChange:I}),Ht?e.jsx("p",{className:"control-rule-note",children:Ht}):null,e.jsx(Oe,{type:"submit",disabled:!vs,title:Rt,children:"Create workspace"})]}):e.jsxs("form",{onSubmit:Cn,className:"control-create-form",children:[e.jsx(rn,{label:"Session title",value:V,onChange:be}),e.jsxs("label",{className:"control-field",children:[e.jsx("span",{children:"Provider"}),e.jsxs("select",{value:Pe,onChange:d=>ut(d.currentTarget.value),disabled:!Qt,children:[e.jsx("option",{value:"codex",children:"Codex"}),e.jsx("option",{value:"claude",children:"Claude"}),e.jsx("option",{value:"opencode",children:"OpenCode"})]})]}),Ht?e.jsx("p",{className:"control-rule-note",children:Ht}):null,e.jsx(Oe,{type:"submit",disabled:!Qt,title:Pt,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:(G==null?void 0:G.name)??(W==null?void 0:W.name)??"Not selected"})]}),e.jsxs("div",{className:"control-context-card",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Project"}),e.jsx("strong",{children:(W==null?void 0:W.name)??"Choose project"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Workspace"}),e.jsx("strong",{children:(G==null?void 0:G.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:B.length})]}),e.jsx("div",{className:"control-nav-list","aria-label":"Session filters",children:Ds.map((d,N)=>e.jsxs("button",{type:"button",className:`control-nav-row ${N===0?"selected":""}`,children:[e.jsx("span",{children:d.label}),e.jsx("strong",{children:d.value})]},d.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, ${we(o==null?void 0:o.state)}`,onClick:()=>{pt("summary"),Me(!0)},children:[e.jsx("span",{children:"Sandbox"}),e.jsx("strong",{children:we(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:["$",ot.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..."}):ee.length===0?e.jsx("p",{className:"control-empty",children:"No projects yet."}):ee.map(d=>e.jsxs("div",{className:"control-tree-group",children:[Ts(Ae)===`project:${d.id}`?e.jsx(Mn,{label:"Project name",value:Ve,onChange:rt,onCancel:Ft,onSubmit:ls}):e.jsxs("div",{className:`control-tree-item ${T===d.id?"selected":""}`,children:[e.jsxs("button",{type:"button","aria-label":`Select project ${d.name}`,onClick:()=>{K(d.id),L(""),ne([]),A(""),fe(null),re(null),bt(),vt(),qe("idle")},className:"control-tree-row project",children:[e.jsx("span",{className:"control-tree-caret",children:e.jsx(Br,{open:T===d.id})}),e.jsx("span",{className:"control-tree-icon",children:e.jsx(ki,{})}),e.jsx("strong",{children:d.name}),e.jsx("small",{children:we(d.status)})]}),e.jsx(On,{label:`project ${d.name}`,onEdit:()=>os({type:"project",id:d.id},d.name),onDelete:()=>Ze({type:"project",id:d.id})})]}),T===d.id?e.jsx("div",{className:"control-tree-children",children:et.workspaces?e.jsx("p",{className:"control-empty",children:"Loading workspaces..."}):le.length===0?e.jsx("p",{className:"control-empty",children:"No workspaces in this project."}):le.map(N=>e.jsxs("div",{className:"control-tree-group",children:[Ts(Ae)===`workspace:${N.id}`?e.jsx(Mn,{label:"Workspace name",value:Ve,onChange:rt,onCancel:Ft,onSubmit:ls}):e.jsxs("div",{className:`control-tree-item ${z===N.id?"selected":""}`,children:[e.jsxs("button",{type:"button","aria-label":`Select workspace ${N.name}`,onClick:()=>{L(N.id),A(""),fe(null),re(null),bt(),vt(),qe("idle")},className:"control-tree-row workspace",children:[e.jsx("span",{className:"control-tree-caret",children:e.jsx(Br,{open:z===N.id})}),e.jsx("span",{className:"control-tree-icon",children:e.jsx(Ci,{})}),e.jsx("strong",{children:N.name}),e.jsx("small",{children:Si(N)})]}),e.jsx(On,{label:`workspace ${N.name}`,onEdit:()=>os({type:"workspace",id:N.id},N.name),onDelete:()=>Ze({type:"workspace",id:N.id})})]}),z===N.id?e.jsx("div",{className:"control-tree-children sessions",children:et.sessions?e.jsx("p",{className:"control-empty",children:"Loading sessions..."}):B.length===0?e.jsx("p",{className:"control-empty",children:"No sessions for this workspace."}):B.map(S=>e.jsx("div",{className:"control-tree-group",children:Ts(Ae)===`session:${S.id}`?e.jsx(Mn,{label:"Session title",value:Ve,onChange:rt,onCancel:Ft,onSubmit:ls}):e.jsxs("div",{className:`control-tree-item ${Z===S.id?"selected":""}`,children:[e.jsxs("button",{type:"button","aria-label":`Open session ${S.title} from workspace browser`,onClick:()=>void Yt(S),className:"control-tree-row session",children:[e.jsx("span",{className:"control-tree-caret"}),e.jsx("span",{className:"control-tree-icon",children:e.jsx(Ti,{})}),e.jsx("strong",{children:S.title}),e.jsxs("small",{children:[nn(S.provider)," / ",we(S.status),S.workerSessionId?"":" / Not started"]})]}),e.jsx(On,{label:`session ${S.title}`,onEdit:()=>os({type:"session",id:S.id},S.title),onDelete:()=>Ze({type:"session",id:S.id})})]})},S.id))}):null]},N.id))}):null]},d.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:(G==null?void 0:G.name)??(W==null?void 0:W.name)??"Select a workspace"}),e.jsx("p",{children:G?`${(W==null?void 0:W.name)??"Project"} · ${Es(G.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 ${Ot((o==null?void 0:o.state)??"unknown")}`,children:we(o==null?void 0:o.state)}),e.jsx(Oe,{onClick:()=>void _t("start"),disabled:ve.start.disabled,title:ve.start.title,ariaLabel:`Sandbox ${ve.start.label}`,children:ve.start.label}),e.jsx(Oe,{onClick:()=>void _t("restart"),disabled:ve.restart.disabled,title:ve.restart.title,ariaLabel:"Sandbox restart",children:ve.restart.label}),e.jsx(Oe,{onClick:()=>void _t("health"),disabled:ve.health.disabled,title:ve.health.title,ariaLabel:"Sandbox health",children:ve.health.label}),e.jsxs(Oe,{onClick:()=>F(kt),disabled:kt==="workspace"?!vs:kt==="session"?!Qt:!St,title:kt==="workspace"?Rt:kt==="session"?Pt:void 0,children:["New ",Dt]})]})]}),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:ee.length})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Workspaces"}),e.jsx("strong",{children:le.length})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Active sessions"}),e.jsx("strong",{children:ss})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Sandbox"}),e.jsx("strong",{children:we(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:G?`${B.length} in workspace`:"Select workspace"})]}),G?e.jsxs(e.Fragment,{children:[Pt?e.jsx("p",{className:"control-rule-note",children:Pt}):null,et.sessions?e.jsx("p",{className:"control-empty",children:"Loading sessions..."}):B.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:B.map(d=>e.jsxs("article",{role:"listitem",className:`control-session-row ${Z===d.id?"selected":""}`,children:[e.jsxs("button",{type:"button","aria-label":`Open session ${d.title} summary`,className:"control-session-row-main",onClick:()=>void Yt(d),children:[e.jsx("strong",{children:d.title}),e.jsxs("span",{children:[nn(d.provider)," · ",sn(d.lastActivityAt??d.updatedAt)]})]}),e.jsxs("div",{className:"control-session-row-state",children:[e.jsx(Mi,{status:d.status}),e.jsx("span",{children:Un(d)})]}),e.jsxs("div",{className:"control-session-row-actions",children:[e.jsx(Oe,{onClick:()=>void Ys(d),disabled:!s||!ke,title:ke?void 0:"Start the sandbox before opening this session.",ariaLabel:`${d.workerSessionId?"Resume":"Start"} session ${d.title} from summary`,children:d.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 ${d.title}`,"aria-haspopup":"menu","aria-expanded":ie===d.id,onClick:()=>Y(N=>N===d.id?null:d.id),children:"..."}),ie===d.id?e.jsxs("div",{className:"control-row-menu-popover",role:"menu",children:[e.jsx("button",{type:"button",role:"menuitem",onClick:()=>Vs(d),children:"Show details"}),e.jsx("button",{type:"button",role:"menuitem",onClick:()=>Gs("Session ID",d.id),children:"Copy session ID"}),d.sandboxId?e.jsx("button",{type:"button",role:"menuitem",onClick:()=>Gs("Sandbox ID",d.sandboxId),children:"Copy sandbox ID"}):null,e.jsx("button",{type:"button",role:"menuitem",disabled:!s||!d.workerSessionId||!ke,title:d.workerSessionId?void 0:"Session has not been started yet.",onClick:()=>{Y(null),Ks(d)},children:"Close session"})]}):null]})]})]},d.id))}),e.jsx("div",{className:"control-action-row start",children:e.jsx(Oe,{onClick:()=>F("session"),disabled:!Qt,title:Pt,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":G?"Workspace context":W?"Project context":"Selection"}),e.jsx("span",{children:te?we(te.status):G?Es(G.sourceType):W?we(W.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:nn(te.provider)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Status"}),e.jsx("dd",{children:e.jsx("span",{className:`control-status-pill compact ${Ot(te.status)}`,children:we(te.status)})})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Last activity"}),e.jsx("dd",{children:sn(Hs)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Sandbox"}),e.jsx("dd",{children:ke?"Ready":we(o==null?void 0:o.state)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Runtime"}),e.jsx("dd",{children:Un(te)})]})]}),e.jsxs("div",{className:"control-action-row start",children:[e.jsx(Oe,{onClick:()=>void Ys(te),disabled:!s||!ke,title:ke?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:()=>{pt("metadata"),Me(!0)},children:"Details"})]})]}):G?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:G.name})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Project"}),e.jsx("dd",{children:(W==null?void 0:W.name)??G.projectId})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Source"}),e.jsx("dd",{children:Es(G.sourceType)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Sessions"}),e.jsx("dd",{children:B.length})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Active"}),e.jsx("dd",{children:ss})]}),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:we(o==null?void 0:o.state)})]})]})}):W?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:W.name})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Status"}),e.jsx("dd",{children:we(W.status)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Workspaces"}),e.jsx("dd",{children:le.length})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Path"}),e.jsx("dd",{children:ys})]})]}),e.jsx("div",{className:"control-action-row start",children:e.jsx(Oe,{onClick:()=>F("workspace"),disabled:!vs,title:Rt,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:()=>Me(!1)}):null,e.jsxs(gi,{eyebrow:te?"Session":G?"Workspace":W?"Project":"Sandbox",hidden:!Xe,onClose:()=>Me(!1),children:[e.jsx("div",{className:"control-inspector-tabs",role:"tablist","aria-label":"Inspector sections",children:["summary","metadata","route","logs"].map(d=>e.jsx("button",{type:"button",role:"tab","aria-selected":Qe===d,className:Qe===d?"selected":"",onClick:()=>pt(d),children:d==="summary"?"Summary":d==="metadata"?"Metadata":d==="route"?"Route":"Logs"},d))}),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 ${Ot(o.state)}`,children:we(o.state)})})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Stage"}),e.jsx("dd",{children:Bs})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Health"}),e.jsx("dd",{children:wn})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Last seen"}),e.jsx("dd",{children:sn(yn)})]})]}):e.jsx("p",{className:"control-empty",children:"Loading sandbox registry."})]}),e.jsxs("div",{className:"control-action-row",children:[e.jsx(Oe,{onClick:()=>void _t("stop"),disabled:ve.stop.disabled,title:ve.stop.title,children:ve.stop.label}),e.jsx(Oe,{onClick:rs,disabled:ve.inspect.disabled,title:ve.inspect.title,children:ve.inspect.label})]}),o&&typeof o.startupProgress=="number"&&o.startupProgress>0&&o.startupProgress<100?e.jsxs("div",{className:"control-progress",children:[e.jsx("span",{children:Bs}),e.jsxs("span",{children:[o.startupProgress,"%"]}),e.jsx("div",{children:e.jsx("i",{style:{width:`${o.startupProgress}%`}})})]}):null,te||G||W?e.jsxs("div",{className:"control-inspector-section",children:[e.jsxs("div",{className:"control-panel-heading compact",children:[e.jsx("h2",{children:te?"Session":G?"Workspace":"Project"}),e.jsx("span",{children:te?we(te.status):G?Es(G.sourceType):we(W==null?void 0:W.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:nn(te.provider)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Runtime"}),e.jsx("dd",{children:Un(te)})]})]}):G?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Workspace"}),e.jsx("dd",{children:G.name})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Sessions"}),e.jsx("dd",{children:B.length})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Active"}),e.jsx("dd",{children:ss})]})]}):W?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Project"}),e.jsx("dd",{children:W.name})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Workspaces"}),e.jsx("dd",{children:le.length})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Status"}),e.jsx("dd",{children:we(W.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 ${Fr(Kt)}`,children:we(Kt)})]}),ke?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"control-action-row",children:e.jsx(Oe,{onClick:()=>void _s(s,pe),disabled:!s||et.harness,children:et.harness?"Checking...":"Refresh"})}),dt?e.jsxs("div",{className:"control-alert warning",children:["Harness unavailable: ",dt]}):null,e.jsxs("dl",{className:"control-detail-list compact summary",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Key"}),e.jsx("dd",{children:H!=null&&H.keyPresent?"Present":"Not present"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Chemistry"}),e.jsx("dd",{children:H!=null&&H.chemistryToolsEnabled?"Enabled":"Disabled"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Health"}),e.jsx("dd",{children:H!=null&&H.health?"OK":"Not available"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Module"}),e.jsx("dd",{children:tn[pe]})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Tools"}),e.jsx("dd",{children:he.length||"folder index"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Runs"}),e.jsx("dd",{children:At.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,G?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:G.id}),e.jsx(Fe,{label:"Project ID",value:G.projectId}),e.jsx(Fe,{label:"Path",value:G.path}),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,W?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:W.id}),e.jsxs("div",{children:[e.jsx("dt",{children:"Slug"}),e.jsx("dd",{children:W.slug})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Created"}),e.jsx("dd",{children:W.createdAt})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Updated"}),e.jsx("dd",{children:W.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 as("connecting",Z),disabled:!ke||!te,title:Us,children:"Create route token"})]}),Ce?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)??Z})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Connection"}),e.jsx("dd",{children:_r(Et)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Token"}),e.jsxs("dd",{children:[sn(Ce.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."})]}),Ce?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:Ce.routerBaseUrl}),e.jsx(Fe,{label:"WebSocket URL",value:Ce.wsBaseUrl}),e.jsx(Fe,{label:"Worker socket",value:D}),e.jsxs("div",{children:[e.jsx("dt",{children:"Connection"}),e.jsx("dd",{children:_r(Et)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Expires"}),e.jsx("dd",{children:Ce.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 ${Fr(Kt)}`,children:we(Kt)})]}),ke?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"control-segment-row",role:"tablist","aria-label":"Harness modules",children:Os.map(d=>e.jsx("button",{type:"button",role:"tab","aria-selected":pe===d,className:pe===d?"selected":"",onClick:()=>void ns(d),disabled:et.harness||!(H!=null&&H.enabled)||!H.keyPresent,children:tn[d]},d))}),e.jsxs("dl",{className:"control-detail-list",children:[e.jsx(Fe,{label:"Base URL",value:H==null?void 0:H.baseUrl}),e.jsxs("div",{children:[e.jsx("dt",{children:"Enabled"}),e.jsx("dd",{children:H!=null&&H.enabled?"yes":"no"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Modules"}),e.jsx("dd",{children:Os.map(d=>tn[d]).join(", ")})]})]}),e.jsxs("div",{className:"control-usage-events compact",children:[e.jsxs("div",{children:[e.jsxs("strong",{children:[tn[pe]," tools"]}),e.jsxs("small",{children:[he.length," advertised"]})]}),he.slice(0,5).map((d,N)=>e.jsxs("div",{children:[e.jsx("strong",{children:zr(d,`tool-${N+1}`)}),e.jsx("span",{children:Jr(d)||"tool"})]},`${pe}-tool-${N}`)),he.length===0&&es?e.jsx("div",{children:e.jsx("span",{children:es.slice(0,180)})}):null,he.length===0&&!es?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:[At.length," reported"]})]}),At.slice(0,4).map((d,N)=>e.jsxs("div",{children:[e.jsx("strong",{children:zr(d,`run-${N+1}`)}),e.jsx("span",{children:Jr(d)||"run"})]},`${pe}-run-${N}`)),At.length===0&&ts?e.jsx("div",{children:e.jsx("span",{children:ts.slice(0,180)})}):null,At.length===0&&!ts?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."})]}),m?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:we(m.runtimeStatus.state)})]}),e.jsxs("dl",{className:"control-detail-list",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Namespace"}),e.jsx("dd",{children:m.sandbox.k8sNamespace??m.runtimeStatus.k8sNamespace??"not assigned"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Pod"}),e.jsx("dd",{children:m.sandbox.k8sPodName??m.runtimeStatus.k8sPodName??"not assigned"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Endpoint"}),e.jsx("dd",{children:m.endpoint.routerBaseUrl??"not assigned"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Worker URL"}),e.jsx("dd",{children:m.workerBaseUrl??"not assigned"})]})]}),m.runtimeStatus.statusReason?e.jsx("p",{className:"control-empty",children:m.runtimeStatus.statusReason}):null,e.jsx("div",{className:"control-usage-events",children:m.recentLifecycleErrors.length===0?e.jsx("p",{className:"control-empty",children:"No lifecycle audit entries."}):m.recentLifecycleErrors.slice(0,5).map(d=>e.jsxs("div",{children:[e.jsx("strong",{children:d.action}),e.jsx("small",{children:d.createdAt})]},d.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(fn,{open:!!Ge,title:Xs.title,description:Xs.description,confirmLabel:"Delete",busy:!!(Tt!=null&&Tt.startsWith("Delete ")),onCancel:()=>Ze(null),onConfirm:ks})]})}const Li="http://127.0.0.1:8790";function Vr({children:t}){const s=Ps(),[r,n]=a.useState(null);return a.useEffect(()=>{let c=!1;return Promise.resolve().then(()=>{c||n(xi())}),()=>{c=!0}},[s.pathname]),r===null?e.jsx("div",{className:"grid min-h-[60vh] place-items-center text-sm text-[var(--theme-fg-muted)]",children:"Loading account session..."}):r?t:e.jsx(rr,{to:"/control-plane/login",replace:!0,state:{from:s}})}function Di(t){return{baseUrl:t.baseUrl,token:t.token}}function Hi(){if(typeof window>"u")return null;const t=new URLSearchParams(window.location.search),s=t.get("control_plane_token"),r=t.get("control_plane_expires_at"),n=t.get("control_plane_base_url"),c=t.get("auth_error");return{token:s,expiresAt:r,baseUrl:n,error:c}}function Bi(){var ne;const t=ht(),s=Ps(),r=Zt(),[n,c]=a.useState("login"),[o,p]=a.useState((r==null?void 0:r.baseUrl)??Li),[m,g]=a.useState((r==null?void 0:r.email)??"dev@example.com"),[w,P]=a.useState((r==null?void 0:r.displayName)??"Developer"),[x,f]=a.useState(""),[k,C]=a.useState(!1),[R,v]=a.useState(null),[Q,oe]=a.useState(null),ee=s.state,_=((ne=ee==null?void 0:ee.from)==null?void 0:ne.pathname)??"/control-plane",le=a.useMemo(()=>{if(typeof window>"u")return;const T=new URL(window.location.href);return T.search="",T.toString()},[]);a.useEffect(()=>{const T=Hi();if(!T)return;if(T.error){oe(`OAuth sign in failed: ${T.error}`);return}if(!T.token||!T.baseUrl)return;const K={baseUrl:T.baseUrl,token:T.token};T.expiresAt&&(K.expiresAt=T.expiresAt),un(K),ir(Di(K)).then(z=>{un({...K,email:z.user.email,displayName:z.user.displayName}),t("/control-plane",{replace:!0})}).catch(z=>{hn(),oe(z instanceof Error?z.message:"Unable to finish OAuth sign in.")})},[t]);async function u(T){T.preventDefault(),C(!0),oe(null),v(null);try{const K=n==="register"?await Po(o,{email:m,password:x,displayName:w||null}):await Ao(o,{email:m,password:x});un({baseUrl:o,token:K.session.token,expiresAt:K.session.expiresAt,email:K.user.email,displayName:K.user.displayName}),v("Account session is ready."),t(_,{replace:!0})}catch(K){K instanceof ae&&K.payload.code==="conflict"?oe("An account already exists for this email. Use sign in instead."):oe(K instanceof Error?K.message:"Unable to authenticate.")}finally{C(!1)}}function B(T){window.location.assign(Ro(o,T,le))}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:u,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:()=>c("login"),children:"Sign in"}),e.jsx("button",{type:"button",role:"tab","aria-selected":n==="register",onClick:()=>c("register"),children:"Create account"})]}),e.jsxs("label",{className:"control-field",children:[e.jsx("span",{children:"Control plane URL"}),e.jsx("input",{value:o,onChange:T=>p(T.currentTarget.value)})]}),e.jsxs("div",{className:"control-oauth-row",children:[e.jsx("button",{type:"button",onClick:()=>B("google"),children:"Continue with Google"}),e.jsx("button",{type:"button",onClick:()=>B("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:w,onChange:T=>P(T.currentTarget.value)})]}):null,e.jsxs("label",{className:"control-field",children:[e.jsx("span",{children:"Email address"}),e.jsx("input",{type:"email",value:m,autoComplete:"email",onChange:T=>g(T.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:T=>f(T.currentTarget.value)})]}),Q?e.jsx("p",{className:"control-auth-error",children:Q}):null,R?e.jsx("p",{className:"control-auth-message",children:R}):null,e.jsx("button",{type:"submit",className:"control-primary-button",disabled:k,children:k?"Working...":n==="register"?"Create account":"Sign in"})]})]})})}function _i(t){return t.sandboxMode??(t.approvalMode==="guarded"?"workspace-write":"danger-full-access")}function Fi(t,s){const r=new Set(s.map(n=>n.id));return[...s,...t.filter(n=>!r.has(n.id))]}function Wt(t,s){const r=new Set(s.map(n=>n.id));return[...t.filter(n=>!r.has(n.id)),...s]}function Wi(t,s){return{...t,pendingRequests:[...t.pendingRequests.filter(r=>r.id!==s.id),s]}}function qi(t,s){const r=t.pendingRequests.filter(n=>n.id!==s);return r.length===t.pendingRequests.length?t:{...t,pendingRequests:r}}function sr(t,s,r){const n=s.filter(m=>!r.has(m.id)),c=t.filter(m=>!r.has(m.id));if(c.length===0)return n;const o=new Map(n.map(m=>[m.id,m]));return[...c.map(m=>o.get(m.id)??m),...n.filter(m=>!c.some(g=>g.id===m.id))].sort((m,g)=>m.createdAt.localeCompare(g.createdAt))}function zi(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 Ua(t,s){var o,p;if(!t||t.kind!==s.kind)return s;const r=m=>{let g=m;const w=typeof s.sequence=="number"&&Number.isFinite(s.sequence)?s.sequence:typeof t.sequence=="number"&&Number.isFinite(t.sequence)?t.sequence:null;w!==null&&g.sequence!==w&&(g={...g,sequence:w});const P=typeof s.transcriptOrder=="number"&&Number.isFinite(s.transcriptOrder)?s.transcriptOrder:typeof t.transcriptOrder=="number"&&Number.isFinite(t.transcriptOrder)?t.transcriptOrder:null;return P!==null&&g.transcriptOrder!==P&&(g={...g,transcriptOrder:P}),g};if(t.kind==="agentMessage"&&s.kind==="agentMessage")return r(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(),c=((p=s.detailText)==null?void 0:p.trim())||s.text.trim();return r(n.length>c.length?t:s)}function Ji(t,s,r){if(!t||s&&s.turnId!==t.turnId)return s;const n=r.find(x=>x.id===t.turnId),c=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))??[],p=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=c.get(f.id);return k?k.kind!==f.kind||typeof f.sequence=="number"&&Number.isFinite(f.sequence)&&k.sequence!==f.sequence:!p(f)});return x.length===0?null:{...t,items:x}}const m=new Map(t.items.map(x=>[x.id,x])),g=new Map(s.items.map(x=>[x.id,x])),P=[...t.items.map(x=>x.id),...s.items.map(x=>x.id).filter(x=>!m.has(x))].map(x=>{const f=g.get(x),k=m.get(x);if(!f){const C=c.get(x);return!C&&k&&p(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 Ua(k,f)}).filter(x=>!!x);return P.length===0?null:{turnId:s.turnId,items:P,updatedAt:s.updatedAt.localeCompare(t.updatedAt)>=0?s.updatedAt:t.updatedAt}}function Is(t,s){const r=t.filter(n=>n.id!==s.id);return[s,...r]}function Vi(t){return`${t.threadId}:${t.objective}:${t.createdAt}`}function Gi(t,s){const r=Date.parse(t.updatedAt)||0,c=(Date.parse(s.updatedAt)||0)>=r?s:t,o=c===s?t:s;return{...c,localGoalId:c.localGoalId??o.localGoalId??null}}function Oa(t){const s=new Map;for(const r of t){const n=Vi(r),c=s.get(n);s.set(n,c?Gi(c,r):r)}return[...s.values()].sort((r,n)=>Date.parse(n.updatedAt)-Date.parse(r.updatedAt))}function an(t,s){return Oa([s,...t])}function Ki(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 Yi(t){const s=Math.max(0,Math.floor(t/60)),r=Math.floor(s/60),n=s%60;return r>0?`${r}h ${n}m`:`${s}m`}function Gr(t,s){if(!s)return null;const r=t.find(n=>n.model===s);return r?r.supportedReasoningEfforts.length>1:null}function Zi(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`client-${Date.now()}-${Math.random().toString(16).slice(2,10)}`}function Rs(t,s){return(t==null?void 0:t.items.some(r=>r.kind==="userMessage"&&r.text.trim()===s))??!1}function Kr(t){return t.replace(/\s*\[PHOTO\s+[^\]]+\]\s*/g," ").replace(/\s+/g," ").trim()}function mn(t,s){const r=Kr(s);return r?(t==null?void 0:t.items.some(n=>n.kind==="userMessage"&&Kr(n.text)===r))??!1:!1}function $n(t){return(t==null?void 0:t.items.some(s=>s.kind==="userMessage"&&/\[PHOTO\s+\.\/\.temp\/threads\/[^\]]+\]/.test(s.text)))??!1}function Xi(t,s){return t.find(r=>Rs(r,s))??(s.includes("[PHOTO ")?t.find(r=>mn(r,s))??null:null)}function Qi(t,s,r,n){let c=!1;const o=t.map(p=>p.id!==s?p:(c=!0,{...p,tokenUsage:r,priceEstimate:n}));return c?o:t}const ed=3e3,td=6e4,sd=5e3,nd=2147e6,rd=["worker:read","worker:write","session:prompt","provider:turn:create","provider:turn:interrupt"];function ad(t){if(!t)return"no activity yet";const s=Date.parse(t);if(!Number.isFinite(s))return t;const r=Date.now()-s,n=Math.abs(r),c=r>=0?"ago":"from now",o=6e4,p=60*o,m=24*p;return n<o?"just now":n<p?`${Math.round(n/o)}m ${c}`:n<m?`${Math.round(n/p)}h ${c}`:`${Math.round(n/m)}d ${c}`}function od({title:t,children:s}){const[r,n]=a.useState(!1);return e.jsxs("section",{className:"control-metadata-disclosure",children:[e.jsxs("button",{type:"button","aria-expanded":r,onClick:()=>n(c=>!c),className:"control-metadata-trigger",children:[e.jsx("span",{children:t}),e.jsx("span",{children:r?"Hide":"Show"})]}),r?s:null]})}function Re({label:t,value:s}){const r=s&&s.trim()?s:"not assigned";return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsxs("dd",{children:[e.jsx("span",{children:r}),s?e.jsx("button",{type:"button",className:"control-copy-button",onClick:()=>{var n;(n=navigator.clipboard)==null||n.writeText(s)},children:"Copy"}):null]})]})}function ld(t){if(!t||typeof t!="object")return null;const s=t,r=Array.isArray(s.content)?s.content.filter(n=>typeof n=="string"):typeof s.content=="string"?[s.content]:[];return r.length===0?null:{content:r.join(`
5
- `),format:typeof s.format=="string"?s.format:"text",name:typeof s.name=="string"?s.name:null}}function id({selected:t,onClose:s}){const r=ar(),[n,c]=a.useState(t.kind==="artifact"?"preview":"logs"),[o,p]=a.useState(!0),m=t.kind==="artifact"?t.artifact:null,g=t.kind==="historyDetail"?t.detail:null,w=t.item,P=m?ld(m.payload):null,x=m?r.renderArtifact({artifact:m,expanded:o,onToggleExpanded:()=>p(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:(m==null?void 0:m.type)??w.kind}),e.jsx("h2",{children:(m==null?void 0:m.title)??(g==null?void 0:g.title)??w.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:()=>c(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}):P?e.jsxs("div",{className:"control-artifact-source",children:[e.jsxs("div",{children:[e.jsx("span",{children:P.format}),P.name?e.jsx("strong",{children:P.name}):null]}),e.jsx("pre",{children:P.content})]}):e.jsx("pre",{className:"control-artifact-source-raw",children:JSON.stringify(m==null?void 0:m.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:w.text||w.previewText||(m==null?void 0:m.summaryText)||"Artifact created"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Status"}),e.jsx("dd",{children:w.status??"completed"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Source turn"}),e.jsx("dd",{children:(m==null?void 0:m.sourceTurnId)??w.sourceTurnId??"not assigned"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Source item"}),e.jsx("dd",{children:(m==null?void 0:m.sourceItemId)??w.id})]})]})}):null,n==="metadata"?e.jsxs("dl",{className:"control-detail-list",children:[e.jsx(Re,{label:"Timeline item id",value:w.id}),e.jsx(Re,{label:"Timeline kind",value:w.kind}),m?e.jsxs(e.Fragment,{children:[e.jsx(Re,{label:"Artifact id",value:m.id}),e.jsx(Re,{label:"Plugin id",value:m.pluginId}),e.jsx(Re,{label:"Artifact type",value:m.type}),e.jsx(Re,{label:"Created",value:ms(m.createdAt)}),e.jsx(Re,{label:"Source turn",value:m.sourceTurnId}),e.jsx(Re,{label:"Source item",value:m.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(m?m.payload:{item:w,detail:g},null,2)})})]})]}):null]})]})}const dd=[],cd=[],ud=[],md={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 hd(){const t=Zt();return t?{baseUrl:t.baseUrl,token:t.token}:null}function Ma(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 Yr(t,s,r){const n=r==null?void 0:r.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)??Ma(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 pd(t,s,r){const n=new URL(`/api/sandboxes/${encodeURIComponent(t.sandboxId)}/api/threads/${encodeURIComponent(s)}/assets/image`,t.routerBaseUrl);return n.searchParams.set("path",r),n.toString()}const fd={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 Ln(t){return t instanceof ae&&t.statusCode===401&&t.payload.code==="invalid_route_token"}function Zr(t){return t instanceof ae&&(t.statusCode===404||t.statusCode===409)}function $a(t,s){return Object.is(t,s)?!0:JSON.stringify(t)===JSON.stringify(s)}function Dn(t,s){let r=t.length!==s.length||t.some((o,p)=>{var m;return o.id!==((m=s[p])==null?void 0:m.id)});const n=new Map(t.map(o=>[o.id,o])),c=s.map(o=>{const p=n.get(o.id);return p&&$a(p,o)?p:(r=!0,o)});return r?c:t}function on(t,s){return $a(t,s)?t:s}function xd(t,s){if(!t)return s;const r=Dn(t.turns,Wt(t.turns,s.turns)),n=Dn(t.pendingRequests,sr(t.pendingRequests,s.pendingRequests,new Set)),c={...s,turns:r,pendingRequests:n,pendingSteers:Dn(t.pendingSteers,s.pendingSteers)};return("answeredRequestNotes"in s||"answeredRequestNotes"in t)&&(c.answeredRequestNotes=on(t.answeredRequestNotes,s.answeredRequestNotes)??[]),("activityNotes"in s||"activityNotes"in t)&&(c.activityNotes=on(t.activityNotes,s.activityNotes)??[]),("livePlan"in s||"livePlan"in t)&&(c.livePlan=on(t.livePlan,s.livePlan)??null),("liveItems"in s||"liveItems"in t)&&(c.liveItems=on(t.liveItems,s.liveItems)??null),c}function gd(){return e.jsx(bd,{})}function bd(){const{sessionId:t=""}=na(),s=ht(),r=zt(),n=a.useMemo(hd,[]),[c,o]=a.useState(null),[p,m]=a.useState(null),[g,w]=a.useState(null),[P,x]=a.useState([]),[f,k]=a.useState(null),[C,R]=a.useState(null),[v,Q]=a.useState(null),[oe,ee]=a.useState({prompt:"",attachments:[]}),[_,le]=a.useState(!0),[u,B]=a.useState(!1),[ne,T]=a.useState(null),[K,z]=a.useState(0),[L,Z]=a.useState("chat"),[A,ie]=a.useState(!0),[Y,Ce]=a.useState(null),fe=a.useRef(!1),D=a.useRef(null),re=a.useRef(null),H=a.useCallback(X=>{Q(de=>{const ue=xd(de,X);return re.current=ue,ue})},[]),ge=a.useCallback(async X=>{if(!n)return null;const de=await ya(n,X.sandbox.id,{projectId:X.project.id,workspaceId:X.workspace.id,sessionId:X.session.id,scopes:rd});return R(de),de},[n]),pe=a.useCallback(async()=>!c||!p||!g||!f||c.state!=="running"?null:ge({sandbox:c,project:p,workspace:g,session:f}),[ge,p,c,f,g]),nt=a.useCallback(async()=>{if(!n)return s("/control-plane/login",{replace:!0}),null;le(!0),T(null);try{const X=await ir(n);if(o(X.sandbox),X.sandbox.state!=="running")return k(null),R(null),Q(null),re.current=null,T("Sandbox is not running. Start the sandbox from the control plane before opening chat."),null;const de=await va(n);for(const ue of de.projects){const me=await Zn(n,ue.id);for(const Se of me.workspaces){const F=await Xn(n,Se.id),Xe=F.sessions.find(ft=>ft.id===t);if(!Xe)continue;const Me=await ja(n,Xe.id),Qe=F.sessions.map(ft=>ft.id===Me.session.id?Me.session:ft),pt=await ge({sandbox:X.sandbox,project:ue,workspace:Se,session:Me.session});if(!pt)return T("Unable to issue a router token for this session."),null;if(m(ue),w(Se),x(Qe),k(Me.session),!Me.session.workerSessionId)return Q(null),re.current=null,T("Session resumed, but the worker did not return a thread id."),null;const $t=await ds(pt,Me.session.workerSessionId);return H($t),z(ft=>ft+1),{session:Me.session,token:pt,detail:$t}}}return T("Session was not found in any project workspace."),null}catch(X){return X instanceof ae&&X.payload.code==="unauthorized"?(hn(),s("/control-plane/login",{replace:!0}),null):(T(X instanceof Error?X.message:"Unable to open control-plane session."),null)}finally{le(!1)}},[H,n,ge,s,t]);a.useEffect(()=>{nt()},[nt]),a.useEffect(()=>{Ce(null)},[t]),a.useEffect(()=>{if(D.current&&(window.clearTimeout(D.current),D.current=null),!C)return;const X=Date.parse(C.expiresAt);if(!Number.isFinite(X))return;const de=Math.max(sd,Math.min(nd,X-Date.now()-td));return D.current=window.setTimeout(()=>{pe().catch(ue=>{T(ue instanceof Error?ue.message:"Unable to refresh router token.")})},de),()=>{D.current&&(window.clearTimeout(D.current),D.current=null)}},[pe,C]);const it=a.useCallback(async(X={})=>{if(!(!C||!(f!=null&&f.workerSessionId))){X.silent||T(null);try{H(await ds(C,f.workerSessionId))}catch(de){if(Ln(de))try{const ue=await pe();if(ue&&f.workerSessionId){H(await ds(ue,f.workerSessionId));return}}catch(ue){T(ue instanceof Error?ue.message:"Unable to refresh worker thread.");return}if(Zr(de)&&!fe.current){fe.current=!0;try{await nt();return}finally{fe.current=!1}}T(de instanceof Error?de.message:"Unable to refresh worker thread.")}}},[H,nt,pe,C,f==null?void 0:f.workerSessionId]);a.useEffect(()=>{if(!((v==null?void 0:v.thread.status)==="running"||!!(v!=null&&v.thread.activeTurnId)||u)||!C||!(f!=null&&f.workerSessionId))return;const de=window.setInterval(()=>{it({silent:!0})},ed);return()=>window.clearInterval(de)},[v==null?void 0:v.thread.activeTurnId,v==null?void 0:v.thread.status,it,C,u,f==null?void 0:f.workerSessionId]);async function Ye(X){const de=X.prompt.trim();if(!de||!C||!(f!=null&&f.workerSessionId))return!1;B(!0),T(null);try{return await En(C,f.workerSessionId,{prompt:de}),ee({prompt:"",attachments:[]}),await it(),z(ue=>ue+1),!0}catch(ue){if(Ln(ue))try{const me=await pe();if(!me||!f.workerSessionId)throw ue;await En(me,f.workerSessionId,{prompt:de});const Se=await ds(me,f.workerSessionId);return H(Se),ee({prompt:"",attachments:[]}),z(F=>F+1),!0}catch(me){return T(me instanceof Error?me.message:"Unable to send prompt."),!1}if(Zr(ue)&&!fe.current){fe.current=!0;try{const me=await nt();if(!(me!=null&&me.session.workerSessionId))throw ue;await En(me.token,me.session.workerSessionId,{prompt:de});const Se=await ds(me.token,me.session.workerSessionId);return H(Se),ee({prompt:"",attachments:[]}),z(F=>F+1),!0}catch(me){return T(me instanceof Error?me.message:"Unable to send prompt."),!1}finally{fe.current=!1}}return T(ue instanceof Error?ue.message:"Unable to send prompt."),!1}finally{B(!1)}}async function jt(){var X,de;if(!(!C||!(f!=null&&f.workerSessionId))){B(!0),T(null);try{const ue=((X=re.current)==null?void 0:X.thread.activeTurnId)??void 0,me=await Or(C,f.workerSessionId,ue?{turnId:ue}:{});Q(Se=>Se&&{...Se,thread:me}),await it({silent:!0})}catch(ue){if(Ln(ue))try{const me=await pe();if(!me||!f.workerSessionId)throw ue;const Se=((de=re.current)==null?void 0:de.thread.activeTurnId)??void 0,F=await Or(me,f.workerSessionId,Se?{turnId:Se}:{});Q(Xe=>Xe&&{...Xe,thread:F}),H(await ds(me,f.workerSessionId));return}catch(me){T(me instanceof Error?me.message:"Unable to interrupt turn.");return}T(ue instanceof Error?ue.message:"Unable to interrupt turn.")}finally{B(!1)}}}const We=C?f!=null&&f.workerSessionId?void 0:"Reconnect this session before sending a prompt.":"Waiting for a router token...",dt=g?P.map(X=>Yr(X,g,X.id===(f==null?void 0:f.id)?v:null)):[],Le=f&&g?Yr(f,g,v):null,ct=Le&&dt.every(X=>X.id!==Le.id)?[Le,...dt]:dt,b=(v==null?void 0:v.thread.status)??Ma(f==null?void 0:f.status),y=la(b),I=(v==null?void 0:v.thread.lastTurnStartedAt)??(v==null?void 0:v.thread.updatedAt)??(f==null?void 0:f.lastActivityAt)??(f==null?void 0:f.updatedAt)??null,V=(f==null?void 0:f.provider)??(v==null?void 0:v.thread.provider)??"codex",be=(v==null?void 0:v.thread.model)??"default model",Pe=(C==null?void 0:C.expiresAt)??null,ut=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:y})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Provider"}),e.jsx("dd",{children:V})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Workspace"}),e.jsx("dd",{children:(g==null?void 0:g.name)??(v==null?void 0:v.workspace.label)??"Unavailable"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Project"}),e.jsx("dd",{children:(p==null?void 0:p.name)??"None"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Model"}),e.jsx("dd",{children:be})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Last activity"}),e.jsx("dd",{children:ad(I)})]})]}),e.jsx(od,{title:"Diagnostics",children:e.jsxs("dl",{className:"control-detail-list",children:[e.jsx(Re,{label:"Control session id",value:(f==null?void 0:f.id)??t}),e.jsx(Re,{label:"Worker thread id",value:f==null?void 0:f.workerSessionId}),e.jsx(Re,{label:"Workspace path",value:(g==null?void 0:g.path)??(v==null?void 0:v.workspace.absPath)}),e.jsx(Re,{label:"Workspace id",value:g==null?void 0:g.id}),e.jsx(Re,{label:"Project id",value:p==null?void 0:p.id}),e.jsx(Re,{label:"Sandbox id",value:c==null?void 0:c.id}),e.jsx(Re,{label:"Router URL",value:(C==null?void 0:C.routerBaseUrl)??(c==null?void 0:c.routerBaseUrl)}),e.jsx(Re,{label:"Image",value:c==null?void 0:c.image}),e.jsx(Re,{label:"Worker service",value:c==null?void 0:c.workerServiceName}),e.jsx(Re,{label:"Session updated",value:ms((f==null?void 0:f.updatedAt)??null)}),e.jsx(Re,{label:"Route token expires",value:ms(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 nt(),disabled:_,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:_?"Reconnecting...":"Reconnect session"}),e.jsx("button",{type:"button",onClick:()=>void it(),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"})]})}),yt=a.useCallback(X=>{Ce({kind:"artifact",...X})},[]),Ve=a.useCallback(X=>{Ce({kind:"historyDetail",...X})},[]),rt=a.useCallback(async X=>{if(!C||!(f!=null&&f.workerSessionId))throw new Error("Reconnect this session before loading item details.");return Go(C,f.workerSessionId,X)},[C,f==null?void 0:f.workerSessionId]),Ge=a.useMemo(()=>({scrollRequestKey:K,className:"thread-timeline-surface min-h-0 flex-1",onTailVisibilityChange:ie,answeredRequestNotes:(v==null?void 0:v.answeredRequestNotes)??dd,activityNotes:(v==null?void 0:v.activityNotes)??cd,pendingSteers:(v==null?void 0:v.pendingSteers)??ud,onLoadHistoryItemDetail:rt,onSelectArtifact:yt,onSelectHistoryItemDetail:Ve}),[v==null?void 0:v.activityNotes,v==null?void 0:v.answeredRequestNotes,v==null?void 0:v.pendingSteers,yt,Ve,rt,K]),Ze=v?{busy:u,error:ne,model:v.thread.model,reasoningEffort:v.thread.reasoningEffort,fastMode:v.thread.fastMode??!1,collaborationMode:v.thread.collaborationMode,contextUsage:v.thread.contextUsage,capabilities:md,toolboxItems:[],followTail:A,threadConnected:v.thread.isLoaded,disabled:!!We,...We?{disabledPlaceholder:We}:{},draftPrompt:oe.prompt,draftAttachments:oe.attachments,onDraftChange:ee,canInterrupt:!!v.thread.activeTurnId,onInterrupt:jt,shellControlState:fd,onToggleView:()=>Z("shell"),onToggleFollow:()=>z(X=>X+1)}:null,Tt=e.jsx("span",{className:"control-session-status-badge",children:y}),Mt=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:()=>Z("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"})]})}),Jt=a.useCallback(X=>C&&(f!=null&&f.workerSessionId)?pd(C,f.workerSessionId,X):"",[C,f==null?void 0:f.workerSessionId]),Vt=a.useMemo(()=>({openThread:X=>{s(`/control-plane/sessions/${X}`)},getThreadHref:X=>`/control-plane/sessions/${X}`,getNewThreadHref:()=>"/control-plane",sendPrompt:Ye,interrupt:jt,getImageAssetUrl:Jt,shell:null}),[Jt,s]);return e.jsxs("div",{className:"control-chat-workspace",children:[e.jsx(oa,{threads:ct,detail:v,status:null,loading:_,error:_?null:ne,adapter:Vt,currentWorkspaceId:(g==null?void 0:g.id)??null,currentWorkspaceLabel:(g==null?void 0:g.name)??(v==null?void 0:v.workspace.label)??null,metaContent:ut,settingsContent:Ae,surfaceActions:Tt,appMenuButton:e.jsx(ro,{}),appNavigationMenu:e.jsx(no,{currentPath:`/control-plane/sessions/${t}`,items:[{label:"Control Plane",href:"/control-plane"},{label:"Workspaces",href:"/workspaces"}],onNavigate:s}),onCloseAppNavigation:(r==null?void 0:r.closeNav)??(()=>{}),activeView:L,timelineProps:Ge,shellEffectiveTheme:(r==null?void 0:r.effectiveTheme)??"dark",shellThemeMode:(r==null?void 0:r.themeMode)??"system",...r!=null&&r.setThemeMode?{onShellThemeModeChange:r.setThemeMode}:{},shellUnavailableContent:Mt,shellDisconnectedContent:Mt,shellContent:Mt,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}:{}}),Y?e.jsx("div",{className:"control-artifact-inspector-overlay",children:e.jsx(id,{selected:Y,onClose:()=>Ce(null)})}):null]})}function Hn({eyebrow:t,title:s,description:r}){return e.jsxs("div",{className:"host-card rounded-3xl border p-5",children:[e.jsx("p",{className:"host-page-eyebrow text-xs uppercase tracking-[0.3em]",children:t}),e.jsx("h2",{className:"host-page-title mt-3 text-xl font-semibold",children:s}),e.jsx("p",{className:"host-page-description mt-2 text-sm leading-6",children:r})]})}function La(){const[t,s]=a.useState(null),[r,n]=a.useState(null);return a.useEffect(()=>{Ko().then(s).catch(c=>{n(c instanceof Error?c.message:"Unable to load runtime config.")})},[]),e.jsx("div",{className:"min-h-screen bg-[var(--app-bg)] px-4 py-8 text-[var(--app-fg)] sm:px-6",children:e.jsx("div",{className:"mx-auto max-w-7xl",children:e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[1.2fr_0.8fr]",children:[e.jsxs("section",{className:"host-card rounded-[2rem] border p-8 sm:p-10",children:[e.jsx("p",{className:"text-xs uppercase tracking-[0.35em] text-[var(--theme-accent-strong)]",children:"Local Supervisor"}),e.jsx("h1",{className:"host-page-title mt-4 max-w-3xl text-4xl font-semibold tracking-tight sm:text-6xl",children:"Bring your local workspaces into a mobile-ready control surface."}),e.jsx("p",{className:"host-page-description mt-6 max-w-2xl text-base leading-7 sm:text-lg",children:"Phase 1 focuses on a stable supervisor shell: runtime config, workspace onboarding, database bootstrap, and a read-only file tree that already respects workspace root boundaries."}),e.jsxs("div",{className:"mt-8 flex flex-wrap gap-4",children:[e.jsx(qt,{to:"/workspaces",className:"ui-action-primary rounded-full px-5 py-3 font-medium transition",children:"Enter Workspace Console"}),e.jsx(qt,{to:"/workspaces/new",className:"host-secondary-button rounded-full border px-5 py-3 font-medium transition",children:"Add First Workspace"})]})]}),e.jsxs("section",{className:"grid gap-4",children:[e.jsx(Hn,{eyebrow:"Health",title:r?"API unavailable":"Supervisor reachable",description:r??`Connected to ${(t==null?void 0:t.appName)??"Remote Codex Supervisor"} ${(t==null?void 0:t.appVersion)??""}`.trim()}),e.jsx(Hn,{eyebrow:"Workspace Root",title:(t==null?void 0:t.workspaceRoot)??"Loading root path",description:"The file tree and workspace creation flow stay inside this boundary in Phase 1."}),e.jsx(Hn,{eyebrow:"Environment",title:(t==null?void 0:t.environment)??"Loading environment",description:t?`${t.host}:${t.port}`:"Runtime metadata appears here after bootstrap."})]})]})})})}function vd({onLogin:t}){const[s,r]=a.useState(""),[n,c]=a.useState(""),[o,p]=a.useState(null),[m,g]=a.useState(!1);async function w(P){P.preventDefault(),p(null),g(!0);try{await t({username:s,password:n})}catch(x){x instanceof ae?p(x.payload.message):p("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:w,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:m,name:"username",onChange:P=>r(P.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:m,name:"password",onChange:P=>c(P.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:m||!s.trim()||!n,type:"submit",children:m?"Signing in...":"Sign in"})]})]})})}function Bn(t){return t instanceof ae?t.payload.message:t instanceof Error?t.message:"Unable to update relay admin state."}function jd(){const[t,s]=a.useState(null),[r,n]=a.useState(!0),[c,o]=a.useState(null),[p,m]=a.useState(null);async function g(){n(!0),o(null);try{xn(),s(await ol())}catch(x){o(Bn(x))}finally{n(!1)}}a.useEffect(()=>{g()},[]);async function w(x){m("registration"),o(null);try{const f=await ll(x);s(k=>k&&{...k,registrationEnabled:f.registrationEnabled})}catch(f){o(Bn(f))}finally{m(null)}}async function P(x,f){m(x),o(null);try{const k=await il(x,f);s(C=>C&&{...C,users:C.users.map(R=>R.id===k.id?k:R)})}catch(k){o(Bn(k))}finally{m(null)}}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 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(qt,{className:"relay-button-secondary",to:"/relay-portal",children:"Portal"}),e.jsx("button",{className:"relay-button-secondary",onClick:()=>void g(),type:"button",children:"Refresh"})]})]}),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 relay admin..."}):c?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:c}):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:p==="registration",onClick:()=>void w(!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:p===x.id||x.role==="admin",onClick:()=>void P(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 vn(t,s){return t instanceof ae?t.payload.message:t instanceof Error?t.message:s}function hr(){var _,le;const t=ht(),[s,r]=a.useState(null),[n,c]=a.useState(null),[o,p]=a.useState(!0),[m,g]=a.useState(null),[w,P]=a.useState(null);async function x(){p(!0),g(null);try{xn();const u=await Qn();r(u),u.authenticated?c(await tl()):c(null)}catch(u){g(vn(u,"Unable to load relay portal."))}finally{p(!1)}}a.useEffect(()=>{x()},[]);async function f(){P(null),await x()}async function k(u){const B=await sl({name:u});P(B),await x()}async function C(u){await nl(u),await x()}async function R(u){await rl(u),await x()}async function v(u){await al(u),await x()}async function Q(){await el(),r(await Qn()),c(null),P(null)}function oe(u){Kn(u),Yn(null),t("/workspaces")}function ee(u,B){Kn(u),Yn(B),t(`/threads/${encodeURIComponent(B)}`)}return o?e.jsx(_n,{children:"Checking relay session..."}):s!=null&&s.authenticated?e.jsx(_n,{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:(_=s.user)==null?void 0:_.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:[((le=s.user)==null?void 0:le.role)==="admin"?e.jsx(qt,{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 Q(),type:"button",children:"Sign out"})]})]}),m?e.jsx(nr,{tone:"danger",children:m}):null,w?e.jsxs(nr,{tone:"accent",children:["Device token for ",w.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:w.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:Sd(w.token)})]}):null,e.jsxs("section",{className:"grid gap-4 lg:grid-cols-[minmax(0,1.2fr)_minmax(20rem,0.8fr)]",children:[e.jsxs(Fn,{title:"Devices",description:"Owned devices and sessions shared with you.",children:[e.jsx(wd,{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(u=>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 ${u.connected?"bg-emerald-500":"bg-[var(--theme-fg-muted)]"}`}),e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:u.name})]}),e.jsx("p",{className:"mt-1 font-mono text-xs text-[var(--theme-fg-muted)]",children:u.tokenPreview}),e.jsx("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:u.connected?`Online. Last heartbeat: ${Xr(u.lastHeartbeatAt??u.connectedAt)}`:`Offline. Last online: ${Xr(u.lastHeartbeatAt??u.connectedAt)}`})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{className:"relay-button-primary",disabled:!u.connected,onClick:()=>oe(u.id),type:"button",children:"Open"}),e.jsx("button",{className:"relay-button-secondary",onClick:()=>void C(u.id),type:"button",children:"Delete"})]})]},u.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(u=>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:u.label||u.threadId}),e.jsxs("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:[u.ownerUsername," / ",u.deviceName]})]}),e.jsx("button",{className:"relay-button-primary",onClick:()=>ee(u.deviceId,u.threadId),type:"button",children:"Continue"})]})},u.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(Fn,{title:"Invite",description:"Share a single thread with another relay user.",children:e.jsx(Nd,{devices:(n==null?void 0:n.devices)??[],onShare:R})})]}),e.jsx("section",{children:e.jsx(Fn,{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(u=>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:u.label||u.threadId}),e.jsxs("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:["Shared with ",u.targetUsername," on ",u.deviceName]}),e.jsx("button",{className:"relay-button-secondary mt-3",onClick:()=>void v(u.id),type:"button",children:"Revoke"})]},u.id)):e.jsx("p",{className:"text-sm text-[var(--theme-fg-muted)]",children:"No active shares."})})})})]})}):e.jsx(_n,{children:e.jsx(yd,{registrationEnabled:(s==null?void 0:s.registrationEnabled)??!0,initialError:m,onAuthenticated:f})})}function yd({registrationEnabled:t,initialError:s,onAuthenticated:r}){const[n,c]=a.useState("login"),[o,p]=a.useState(""),[m,g]=a.useState(""),[w,P]=a.useState(""),[x,f]=a.useState(""),[k,C]=a.useState(s),[R,v]=a.useState(!1);async function Q(oe){oe.preventDefault(),v(!0),C(null);try{n==="login"?await Xo({identifier:o,password:x}):await Qo({email:m,username:w,password:x}),await r()}catch(ee){C(vn(ee,"Unable to authenticate with relay."))}finally{v(!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:Q,children:[n==="login"?e.jsx(Xt,{autoComplete:"username",label:"Email or username",onChange:p,value:o}):e.jsxs(e.Fragment,{children:[e.jsx(Xt,{autoComplete:"email",label:"Email",onChange:g,value:m}),e.jsx(Xt,{autoComplete:"username",label:"Username",onChange:P,value:w})]}),e.jsx(Xt,{autoComplete:n==="login"?"current-password":"new-password",label:"Password",onChange:f,type:"password",value:x}),k?e.jsx(nr,{tone:"danger",children:k}):null,e.jsx("button",{className:"relay-button-primary h-11 w-full",disabled:R,type:"submit",children:R?"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:()=>c(n==="login"?"register":"login"),type:"button",children:n==="login"?t?"Create relay account":"Registration is disabled":"Use an existing account"})]})}function wd({onCreate:t}){const[s,r]=a.useState(""),[n,c]=a.useState(!1),[o,p]=a.useState(null);async function m(g){g.preventDefault(),c(!0),p(null);try{await t(s),r("")}catch(w){p(vn(w,"Unable to create device."))}finally{c(!1)}}return e.jsxs("form",{className:"flex flex-col gap-2 sm:flex-row",onSubmit:m,children:[e.jsx("input",{className:"relay-input min-w-0 flex-1",onChange:g=>r(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 Nd({devices:t,onShare:s}){const r=a.useMemo(()=>{var v;return((v=t[0])==null?void 0:v.id)??""},[t]),[n,c]=a.useState(r),[o,p]=a.useState(""),[m,g]=a.useState(""),[w,P]=a.useState(""),[x,f]=a.useState(!1),[k,C]=a.useState(null);a.useEffect(()=>{!n&&r&&c(r)},[n,r]);async function R(v){v.preventDefault(),f(!0),C(null);try{await s({targetUsername:o,deviceId:n,threadId:m,...w.trim()?{label:w}:{}}),p(""),g(""),P(""),C("Invitation created.")}catch(Q){C(vn(Q,"Unable to create invitation."))}finally{f(!1)}}return e.jsxs("form",{className:"space-y-3",onSubmit:R,children:[e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Device",e.jsx("select",{className:"relay-input mt-2 w-full",onChange:v=>c(v.target.value),value:n,children:t.map(v=>e.jsx("option",{value:v.id,children:v.name},v.id))})]}),e.jsx(Xt,{label:"Username",onChange:p,value:o}),e.jsx(Xt,{label:"Thread ID",onChange:g,value:m}),e.jsx(Xt,{label:"Label",onChange:P,value:w}),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()||!m.trim(),type:"submit",children:"Invite"})]})}function _n({children:t}){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.jsx("div",{className:"flex min-h-[calc(100vh-3rem)] items-center justify-center",children:t})})}function Fn({title:t,description:s,children:r}){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})]}),r]})}function Xt({label:t,value:s,onChange:r,type:n="text",autoComplete:c}){return e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:[t,e.jsx("input",{autoComplete:c,className:"relay-input mt-2 w-full",onChange:o=>r(o.target.value),type:n,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(--theme-accent-border)] bg-[var(--theme-accent-soft)] text-[var(--theme-fg)]"}`,children:s})}function Sd(t){return`REMOTE_CODEX_RELAY_SERVER_URL=${kd()} REMOTE_CODEX_RELAY_AGENT_TOKEN=${t} remote-codex relay-supervisor`}function kd(){return typeof window>"u"?"wss://relay.example.com":window.location.origin.replace(/^https:\/\//,"wss://").replace(/^http:\/\//,"ws://")}function Xr(t){return t??"never"}const Qr=3,Cd=10,Td=1e3,Id=2e3,Wn=5500,Ed=3e3,qn=0,cs=1,ln=3,Rd=["read-only","workspace-write","danger-full-access"],Pd=[],Ad=[],Ud=[],Od={workspace:!0,toolUsage:!1,guide:!1,threadGraph:!1,extensions:!1,defaultTab:"workspace"};function Md(){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 $d(){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 dn({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 Ld(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 Dd(){var Sr;const{id:t=""}=na(),s=ht(),r=zt(),n=ar(),c=a.useRef(""),o=a.useRef(null),p=a.useRef(null),m=a.useRef(null),g=a.useRef(!1),w=a.useRef(null),P=a.useRef(null),x=a.useRef(typeof navigator>"u"?!0:navigator.onLine),f=a.useRef(!1),k=a.useRef(null),C=a.useRef(null),R=a.useRef(0),v=a.useRef(0),Q=a.useRef(null),oe=a.useRef(null),ee=a.useRef(null),_=a.useRef(null),le=a.useRef(new Set),[u,B]=a.useState(null),[ne,T]=a.useState([]),[K,z]=a.useState([]),[L,Z]=a.useState(null),[A,ie]=a.useState(null),[Y,Ce]=a.useState(null),[fe,D]=a.useState(""),[re,H]=a.useState(null),[ge,pe]=a.useState(null),[nt,it]=a.useState(!0),[Ye,jt]=a.useState(0),[We,dt]=a.useState(!0),[Le,ct]=a.useState(!1),[b,y]=a.useState(!1),[I,V]=a.useState("chat"),be=n.getThreadPanels().some(l=>l.kind==="terminal"),Pe=a.useMemo(()=>({fetchState:Al,createShell:Ml,terminateShell:$l,updateShell:Ll,connectSocket:ri}),[]),ut=a.useCallback(l=>`/threads/${l}`,[]),Ae=a.useCallback(l=>{s(`/threads/${l}`)},[s]),yt=a.useCallback(l=>l?`/threads/new?workspaceId=${encodeURIComponent(l)}`:"/threads/new",[]),Ve=a.useCallback(({threadId:l,path:i})=>`/api/threads/${l}/assets/image?path=${encodeURIComponent(i)}`,[]),[rt,Ge]=a.useState({prompt:"",attachments:[]}),[Ze,Tt]=a.useState(!1),[Mt,Jt]=a.useState(0),[Vt,X]=a.useState(0),[de,ue]=a.useState(0),[me,Se]=a.useState(!1),[F,Xe]=a.useState(null),[Me,Qe]=a.useState(!1),[pt,$t]=a.useState(!1),[ft,ps]=a.useState(!1),[fs,xs]=a.useState(null),[wt,Gt]=a.useState("idle"),[xt,gs]=a.useState({status:x.current?"checking":"offline",browserOnline:x.current,healthOk:!1,socketOpen:!1,lastHealthyAt:null}),[ye,at]=a.useState(null),[Nt,It]=a.useState([]),[bs,et]=a.useState({status:"idle",data:null,error:null}),[mt,Et]=a.useState({status:"idle",data:null,error:null}),[qe,Te]=a.useState({status:"idle",data:null,error:null}),[Lt,St]=a.useState({status:"idle",data:null,error:null}),[ke,ve]=a.useState({status:"idle",data:null,error:null}),[As,W]=a.useState(!1),[G,te]=a.useState(!1),[vs,Qt]=a.useState(()=>new Set),[js,Rt]=a.useState(!1),[Pt,Us]=a.useState(!1),[kt,Dt]=a.useState({status:"idle",data:null,error:null}),[gt,Ht]=a.useState(null),[ys,Kt]=a.useState(!1),[Os,he]=a.useState(null),At=((Sr=Y==null?void 0:Y.hostConfigFiles.find(l=>{var i;return(i=l.roles)==null?void 0:i.includes("mcp")}))==null?void 0:Sr.name)??null,es=a.useCallback(()=>{const l=c.current;c.current="",o.current=null,l&&a.startTransition(()=>{D(i=>i+l)})},[]),ts=a.useCallback(l=>{c.current+=l,o.current===null&&(o.current=window.requestAnimationFrame(()=>{es()}))},[es]),ws=a.useCallback((l,i)=>{pe(h=>{const E=(h==null?void 0:h.turnId)===l?h.items:[],O=E.findIndex(Ue=>Ue.id===i.id),J=Ua(E[O],i),ce=O>=0?E.map((Ue,$)=>$===O?J:Ue):[...E,J];return{turnId:l,items:ce,updatedAt:new Date().toISOString()}})},[]),Ms=a.useCallback((l,i,h,E)=>{pe(O=>{const J=(O==null?void 0:O.turnId)===l?O.items:[],ce=J.find(Be=>Be.id===i),Ue=(ce==null?void 0:ce.kind)==="agentMessage"?{...ce,text:`${ce.text}${h}`,sequence:E??ce.sequence??null}:{id:i,kind:"agentMessage",text:h,sequence:E},$=J.findIndex(Be=>Be.id===i),Je=$>=0?J.map((Be,_e)=>_e===$?Ue:Be):[...J,Ue];return{turnId:l,items:Je,updatedAt:new Date().toISOString()}})},[]),ot=a.useCallback(()=>{c.current="",o.current!==null&&(window.cancelAnimationFrame(o.current),o.current=null)},[]);a.useEffect(()=>{et({status:"idle",data:null,error:null}),Et({status:"idle",data:null,error:null}),Te({status:"idle",data:null,error:null}),St({status:"idle",data:null,error:null}),ve({status:"idle",data:null,error:null}),Rt(!1),Dt({status:"idle",data:null,error:null})},[t]);const ss=a.useCallback(async()=>{if(t){Dt(l=>({status:"loading",data:l.data,error:null}));try{const l=await El(t);Dt({status:"ready",data:l,error:null})}catch(l){const i=l instanceof ae?l.payload.message:"Unable to load export turns.";Dt(h=>({status:"failed",data:h.data,error:i}))}}},[t]);async function $s(l){if(t){he(null),Us(!0);try{const{blob:i,filename:h}=await Pl(t,l),E=URL.createObjectURL(i),O=document.createElement("a");O.href=E,O.download=h,document.body.append(O),O.click(),O.remove(),window.setTimeout(()=>URL.revokeObjectURL(E),3e4),Rt(!1)}catch(i){const h=i instanceof ae?i.payload.message:"Unable to export transcript.";he(h)}finally{Us(!1)}}}async function Ls(){if(t){ve(l=>{var i;return{status:"loading",data:l.data??((i=ee.current)==null?void 0:i.goal)??null,error:null}});try{const l=await Fl(t);ve({status:"ready",data:l.goal,error:null}),B(i=>i&&(l.goal?{...i,goal:l.goal,goalHistory:an(i.goalHistory??[],l.goal)}:{...i,goal:l.goal}))}catch(l){ve(i=>({status:"failed",data:i.data,error:l instanceof ae?l.payload.message:"Unable to load goal."}))}}}async function Ds(l){if(t){ve(i=>{var h;return{status:"loading",data:i.data??((h=ee.current)==null?void 0:h.goal)??null,error:null}});try{const i=await Wl(t,l);ve({status:"ready",data:i.goal,error:null}),B(h=>h&&(i.goal?{...h,goal:i.goal,goalHistory:an(h.goalHistory??[],i.goal)}:{...h,goal:i.goal}))}catch(i){throw ve(h=>({status:"failed",data:h.data,error:i instanceof ae?i.payload.message:"Unable to update goal."})),i}}}async function jn(){if(t){ve(l=>{var i;return{status:"loading",data:l.data??((i=ee.current)==null?void 0:i.goal)??null,error:null}});try{const l=await ql(t);ve({status:"ready",data:null,error:null}),B(i=>i&&(l.goalHistory?{...i,goal:null,goalHistory:l.goalHistory}:{...i,goal:null}))}catch(l){throw ve(i=>({status:"failed",data:i.data,error:l instanceof ae?l.payload.message:"Unable to clear goal."})),l}}}async function Hs(l){te(!0);try{await Ds({status:l})}finally{te(!1)}}async function yn(){te(!0);try{await jn()}finally{te(!1)}}async function Bs(){if(t){et(l=>({status:"loading",data:l.data,error:null}));try{const l=await Jl(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 wn(){if(t){Et(l=>({status:"loading",data:l.data,error:null}));try{const l=await Vl(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 MCP servers."}))}}}async function Nn(){if(t){Te(l=>({status:"loading",data:l.data,error:null}));try{const l=await Gl(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 Sn(l){if(t){Te(i=>({status:"loading",data:i.data,error:null}));try{const i=await Kl(t,l);Te({status:"ready",data:i,error:null})}catch(i){throw Te(h=>({status:"failed",data:h.data,error:i instanceof ae?i.payload.message:"Unable to create hook."})),i}}}async function ze(l){if(t){Te(i=>({status:"loading",data:i.data,error:null}));try{const i=await Yl(t,l);Te({status:"ready",data:i,error:null})}catch(i){throw Te(h=>({status:"failed",data:h.data,error:i instanceof ae?i.payload.message:"Unable to update hook."})),i}}}async function Ns(l){if(t){Te(i=>({status:"loading",data:i.data,error:null}));try{const i=await Zl(t,l);Te({status:"ready",data:i,error:null})}catch(i){throw Te(h=>({status:"failed",data:h.data,error:i instanceof ae?i.payload.message:"Unable to trust hook."})),i}}}async function _s(l){if(t){Te(i=>({status:"loading",data:i.data,error:null}));try{const i=await Xl(t,l);Te({status:"ready",data:i,error:null})}catch(i){throw Te(h=>({status:"failed",data:h.data,error:i instanceof ae?i.payload.message:"Unable to untrust hook."})),i}}}async function bt(){if(t){St(l=>({status:"loading",data:l.data,error:null}));try{const l=await zl(t);St({status:"ready",data:l,error:null})}catch(l){St(i=>({status:"failed",data:i.data,error:l instanceof ae?l.payload.message:"Unable to load turns for forking."}))}}}async function vt(){if(!t)return;const l=await Hr(t,{mode:"latest"});T(i=>Is(i,l.thread.thread)),s(`/threads/${l.thread.thread.id}`)}async function kn(l){if(!t)return;const i=await Hr(t,{mode:"turn",turnId:l});T(h=>Is(h,i.thread.thread)),s(`/threads/${i.thread.thread.id}`)}const Fs=a.useCallback(l=>{const i=_.current,h=i&&Object.keys(i).length>0?{...l,thread:{...l.thread,...i}}:l,E=ee.current;ee.current=h,H(h.livePlan??null);const O=E?Wt(E.turns,h.turns):h.turns;pe($=>Ji($,h.liveItems??null,O)),ve($=>$.status==="idle"?$:{...$,data:h.goal??null});const J=h.thread.activeTurnId===null&&h.thread.status!=="running";B($=>$&&!h.goalHistory?{...h,turns:Wt($.turns,h.turns),pendingRequests:sr($.pendingRequests,h.pendingRequests,le.current),...$.goalHistory?{goalHistory:$.goalHistory}:{}}:$?{...h,turns:Wt($.turns,h.turns),pendingRequests:sr($.pendingRequests,h.pendingRequests,le.current)}:h),T($=>Is($,h.thread));const ce=new Map(h.turns.map($=>[$.id,$])),Ue=new Set((h.pendingSteers??[]).map($=>$.clientRequestId).filter($=>!!$));It($=>$.filter(Je=>{if(Ue.has(Je.clientRequestId))return!1;const Be=ce.get(Je.turnId);return!(!Be||Rs(Be,Je.prompt)||h.thread.activeTurnId!==Je.turnId&&Be.status!=="inProgress")})),at($=>{if(!$)return $;const Je=$.serverTurnId??$.id,Be=h.turns.some(M=>M.id===Je),_e=ce.get(Je)??null,je=Xi(h.turns,$.prompt),j=!!je;if(je&&!$.serverTurnId)return{...$,id:je.id,serverTurnId:je.id,status:$.status==="failed"?$.status:je.status==="inProgress"?"inProgress":$.status};if(_e&&$.serverTurnId)return Rs(_e,$.prompt)||$.prompt.includes("[PHOTO ")&&(mn(_e,$.prompt)||$n(_e))?_e.status==="inProgress"?{...$,id:_e.id,serverTurnId:_e.id,status:$.status==="failed"?$.status:"inProgress"}:null:{...$,id:_e.id,serverTurnId:_e.id,status:$.status==="failed"?$.status:"inProgress"};if(!$.serverTurnId&&$.prompt.includes("[PHOTO ")&&h.thread.activeTurnId&&h.thread.status==="running"){const M=ce.get(h.thread.activeTurnId);if(M&&$n(M))return{...$,id:M.id,serverTurnId:M.id,status:$.status==="failed"?$.status:"inProgress"}}return Be||J&&j?null:$}),(J||oe.current&&h.turns.some($=>$.id===oe.current))&&(oe.current=null,ot(),D(""),H(null),pe(null))},[ot]);a.useEffect(()=>{ee.current=u},[u]);const Ws=a.useCallback(async({seedThread:l}={})=>{var ce;const i=v.current+1;v.current=i;const h=(l==null?void 0:l.provider)??((ce=ee.current)==null?void 0:ce.thread.provider)??"codex",[E,O,J]=await Promise.allSettled([ka(),wa(h),er(h)]);v.current===i&&(E.status==="fulfilled"?T(l?Is(E.value,l):E.value):l&&T(Ue=>Is(Ue,l)),O.status==="fulfilled"&&(Q.current=h,Z(O.value.status),ie(O.value.capabilities),Ce(O.value.managementSchema)),J.status==="fulfilled"&&(Q.current=h,z(J.value)))},[]),Bt=a.useCallback(async({showLoading:l=!0,clearError:i=!0,reportError:h=!0,limit:E=Qr}={})=>{const O=R.current+1;R.current=O,l&&dt(!0),i&&he(null);try{const J=await $r(t,{limit:E});if(R.current!==O)return;Fs(J),Q.current!==J.thread.provider&&Ws({seedThread:J.thread})}catch(J){if(R.current!==O||!h)return;he(J instanceof Error?J.message:"Unable to load thread detail.")}finally{R.current===O&&dt(!1)}},[Fs,t,Ws]),De=a.useCallback(()=>{var Ue;const l=((Ue=p.current)==null?void 0:Ue.readyState)??ln,i=l===cs,h=x.current,E=Date.now(),O=w.current!==null&&E-Date.parse(w.current)<=Wn,J=P.current!==null&&E-P.current<=Wn;let ce;h?i&&J?ce="connected":l===qn||m.current!==null||O||J||g.current?ce="reconnecting":ce="checking":ce="offline",gs($=>$.status===ce&&$.browserOnline===h&&$.healthOk===O&&$.socketOpen===i&&$.lastHealthyAt===w.current?$:{status:ce,browserOnline:h,healthOk:O,socketOpen:i,lastHealthyAt:w.current})},[]);a.useEffect(()=>{R.current+=1,v.current+=1,B(null),Ge({prompt:"",attachments:[]}),ct(!1),Gt("idle"),at(null),It([]),pe(null),_.current=null,oe.current=null,le.current=new Set,w.current=null,P.current=null,f.current=!1,x.current=typeof navigator>"u"?!0:navigator.onLine,gs({status:x.current?"checking":"offline",browserOnline:x.current,healthOk:!1,socketOpen:!1,lastHealthyAt:null})},[t]),a.useEffect(()=>{if(wt==="idle")return;const l=window.setTimeout(()=>{Gt("idle")},wt==="copied"?1200:1600);return()=>{window.clearTimeout(l)}},[wt]),a.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")}},[]),a.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const l=window.matchMedia("(max-width: 639px)"),i=()=>Tt(l.matches);return i(),l.addEventListener("change",i),()=>{l.removeEventListener("change",i)}},[]),a.useEffect(()=>{var i,h;if(typeof window>"u")return;const l=()=>{const E=window.visualViewport,O=E?Math.max(0,Math.round(window.innerHeight-E.height-E.offsetTop)):0;ue(O),document.documentElement.style.setProperty("--thread-detail-keyboard-inset",`${O}px`)};return l(),(i=window.visualViewport)==null||i.addEventListener("resize",l),(h=window.visualViewport)==null||h.addEventListener("scroll",l),window.addEventListener("resize",l),()=>{var E,O;(E=window.visualViewport)==null||E.removeEventListener("resize",l),(O=window.visualViewport)==null||O.removeEventListener("scroll",l),window.removeEventListener("resize",l),document.documentElement.style.removeProperty("--thread-detail-keyboard-inset")}},[]),a.useEffect(()=>{if(typeof document>"u")return;const l=()=>{const i=document.activeElement,h=C.current,E=h==null?void 0:h.querySelector('[aria-label="Prompt"]');Se(!!(i&&E&&(i===E||E.contains(i))))};return l(),document.addEventListener("focusin",l),document.addEventListener("focusout",l),()=>{document.removeEventListener("focusin",l),document.removeEventListener("focusout",l)}},[I,u==null?void 0:u.thread.id,Ze]),a.useEffect(()=>{const l=C.current;if(!l||typeof ResizeObserver>"u")return;const i=l.querySelector("form")??l,h=()=>{Jt(Math.max(l.getBoundingClientRect().height,i.getBoundingClientRect().height))};h();const E=new ResizeObserver(()=>{h()});return E.observe(i),()=>{E.disconnect()}},[I,Ze]),a.useEffect(()=>{var E,O;const l=C.current;if(!l||!Ze||I!=="chat"){X(0);return}const i=()=>{const J=l.getBoundingClientRect();X(Math.max(0,Math.ceil(window.innerHeight-J.top)))};i(),window.addEventListener("resize",i),(E=window.visualViewport)==null||E.addEventListener("resize",i),(O=window.visualViewport)==null||O.addEventListener("scroll",i);let h=null;return typeof ResizeObserver<"u"&&(h=new ResizeObserver(i),h.observe(l)),()=>{var J,ce;window.removeEventListener("resize",i),(J=window.visualViewport)==null||J.removeEventListener("resize",i),(ce=window.visualViewport)==null||ce.removeEventListener("scroll",i),h==null||h.disconnect()}},[I,u==null?void 0:u.thread.id,Ze,de,me]),a.useEffect(()=>{Bt({showLoading:!0,limit:Qr})},[Bt]),a.useEffect(()=>{let l=!1,i=null;const h=()=>{Bt({showLoading:!1,clearError:!1,reportError:!1})},E=()=>{m.current!==null&&(window.clearTimeout(m.current),m.current=null)},O=()=>{l||!x.current||m.current!==null||(m.current=window.setTimeout(()=>{m.current=null,!l&&$()},Td),De())},J=()=>{const j=p.current;if(p.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 M=typeof j.payload.turnId=="string"?j.payload.turnId:null,se=typeof j.payload.itemId=="string"?j.payload.itemId:null,Ie=typeof j.payload.sequence=="number"&&Number.isFinite(j.payload.sequence)?j.payload.sequence:null;M&&se?Ms(M,se,j.payload.delta,Ie):ts(j.payload.delta),M&&at(xe=>xe&&(xe.serverTurnId===null||xe.serverTurnId===M)?{...xe,serverTurnId:M,id:M,status:xe.status==="failed"?xe.status:"inProgress",tokenUsage:xe.tokenUsage}:xe)}if(j.type==="thread.context.updated"){const M=j.payload.contextUsage&&typeof j.payload.contextUsage=="object"?j.payload.contextUsage:null;if(M){const se=M;B(Ie=>Ie&&{...Ie,thread:{...Ie.thread,contextUsage:se}}),T(Ie=>Ie.map(xe=>xe.id===t?{...xe,contextUsage:se}:xe))}}if(j.type==="thread.turn.token.updated"&&typeof j.payload.turnId=="string"&&j.payload.tokenUsage&&typeof j.payload.tokenUsage=="object"){const M=j.payload.turnId,se=j.payload.tokenUsage,Ie=j.payload.priceEstimate&&typeof j.payload.priceEstimate=="object"?j.payload.priceEstimate:null;B(xe=>{if(!xe)return xe;const tt=Qi(xe.turns,M,se,Ie);return tt===xe.turns?xe:{...xe,turns:tt}}),at(xe=>xe&&(xe.serverTurnId===M||xe.id===M)?{...xe,tokenUsage:se,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 M=j.payload.goal&&typeof j.payload.goal=="object"?j.payload.goal:null,se=Array.isArray(j.payload.goalHistory)?j.payload.goalHistory:null;ve({status:"ready",data:M,error:null}),B(Ie=>Ie&&(se?{...Ie,goal:M,goalHistory:se}:M?{...Ie,goal:M,goalHistory:an(Ie.goalHistory??[],M)}:{...Ie,goal:M}))}if(j.type==="thread.goal.cleared"){const M=Array.isArray(j.payload.goalHistory)?j.payload.goalHistory:null;ve({status:"ready",data:null,error:null}),B(se=>se&&(M?{...se,goal:null,goalHistory:M}:{...se,goal:null}))}if(h(),j.type==="thread.turn.started"){ot(),D(""),pe(null),oe.current=null;const M=typeof j.payload.turnId=="string"?j.payload.turnId:null;M&&at(se=>se&&{...se,serverTurnId:M,id:M,status:se.status==="failed"?se.status:"inProgress",error:null,tokenUsage:se.tokenUsage})}if(j.type==="thread.turn.completed"||j.type==="thread.turn.failed"){ot(),D("");const M=typeof j.payload.turnId=="string"?j.payload.turnId:null;M&&(oe.current=M,j.type==="thread.turn.failed"&&at(se=>se&&(se.serverTurnId===M||se.id===M)?{...se,status:"failed",error:typeof j.payload.error=="string"?j.payload.error:"Unable to complete the turn.",tokenUsage:se.tokenUsage}:se))}}if(j.type==="thread.request.created"&&zi(j.payload.request)&&(le.current.delete(j.payload.request.id),B(M=>M&&Wi(M,j.payload.request))),j.type==="thread.request.resolved"&&typeof j.payload.requestId=="string"){const M=j.payload.requestId;le.current.add(M),B(se=>se&&qi(se,M))}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 M=j.payload.turnId,se=j.payload.item;typeof se.id=="string"&&typeof se.text=="string"&&ws(M,se)}j.type==="thread.plan.updated"&&Array.isArray(j.payload.plan)&&H({turnId:String(j.payload.turnId??""),explanation:typeof j.payload.explanation=="string"?j.payload.explanation:null,plan:j.payload.plan})}},Ue=()=>{const j=p.current;if(!(!j||j.readyState!==cs))try{j.send(JSON.stringify({type:"supervisor.ping",timestamp:new Date().toISOString()}))}catch{f.current=!0,J(),O(),De()}},$=()=>{var se;if(l||!x.current){De();return}const j=((se=p.current)==null?void 0:se.readyState)??ln;if(j===qn||j===cs){De();return}const M=Ia(ce);p.current=M,De(),M.addEventListener("message",Ie=>{if(p.current===M)try{const xe=JSON.parse(Ie.data);(xe.type==="supervisor.connected"||xe.type==="supervisor.pong")&&(P.current=Date.now(),De())}catch{}}),M.addEventListener("open",()=>{p.current===M&&(f.current=!0,h(),Ue(),De())}),M.addEventListener("close",()=>{p.current===M&&(p.current=null),f.current=!0,O(),De()}),M.addEventListener("error",()=>{p.current===M&&(p.current=null),f.current=!0,O(),De()})},Je=async()=>{var j;if(!(l||!x.current||g.current)){g.current=!0,De();try{await bl();const M=f.current;w.current=new Date().toISOString(),M&&(f.current=!1,h()),(((j=p.current)==null?void 0:j.readyState)??ln)!==cs&&$()}catch{w.current=null,f.current=!0,O()}finally{g.current=!1,De()}}},Be=()=>{x.current=!0,f.current=!0,De(),$(),Je()},_e=()=>{x.current=!1,w.current=null,P.current=null,f.current=!0,E(),J(),De()},je=()=>{var se;if(l||!x.current){De();return}const j=((se=p.current)==null?void 0:se.readyState)??ln,M=P.current===null?null:Date.now()-P.current;j===cs&&M!==null&&M>Wn?(f.current=!0,J(),O()):j===cs?Ue():j!==qn&&$(),Je(),De()};return window.addEventListener("online",Be),window.addEventListener("offline",_e),$(),Je(),i=window.setInterval(je,Id),()=>{l=!0,window.removeEventListener("online",Be),window.removeEventListener("offline",_e),E(),i!==null&&window.clearInterval(i),ot(),J()}},[Ms,ot,t,Bt,ts,De,ws]),a.useEffect(()=>{if(!((u==null?void 0:u.thread.activeTurnId)!==null||(u==null?void 0:u.thread.status)==="running"||ye!==null||Nt.length>0||fe.length>0||re!==null||ge!==null))return;const i=window.setInterval(()=>{Bt({showLoading:!1,clearError:!1,reportError:!1})},Ed);return()=>{window.clearInterval(i)}},[u==null?void 0:u.thread.activeTurnId,u==null?void 0:u.thread.status,fe.length,ge,re,Bt,Nt.length,ye]);const qs=a.useCallback(async()=>{var l;if(!(!u||u.turns.length===0||Le)){ct(!0),he(null);try{const i=(l=u.turns[0])==null?void 0:l.id,h=await $r(t,{limit:Cd,...i?{beforeTurnId:i}:{}});B(E=>E?{...h,turns:Fi(E.turns,h.turns)}:h),T(E=>E.map(O=>O.id===h.thread.id?h.thread:O))}catch(i){he(i instanceof Error?i.message:"Unable to load earlier turns.")}finally{ct(!1)}}},[u,t,Le]);async function zs(l){var Je,Be,_e;if(I==="shell"){if((u==null?void 0:u.thread.isLoaded)===!1)return await _t({attachShell:!0}),!1;let je=!1;if((F==null?void 0:F.shellInputEnabled)!==!0&&((F==null?void 0:F.loading)===!1&&(F==null?void 0:F.isConnecting)!==!0&&(F==null?void 0:F.status)!=="creating"&&(F==null?void 0:F.status)!=="workspace_missing"&&(await((Je=k.current)==null?void 0:Je.toggleConnection()),je=!0),(F==null?void 0:F.isConnecting)===!0))return he("Connecting to the shell. Try again after it attaches."),!1;if(((Be=k.current)==null?void 0:Be.sendCommand(l.prompt))??!1)he(null);else return he(je?"Shell is still attaching. Try again after it connects.":"Connect the shell before sending commands."),!1;return!0}y(!0),he(null),jt(je=>je+1);const i=ee.current,h=i?{...i.thread,..._.current??{}}:null,E=(h==null?void 0:h.model)??null,O=(h==null?void 0:h.reasoningEffort)??null,J=Zi(),ce=`optimistic-${Date.now()}`,Ue=`optimistic-steer-${J}`,$=new Date().toISOString();try{let je=ee.current;if(je&&!je.thread.isLoaded){const Ee={...je.thread,..._.current??{}},lt=await Lr(t,{...je.thread.model?{model:je.thread.model}:{},...je.thread.sandboxMode?{sandboxMode:je.thread.sandboxMode}:{}}),st={...lt,thread:{...lt.thread,model:Ee.model??lt.thread.model,reasoningEffort:Ee.reasoningEffort??lt.thread.reasoningEffort,collaborationMode:Ee.collaborationMode??lt.thread.collaborationMode,sandboxMode:Ee.sandboxMode??lt.thread.sandboxMode??null}};je=st,ee.current=st,B(en=>en?{...st,turns:Wt(en.turns,st.turns)}:st),T(en=>en.map(kr=>kr.id===st.thread.id?st.thread:kr))}const j=je?{...je.thread,..._.current??{}}:null,M=(j==null?void 0:j.status)==="running"?j.activeTurnId:null,se=I==="chat"&&!!M;se&&M?It(Ee=>[...Ee,{id:Ue,clientRequestId:J,turnId:M,prompt:l.prompt,createdAt:$,status:"steering"}]):(ot(),D(""),at({id:ce,serverTurnId:null,startedAt:$,status:"sending",error:null,prompt:l.prompt,model:E,reasoningEffort:O,reasoningEffortAvailable:Gr(K,E),tokenUsage:null,priceEstimate:null}));const Ie={prompt:l.prompt,clientRequestId:J,...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}:{},...(_e=l.attachments)!=null&&_e.length?{attachments:l.attachments}:{}},xe=await Hl(t,Ie),tt=_.current&&Object.keys(_.current).length>0?{...xe,..._.current}:xe;B(Ee=>Ee&&{...Ee,thread:tt}),T(Ee=>Ee.map(lt=>lt.id===tt.id?tt:lt)),se&&M?tt.activeTurnId!==null&&tt.activeTurnId!==M&&tt.lastTurnStartedAt!==(j==null?void 0:j.lastTurnStartedAt)?(ot(),D(""),H(null),It(lt=>lt.filter(st=>st.id!==Ue)),at({id:ce,serverTurnId:tt.activeTurnId,startedAt:tt.lastTurnStartedAt??$,status:"inProgress",error:null,prompt:l.prompt,model:E,reasoningEffort:O,reasoningEffortAvailable:Gr(K,E),tokenUsage:null,priceEstimate:null})):It(lt=>lt.map(st=>st.id===Ue?{...st,turnId:tt.activeTurnId??st.turnId,status:"accepted"}:st)):(at(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),H(null)),Ge({prompt:"",attachments:[]})}catch(je){const j=je instanceof ae?je.payload.message:je instanceof Error?je.message:"Unable to send prompt.";je instanceof ae?he(je.payload.message):he(j),It(M=>M.filter(se=>se.clientRequestId!==J)),at(M=>M&&M.id===ce?{...M,status:"failed",error:j}:M)}finally{y(!1)}}async function Cn(){const l=u==null?void 0:u.thread.providerSessionId;if(l)try{await navigator.clipboard.writeText(l),Gt("copied")}catch{Gt("failed")}}async function _t(l){if(u){y(!0),he(null),ot(),D("");try{if(u.thread.isLoaded){const h=await Dl(t);B(E=>E?{...h,turns:Wt(E.turns,h.turns)}:h),Xe(null),T(E=>E.map(O=>O.id===h.thread.id?h.thread:O)),Qe(!1);return}const i=await Lr(t,{...u.thread.model?{model:u.thread.model}:{},...u.thread.sandboxMode?{sandboxMode:u.thread.sandboxMode}:{}});B(h=>h?{...i,turns:Wt(h.turns,i.turns)}:i),T(h=>h.map(E=>E.id===i.thread.id?i.thread:E)),l!=null&&l.attachShell&&I==="shell"&&Qe(!0)}catch(i){he(i instanceof Error?i.message:"Unable to change connection state.")}finally{y(!1)}}}async function ns(){var l;if(I==="shell"){const i=((l=k.current)==null?void 0:l.sendControl("ctrl_c"))??!1;he(i?null:"Connect the shell before sending Ctrl-C.");return}y(!0),he(null);try{const i=u!=null&&u.thread.activeTurnId?await Dr(t,{turnId:u.thread.activeTurnId}):await Dr(t);B(h=>h&&{...h,thread:i}),T(h=>h.map(E=>E.id===i.id?i:E)),ot(),D("")}catch(i){he(i instanceof Error?i.message:"Unable to interrupt turn.")}finally{y(!1)}}async function rs(l){if(!u)return;const i=u,h={..._.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}:{}},E={...u.thread,...h};$t(!0),_.current=h,ee.current={...u,thread:E},B(O=>O&&{...O,thread:E}),T(O=>O.map(J=>J.id===E.id?{...J,...E}:J));try{const O=await Bl(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}:{}});_.current=null,ee.current=i?{...i,thread:O}:null,B(J=>J&&{...J,thread:O}),T(J=>J.map(ce=>ce.id===O.id?O:ce))}catch(O){_.current=null,ee.current=i,B(i),T(J=>J.map(ce=>ce.id===i.thread.id?i.thread:ce)),he(O instanceof Error?O.message:"Unable to update thread settings.")}finally{$t(!1)}}const as=a.useCallback(async(l,i)=>{xs(l),he(null);try{const h=await Ql(t,l,i);B(E=>E?{...h,turns:Wt(E.turns,h.turns)}:h),H(h.livePlan??null),pe(h.liveItems??null)}catch(h){he(h instanceof Error?h.message:"Unable to answer this request.")}finally{xs(null)}},[t]),Js=a.useCallback(l=>Sl(t,l),[t]);async function Yt(){if(u){ps(!0),he(null);try{const l=await _l(t);B(i=>i&&{...i,thread:l}),T(i=>i.map(h=>h.id===l.id?l:h))}catch(l){he(l instanceof Error?l.message:"Unable to compact this thread context.")}finally{ps(!1)}}}async function Vs(l,i){try{const h=await Ca(l,{title:i});T(E=>E.map(O=>O.id===h.id?{...O,title:h.title,updatedAt:h.updatedAt}:O)),B(E=>E&&E.thread.id===h.id?{...E,thread:{...E.thread,title:h.title,updatedAt:h.updatedAt}}:E)}catch(h){throw he(h instanceof Error?h.message:"Unable to rename thread."),h}}async function Gs(){if(gt){Kt(!0),he(null);try{await Ta(gt.id),T(i=>i.filter(h=>h.id!==gt.id));const l=gt.id===(u==null?void 0:u.thread.id);if(Ht(null),l){const i=ne.find(h=>h.id!==gt.id&&h.workspaceId===(u==null?void 0:u.thread.workspaceId))??ne.find(h=>h.id!==gt.id);s(i?`/threads/${i.id}`:"/threads")}}catch(l){he(l instanceof Error?l.message:"Unable to delete thread.")}finally{Kt(!1)}}}function os(){V(l=>l==="chat"?(u!=null&&u.thread.isLoaded&&Qe(!0),"shell"):"chat")}async function Ft(){var i;const l=await((i=k.current)==null?void 0:i.copyLastCommandOutput());he(l?null:"Unable to copy the last shell command output.")}function ls(l){var h,E;const i=l==="clear"?((h=k.current)==null?void 0:h.sendCommand("clear"))??!1:((E=k.current)==null?void 0:E.sendControl(l))??!1;he(i?null:"Connect the shell before sending control input.")}a.useEffect(()=>{if(!(!Me||I!=="shell"||!k.current||(u==null?void 0:u.thread.isLoaded)===!1||(F==null?void 0:F.loading)!==!1)){if((F==null?void 0:F.status)==="attached"){Qe(!1);return}Qe(!1),k.current.toggleConnection()}},[I,u==null?void 0:u.thread.isLoaded,Me,F==null?void 0:F.loading,F==null?void 0:F.status]),a.useEffect(()=>{if(I!=="shell")return;const l=window.requestAnimationFrame(()=>{var i;(i=k.current)==null||i.refreshLayout({syncBackendSize:!1})});return()=>{window.cancelAnimationFrame(l)}},[I]);const Ss=u&&u.workspacePathStatus==="missing"?"Restore this workspace path on the current machine before continuing.":null,ks=Ze&&I==="chat",Ks=ks&&me?de:0,Ys=Math.max(Mt,144),Tn=Math.max(Vt,Ys+Ks),Zs=ks?Tn+12:0,Xs=u?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:u.thread.providerSessionId??"Unavailable"}),u.thread.providerSessionId&&e.jsx("button",{type:"button","aria-label":"Copy session ID",title:wt==="copied"?"Copied":wt==="failed"?"Copy failed":"Copy session ID",onClick:()=>void Cn(),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 ${wt==="copied"?"ui-status-info":wt==="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(Md,{})})})]}),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:u.thread.source==="local_codex_import"?`Imported local ${u.thread.provider} session`:`${u.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:la(u.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:ms(u.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:u.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:u.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:u.thread.activeTurnId??"None"})]})]}):null,Qs=u&&(A!=null&&A.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:Rd.map(l=>{const i=_i(u.thread)===l;return e.jsx("button",{type:"button",disabled:pt,onClick:()=>void rs({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,d=(ye==null?void 0:ye.serverTurnId)??null,N=ye&&u?u.turns.find(l=>(Rs(l,ye.prompt)||ye.prompt.includes("[PHOTO ")&&(mn(l,ye.prompt)||$n(l)))&&(d&&l.id===d||l.id===ye.id||Rs(l,ye.prompt)||ye.prompt.includes("[PHOTO ")&&mn(l,ye.prompt)))??null:null,S=a.useMemo(()=>ye&&!N?{id:ye.id,startedAt:ye.startedAt,status:ye.status,error:ye.error,model:ye.model,reasoningEffort:ye.reasoningEffort,reasoningEffortAvailable:ye.reasoningEffortAvailable,tokenUsage:ye.tokenUsage,priceEstimate:ye.priceEstimate,items:[{id:`${ye.id}-user-message`,kind:"userMessage",text:ye.prompt}]}:null,[N,ye]),q=(u==null?void 0:u.thread.isLoaded)??!1,$e=q?xt.status==="connected"?"ui-action-success shadow-lg shadow-stone-950/20":xt.status==="reconnecting"?"thread-live-connection-reconnecting ui-status-success shadow-lg shadow-stone-950/20":xt.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=Ld(q,xt),Ut=[He,q?null:"Tap to connect this thread",xt.lastHealthyAt?`Last healthy ${ms(xt.lastHealthyAt)}`:null].filter(Boolean).join(" · "),In=q?e.jsx("div",{role:"status","aria-live":"polite","aria-label":He,title:Ut,className:`inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition ${$e}`,children:e.jsx(dn,{status:xt.status})}):e.jsx("button",{type:"button",onClick:()=>void _t(),disabled:b||!u,"aria-label":b?"Connecting thread":"Connect thread",title:b?"Connecting thread":Ut,className:`inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition ${$e}`,children:e.jsx(dn,{status:"detached"})}),Wa=q?e.jsx("div",{title:Ut,className:`hidden lg:inline-flex h-9 w-9 items-center justify-center rounded-full transition ${$e}`,children:e.jsx(dn,{status:xt.status})}):e.jsx("button",{type:"button",onClick:()=>void _t(),disabled:b||!u,title:b?"Connecting thread":Ut,className:`hidden lg:inline-flex h-9 w-9 items-center justify-center rounded-full transition ${$e}`,children:e.jsx(dn,{status:"detached"})}),pr=ke.data??(u==null?void 0:u.goal)??null,fr=(u==null?void 0:u.goalHistory)??[],xr=pr?an(fr,pr):Oa(fr),gr=(A==null?void 0:A.controls.goals)??!1,qa=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"})]}),za=As&&gr?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:()=>W(!1),className:"host-secondary-button rounded-full border px-2.5 py-1 text-xs transition",children:"Close"})]}),ke.error?e.jsx("p",{className:"host-error mt-3 rounded-2xl border px-3 py-2 text-xs",children:ke.error}):null,e.jsx("div",{className:"mt-3 max-h-[28rem] space-y-2 overflow-auto pr-1",children:xr.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."}):xr.map(l=>{const i=`${l.threadId}:${l.objective}:${l.createdAt}`,h=vs.has(i),E=["active","paused","budgetLimited"].includes(l.status);return e.jsxs("div",{className:`rounded-2xl border px-3 py-3 ${E?"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:()=>Qt(O=>{const J=new Set(O);return J.has(i)?J.delete(i):J.add(i),J}),className:"min-w-0 flex-1 text-left",children:e.jsx("p",{className:`text-sm font-medium leading-5 ${h?"":"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:Yi(l.timeUsedSeconds)}),e.jsx("span",{children:Ki(l)}),e.jsxs("span",{title:ms(l.updatedAt),children:["Updated ",new Date(l.updatedAt).toLocaleTimeString()]})]}),E?e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",disabled:G||l.status==="active",onClick:()=>void Hs("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:G||l.status==="paused",onClick:()=>void Hs("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:G,onClick:()=>void yn(),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,br=gr?e.jsx("button",{type:"button","aria-label":"Open goal monitor",title:"Open goal monitor",onClick:()=>{W(l=>!l),Ls()},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:qa}):null,vr=e.jsx("button",{type:"button","aria-label":"Export transcript",title:"Export transcript",onClick:()=>Rt(!0),disabled:!u,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($d,{})}),Ja=e.jsxs("div",{className:"relative flex items-center justify-end gap-1.5",children:[vr,br,In]}),Va=e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[vr,br,Wa]}),Ga=a.useMemo(()=>({livePlan:re,liveItems:ge,respondingRequestId:fs,onRespondToRequest:as,scrollRequestKey:Ye,bottomSpacer:Zs,className:"thread-timeline-surface min-h-0 flex-1",onTailVisibilityChange:it,loadingEarlier:Le,onLoadEarlier:qs,onOpenThread:Ae,answeredRequestNotes:(u==null?void 0:u.answeredRequestNotes)??Pd,activityNotes:(u==null?void 0:u.activityNotes)??Ad,pendingSteers:(u==null?void 0:u.pendingSteers)??Ud,optimisticSteers:Nt,optimisticTurn:S}),[u==null?void 0:u.answeredRequestNotes,u==null?void 0:u.activityNotes,u==null?void 0:u.pendingSteers,qs,as,ge,re,Le,Ae,Nt,fs,Ye,Zs,S]),jr=u?{busy:I==="chat"?b:!1,settingsBusy:pt,error:null,model:u.thread.model,reasoningEffort:u.thread.reasoningEffort,fastMode:u.thread.fastMode??!1,collaborationMode:u.thread.collaborationMode,modelOptions:K,contextUsage:u.thread.contextUsage,capabilities:A,toolboxItems:(Y==null?void 0:Y.toolboxItems)??[],hookCommandTemplates:(Y==null?void 0:Y.hookCommandTemplates)??[],mcpConfigFormat:(Y==null?void 0:Y.mcpConfigFormat)??"none",followTail:nt,threadConnected:u.thread.isLoaded,shellAvailable:be,disabled:!!Ss,...Ss?{disabledPlaceholder:Ss}:{},shellControlState:F,draftPrompt:rt.prompt,draftAttachments:rt.attachments,onDraftChange:Ge,canInterrupt:!!u.thread.activeTurnId,onInterrupt:ns,onCompact:Yt,onOpenForkTurns:bt,onForkLatest:vt,onForkTurn:kn,onOpenSkills:Bs,onOpenMcp:wn,onOpenHooks:Nn,onCreateHook:Sn,onUpdateHook:ze,onTrustHook:Ns,onUntrustHook:_s,goalState:ke,onOpenGoal:Ls,onUpdateGoal:Ds,...At?{onReadProviderConfig:()=>Na(u.thread.provider,At),onWriteProviderConfig:l=>Sa(u.thread.provider,At,{content:l})}:{},onToggleFollow:()=>jt(l=>l+1),onUpdateSettings:rs,onToggleView:os,onShellCopy:Ft,onShellControl:ls,compactBusy:ft,skillsState:bs,mcpState:mt,hooksState:qe,forkTurnOptionsState:Lt}:null,yr=u?{busy:b,settingsBusy:!1,error:u.thread.isLoaded?(F==null?void 0:F.error)??null:null,followTail:!1,capabilities:A,toolboxItems:(Y==null?void 0:Y.toolboxItems)??[],hookCommandTemplates:(Y==null?void 0:Y.hookCommandTemplates)??[],mcpConfigFormat:(Y==null?void 0:Y.mcpConfigFormat)??"none",threadConnected:u.thread.isLoaded,shellAvailable:be,shellControlState:F,canInterrupt:!!(u.thread.isLoaded&&(F!=null&&F.isCommandRunning)),onInterrupt:ns,onToggleView:os,onShellCopy:Ft,onShellControl:ls}:null,wr=a.useCallback(l=>u?Ve({threadId:u.thread.id,path:l}):"",[u==null?void 0:u.thread.id,Ve]),Nr=a.useMemo(()=>{const l=(u==null?void 0:u.workspace.id)??null;return l?{listTree:()=>vl(l),readFile:i=>jl(l,{path:i.path,...i.offset!==void 0?{offset:i.offset}:{},...i.limit!==void 0?{limit:i.limit}:{}}),getRawFileUrl:i=>yl(l,{path:i.path}),uploadFile:i=>Nl(l,{file:i.file}),downloadNode:async i=>{if(i.kind!=="file")return;const h=await wl(l,{path:i.path}),E=URL.createObjectURL(h.blob),O=document.createElement("a");O.href=E,O.download=h.filename,document.body.append(O),O.click(),O.remove(),URL.revokeObjectURL(E)}}:null},[u==null?void 0:u.workspace.id]),Ka=a.useMemo(()=>({openThread:Ae,getThreadHref:ut,getNewThreadHref:yt,renameThread:Vs,deleteThread:Ht,sendPrompt:zs,interrupt:ns,compact:Yt,updateSettings:rs,loadHistoryItemDetail:Js,getImageAssetUrl:wr,workspace:Nr,shell:Pe}),[wr,yt,ut,Yt,ns,Js,zs,Vs,rs,Pe,Ae,Nr]),Ya=u!=null&&u.thread.workspaceId?`/threads?workspaceId=${encodeURIComponent(u.thread.workspaceId)}`:"/workspaces",Za=e.jsxs(e.Fragment,{children:[e.jsx(ao,{open:js,busy:Pt,turnsState:kt,onCancel:()=>{Pt||Rt(!1)},onLoadTurns:ss,onExport:$s}),e.jsx(fn,{open:gt!==null,title:"Delete Thread",description:gt?`Delete ${yo(gt.title)} from supervisor. The backend session id will no longer appear in this workspace list.`:"",confirmLabel:"Delete Thread",busy:ys,onCancel:()=>{ys||Ht(null)},onConfirm:()=>void Gs()})]});return e.jsx(oa,{threads:ne,detail:u,status:L,loading:We,error:We?null:Os,plugins:n,adapter:Ka,metaContent:Xs,settingsContent:Qs,globalSettingsContent:e.jsx(ur,{embedded:!0}),mobileHeaderAction:Ja,workspaceReturnHref:Ya,onCloseAppNavigation:(r==null?void 0:r.closeNav)??(()=>{}),surfaceActions:Va,floatingPanel:za,workspaceFeatures:Od,activeView:I,liveOutput:fe,timelineProps:Ga,timelineComponent:lo,useFloatingMobileComposer:ks,floatingMobileComposerBottomOffset:Ks,composerHostRef:C,shellPanelRef:k,shellPanelComponent:oo,shellEffectiveTheme:(r==null?void 0:r.effectiveTheme)??"dark",shellThemeMode:(r==null?void 0:r.themeMode)??"system",...r!=null&&r.setThemeMode?{onShellThemeModeChange:r.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:Za,...jr?{composerProps:jr}:{},...yr?{shellComposerProps:yr}:{}})}function Hd(){const t=ht(),[s,r]=a.useState(""),[n,c]=a.useState(Ct),[o,p]=a.useState([]),[m,g]=a.useState(!0),[w,P]=a.useState(!1),[x,f]=a.useState(null);a.useEffect(()=>{let R=!1;return g(!0),dr().then(v=>{var oe,ee;if(R)return;p(v);const Q=((oe=v.find(_=>_.isDefault&&_.enabled))==null?void 0:oe.provider)??((ee=v.find(_=>_.enabled))==null?void 0:ee.provider)??Ct;c(Q)}).catch(()=>{R||p([])}).finally(()=>{R||g(!1)}),()=>{R=!0}},[]);const k=a.useMemo(()=>o.length>0?o:[{provider:Ct,displayName:Cr[Ct].displayName,enabled:!0}],[o]);async function C(R){R.preventDefault();const v=s.trim();if(!v){f("Session ID is required.");return}P(!0),f(null);try{const Q=await Ol({sessionId:v,provider:n});t(`/threads/${Q.thread.id}`)}catch(Q){Q instanceof ae?f(Q.payload.message):f(Q instanceof Error?Q.message:"Unable to import session.")}finally{P(!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:R=>c(R.target.value),disabled:w||m,className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition",children:k.map(R=>e.jsxs("option",{value:R.provider,children:[R.displayName||Cr[R.provider].displayName,R.enabled?"":" (not ready)"]},R.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:R=>r(R.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:w,className:"ui-action-primary rounded-full px-5 py-3 font-medium transition disabled:cursor-not-allowed",children:w?"Importing...":"Import Session"})})]})]})}function pn(t){return t.enabled&&t.capabilities.sessions.resume&&t.capabilities.turns.start}function Bd(t,s){var n;const r=t.find(c=>c.provider===s);return r&&pn(r)?r.provider:((n=t.find(pn))==null?void 0:n.provider)??Ct}function _d(){const t=ht(),s=zt(),[r]=ra(),[n,c]=a.useState([]),[o,p]=a.useState([]),[m,g]=a.useState([]),[w,P]=a.useState((s==null?void 0:s.defaultBackend)??Ct),[x,f]=a.useState(""),[k,C]=a.useState(""),R=r.get("title"),[v,Q]=a.useState(()=>R??""),[oe,ee]=a.useState("yolo"),[_,le]=a.useState(!0),[u,B]=a.useState(!1),[ne,T]=a.useState(null),K=r.get("workspaceId"),z=(s==null?void 0:s.defaultBackend)??Ct;a.useEffect(()=>{let A=!1;return Promise.all([cr(),dr()]).then(async([ie,Y])=>{var re,H,ge;if(A)return;const Ce=Bd(Y,z);P(Ce),p(Y);const fe=await er(Ce);if(A)return;c(ie),g(fe);const D=ie.some(pe=>pe.id===K)?K:((re=ie[0])==null?void 0:re.id)??"";f(D),C(((H=fe.find(pe=>pe.isDefault))==null?void 0:H.model)??((ge=fe[0])==null?void 0:ge.model)??"")}).catch(ie=>{A||T(ie instanceof Error?ie.message:"Unable to load creation form data.")}).finally(()=>{A||le(!1)}),()=>{A=!0}},[z,K]),a.useEffect(()=>{if(!w)return;let A=!1;return g([]),C(""),T(null),er(w).then(ie=>{var Y,Ce;A||(g(ie),C(((Y=ie.find(fe=>fe.isDefault))==null?void 0:Y.model)??((Ce=ie[0])==null?void 0:Ce.model)??""))}).catch(ie=>{A||(g([]),C(""),T(ie instanceof Error?ie.message:"Unable to load backend models."))}),()=>{A=!0}},[w]);function L(){if(window.history.length>1){t(-1);return}if(K){t(`/threads?workspaceId=${encodeURIComponent(K)}`);return}t("/workspaces")}async function Z(A){A.preventDefault(),B(!0),T(null);try{const ie=await Ul(v.trim()?{workspaceId:x,provider:w,model:k,approvalMode:oe,title:v.trim()}:{workspaceId:x,provider:w,model:k,approvalMode:oe});t(`/threads/${ie.id}`)}catch(ie){ie instanceof ae?T(ie.payload.message):T(ie instanceof Error?ie.message:"Unable to create thread.")}finally{B(!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.jsx("div",{className:"host-empty-state rounded-3xl border px-6 py-12 text-center",children:"Loading creation form..."}):e.jsxs("form",{onSubmit:Z,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:w,onChange:A=>{const ie=A.target.value;P(ie)},className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition",children:o.map(A=>e.jsxs("option",{value:A.provider,disabled:!pn(A),children:[A.displayName,pn(A)?"":" (not available)"]},A.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:A=>f(A.target.value),className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition",children:n.map(A=>e.jsxs("option",{value:A.id,children:[A.label," · ",A.absPath]},A.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:A=>C(A.target.value),disabled:m.length===0,className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition",children:[m.length===0?e.jsx("option",{value:"",children:"No models available"}):null,m.map(A=>e.jsxs("option",{value:A.model,children:[A.displayName," · ",A.model]},A.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"host-form-label text-sm font-medium",htmlFor:"thread-title",children:"Title"}),e.jsx("input",{id:"thread-title",value:v,onChange:A=>Q(A.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:oe,onChange:A=>ee(A.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"})]})]}),ne&&e.jsx("div",{className:"host-error rounded-2xl border px-4 py-3 text-sm",children:ne}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("button",{type:"submit",disabled:u||!x||!k,className:"ui-action-primary rounded-full px-5 py-3 font-medium transition disabled:cursor-not-allowed",children:u?"Creating...":"Create Thread"}),e.jsx("button",{type:"button",onClick:L,disabled:u,className:"host-secondary-button rounded-full border px-5 py-3 font-medium transition disabled:cursor-not-allowed disabled:opacity-60",children:"Cancel"})]})]})]})}function Fd(t){return t?`/threads/new?workspaceId=${encodeURIComponent(t)}`:"/threads/new"}function Wd({getThreadHref:t,onOpenThread:s,getNewThreadHref:r,renderThreadLink:n,onCloseAppNavigation:c,...o}){const p=ht(),m=zt(),g=c??(m==null?void 0:m.closeNav),w=o.effectiveTheme??(m==null?void 0:m.effectiveTheme),P=o.themeMode??(m==null?void 0:m.themeMode),x=o.onThemeModeChange??(m==null?void 0:m.setThemeMode);return e.jsx(io,{...o,workspaceReturnHref:o.workspaceReturnHref??"/workspaces",globalSettingsContent:o.globalSettingsContent??e.jsx(ur,{embedded:!0}),...w?{effectiveTheme:w}:{},...P?{themeMode:P}:{},...x?{onThemeModeChange:x}:{},getThreadHref:t??(f=>`/threads/${f}`),onOpenThread:s??(f=>p(`/threads/${f}`)),getNewThreadHref:r??Fd,renderThreadLink:n??(({thread:f,children:k,className:C,onClick:R})=>e.jsx(qt,{to:`/threads/${f.id}`,className:C,onClick:R,children:k})),...g?{onCloseAppNavigation:g}:{}})}function Da({open:t,title:s,label:r,value:n,busy:c=!1,onChange:o,onCancel:p,onSubmit:m}){if(a.useEffect(()=>{if(!t)return;function w(P){P.key==="Escape"&&!c&&p()}return window.addEventListener("keydown",w),()=>{window.removeEventListener("keydown",w)}},[c,p,t]),!t)return null;function g(w){w.preventDefault(),m()}return Xa.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:p,disabled:c,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:p,disabled:c,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:r}),e.jsx("input",{id:"rename-dialog-input","aria-label":r,autoFocus:!0,value:n,onChange:w=>o(w.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:p,disabled:c,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:c||!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 qd(){const[t]=ra(),s=ht(),r=zt(),n=t.get("workspaceId"),[c,o]=a.useState([]),[p,m]=a.useState([]),[g,w]=a.useState(null),[P,x]=a.useState(!0),[f,k]=a.useState(null),[C,R]=a.useState(null),[v,Q]=a.useState(""),[oe,ee]=a.useState(null),[_,le]=a.useState(null),[u,B]=a.useState(!1),ne=(r==null?void 0:r.defaultBackend)??Ct,T=a.useCallback(async()=>{x(!0),k(null);try{const[D,re,H]=await Promise.all([wa(ne).then(ge=>ge.status),ka(),cr()]);w(D),o(re),m(H)}catch(D){k(D instanceof Error?D.message:"Unable to load threads.")}finally{x(!1)}},[ne]);a.useEffect(()=>{if(n===null)return;T();const D=Ia(re=>{o(H=>H.map(ge=>ge.id===re.threadId?{...ge,status:re.type==="thread.updated"&&typeof re.payload.status=="string"?re.payload.status:ge.status,lastError:(re.type==="thread.turn.failed"||re.type==="thread.turn.completed")&&typeof re.payload.error=="string"?re.payload.error:ge.lastError,title:re.type==="thread.updated"&&typeof re.payload.title=="string"?re.payload.title:ge.title}:ge))});return()=>{D.close()}},[T,n]);const K=Object.fromEntries(p.map(D=>[D.id,D.label])),z=p.find(D=>D.id===n)??null,L=a.useMemo(()=>n?c.filter(D=>D.workspaceId===n):[],[n,c]),Z=L.filter(D=>D.status==="running").length,A=n?`/threads/new?workspaceId=${encodeURIComponent(n)}`:"/threads/new";if(n===null)return e.jsx(rr,{to:"/workspaces",replace:!0});function ie(){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 Y(D,re){try{const H=await Ca(D,{title:re});o(ge=>ge.map(pe=>pe.id===H.id?{...pe,title:H.title,updatedAt:H.updatedAt}:pe))}catch(H){throw k(H instanceof Error?H.message:"Unable to rename thread."),H}}async function Ce(){if(!C)return;const D=v.trim();if(D){ee(C);try{await Y(C,D),R(null),Q("")}finally{ee(null)}}}async function fe(){if(_){B(!0);try{await Ta(_.id),o(D=>D.filter(re=>re.id!==_.id)),le(null)}catch(D){k(D instanceof Error?D.message:"Unable to delete thread.")}finally{B(!1)}}}return e.jsx(Wd,{threads:c,workspaceLabels:K,status:g,loading:P,error:f,viewportConstrained:n!==null,showMobileAppMenu:!0,showMobileThreadNavToggle:!1,showMobileNewThreadShortcut:!1,currentWorkspaceId:n,currentWorkspaceLabel:(z==null?void 0:z.label)??null,onRenameThread:Y,onDeleteThread:le,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:z?`${z.label} threads`:"All threads",children:z?z.label:"All Threads"}),e.jsx(qt,{to:A,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 ${ie()}`}),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")})]})]})}),!P&&!f&&L.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:[L.length," total"]}),Z>0&&e.jsxs("span",{className:"host-muted text-xs",children:["· ",Z," running"]})]}),e.jsx("div",{className:"mt-3 min-h-0 flex-1",children:e.jsx(co,{threads:L,currentWorkspaceId:n,workspaceLabels:K,onOpenThread:D=>s(`/threads/${D}`),onBeginRenameThread:D=>{R(D.id),Q(D.title)},onDeleteThread:D=>le(D),scrollable:!0,maxHeightClassName:"max-h-full",showDeleteButton:!0,showSessionCopyButton:!0})})]}),!P&&!f&&L.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(Da,{open:C!==null,title:"Rename Thread",label:"Thread Title",value:v,busy:oe!==null,onChange:Q,onCancel:()=>{R(null),Q("")},onSubmit:()=>void Ce()}),e.jsx(fn,{open:_!==null,title:"Delete Thread",description:_?`Delete ${bo(_.title)} from supervisor. The backend session id will no longer appear in this workspace list.`:"",confirmLabel:"Delete Thread",busy:u,onCancel:()=>{u||le(null)},onConfirm:()=>void fe()})]})})}function ea(t){const s=t.trim(),r=s.replace(/[\\/]+$/,"");if(!r)return"";if(Ha(s)){const c=(r.split(/[?#]/)[0]??r).split(/[/:]/).filter(Boolean).at(-1)??"";return c.endsWith(".git")?c.slice(0,-4):c}return r.split(/[\\/]/).filter(Boolean).at(-1)??""}function Ha(t){const s=t.trim();return/^https?:\/\/.+/i.test(s)||/^ssh:\/\/.+/i.test(s)||/^git@[^:]+:.+/.test(s)}function zd({initialPath:t="",initialLabel:s="",submitLabel:r="Save Workspace",error:n,busy:c=!1,onSubmit:o}){const p=ea(t),[m,g]=a.useState(t),[w,P]=a.useState(s||p),[x,f]=a.useState(null),k=a.useRef(p);a.useEffect(()=>{const R=ea(m);P(v=>!v.trim()||v===k.current?R:v),k.current=R},[m]);async function C(R){R.preventDefault();const v=m.trim();if(!v){f("Workspace path or Git URL is required.");return}f(null);const Q=w.trim(),oe=Ha(v)?"gitUrl":"absPath";await o(Q?{[oe]:v,label:Q}:{[oe]:v})}return e.jsxs("form",{onSubmit:C,className:"host-panel space-y-5 rounded-3xl border p-6",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"workspace-path",className:"host-form-label text-sm font-medium",children:"Path or Git URL"}),e.jsx("input",{id:"workspace-path",name:"absPath",value:m,onChange:R=>g(R.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:w,onChange:R=>P(R.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:c,className:"ui-action-primary rounded-full px-5 py-3 font-medium transition disabled:cursor-not-allowed",children:c?"Saving...":r})]})}function Jd(){const t=ht(),[s,r]=a.useState(null),[n,c]=a.useState(!1);async function o(p){c(!0),r(null);try{const m=await ei(p);t(`/threads?workspaceId=${encodeURIComponent(m.id)}`)}catch(m){m instanceof ae?r(m.payload.message):r(m instanceof Error?m.message:"Unable to create workspace.")}finally{c(!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(zd,{busy:n,error:s,submitLabel:"Create Workspace",onSubmit:o})]})}function ta(t){return Date.parse(t.lastOpenedAt??t.createdAt)}function Vd(t,s){return t.isFavorite!==s.isFavorite?t.isFavorite?-1:1:ta(s)-ta(t)}function Gd(t){return t?new Date(t).toLocaleString():"Never opened"}function Kd(t,s=28){return t.length<=s?t:`...${t.slice(-(s-3))}`}function Yd({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 Zd(){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 Xd(){const t=ht(),[s,r]=a.useState([]),[n,c]=a.useState(!0),[o,p]=a.useState(null),[m,g]=a.useState(null),[w,P]=a.useState(""),[x,f]=a.useState(null),[k,C]=a.useState(null),[R,v]=a.useState(null),[Q,oe]=a.useState(!1);async function ee(){c(!0),p(null);try{r(await cr())}catch(L){p(L instanceof Error?L.message:"Unable to load workspaces.")}finally{c(!1)}}a.useEffect(()=>{ee()},[]);async function _(L){const Z={...L,isFavorite:!L.isFavorite};r(A=>A.map(ie=>ie.id===L.id?Z:ie));try{const A=await ni(L.id,{isFavorite:!L.isFavorite});r(ie=>ie.map(Y=>Y.id===A.id?A:Y))}catch(A){r(ie=>ie.map(Y=>Y.id===L.id?L:Y)),p(A instanceof Error?A.message:"Unable to update workspace.")}}async function le(L){const Z=w.trim();if(Z){f(L);try{const A=await ti(L,{label:Z});r(ie=>ie.map(Y=>Y.id===A.id?A:Y)),g(null),P("")}catch(A){p(A instanceof Error?A.message:"Unable to rename workspace.")}finally{f(null)}}}function u(L){g(L.id),P(L.label)}function B(){g(null),P("")}function ne(L){t(`/threads?workspaceId=${encodeURIComponent(L)}`)}async function T(){if(R){oe(!0);try{await si(R.id),r(L=>L.filter(Z=>Z.id!==R.id)),v(null)}catch(L){p(L instanceof Error?L.message:"Unable to delete workspace.")}finally{oe(!1)}}}function K(L,Z){(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),ne(Z))}const z=a.useMemo(()=>[...s].sort(Vd),[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(Pa,{}),e.jsx(qt,{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(qt,{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(Aa,{className:"absolute left-0 top-[calc(100%+0.5rem)] z-30 w-[min(22rem,calc(100vw-1rem))]"})]})}),n&&e.jsx("div",{className:"host-empty-state rounded-[1.6rem] border px-6 py-12 text-center",children:"Loading workspace registry..."}),o&&e.jsx("div",{className:"host-error rounded-[1.4rem] border px-4 py-4",children:o}),!n&&!o&&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&&z.length>0&&e.jsx("div",{className:"space-y-2 overflow-x-hidden",children:z.map(L=>e.jsxs("article",{role:"link",tabIndex:0,onClick:()=>ne(L.id),onKeyDown:Z=>K(Z,L.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 ${L.label}`,title:"Delete workspace",onClick:Z=>{Z.stopPropagation(),v(L)},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(Zd,{})}),e.jsx("button",{type:"button","aria-label":L.isFavorite?`Unpin workspace ${L.label}`:`Pin workspace ${L.label}`,title:L.isFavorite?"Unpin workspace":"Pin workspace",onClick:Z=>{Z.stopPropagation(),_(L)},className:`inline-flex h-7 w-7 items-center justify-center rounded-full border transition ${L.isFavorite?"host-warning-pill":"host-icon-button"}`,children:e.jsx(Yd,{active:L.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:L.label,children:L.label}),e.jsx("button",{type:"button",onClick:Z=>{Z.stopPropagation(),u(L)},"aria-label":`Rename workspace ${L.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":L.absPath,title:L.absPath,onClick:Z=>{Z.stopPropagation(),C(L.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:Kd(L.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: ",Gd(L.lastOpenedAt)]})})]})})]},L.id))}),e.jsx(Da,{open:m!==null,title:"Rename Workspace",label:"Workspace Label",value:w,busy:x!==null,onChange:P,onCancel:B,onSubmit:()=>m?le(m):void 0}),e.jsx(uo,{open:k!==null,title:"Workspace Path",text:k??"",onClose:()=>C(null)}),e.jsx(fn,{open:R!==null,title:"Delete Workspace",description:R?`Delete ${R.label} from supervisor. This also removes its threads and local supervisor metadata.`:"",confirmLabel:"Delete Workspace",busy:Q,onCancel:()=>{Q||v(null)},onConfirm:()=>void T()})]})}const Ba="remote-codex-theme-mode",_a="remote-codex-default-backend";function Fa(){return!1}function Qd(){return Fa()?e.jsx(rr,{to:"/control-plane",replace:!0}):e.jsx(La,{})}function ec({children:t}){const s=Ps(),r=s.pathname.startsWith("/control-plane")||s.pathname==="/"&&Fa(),n=a.useMemo(()=>r?{}:{fetchPlugins:kl,importPlugin:Cl,updatePlugin:Tl,deletePlugin:Il},[r]);return e.jsx(mo,{adapter:n,children:t})}function tc(){if(typeof window>"u")return"system";const t=window.localStorage.getItem(Ba);return t==="light"||t==="dark"||t==="system"?t:"system"}function sc(){if(typeof window>"u")return Ct;const t=window.localStorage.getItem(_a);return xo(t)??Ct}function nc(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function rc({themeMode:t,setThemeMode:s,effectiveTheme:r}){const[n,c]=a.useState(!1),[o,p]=a.useState(!1),[m,g]=a.useState(sc),w=Ps(),P=/^\/threads\/[^/]+$/.test(w.pathname),x=/^\/control-plane\/sessions\/[^/]+$/.test(w.pathname),f=w.pathname==="/threads",k=P||x||f,C=f||P||x,R=P||x,v=w.pathname==="/workspaces",Q=w.pathname.startsWith("/control-plane"),oe=v||f||Q;a.useEffect(()=>{c(!1)},[w.pathname,w.search]);function ee(le){g(le),window.localStorage.setItem(_a,le)}const _={navOpen:n,openNav:()=>c(!0),toggleNav:()=>c(le=>!le),closeNav:()=>c(!1),settingsOpen:o,openSettings:()=>{c(!1),p(!0)},closeSettings:()=>p(!1),themeMode:t,setThemeMode:s,effectiveTheme:r,defaultBackend:m,setDefaultBackend:ee};return e.jsxs(ho.Provider,{value:_,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:[!oe&&!R&&e.jsxs("div",{className:"fixed left-4 top-4 z-50",children:[e.jsx(Pa,{}),e.jsx(Aa,{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?P||x?"pt-0":f?"pt-[env(safe-area-inset-top)] sm:pt-4":"pt-[calc(env(safe-area-inset-top)+4rem)] sm:pt-4":v||Q?"pt-[env(safe-area-inset-top)] sm:pt-4":"pt-4"} ${k?P||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?P||x?"h-full min-h-0 overflow-hidden overscroll-none":"h-full overflow-hidden overscroll-none":""}`,children:e.jsx(eo,{})})})]}),e.jsx(ur,{})]})}function ac({children:t}){const[s,r]=a.useState({status:"checking"});async function n(p){try{const m=await Yo();if(p!=null&&p())return;r(!m.authRequired||m.authenticated?{status:"authenticated"}:{status:"loginRequired",session:m,error:null})}catch(m){if(p!=null&&p())return;if(m instanceof ae&&m.statusCode===401){r({status:"loginRequired",session:{authenticated:!1,username:null,expiresAt:null,mode:"server",authRequired:!0},error:null});return}r({status:"unavailable",error:m instanceof Error?m.message:"Unable to check supervisor access."})}}a.useEffect(()=>{let p=!1;return n(()=>p),()=>{p=!0}},[]);async function c(p){await Zo(p),r({status:"authenticated"})}function o(){r({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(vd,{onLogin:c})]}):t}function oc({children:t}){const[s,r]=a.useState({status:"checking"});return a.useEffect(()=>{let n=!1;return Qn().then(c=>{n||r(c.authenticated?{status:"authenticated",session:c}:{status:"loginRequired"})}).catch(()=>{n||r({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(hr,{}):t}function sa({themeMode:t,setThemeMode:s,effectiveTheme:r}){return e.jsxs(aa,{children:[e.jsx(Ke,{path:"/",element:ha()?e.jsx(hr,{}):e.jsx(La,{})}),e.jsxs(Ke,{element:e.jsx(rc,{themeMode:t,setThemeMode:s,effectiveTheme:r}),children:[e.jsx(Ke,{path:"/workspaces",element:e.jsx(Xd,{})}),e.jsx(Ke,{path:"/workspaces/new",element:e.jsx(Jd,{})}),e.jsx(Ke,{path:"/control-plane/login",element:e.jsx(Bi,{})}),e.jsx(Ke,{path:"/control-plane",element:e.jsx(Vr,{children:e.jsx($i,{})})}),e.jsx(Ke,{path:"/control-plane/sessions/:sessionId",element:e.jsx(Vr,{children:e.jsx(gd,{})})}),e.jsx(Ke,{path:"/threads",element:e.jsx(qd,{})}),e.jsx(Ke,{path:"/threads/import",element:e.jsx(Hd,{})}),e.jsx(Ke,{path:"/threads/new",element:e.jsx(_d,{})}),e.jsx(Ke,{path:"/threads/:id",element:e.jsx(Dd,{})})]})]})}function lc(){const[t,s]=a.useState(()=>tc()),[r,n]=a.useState(()=>nc()),c=t==="system"?r:t;return a.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const o=window.matchMedia("(prefers-color-scheme: dark)"),p=()=>{n(o.matches?"dark":"light")};return p(),typeof o.addEventListener=="function"?o.addEventListener("change",p):o.addListener(p),()=>{typeof o.removeEventListener=="function"?o.removeEventListener("change",p):o.removeListener(p)}},[]),a.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(Ba,t)},[t]),a.useEffect(()=>{const o=document.documentElement;o.dataset.themeMode=t,o.dataset.themeEffective=c,o.style.colorScheme=c},[c,t]),e.jsx("div",{className:"theme-shell theme-scrollbar",children:e.jsx(Qa,{children:e.jsx(ec,{children:e.jsxs(aa,{children:[e.jsx(Ke,{path:"/",element:e.jsx(Qd,{})}),e.jsx(Ke,{path:"/relay-portal",element:e.jsx(hr,{})}),e.jsx(Ke,{path:"/relay-admin",element:e.jsx(jd,{})}),e.jsx(Ke,{path:"/*",element:ha()?e.jsx(oc,{children:e.jsx(sa,{themeMode:t,setThemeMode:s,effectiveTheme:c})}):e.jsx(ac,{children:e.jsx(sa,{themeMode:t,setThemeMode:s,effectiveTheme:c})})})]})})})})}to.createRoot(document.getElementById("root")).render(e.jsx(so.StrictMode,{children:e.jsx(lc,{})}));