remote-codex 0.11.2 → 0.11.4

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