remote-codex 0.11.14 → 0.11.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ import{j as e,u as Xt,d as it,r,L as Rt,N as _s,e as ur,f as mr,b as ho,B as po,h as hr,i as ze,O as fo,k as xo,c as go}from"./react-vendor-CgLzZcV4.js";import{u as Bt,a as ca,C as wn,f as ps,T as pr,A as bo,b as vo,t as fr,E as yo,c as jo,d as wo,e as No,g as So,L as ko,P as Co,h as To}from"./thread-ui-q6mjcjXn.js";import{l as lt}from"./ui-vendor-CeKGesq3.js";import"./graph-vendor-DVPtkh3h.js";import"./terminal-vendor-B365Go3Z.js";import"./markdown-vendor-BQJfKm05.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const d of document.querySelectorAll('link[rel="modulepreload"]'))n(d);new MutationObserver(d=>{for(const o of d)if(o.type==="childList")for(const m of o.addedNodes)m.tagName==="LINK"&&m.rel==="modulepreload"&&n(m)}).observe(document,{childList:!0,subtree:!0});function a(d){const o={};return d.integrity&&(o.integrity=d.integrity),d.referrerPolicy&&(o.referrerPolicy=d.referrerPolicy),d.crossOrigin==="use-credentials"?o.credentials="include":d.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function n(d){if(d.ep)return;d.ep=!0;const o=a(d);fetch(d.href,o)}})();var Io=["codex","claude","opencode"],Et="codex",Pa={codex:{displayName:"Codex",description:"Local Codex app-server runtime.",defaultTransport:"stdio",homeEnvVar:"CODEX_HOME",commandEnvVar:"CODEX_COMMAND",defaultHomeDir:".codex",defaultCommand:"codex"},claude:{displayName:"Claude Code",description:"Local Claude Code Agent SDK runtime.",defaultTransport:"sdk",homeEnvVar:"CLAUDE_HOME",commandEnvVar:"CLAUDE_COMMAND",defaultHomeDir:".claude",defaultCommand:"claude"},opencode:{displayName:"OpenCode",description:"Local OpenCode runtime.",defaultTransport:"sdk",homeEnvVar:"OPENCODE_HOME",commandEnvVar:"OPENCODE_COMMAND",defaultHomeDir:".opencode",defaultCommand:"opencode"}};function Eo(t){return typeof t=="string"&&Io.includes(t)}function Ro(t){return Eo(t)?t:null}var Aa=15;function Po(t){return t.replace(/\s+/g," ").trim()}function Ao(t){const s=Po(t);if(!s)return"";const a=Array.from(s);return a.length<=Aa?s:`${a.slice(0,Aa).join("")}...`}const Uo=["codex","claude","opencode"],xr="codex",gr={codex:{displayName:"Codex",description:"Local Codex app-server runtime.",defaultTransport:"stdio",homeEnvVar:"CODEX_HOME",commandEnvVar:"CODEX_COMMAND",defaultHomeDir:".codex",defaultCommand:"codex"},claude:{displayName:"Claude Code",description:"Local Claude Code Agent SDK runtime.",defaultTransport:"sdk",homeEnvVar:"CLAUDE_HOME",commandEnvVar:"CLAUDE_COMMAND",defaultHomeDir:".claude",defaultCommand:"claude"},opencode:{displayName:"OpenCode",description:"Local OpenCode runtime.",defaultTransport:"sdk",homeEnvVar:"OPENCODE_HOME",commandEnvVar:"OPENCODE_COMMAND",defaultHomeDir:".opencode",defaultCommand:"opencode"}},Ua=15;function Oo(t){return t.replace(/\s+/g," ").trim()}function $o(t){const s=Oo(t);if(!s)return"";const a=Array.from(s);return a.length<=Ua?s:`${a.slice(0,Ua).join("")}...`}class re extends Error{constructor(s,a){super(a.message),this.statusCode=s,this.payload=a}}const Qn="remote-codex-auth-token",ea="remote-codex-relay-token",br="remote-codex-relay-mode",ta="remote-codex-relay-device-id",sa="remote-codex-relay-thread-id";function vr(){return typeof window>"u"?null:window.localStorage.getItem(Qn)}function Mo(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(Qn,t);return}window.localStorage.removeItem(Qn)}}function yr(){return typeof window>"u"?null:window.localStorage.getItem(ea)}function ua(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(ea,t);return}window.localStorage.removeItem(ea)}}function fs(){var t;return typeof window>"u"?!1:((t=window.__REMOTE_CODEX_BOOTSTRAP__)==null?void 0:t.mode)==="relay"||window.location.pathname.startsWith("/relay-portal")||window.location.pathname.startsWith("/relay-admin")||window.location.search.includes("relay=1")||window.localStorage.getItem(br)==="true"}function xs(){typeof window>"u"||window.localStorage.setItem(br,"true")}function na(){return fs()}function jr(){return typeof window>"u"?null:window.localStorage.getItem(ta)}function bn(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(ta,t);return}window.localStorage.removeItem(ta)}}function Lo(){return typeof window>"u"?null:window.localStorage.getItem(sa)}function vn(t){if(!(typeof window>"u")){if(t){window.localStorage.setItem(sa,t);return}window.localStorage.removeItem(sa)}}function wr(t){if(!fs())return t;if(t.startsWith("/api/")){const s=jr();return s?`/relay/devices/${encodeURIComponent(s)}${t}`:`/relay${t}`}return t}function Do(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 Ho(t,s){const a=s==null?void 0:s.trim(),n=a?`${t} ${a}`:`${t}`;return t===429?`Too many requests (${n}).`:t===503?`Upstream service unavailable (${n}).`:`Request failed (${n}).`}function cs(t,s,a){const n=typeof(s==null?void 0:s.message)=="string"&&s.message.trim()?s.message.trim():a,d=s!=null&&s.details&&typeof s.details=="object"?s.details:void 0;return{code:(s==null?void 0:s.code)??Do(t.status),message:n,...d?{details:d}:{}}}async function Nr(t){var d,o;const s=Ho(t.status,t.statusText),a=((o=(d=t.headers)==null?void 0:d.get)==null?void 0:o.call(d,"content-type"))??"",n=async()=>cs(t,await t.json(),s);if(a.includes("application/json"))try{return await n()}catch{return cs(t,null,s)}try{if(typeof t.text!="function")try{return await n()}catch{return cs(t,null,s)}const m=(await t.text()).trim();if(m.startsWith("{"))try{return cs(t,JSON.parse(m),s)}catch{}return cs(t,m?{message:`${s}
2
+ ${m}`}:null,s)}catch{try{return await n()}catch{return cs(t,null,s)}}}async function O(t,s){const a=new Headers(s==null?void 0:s.headers);(s==null?void 0:s.body)!==void 0&&!(s.body instanceof FormData)&&!a.has("Content-Type")&&a.set("Content-Type","application/json");const n=await fetch(wr(String(t)),kr({...s,headers:a}));if(!n.ok){const d=await Nr(n);throw new re(n.status,d)}return await n.json()}function _o(t){const s=String(t);return s.includes("/exports/pdf")?s.includes("format=html")?"remote-codex-transcript.html":"remote-codex-transcript.pdf":"download"}function Bo(t){var d;if(!t)return null;const s=t.match(/filename\*=UTF-8''([^;]+)/i);if(s!=null&&s[1])try{return decodeURIComponent(s[1].trim())}catch{return s[1].trim()}const a=t.match(/filename="([^"]+)"/i);if(a!=null&&a[1])return a[1].trim();const n=t.match(/filename=([^;]+)/i);return((d=n==null?void 0:n[1])==null?void 0:d.trim())??null}async function Sr(t,s){const a=await fetch(wr(String(t)),kr(s));if(!a.ok){const d=await Nr(a);throw new re(a.status,d)}const n=Bo(a.headers.get("content-disposition"))??_o(t);return{blob:await a.blob(),filename:n}}function kr(t={}){const s=new Headers(t.headers),a=yr(),n=vr();return fs()&&a&&!s.has("Authorization")?s.set("Authorization",`Bearer ${a}`):n&&!s.has("Authorization")&&s.set("Authorization",`Bearer ${n}`),{...t,credentials:t.credentials??"same-origin",headers:s}}function Fo(t,s){return`${t.baseUrl.replace(/\/+$/,"")}${s}`}function Wo(t,s){const a=new Headers(s==null?void 0:s.headers);return a.set("Authorization",`Bearer ${t.token}`),a}async function ke(t,s,a){return O(Fo(t,s),{...a,headers:Wo(t,a)})}function ma(t,s){return`${t.replace(/\/+$/,"")}${s}`}function qo(t,s,a=typeof window>"u"?void 0:window.location.href){const n=new URL(ma(t,`/api/auth/oauth/${s}/start`));return a&&n.searchParams.set("returnTo",a),n.toString()}function zo(t,s){return O(ma(t,"/api/auth/password/register"),{method:"POST",body:JSON.stringify(s)})}function Vo(t,s){return O(ma(t,"/api/auth/password/login"),{method:"POST",body:JSON.stringify(s)})}function ha(t){return ke(t,"/api/me",{cache:"no-store"})}function Jo(t,s=10){const a=new URLSearchParams({limit:String(s)});return ke(t,`/api/usage/events?${a.toString()}`,{cache:"no-store"})}function Go(t){return ke(t,"/api/usage/harness/summary",{cache:"no-store"})}function Ko(t,s=10){const a=new URLSearchParams({limit:String(s)});return ke(t,`/api/usage/harness/events?${a.toString()}`,{cache:"no-store"})}function Yo(t,s){return ke(t,"/api/me",{method:"PATCH",body:JSON.stringify(s)})}function Cr(t){return ke(t,"/api/projects",{cache:"no-store"})}function Zo(t,s){return ke(t,"/api/projects",{method:"POST",body:JSON.stringify(s)})}function Xo(t,s,a){return ke(t,`/api/projects/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(a)})}function Qo(t,s){return ke(t,`/api/projects/${encodeURIComponent(s)}`,{method:"DELETE"})}function aa(t,s){const a=s?`?projectId=${encodeURIComponent(s)}`:"";return ke(t,`/api/workspaces${a}`,{cache:"no-store"})}function el(t,s){const a=s.projectId?`/api/projects/${encodeURIComponent(s.projectId)}/workspaces`:"/api/workspaces",n=s.projectId?{name:s.name,slug:s.slug}:s;return ke(t,a,{method:"POST",body:JSON.stringify(n)})}function Oa(t,s,a){return ke(t,`/api/workspaces/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(a)})}function ra(t,s){return ke(t,`/api/workspaces/${encodeURIComponent(s)}/sessions`,{cache:"no-store"})}function tl(t,s,a){return ke(t,`/api/workspaces/${encodeURIComponent(s)}/sessions`,{method:"POST",body:JSON.stringify(a)})}function $a(t,s,a){return ke(t,`/api/sessions/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(a)})}function sl(t,s){return ke(t,`/api/sessions/${encodeURIComponent(s)}/close`,{method:"POST"})}function Tr(t,s){return ke(t,`/api/sessions/${encodeURIComponent(s)}/resume`,{method:"POST"})}function nl(t){return ke(t,"/api/sandbox/start",{method:"POST"})}function al(t){return ke(t,"/api/sandbox/stop",{method:"POST"})}function rl(t){return ke(t,"/api/sandbox/restart",{method:"POST"})}function Ma(t){return ke(t,"/api/sandbox/health",{cache:"no-store"})}function ol(t){return ke(t,"/api/sandbox/harness/status",{cache:"no-store"})}function La(t,s){return ke(t,`/api/sandbox/harness/modules/${encodeURIComponent(s)}/tools`,{cache:"no-store"})}function Da(t,s){return ke(t,`/api/sandbox/harness/modules/${encodeURIComponent(s)}/runs`,{cache:"no-store"})}function ll(t,s){return ke(t,`/api/admin/sandboxes/${encodeURIComponent(s)}`,{cache:"no-store"})}function Ir(t,s,a){return ke(t,`/api/sandboxes/${encodeURIComponent(s)}/route-token`,{method:"POST",body:JSON.stringify(a)})}function Nn(t,s,a){const n=s.replace(/^\/+/,""),d=new URL(`/api/sandboxes/${encodeURIComponent(t.sandboxId)}/${n}`,t.routerBaseUrl);for(const[o,m]of Object.entries(a??{}))m!=null&&d.searchParams.set(o,String(m));return d.toString()}function Sn(t,s){const a=new Headers(s==null?void 0:s.headers);return a.set("Authorization",`Bearer ${t.token}`),a}function us(t,s,a={}){return O(Nn(t,`/api/threads/${encodeURIComponent(s)}`,a),{cache:"no-store",headers:Sn(t)})}function il(t,s,a){return O(Nn(t,`/api/threads/${encodeURIComponent(s)}/items/${encodeURIComponent(a)}/detail`),{cache:"no-store",headers:Sn(t)})}function $n(t,s,a){return O(Nn(t,`/api/threads/${encodeURIComponent(s)}/prompt`),{method:"POST",body:JSON.stringify(a),headers:Sn(t)})}function Ha(t,s,a={}){return O(Nn(t,`/api/threads/${encodeURIComponent(s)}/interrupt`),{method:"POST",body:JSON.stringify(a),headers:Sn(t)})}function _a(t,s){const a=t.originalName.trim();if(a)return a;const n=t.file.name.trim();return n||(t.kind==="photo"?`photo-${s+1}.jpg`:`file-${s+1}`)}function dl(){return O("/api/config/runtime")}function cl(){return O("/api/auth/session",{cache:"no-store"})}async function ul(t){const s=await O("/api/auth/login",{method:"POST",body:JSON.stringify(t)});return Mo(s.token??null),s}function Bs(){return O("/relay/auth/session",{credentials:"same-origin"})}async function ml(t){xs();const s=await O("/relay/auth/login",{method:"POST",body:JSON.stringify(t)});return ua(s.token),s}async function hl(t){xs();const s=await O("/relay/auth/register",{method:"POST",body:JSON.stringify(t)});return ua(s.token),s}async function Er(){const t=await O("/relay/auth/logout",{method:"POST"});return ua(null),bn(null),vn(null),t}function Rr(){return O("/relay/portal")}function Pr(t){return O("/relay/devices",{method:"POST",body:JSON.stringify(t)})}function Ar(t){return O(`/relay/devices/${encodeURIComponent(t)}`,{method:"DELETE"})}function pl(t){return O("/relay/account",{method:"PATCH",body:JSON.stringify(t)})}function fl(t){return O("/relay/account/password",{method:"PATCH",body:JSON.stringify(t)})}function xl(t){return O("/relay/shares",{method:"POST",body:JSON.stringify(t)})}function gl(t){return O(`/relay/shares/${encodeURIComponent(t)}`,{method:"DELETE"})}function bl(){return O("/relay/admin")}function vl(t){return O("/relay/admin/settings/registration",{method:"PATCH",body:JSON.stringify({enabled:t})})}function yl(t,s){return O(`/relay/admin/users/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify({enabled:s})})}function jl(){return O("/api/config/workspace-settings",{cache:"no-store"})}function wl(t){return O("/api/config/workspace-settings",{method:"PATCH",body:JSON.stringify(t)})}function pa(){return O("/api/agent-runtimes",{cache:"no-store"})}function Ur(t){return O(`/api/agent-runtimes/${encodeURIComponent(t)}/status`,{cache:"no-store"})}function Nl(t){return O(`/api/agent-runtimes/${encodeURIComponent(t)}/restart`,{method:"POST"})}function Sl(t,s){return O(`/api/agent-runtimes/${encodeURIComponent(t)}/install`,{method:"POST",body:JSON.stringify({action:s})})}function oa(t){return O(`/api/agent-runtimes/${encodeURIComponent(t)}/models`,{cache:"no-store"})}function Or(t,s){return O(`/api/config/providers/${encodeURIComponent(t)}/files/${encodeURIComponent(s)}`,{cache:"no-store"})}function $r(t,s,a){return O(`/api/config/providers/${encodeURIComponent(t)}/files/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(a)})}function kl(t){return O(`/api/config/providers/${encodeURIComponent(t)}/archives`,{cache:"no-store"})}function Cl(t,s={}){return O(`/api/config/providers/${encodeURIComponent(t)}/archives`,{method:"POST",body:JSON.stringify(s)})}function Tl(t,s,a){return O(`/api/config/providers/${encodeURIComponent(t)}/archives/${encodeURIComponent(s)}`,{method:"PATCH",body:JSON.stringify(a)})}function Il(t,s){return O(`/api/config/providers/${encodeURIComponent(t)}/archives/${encodeURIComponent(s)}/apply`,{method:"POST"})}function El(){return O("/api/service/build-restart",{method:"POST"})}function Rl(){return O("/healthz",{cache:"no-store"})}function fa(){return O("/api/workspaces")}function Pl(t){return O(`/api/workspaces/${encodeURIComponent(t)}/files/tree`,{cache:"no-store"})}function Al(t,s){const a=new URLSearchParams({path:s.path});return s.offset!==void 0&&a.set("offset",String(s.offset)),s.limit!==void 0&&a.set("limit",String(s.limit)),O(`/api/workspaces/${encodeURIComponent(t)}/files/preview?${a.toString()}`,{cache:"no-store"})}function Ul(t,s){const a=new URLSearchParams({path:s.path});return`/api/workspaces/${encodeURIComponent(t)}/files/raw?${a.toString()}`}function Ol(t,s){const a=new URLSearchParams({path:s.path});return Sr(`/api/workspaces/${encodeURIComponent(t)}/files/download?${a.toString()}`,{cache:"no-store"})}function $l(t,s){const a=new FormData;return a.append("file",s.file,s.file.name),O(`/api/workspaces/${encodeURIComponent(t)}/files/upload`,{method:"POST",body:a})}function Ml(t,s){return O(`/api/workspaces/${encodeURIComponent(t)}/files`,{method:"PUT",body:JSON.stringify(s)})}function Mr(){return O("/api/threads")}function Ba(t,s={}){const a=new URLSearchParams;return s.limit!==void 0&&a.set("limit",String(s.limit)),s.beforeTurnId&&a.set("beforeTurnId",s.beforeTurnId),O(`/api/threads/${t}${a.size>0?`?${a.toString()}`:""}`)}function Ll(t,s){return O(`/api/threads/${t}/items/${encodeURIComponent(s)}/detail`)}function Dl(){return O("/api/plugins",{cache:"no-store"})}function Hl(t){return O("/api/plugins/import",{method:"POST",body:JSON.stringify(t)})}function _l(t,s){return O(`/api/plugins/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(s)})}function Bl(t){return O(`/api/plugins/${encodeURIComponent(t)}`,{method:"DELETE"})}function Fl(t){return O(`/api/threads/${t}/export-turns`,{cache:"no-store"})}function Wl(t,s){var n,d,o;const a=new URLSearchParams;return s.format!==void 0&&a.set("format",s.format),a.set("mode",s.mode),s.limit!==void 0&&a.set("limit",String(s.limit)),s.turnIds!==void 0&&a.set("turnIds",s.turnIds.join(",")),s.profile!==void 0&&a.set("profile",s.profile),((n=s.options)==null?void 0:n.includeTokenAndPrice)!==void 0&&a.set("includeTokenAndPrice",String(s.options.includeTokenAndPrice)),((d=s.options)==null?void 0:d.includeCommandOutput)!==void 0&&a.set("includeCommandOutput",String(s.options.includeCommandOutput)),((o=s.options)==null?void 0:o.includeAbsolutePaths)!==void 0&&a.set("includeAbsolutePaths",String(s.options.includeAbsolutePaths)),`/api/threads/${encodeURIComponent(t)}/exports/pdf?${a.toString()}`}function ql(t,s){return Sr(Wl(t,s),{cache:"no-store"})}function zl(t){return O(`/api/threads/${t}/shell`)}function Vl(t){return O("/api/threads/start",{method:"POST",body:JSON.stringify(t)})}function Jl(t){return O("/api/threads/import",{method:"POST",body:JSON.stringify(typeof t=="string"?{sessionId:t}:t)})}function Gl(t,s={}){return O(`/api/threads/${t}/shell`,{method:"POST",...Object.keys(s).length>0?{body:JSON.stringify(s)}:{}})}function Kl(t){return O(`/api/shells/${t}/terminate`,{method:"POST"})}function Yl(t,s){return O(`/api/shells/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Fa(t,s={}){return O(`/api/threads/${t}/resume`,{method:"POST",...Object.keys(s).length>0?{body:JSON.stringify(s)}:{}})}function Zl(t){return O(`/api/threads/${t}/disconnect`,{method:"POST"})}function Xl(t,s){const a=s.attachments??[];if(a.length===0)return O(`/api/threads/${t}/prompt`,{method:"POST",body:JSON.stringify(s)});const n=new FormData;n.append("prompt",s.prompt),s.clientRequestId!==void 0&&n.append("clientRequestId",s.clientRequestId),s.model!==void 0&&n.append("model",s.model),s.reasoningEffort!==void 0&&s.reasoningEffort!==null&&n.append("reasoningEffort",s.reasoningEffort),s.collaborationMode!==void 0&&n.append("collaborationMode",s.collaborationMode),s.sandboxMode!==void 0&&s.sandboxMode!==null&&n.append("sandboxMode",s.sandboxMode);const d=a.map((o,m)=>({clientId:o.clientId,kind:o.kind,originalName:_a(o,m),placeholder:o.placeholder}));n.append("attachmentManifest",JSON.stringify(d));for(const[o,m]of a.entries())n.append("attachments",m.file,_a(m,o));return O(`/api/threads/${t}/prompt`,{method:"POST",body:n})}function Wa(t,s={}){return O(`/api/threads/${t}/interrupt`,{method:"POST",body:JSON.stringify(s)})}function Lr(t,s){return O(`/api/threads/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function Dr(t){return O(`/api/threads/${t}`,{method:"DELETE"})}function Ql(t,s){return O(`/api/threads/${t}/settings`,{method:"PATCH",body:JSON.stringify(s)})}function ei(t){return O(`/api/threads/${t}/compact`,{method:"POST"})}function ti(t){return O(`/api/threads/${t}/goal`,{cache:"no-store"})}function si(t,s){return O(`/api/threads/${t}/goal`,{method:"PATCH",body:JSON.stringify(s)})}function ni(t){return O(`/api/threads/${t}/goal`,{method:"DELETE"})}function ai(t){return O(`/api/threads/${t}/fork-turns`,{cache:"no-store"})}function qa(t,s){return O(`/api/threads/${t}/fork`,{method:"POST",body:JSON.stringify(s)})}function ri(t){return O(`/api/threads/${t}/skills`,{cache:"no-store"})}function oi(t){return O(`/api/threads/${t}/mcp-servers`,{cache:"no-store"})}function li(t){return O(`/api/threads/${t}/hooks`,{cache:"no-store"})}function ii(t,s){return O(`/api/threads/${t}/hooks`,{method:"POST",body:JSON.stringify(s)})}function di(t,s){return O(`/api/threads/${t}/hooks`,{method:"PUT",body:JSON.stringify(s)})}function ci(t,s){return O(`/api/threads/${t}/hooks/trust`,{method:"POST",body:JSON.stringify(s)})}function ui(t,s){return O(`/api/threads/${t}/hooks/untrust`,{method:"POST",body:JSON.stringify(s)})}function mi(t,s,a){return O(`/api/threads/${t}/requests/${encodeURIComponent(s)}/respond`,{method:"POST",body:JSON.stringify(a)})}function hi(t){return O("/api/workspaces",{method:"POST",body:JSON.stringify(t)})}function pi(t,s){return O(`/api/workspaces/${t}`,{method:"PATCH",body:JSON.stringify(s)})}function fi(t){return O(`/api/workspaces/${t}`,{method:"DELETE"})}function xi(t,s){return O(`/api/workspaces/${t}/favorite`,{method:"POST",body:JSON.stringify(s)})}function Hr(t){const s=window.location.protocol==="https:"?"wss:":"ws:",a=new WebSocket(_r(s));return a.addEventListener("message",n=>{try{const d=JSON.parse(n.data);bi(d)&&t(d)}catch{}}),a}function gi(t={}){const s=window.location.protocol==="https:"?"wss:":"ws:",a=new WebSocket(_r(s));return a.addEventListener("message",n=>{var d,o;try{const m=JSON.parse(n.data);if(m.type==="supervisor.connected"){(d=t.onConnected)==null||d.call(t,m);return}vi(m)&&((o=t.onShellEvent)==null||o.call(t,m))}catch{}}),{socket:a,send(n){a.send(JSON.stringify(n))}}}function _r(t){const s=new URL(`${t}//${window.location.host}/ws`);if(fs()){const o=jr();s.pathname=o?`/relay/devices/${encodeURIComponent(o)}/ws`:"/relay/ws"}const a=vr(),n=yr(),d=Lo();return fs()&&n&&s.searchParams.set("relaySession",n),fs()&&d&&s.searchParams.set("threadId",d),a&&s.searchParams.set("token",a),s.toString()}function bi(t){return"threadId"in t&&t.type.startsWith("thread.")&&typeof t.payload=="object"&&t.payload!==null}function vi(t){return"shellId"in t&&t.type.startsWith("shell.")&&typeof t.payload=="object"&&t.payload!==null}function yi(){return e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-4 w-4 fill-current",children:e.jsx("path",{d:"M2 3.25h12v1.5H2Zm0 4h12v1.5H2Zm0 4h12v1.5H2Z"})})}function fn(){return e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-4 w-4 fill-current",children:e.jsx("path",{d:"M3.22 2.47 8 7.25l4.78-4.78 1.06 1.06L9.06 8.31l4.78 4.78-1.06 1.06L8 9.37l-4.78 4.78-1.06-1.06 4.78-4.78-4.78-4.78 1.06-1.06Z"})})}function Mn(t=!1){return`flex w-full items-center rounded-[0.95rem] px-3 py-2 text-left text-sm transition ${t?"cursor-not-allowed bg-[var(--theme-muted)] text-[var(--theme-fg-muted)]":"text-[var(--theme-fg)] hover:bg-[var(--theme-hover)]"}`}const ji=[{value:"light",label:"Light",description:"Always use the bright theme."},{value:"dark",label:"Dark",description:"Always use the dark theme."},{value:"system",label:"System",description:"Follow the operating system appearance."}],Br={hostConfigFiles:[],toolboxItems:[],hookCommandTemplates:[],providerConfigFormat:"none",mcpConfigFormat:"none",configArchives:!1,buildRestart:!1},wi={codex:{packageName:"@openai/codex",installCommand:null,updateCommand:"npm install -g @openai/codex@latest"},claude:{packageName:"@anthropic-ai/claude-agent-sdk",installCommand:"npm install -g @anthropic-ai/claude-code @anthropic-ai/claude-agent-sdk",updateCommand:"npm install -g @anthropic-ai/claude-code@latest @anthropic-ai/claude-agent-sdk@latest"},opencode:{packageName:"opencode-ai",installCommand:"npm install -g opencode-ai @opencode-ai/sdk",updateCommand:"npm install -g opencode-ai@latest @opencode-ai/sdk@latest"}};function la(t){const s=wi[t];return{packageName:s.packageName,installed:t==="codex",installedVersion:null,latestVersion:null,installCommand:s.installCommand,updateCommand:s.updateCommand,busy:!1,lastError:null}}function Ni(t,s){return{provider:t,displayName:s,description:`${s} backend descriptor is not available.`,enabled:!1,isDefault:t===xr,status:{state:"stopped",transport:gr[t].defaultTransport,lastStartedAt:null,lastError:"Backend descriptor is not available.",restartCount:0},capabilities:{sessions:{list:!1,read:!1,resume:!1,importLocal:!1},turns:{start:!1,streamInput:!1,steer:!1,interrupt:!1,compact:!1},branching:{fork:!1,hardRollback:!1,resumeAt:!1,rewindFiles:!1},controls:{planMode:!1,permissionRequests:!1,sandboxMode:!1,performanceMode:!1,goals:!1},management:{models:!1,mcpStatus:!1,skills:!1,hooks:!1,hookTrust:!1,hostConfigFiles:!1,providerSettings:!1},usage:{contextWindow:!1,tokenUsage:!1,costUsd:!1}},managementSchema:Br,installation:la(t)}}function Ln(t){const s=t.installation??la(t.provider);return{...t,installation:{...la(t.provider),...s}}}const hs=[...Uo.map(t=>Ni(t,gr[t].displayName))];function Si(t){var s;return((s=hs.find(a=>a.provider===t))==null?void 0:s.managementSchema)??Br}function ki(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 Ci(t){const s=t.payload.details,a=typeof(s==null?void 0:s.stderr)=="string"&&s.stderr.trim()?s.stderr.trim():typeof(s==null?void 0:s.stdout)=="string"&&s.stdout.trim()?s.stdout.trim():null;return a?`${t.message}
3
+ ${a}`:t.message}function $s(t){return{path:t,exists:!1,originalContent:"",draftContent:"",loading:!1,saving:!1,error:null,saveMessage:null}}function Fr({className:t=""}){const s=Bt();return s?e.jsx("button",{type:"button","aria-label":s.navOpen?"Close Navigation":"Open Navigation","aria-expanded":s.navOpen,"aria-controls":"app-shell-navigation-menu",onClick:s.toggleNav,className:`inline-flex h-10 w-10 shrink-0 items-center justify-center text-[var(--theme-fg)] transition hover:text-[var(--theme-fg-soft)] ${t}`.trim(),children:s.navOpen?e.jsx(fn,{}):e.jsx(yi,{})}):null}function Wr({className:t=""}){const s=Bt(),a=Xt(),n=it(),d=r.useRef(null),o=a.pathname==="/workspaces",m=a.pathname==="/threads/import";return r.useEffect(()=>{if(!(s!=null&&s.navOpen))return;const h=s;function f(v){const A=v.target;if(!A)return;const g=d.current;g!=null&&g.contains(A)||A instanceof Element&&A.closest('[aria-controls="app-shell-navigation-menu"]')||h.closeNav()}return document.addEventListener("pointerdown",f),()=>{document.removeEventListener("pointerdown",f)}},[s]),s!=null&&s.navOpen?e.jsxs("div",{ref:d,id:"app-shell-navigation-menu",onPointerDown:h=>{h.stopPropagation()},onMouseDown:h=>{h.stopPropagation()},onTouchStart:h=>{h.stopPropagation()},className:`rounded-[1.8rem] border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4 shadow-2xl shadow-black/15 backdrop-blur ${t}`.trim(),children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-base font-semibold tracking-wide text-[var(--theme-accent-strong)]",children:"Remote Codex"}),e.jsx("p",{className:"mt-1 text-xs uppercase tracking-[0.24em] text-[var(--theme-fg-muted)]",children:"Navigation"})]}),e.jsxs("nav",{className:"mt-4 flex flex-col gap-1.5 text-sm",children:[e.jsx("button",{type:"button",disabled:o,onClick:()=>{o||(s.closeNav(),n("/workspaces"))},className:Mn(o),children:"Workspaces"}),e.jsx("button",{type:"button",disabled:m,onClick:()=>{m||(s.closeNav(),n("/threads/import"))},className:Mn(m),children:"Import Session"}),e.jsx("button",{type:"button",onClick:()=>{s.openSettings()},className:Mn(),children:"Settings"})]})]}):null}function xa({embedded:t=!1}={}){const s=Bt(),a=ca(),[n,d]=r.useState(""),[o,m]=r.useState({busy:!1,message:null,error:null}),[h,f]=r.useState(!1),[v,A]=r.useState(null),[g,p]=r.useState({}),C=v?g[v]:null,[T,R]=r.useState({busy:!1,message:null,error:null}),[y,V]=r.useState([]),[te,H]=r.useState(hs),[P,Y]=r.useState({loading:!1,saving:!1,error:null,operatingProvider:null,operatingAction:null,message:null}),[c,L]=r.useState(null),[G,E]=r.useState({devHomeDraft:"",loading:!1,saving:!1,message:null,error:null}),[q,_]=r.useState({loading:!1,creating:!1,applyingId:null,renamingId:null,renameDraft:"",message:null,error:null}),ye=(s==null?void 0:s.themeMode)??"system",xe=t||!!(s!=null&&s.settingsOpen);async function D(){const b=n.trim();if(!(!b||o.busy)){m({busy:!0,message:null,error:null});try{await a.importPluginManifest({manifestJson:b,enabled:!0}),d(""),m({busy:!1,message:"Plugin manifest imported.",error:null})}catch(w){m({busy:!1,message:null,error:w instanceof Error?w.message:"Unable to import plugin manifest."})}}}const me=(s==null?void 0:s.effectiveTheme)??"dark",I=(s==null?void 0:s.autoCollapseCompletedTurns)??!0,le=(s==null?void 0:s.defaultBackend)??xr,oe=a.plugins.filter(b=>b.enabled).length,F=a.loading?"Loading...":`${oe}/${a.plugins.length} enabled`,B=te.find(b=>b.provider===le)??hs.find(b=>b.provider===le)??hs[0],z=B.managementSchema??Si(B.provider),de=z.hostConfigFiles;r.useEffect(()=>{if(!xe||t||!s||!z.configArchives)return;const b=s;function w(U){U.key==="Escape"&&b.closeSettings()}return window.addEventListener("keydown",w),()=>{window.removeEventListener("keydown",w)}},[z.configArchives,t,xe,s]),r.useEffect(()=>{if(!xe)return;let b=!1;return Y(w=>({...w,loading:!0,error:null})),pa().then(w=>{if(b)return;const U=[...w.map(Ln),...hs.filter(Q=>!w.some(be=>be.provider===Q.provider))];H(U),Y(Q=>({...Q,loading:!1}))}).catch(w=>{b||(H(hs),Y(U=>({...U,loading:!1,error:w instanceof re?w.message:"Unable to load backend settings."})))}),()=>{b=!0}},[xe]),r.useEffect(()=>{if(!xe)return;let b=!1;return E(w=>({...w,loading:!0,message:null,error:null})),jl().then(w=>{b||(L(w),E(U=>({...U,devHomeDraft:w.devHome,loading:!1})))}).catch(w=>{b||E(U=>({...U,loading:!1,error:w instanceof re?w.message:"Unable to load workspace settings."}))}),()=>{b=!0}},[xe]),r.useEffect(()=>{if(!xe||!B.capabilities.management.hostConfigFiles)return;let b=!1;async function w(){p(Q=>{const be={...Q};for(const Le of de)be[Le.name]={...$s(Le.name),...Q[Le.name],loading:!0,saving:!1,error:null,saveMessage:null};return be});const U=await Promise.allSettled(de.map(async Q=>({name:Q.name,result:await Or(B.provider,Q.name)})));b||p(Q=>{var Le,_e;const be={...Q};for(const Je of U){if(Je.status==="fulfilled"){const{name:gt,result:Fe}=Je.value;be[gt]={path:Fe.path,exists:Fe.exists,originalContent:Fe.content,draftContent:Fe.content,loading:!1,saving:!1,error:null,saveMessage:null};continue}const ft=Je.reason instanceof re?Je.reason.message:"Unable to load the file.",Ge=((Le=de[U.indexOf(Je)])==null?void 0:Le.name)??((_e=de[0])==null?void 0:_e.name);Ge&&(be[Ge]={...$s(Ge),...be[Ge],loading:!1,saving:!1,error:ft,saveMessage:null})}return be})}return w(),()=>{b=!0}},[B.capabilities.management.hostConfigFiles,B.provider,de,xe]),r.useEffect(()=>{if(!xe)return;let b=!1;async function w(){_(U=>({...U,loading:!0,error:null,message:null}));try{const U=await kl(B.provider);if(b)return;V(U),_(Q=>({...Q,loading:!1}))}catch(U){if(b)return;_(Q=>({...Q,loading:!1,error:U instanceof re?U.message:"Unable to load config archives."}))}}return w(),()=>{b=!0}},[B.provider,z.configArchives,xe]);async function ge(){if(!(T.busy||P.saving)){R({busy:!0,message:null,error:null});try{const b=await Nl(B.provider),w=Ln(b);R({busy:!1,message:w.status.state==="ready"?`${w.displayName} backend restarted.`:`${w.displayName} backend state: ${w.status.state}`,error:null}),H(U=>U.map(Q=>Q.provider===w.provider?w:Q))}catch(b){R({busy:!1,message:null,error:b instanceof re?b.message:"Unable to restart the app server."})}}}async function st(b,w){if(T.busy||P.saving)return;const U=te.find(Q=>Q.provider===b);Y(Q=>({...Q,saving:!0,operatingProvider:b,operatingAction:w,message:null,error:null}));try{const Q=await Sl(b,w),be=Ln(Q);H(Le=>Le.map(_e=>_e.provider===be.provider?be:_e)),Y(Le=>({...Le,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(Q){Y(be=>({...be,saving:!1,operatingProvider:null,operatingAction:null,message:null,error:Q instanceof re?Ci(Q):`Unable to ${w} ${(U==null?void 0:U.displayName)??b}.`}))}}async function ht(){if(!(T.busy||P.saving)){R({busy:!0,message:null,error:null});try{await El(),R({busy:!1,message:"Build and restart launched. The page may disconnect briefly.",error:null})}catch(b){R({busy:!1,message:null,error:b instanceof re?b.message:"Unable to launch build and restart."})}}}async function dt(){const b=G.devHomeDraft.trim();if(!(!b||G.saving)){E(w=>({...w,saving:!0,message:null,error:null}));try{const w=await wl({devHome:b});L(w),E(U=>({...U,devHomeDraft:w.devHome,saving:!1,message:"Workspace defaults saved."}))}catch(w){E(U=>({...U,saving:!1,error:w instanceof re?w.message:"Unable to save workspace settings."}))}}}async function kt(b){const w=g[b];if(!(!w||w.saving)){p(U=>({...U,[b]:{...$s(b),...U[b],saving:!0,error:null,saveMessage:null}}));try{const U=await $r(B.provider,b,{content:w.draftContent});p(Q=>({...Q,[b]:{path:U.path,exists:U.exists,originalContent:U.content,draftContent:U.content,loading:!1,saving:!1,error:null,saveMessage:"Saved"}}))}catch(U){p(Q=>({...Q,[b]:{...$s(b),...Q[b],saving:!1,error:U instanceof re?U.message:"Unable to save the file.",saveMessage:null}}))}}}async function Ve(){if(!q.creating){_(b=>({...b,creating:!0,message:null,error:null}));try{const b=await Cl(B.provider);V(w=>[b,...w]),_(w=>({...w,creating:!1,message:"Backup created."}))}catch(b){_(w=>({...w,creating:!1,error:b instanceof re?b.message:"Unable to create a config backup."}))}}}async function pt(b){if(!q.applyingId){_(w=>({...w,applyingId:b.id,message:null,error:null}));try{const w=await Il(B.provider,b.id);_(U=>({...U,applyingId:null,message:w.status.state==="ready"?`Applied "${w.archive.label}" and restarted ${B.displayName}.`:`Applied "${w.archive.label}". ${B.displayName} state: ${w.status.state}.`}))}catch(w){_(U=>({...U,applyingId:null,error:w instanceof re?w.message:"Unable to apply the config archive."}))}}}async function Xe(b){const w=q.renameDraft.trim();if(!(!w||q.renamingId!==b.id)){_(U=>({...U,message:null,error:null}));try{const U=await Tl(B.provider,b.id,{label:w});V(Q=>Q.map(be=>be.id===b.id?U:be)),_(Q=>({...Q,renamingId:null,renameDraft:"",message:"Backup renamed."}))}catch(U){_(Q=>({...Q,error:U instanceof re?U.message:"Unable to rename the config backup."}))}}}if(!xe)return null;const ct=e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mt-3 grid gap-2",children:[a.plugins.map(b=>e.jsxs("label",{className:"flex items-start justify-between gap-3 rounded-[1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-2.5",children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-sm font-medium text-[var(--theme-fg)]",children:b.name}),e.jsx("span",{className:"mt-1 block text-xs leading-5 text-[var(--theme-fg-muted)]",children:b.description}),e.jsx("span",{className:"mt-2 block text-[10px] uppercase tracking-[0.16em] text-[var(--theme-fg-muted)]",children:[...b.capabilities.artifactTypes.map(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 a.setPluginEnabled(b.id,w.currentTarget.checked),className:"mt-1 h-4 w-4 shrink-0 accent-[var(--theme-accent-solid)]"})]},b.id)),a.plugins.length===0&&e.jsx("p",{className:"rounded-[1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-3 text-xs text-[var(--theme-fg-muted)]",children:"No plugins are registered."})]}),e.jsxs("div",{className:"mt-3 border-t border-[var(--theme-border)] pt-3",children:[e.jsx("label",{className:"block text-xs font-medium text-[var(--theme-fg)]",children:"Import manifest JSON"}),e.jsx("textarea",{value:n,onChange:b=>{d(b.currentTarget.value),(o.message||o.error)&&m({busy:!1,message:null,error:null})},placeholder:'{"id":"example.viewer","name":"Example Viewer","version":"0.1.0",...}',rows:4,className:"mt-2 min-h-28 w-full resize-y rounded-[0.9rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-2 font-mono text-xs leading-5 text-[var(--theme-fg)] outline-none transition placeholder:text-[var(--theme-fg-muted)] focus:border-[var(--theme-accent-border)]"}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center justify-between gap-2",children:[e.jsx("p",{className:"max-w-[42rem] text-xs leading-5 text-[var(--theme-fg-muted)]",children:"Imports register manifest-declared artifact types. Rendering code still needs a trusted built-in frontend module."}),e.jsx("button",{type:"button",onClick:()=>void D(),disabled:!n.trim()||o.busy,className:"rounded-full border border-[var(--theme-accent-border)] bg-[var(--theme-accent-soft)] px-3 py-1.5 text-xs font-medium text-[var(--theme-accent-strong)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:border-[var(--theme-border)] disabled:bg-[var(--theme-muted)] disabled:text-[var(--theme-fg-muted)]",children:o.busy?"Importing...":"Import"})]}),o.error&&e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:o.error}),o.message&&e.jsx("p",{className:"mt-2 text-xs text-emerald-300",children:o.message})]}),a.error&&e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:a.error})]}),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(fn,{})})]})}),e.jsx("div",{className:`min-h-0 flex-1 overflow-y-auto ${t?"p-0":"p-5 pt-5"}`,children:e.jsxs("div",{className:"space-y-2",children:[t?null:e.jsxs("div",{className:"rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 py-3",children:[e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:"Appearance"}),e.jsxs("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:["Choose light, dark, or follow the system setting. Active:"," ",me,"."]})]})}),e.jsx("div",{className:"mt-3 grid gap-2 sm:grid-cols-3",children:ji.map(b=>{const w=ye===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)})})]}),s!=null&&s.setAutoCollapseCompletedTurns?e.jsx("div",{className:"rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 py-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:"Thread timeline"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:"Collapse completed turns into prompt, elapsed work, and final reply."})]}),e.jsxs("label",{className:"inline-flex min-h-10 shrink-0 items-center gap-2 text-xs font-medium text-[var(--theme-fg-soft)]",children:[e.jsx("input",{type:"checkbox",checked:I,onChange:b=>{var w;return(w=s.setAutoCollapseCompletedTurns)==null?void 0:w.call(s,b.currentTarget.checked)},className:"h-4 w-4 accent-[var(--theme-accent-solid)]"}),e.jsx("span",{children:"Auto collapse"})]})]})}):null,e.jsxs("div",{className:"rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 py-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:"Plugins"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:"Enable renderers and thread extensions loaded by this supervisor."})]}),e.jsx("button",{type:"button",onClick:()=>void a.refresh(),disabled:a.loading,className:"rounded-full border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-1.5 text-xs font-medium text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:text-[var(--theme-fg-muted)]",children:a.loading?"Loading...":"Refresh"})]}),t?e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between gap-2 rounded-[0.95rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-2",children:[e.jsx("span",{className:"text-xs text-[var(--theme-fg-muted)]",children:F}),e.jsx("button",{type:"button",onClick:()=>f(!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"})]}):ct]}),e.jsxs("div",{className:"rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 py-3",children:[e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:"Workspace defaults"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:"Git projects clone into dev home. New workspace directories can create one missing child under this path."})]})}),e.jsxs("div",{className:"mt-3 grid gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.18em] text-[var(--theme-fg-muted)]",children:"Workspace root"}),e.jsx("p",{title:(c==null?void 0:c.workspaceRoot)??"Loading workspace root",className:"mt-1 truncate rounded-[0.9rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-2 font-mono text-xs text-[var(--theme-fg-soft)]",children:G.loading&&!c?"Loading...":(c==null?void 0:c.workspaceRoot)??"Unavailable"})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"settings-dev-home",className:"text-[11px] uppercase tracking-[0.18em] text-[var(--theme-fg-muted)]",children:"Dev home"}),e.jsxs("div",{className:"mt-1 flex flex-col gap-2 sm:flex-row",children:[e.jsx("input",{id:"settings-dev-home",value:G.devHomeDraft,onChange:b=>E(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 dt(),disabled:G.loading||G.saving||!G.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:G.saving?"Saving...":"Save"})]})]})]}),G.error?e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:G.error}):G.message?e.jsx("p",{className:"mt-2 text-xs text-emerald-300",children:G.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||P.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 ht(),disabled:T.busy||P.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:te.map(b=>{const w=b.installation,U=!w.installed&&!!w.installCommand,Q=w.installed&&!!w.updateCommand,be=P.saving&&P.operatingProvider===b.provider,Le=U?"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]}),U||Q?e.jsx("button",{type:"button","aria-label":`${U?"Install":"Update"} ${b.displayName}`,onClick:()=>void st(b.provider,U?"install":"update"),disabled:T.busy||P.saving||!U&&!Q,className:"shrink-0 rounded-full border border-[var(--theme-border-strong)] bg-[var(--theme-panel)] px-3 py-1.5 text-xs font-medium text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:bg-[var(--theme-muted)] disabled:text-[var(--theme-fg-muted)]",children:be?P.operatingAction==="install"?"Installing...":"Updating...":Le}):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}):P.message?e.jsx("p",{className:`mt-2 whitespace-pre-line text-xs ${P.message.includes("requires attention")?"text-amber-300":"text-emerald-300"}`,children:P.message}):P.error?e.jsx("p",{className:"mt-2 whitespace-pre-line text-xs text-rose-300",children:P.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:[B.displayName," exposes these editable files through its backend schema."]})]})}),e.jsxs("div",{className:"mt-3 grid gap-2 sm:grid-cols-2",children:[de.map(b=>{const w=g[b.name]??{path:b.name,exists:!1,originalContent:"",draftContent:"",loading:!1},U=w.draftContent!==w.originalContent;return e.jsx("button",{type:"button",onClick:()=>A(b.name),className:"block rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-3 text-left transition hover:bg-[var(--theme-hover)]",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:b.label}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:b.description})]}),e.jsx("div",{className:"shrink-0",children:w.loading?e.jsx("span",{className:"text-[11px] uppercase tracking-[0.2em] text-[var(--theme-fg-muted)]",children:"Loading"}):U?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)}),de.length===0?e.jsx("p",{className:"rounded-[1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-3 text-xs text-[var(--theme-fg-muted)]",children:"This backend does not expose editable host files."}):null]})]}),z.configArchives?e.jsxs("div",{className:"rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 py-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:"Config archives"}),e.jsx("p",{className:"mt-1 text-xs leading-5 text-[var(--theme-fg-muted)]",children:"Backup the selected backend host files, then apply a saved archive with a backend restart."})]}),e.jsx("button",{type:"button",onClick:()=>void Ve(),disabled:q.creating,className:"shrink-0 rounded-full border border-[var(--theme-accent-border)] bg-[var(--theme-accent-soft)] px-3 py-1.5 text-xs font-medium text-[var(--theme-accent-strong)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:border-[var(--theme-border)] disabled:bg-[var(--theme-muted)] disabled:text-[var(--theme-fg-muted)]",children:q.creating?"Creating...":"Create backup"})]}),q.error?e.jsx("p",{className:"mt-2 text-xs text-rose-300",children:q.error}):q.message?e.jsx("p",{className:"mt-2 text-xs text-emerald-300",children:q.message}):null,e.jsx("div",{className:"mt-3 space-y-2",children:q.loading?e.jsx("p",{className:"rounded-[1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-3 text-xs text-[var(--theme-fg-muted)]",children:"Loading backups..."}):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=q.renamingId===b.id;return e.jsx("div",{className:"rounded-[1.1rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-3",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[w?e.jsxs("div",{className:"flex max-w-xl gap-2",children:[e.jsx("input",{"aria-label":`Rename ${b.label}`,value:q.renameDraft,onChange:U=>_(Q=>({...Q,renameDraft:U.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 Xe(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:()=>_(U=>({...U,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 ",ki(b.createdAt)]}),de.map(U=>{var Q;return e.jsxs("span",{className:"rounded-full border border-[var(--theme-border)] bg-[var(--theme-panel)] px-2 py-0.5 font-mono",children:[U.name,":"," ",(Q=b.files[U.name])!=null&&Q.exists?"saved":"missing"]},U.name)})]})]}),e.jsxs("div",{className:"flex shrink-0 flex-wrap gap-2",children:[e.jsx("button",{type:"button",onClick:()=>_(U=>({...U,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 pt(b),disabled:q.applyingId!==null,className:"rounded-full border border-emerald-400/35 bg-emerald-400/10 px-3 py-1.5 text-xs font-medium text-emerald-600 transition hover:bg-emerald-400/16 disabled:cursor-not-allowed disabled:border-[var(--theme-border)] disabled:bg-[var(--theme-muted)] disabled:text-[var(--theme-fg-muted)] dark:text-emerald-100",children:q.applyingId===b.id?"Applying...":"Apply"})]})]})},b.id)})})]}):null]})})]});return t?e.jsxs("div",{className:"flex min-h-0 flex-col overflow-hidden",children:[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:()=>f(!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:F})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsx("button",{type:"button",onClick:()=>void a.refresh(),disabled:a.loading,className:"rounded-full border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 py-1.5 text-xs font-medium text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:text-[var(--theme-fg-muted)]",children:a.loading?"Loading...":"Refresh"}),e.jsx("button",{type:"button","aria-label":"Close plugins panel",onClick:()=>f(!1),className:"inline-flex h-8 w-8 items-center justify-center rounded-full border border-[var(--theme-border-strong)] bg-[var(--theme-surface-strong)] text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)]",children:e.jsx(fn,{})})]})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto p-4",children:ct})]})]}):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}),v&&C?e.jsx("div",{className:"pointer-events-none fixed inset-0 z-[71] flex items-center justify-center p-4",children:e.jsxs("div",{className:"pointer-events-auto relative z-10 flex max-h-[min(88vh,56rem)] w-full max-w-3xl flex-col overflow-hidden rounded-[1.6rem] border border-[var(--theme-border)] bg-[var(--theme-panel)] shadow-2xl shadow-black/25",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 border-b border-[var(--theme-border)] px-4 py-3 sm:px-5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:v}),e.jsx("p",{className:"mt-1 break-all font-mono text-xs text-[var(--theme-fg-muted)]",children:C.path})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[C.error?e.jsx("span",{className:"text-xs text-rose-300",children:C.error}):C.saveMessage?e.jsx("span",{className:"text-xs text-emerald-300",children:C.saveMessage}):null,e.jsx("button",{type:"button","aria-label":`Save ${v}`,onClick:()=>void kt(v),disabled:C.loading||C.saving||C.draftContent===C.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:C.saving?"Saving...":"Save"}),e.jsx("button",{type:"button","aria-label":"Close File Editor",onClick:()=>A(null),className:"inline-flex h-9 w-9 items-center justify-center rounded-full border border-[var(--theme-border-strong)] bg-[var(--theme-surface-strong)] text-[var(--theme-fg)] transition hover:border-[var(--theme-border-contrast)] hover:bg-[var(--theme-hover)]",children:e.jsx(fn,{})})]})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto p-4 sm:p-5",children:e.jsx("textarea",{"aria-label":`Edit ${v}`,value:C.draftContent,onChange:b=>p(w=>({...w,[v]:{...$s(v),...w[v],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:C.loading?"Loading...":`Edit ${v} here`})})]})}):null]})}function Ti(t){const s=(t==null?void 0:t.trim())??"";return s?Array.from(s).slice(0,2).join("").toUpperCase():"??"}function ga(){const t=it(),s=Xt(),[a,n]=r.useState(null),[d,o]=r.useState(!1);r.useEffect(()=>{if(!na())return;let v=!1;return Bs().then(A=>{v||n(A.authenticated?A:null)}).catch(()=>{v||n(null)}),()=>{v=!0}},[s.pathname]),r.useEffect(()=>{o(!1)},[s.pathname]);const m=(a==null?void 0:a.user)??null,h=r.useMemo(()=>Ti(m==null?void 0:m.username),[m==null?void 0:m.username]);if(!na()||!m)return null;async function f(){await Er(),n(null),t("/relay-portal")}return e.jsxs("div",{className:"fixed right-3 top-[calc(env(safe-area-inset-top)+0.55rem)] z-50",children:[e.jsx("button",{"aria-expanded":d,"aria-haspopup":"menu","aria-label":`Relay account menu for ${m.username}`,className:"inline-flex h-10 w-10 items-center justify-center rounded-full border border-[var(--theme-border)] bg-[var(--theme-panel)] text-sm font-semibold text-[var(--theme-fg)] shadow-lg transition hover:bg-[var(--theme-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--theme-accent-ring)]",onClick:()=>o(v=>!v),type:"button",children:h}),d?e.jsxs("div",{className:"absolute right-0 mt-2 w-64 overflow-hidden rounded-xl border border-[var(--theme-border)] bg-[var(--theme-panel)] p-1 shadow-xl",role:"menu",children:[e.jsxs("div",{className:"border-b border-[var(--theme-border)] px-3 py-2",children:[e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:m.username}),e.jsx("p",{className:"truncate text-xs text-[var(--theme-fg-muted)]",children:m.email})]}),e.jsxs(Rt,{className:"flex items-center gap-2 rounded-lg px-3 py-2 text-sm text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)]",role:"menuitem",to:"/relay-account",children:[e.jsx(lt.Settings,{className:"h-4 w-4"}),"Account settings"]}),e.jsxs(Rt,{className:"flex items-center gap-2 rounded-lg px-3 py-2 text-sm text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)]",role:"menuitem",to:"/relay-devices",children:[e.jsx(lt.MonitorSmartphone,{className:"h-4 w-4"}),"Device management"]}),e.jsxs("button",{className:"flex w-full items-center gap-2 rounded-lg px-3 py-2 text-left text-sm text-[var(--status-danger-fg)] transition hover:bg-[var(--status-danger-bg)]",onClick:()=>void f(),role:"menuitem",type:"button",children:[e.jsx(lt.LogOut,{className:"h-4 w-4"}),"Logout"]})]}):null]})}const Ii="http://127.0.0.1:8790",ba="remote-codex-control-plane-auth";function Ei(t){const s=t.baseUrl||Ii;if(t.token){const a={baseUrl:s,token:t.token};return t.email!==void 0&&(a.email=t.email),t.displayName!==void 0&&(a.displayName=t.displayName),t.expiresAt!==void 0&&(a.expiresAt=t.expiresAt),a}if(t.subject){const a={baseUrl:s,token:`dev:${t.subject}`};return t.email!==void 0&&(a.email=t.email),t.displayName!==void 0&&(a.displayName=t.displayName),a}return null}function Zt(){if(typeof window>"u")return null;const t=window.localStorage.getItem(ba);if(!t)return null;try{const s=Ei(JSON.parse(t));return!(s!=null&&s.baseUrl)||!s.token||s.expiresAt&&Date.parse(s.expiresAt)<=Date.now()?null:s}catch{return null}}function xn(t){window.localStorage.setItem(ba,JSON.stringify(t))}function yn(){window.localStorage.removeItem(ba)}function Ri(){return!!Zt()}function Pi({eyebrow:t,hidden:s,onClose:a,children:n}){return e.jsx("aside",{className:"control-right-column","aria-hidden":s,children:e.jsxs("section",{className:"control-panel control-inspector-panel",children:[e.jsxs("div",{className:"control-panel-heading",children:[e.jsx("h2",{children:"Inspector"}),e.jsx("span",{children:t}),e.jsx("button",{type:"button",className:"control-inline-icon-button",onClick:a,"aria-label":"Close details inspector",children:"x"})]}),n]})})}function Ai({topBar:t,alerts:s,children:a,sidebar:n,main:d,inspector:o,inspectorOpen:m}){const h=a??e.jsxs(e.Fragment,{children:[n,e.jsx("main",{className:"control-main-column",children:d}),e.jsx("button",{type:"button",className:"control-inspector-scrim","aria-hidden":"true",tabIndex:-1}),o]});return e.jsxs("div",{className:"control-plane-console",children:[t,e.jsx("div",{className:"control-alert-stack",children:s}),e.jsx("div",{className:`control-console-grid ${m?"inspector-open":"inspector-collapsed"}`,children:h})]})}function Ui({children:t}){return e.jsx("aside",{className:"control-explorer-panel",children:t})}function Oi({title:t,subtitle:s,actions:a}){return e.jsxs("header",{className:"control-console-header",children:[e.jsxs("div",{className:"control-window-controls","aria-hidden":"true",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}),e.jsxs("div",{className:"control-titlebar-copy",children:[e.jsx("h1",{children:t}),e.jsx("span",{children:s})]}),e.jsx("div",{className:"control-header-actions",children:a})]})}const $i=6e4,Mi=5e3,Li=3e3,rn={estructural:"Estructural",quntur:"Quntur",farmaco:"Farmaco"};function on(t){if(!t)return"no activity yet";const s=Date.parse(t);if(!Number.isFinite(s))return t;const a=Date.now()-s,n=Math.abs(a),d=a>=0?"ago":"from now",o=6e4,m=60*o,h=24*m;return n<o?"just now":n<m?`${Math.round(n/o)}m ${d}`:n<h?`${Math.round(n/m)}h ${d}`:`${Math.round(n/h)}d ${d}`}function Dn(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function Pt(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 Ds(t){switch(t){case"empty":return"Local workspace";case"git":return"Git workspace";default:return we(t)}}function Di(t){return Ds(t.sourceType)}function Hn(t){return t.workerSessionId?"Runtime ready":"Not started"}function Ms(t){return t?`${t.type}:${t.id}`:""}function ln(t){switch(t){case"codex":return"Codex";case"claude":return"Claude";case"opencode":return"OpenCode";default:return we(t)}}function za({open:t}){return e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",focusable:"false",children:e.jsx("path",{d:t?"M4.5 6.25 8 9.75l3.5-3.5":"M6.25 4.5 9.75 8l-3.5 3.5",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.8"})})}function Hi(){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 _i(){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 Bi(){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 Fi(){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 Wi(){return e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",focusable:"false",children:e.jsx("path",{d:"M3 4.25h10M6.25 4.25V3h3.5v1.25M4.5 4.25l.55 8.25h5.9l.55-8.25M6.75 6.75v3.5M9.25 6.75v3.5",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:"1.25"})})}function Va(t){switch(t){case"connecting":return"Connecting";case"ready":return"Ready";case"reconnecting":return"Reconnecting";default:return"Idle"}}function qi(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 zi(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 Vi(t,s){const a="Sign in before managing the sandbox.";if(!t)return{start:{label:"Start",disabled:!0,title:a},stop:{label:"Stop",disabled:!0,title:a},restart:{label:"Restart",disabled:!0,title:a},health:{label:"Health",disabled:!0,title:a},inspect:{label:"Inspect",disabled:!0,title:a}};if(!s){const f="Wait for the sandbox registry to load.";return{start:{label:"Start",disabled:!0,title:f},stop:{label:"Stop",disabled:!0,title:f},restart:{label:"Restart",disabled:!0,title:f},health:{label:"Health",disabled:!0,title:f},inspect:{label:"Inspect",disabled:!0,title:f}}}const n=s.state,d=n==="running"||n==="degraded"||n==="starting",o=n==="running"||n==="degraded";return{start:{label:n==="starting"?"Starting...":n==="stopping"?"Stopping...":n==="restarting"?"Restarting...":n==="running"?"Running":n==="failed"?"Retry start":"Start",disabled:n==="running"||n==="starting"||n==="stopping"||n==="restarting"||n==="degraded",title:n==="starting"?"Sandbox startup is already in progress.":n==="running"?"Sandbox is already running.":n==="stopping"?"Wait for sandbox shutdown to finish before starting again.":n==="restarting"?"Sandbox restart is already in progress.":n==="degraded"?"Use Restart to recover a degraded sandbox.":void 0},stop:{label:"Stop",disabled:!d,title:d?void 0:"Stop is available only while the sandbox is running or starting."},restart:{label:n==="restarting"?"Restarting...":"Restart",disabled:!o,title:n==="failed"?"Use Retry start after a failed startup.":o?void 0:"Restart is available only when the sandbox is running or degraded."},health:{label:"Health",disabled:!1,title:void 0},inspect:{label:"Inspect",disabled:!1,title:void 0}}}function Ji(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 Gi(t,s){return s?"unavailable":t?!t.enabled||!t.chemistryToolsEnabled?"not configured":t.keyPresent?t.health?"ready":"degraded":"missing key":"idle"}function Ja(t){switch(t){case"ready":return Pt("running");case"unavailable":case"missing key":return Pt("failed");case"not configured":case"idle":return Pt("stopped");default:return Pt("starting")}}function Ga(t){return t?typeof t.text=="string"?t.text.trim():t.payload===void 0?"":JSON.stringify(t.payload,null,2):""}function Ka(t){const s=t==null?void 0:t.payload;if(Array.isArray(s))return s;if(s&&typeof s=="object")for(const a of["tools","runs","items","artifacts"]){const n=s[a];if(Array.isArray(n))return n}return[]}function Ya(t,s){if(!t||typeof t!="object")return String(t??s);const a=t;for(const n of["name","tool","run_id","id","title","path"]){const d=a[n];if(typeof d=="string"&&d.trim())return d}return s}function Za(t){if(!t||typeof t!="object")return"";const s=t;return["status","type","module","execution_mode"].map(a=>{const n=s[a];return typeof n=="string"&&n.trim()?n:null}).filter(Boolean).join(" / ")}function dn({label:t,value:s,onChange:a,type:n="text"}){return e.jsxs("label",{className:"grid gap-1.5 text-xs font-medium text-[var(--theme-fg-muted)]",children:[e.jsx("span",{children:t}),e.jsx("input",{type:n,value:s,onChange:d=>a(d.currentTarget.value),className:"h-10 rounded-[0.7rem] border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 text-sm text-[var(--theme-fg)] outline-none transition focus:border-[var(--theme-accent-border)] focus:ring-2 focus:ring-[var(--theme-accent-soft)]"})]})}function Me({children:t,onClick:s,disabled:a=!1,type:n="button",title:d,ariaLabel:o}){return e.jsx("button",{type:n,"aria-label":o,onClick:s,disabled:a,title:d,className:"h-10 rounded-[0.75rem] border border-[var(--theme-border)] bg-[var(--theme-surface-strong)] px-3 text-sm font-medium text-[var(--theme-fg)] transition hover:bg-[var(--theme-hover)] disabled:cursor-not-allowed disabled:text-[var(--theme-fg-muted)]",children:t})}function qe({label:t,value:s}){const a=s&&s.trim()?s:"not assigned";return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsxs("dd",{children:[e.jsx("span",{children:a}),s?e.jsx("button",{type:"button",className:"control-copy-button",onClick:()=>{var n;(n=navigator.clipboard)==null||n.writeText(s)},children:"Copy"}):null]})]})}function Ki({status:t}){return e.jsx("span",{className:`control-status-pill compact ${Pt(t)}`,children:we(t)})}function _n({label:t,onEdit:s,onDelete:a}){return e.jsxs("span",{className:"control-tree-actions",children:[e.jsx("button",{type:"button",className:"control-tree-action-button",onClick:n=>{n.stopPropagation(),s()},"aria-label":`Rename ${t}`,title:`Rename ${t}`,children:e.jsx(Fi,{})}),e.jsx("button",{type:"button",className:"control-tree-action-button danger",onClick:n=>{n.stopPropagation(),a()},"aria-label":`Delete ${t}`,title:`Delete ${t}`,children:e.jsx(Wi,{})})]})}function Bn({label:t,value:s,onChange:a,onCancel:n,onSubmit:d}){return e.jsxs("form",{className:"control-tree-edit-form",onSubmit:d,children:[e.jsxs("label",{children:[e.jsx("span",{children:t}),e.jsx("input",{value:s,onChange:o=>a(o.currentTarget.value),autoFocus:!0})]}),e.jsx("button",{type:"submit",children:"Save"}),e.jsx("button",{type:"button",onClick:n,children:"Cancel"})]})}function Yi(){var nn;const t=it(),[s,a]=r.useState(()=>{const u=Zt();return u?{baseUrl:u.baseUrl,token:u.token}:null}),[n,d]=r.useState(null),[o,m]=r.useState(null),[h,f]=r.useState(null),[v,A]=r.useState(null),[g,p]=r.useState(null),[C,T]=r.useState([]),[R,y]=r.useState(null),[V,te]=r.useState([]),[H,P]=r.useState([]),[Y,c]=r.useState([]),[L,G]=r.useState([]),[E,q]=r.useState(""),[_,ye]=r.useState(""),[xe,D]=r.useState(""),[me,I]=r.useState(null),[le,oe]=r.useState(null),[F,B]=r.useState(null),[z,de]=r.useState(null),[ge,st]=r.useState("farmaco"),[ht,dt]=r.useState(null),[kt,Ve]=r.useState(null),[pt,Xe]=r.useState(null),[ct,Ct]=r.useState("Computational chemistry"),[b,w]=r.useState("Molecule study"),[U,Q]=r.useState("Plan calculation"),[be,Le]=r.useState("codex"),[_e,Je]=r.useState(null),[ft,Ge]=r.useState(""),[gt,Fe]=r.useState(null),[ut,At]=r.useState(null),[Ft,Wt]=r.useState(null),[se,ie]=r.useState(null),[ce,he]=r.useState(!1),[Ne,Pe]=r.useState(null),[ne,De]=r.useState(!1),[bt,nt]=r.useState("summary"),[Ut,xt]=r.useState(()=>{var u;return((u=Zt())==null?void 0:u.displayName)??""}),[Fs,gs]=r.useState(null),[bs,vs]=r.useState(null),[Tt,qt]=r.useState(null),[vt,ys]=r.useState(null),[je,Ke]=r.useState(null),[zt,It]=r.useState(null),[yt,Qe]=r.useState({projects:!1,workspaces:!1,sessions:!1,usageEvents:!1,harness:!1}),[Qt,He]=r.useState("idle"),Ot=r.useRef(null),Te=r.useRef(null),Vt=!!(s&&n),Ce=(o==null?void 0:o.state)==="running",Ae=Vi(Vt,o),Ye=(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,K=r.useMemo(()=>H.find(u=>u.id===E)??null,[H,E]),ee=r.useMemo(()=>Y.find(u=>u.id===_)??null,[_,Y]),ae=r.useMemo(()=>L.find(u=>u.id===xe)??null,[xe,L]),$t=Vt&&!!K,es=Vt&&!!ee&&Ce,js=Ji(o),ts=K?void 0:"Select a project before creating a workspace.",jt=ee?Ce?void 0:"Start the sandbox before creating a session.":"Select a workspace before creating a session.",Ws=ae?Ce?void 0:"Start the sandbox before connecting a session.":"Select a session before connecting.",wt=ee?"session":K?"workspace":"project",ws=wt==="project"?"Project":wt==="workspace"?"Workspace":"Session",ss=Ne==="project"?"Create project":Ne==="workspace"?`Create workspace in ${(K==null?void 0:K.name)??"project"}`:Ne==="session"?`Create session in ${(ee==null?void 0:ee.name)??"workspace"}`:"",at=Ne==="workspace"?ts:Ne==="session"?jt:void 0,ns=[K==null?void 0:K.name,ee==null?void 0:ee.name,ae==null?void 0:ae.title].filter(Boolean).join(" / "),Jt=Gi(z,pt),Ns=z!=null&&z.modules.length?z.modules:["farmaco","quntur","estructural"],Gt=Ka(ht),ue=Ka(kt),Kt=Ga(ht),as=Ga(kt),Ss=((n==null?void 0:n.displayName)??(n==null?void 0:n.email)??"U").trim().charAt(0).toUpperCase()||"U",qs=((v==null?void 0:v.inputTokens)??0)+((v==null?void 0:v.outputTokens)??0),ks=(g==null?void 0:g.totalCostUsd)??Number((v==null?void 0:v.costUsd)??0)+Number((R==null?void 0:R.costUsd)??0),et=L.filter(u=>u.status==="active").length,zs=L.filter(u=>!u.workerSessionId).length,Cn=L.filter(u=>u.status==="failed"||u.status==="closed").length,Vs=[{label:"All",value:L.length},{label:"Active",value:et},{label:"Needs runtime",value:zs},{label:"Closed",value:Cn}],Js=(s==null?void 0:s.baseUrl)??((nn=Zt())==null?void 0:nn.baseUrl)??"not connected",Tn=(ae==null?void 0:ae.lastActivityAt)??(ae==null?void 0:ae.updatedAt)??null,Gs=(o==null?void 0:o.lastSeenAt)??(o==null?void 0:o.updatedAt)??null,Ks=qi(o),In=zi(o),En=(ee==null?void 0:ee.name)??(K==null?void 0:K.name)??"Control Plane",Rn=ns||"Choose a project and workspace to manage sessions";async function Ze(u,S){At(u),Wt(null),ie(null),gs(null),vs(null),qt(null),ys(null),Ke(null),It(null);try{return await S()}catch(k){if(k instanceof re&&k.payload.code==="gateway_unavailable"&&gs(k.message),k instanceof re&&k.payload.code==="quota_exceeded"){const X=k.payload.details??{},Oe=typeof X.limit=="number"?X.limit:null,$e=typeof X.used=="number"?X.used:null,Yt=typeof X.quotaProfile=="string"?X.quotaProfile:(n==null?void 0:n.quotaProfile)??"current";vs(Oe!==null&&$e!==null?`${Yt} quota exhausted (${$e}/${Oe}).`:"Quota exceeded.")}return k instanceof re&&k.payload.code==="account_inactive"&&qt(k.message),k instanceof re&&(k.statusCode===401||k.payload.code==="unauthorized")&&(ys(k.message),yn()),k instanceof re&&k.payload.code==="forbidden"&&It(k.message),Wt(k instanceof Error?k.message:`${u} failed.`),null}finally{At(null)}}async function Cs(u=s){if(u){Qe(S=>({...S,projects:!0,usageEvents:!0}));try{const S=await ha(u),[k,X,Oe,$e]=await Promise.all([Cr(u),Jo(u,10),Go(u),Ko(u,10)]);d(S.user),m(S.sandbox),A(S.usage),p(S.billing??null),T(X.events),y(Oe.usage),te($e.events),P(k.projects),xt(S.user.displayName??""),q(Yt=>k.projects.some(ds=>ds.id===Yt)?Yt:"")}finally{Qe(S=>({...S,projects:!1,usageEvents:!1}))}}}async function Ys(u=s,S=ge){if(!u||!Ce){de(null),dt(null),Ve(null),Xe(null);return}Qe(k=>({...k,harness:!0})),Xe(null);try{const k=await ol(u);de(k);const X=k.modules.includes(S)?S:k.modules[0]??S;if(st(X),k.enabled&&k.keyPresent&&k.chemistryToolsEnabled){const[Oe,$e]=await Promise.all([La(u,X),Da(u,X)]);dt(Oe),Ve($e)}else dt(null),Ve(null)}catch(k){de(null),dt(null),Ve(null),Xe(k instanceof Error?k.message:"Harness status refresh failed.")}finally{Qe(k=>({...k,harness:!1}))}}r.useEffect(()=>{s&&Ze("Load control plane",async()=>{await Cs(s),ie("Control plane session is ready.")})},[]),r.useEffect(()=>{if(!s||!_){G([]),D("");return}D(""),Qe(u=>({...u,sessions:!0})),Ze("Load sessions",async()=>{try{const u=await ra(s,_);G(u.sessions)}finally{Qe(u=>({...u,sessions:!1}))}})},[s,_]),r.useEffect(()=>{if(!s||!o||!Ye)return;let u=!1;const S=setTimeout(()=>{Ma(s).then(k=>{u||m(k.sandbox)}).catch(k=>{u||Ke(k instanceof Error?k.message:"Sandbox health refresh failed.")})},Li);return()=>{u=!0,clearTimeout(S)}},[s,o==null?void 0:o.state,o==null?void 0:o.startupProgress,o==null?void 0:o.updatedAt,Ye]),r.useEffect(()=>{if(!s||!Ce){de(null),dt(null),Ve(null),Xe(null);return}Ys(s,ge)},[s,Ce,o==null?void 0:o.updatedAt]),r.useEffect(()=>{if(!s||!E){c([]),ye(""),G([]),D("");return}ye(""),G([]),D(""),Qe(u=>({...u,workspaces:!0})),Ze("Load workspaces",async()=>{try{const u=await aa(s,E);c(u.workspaces)}finally{Qe(u=>({...u,workspaces:!1}))}})},[s,E]),r.useEffect(()=>()=>{Ot.current&&clearTimeout(Ot.current),Nt()},[]),r.useEffect(()=>{function u(S){S.key==="Escape"&&(he(!1),Pe(null),I(null),De(!1))}return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[]);function Nt(){const u=Te.current;Te.current=null,u&&u.readyState!==WebSocket.CLOSED&&u.close()}function St(){Ot.current&&(clearTimeout(Ot.current),Ot.current=null)}function Pn(u){return`${u.wsBaseUrl.replace(/\/+$/,"")}/api/sandboxes/${encodeURIComponent(u.sandboxId)}/ws?token=${encodeURIComponent(u.token)}`}function An(u,S="connecting"){Nt();const k=Pn(u);B(k),Ke(null),He(S);const X=new WebSocket(k);Te.current=X,X.addEventListener("open",()=>{Te.current===X&&He("ready")}),X.addEventListener("error",()=>{Te.current===X&&(Ke("Sandbox route connection failed."),He("idle"))}),X.addEventListener("close",Oe=>{Te.current===X&&(Ke(Oe.reason||"Sandbox route closed before the session could stay connected."),He("idle"))})}function Zs(u){if(St(),!u)return;const S=Date.parse(u.expiresAt);if(!Number.isFinite(S))return;const k=Math.max(Mi,S-Date.now()-$i);Ot.current=setTimeout(()=>{tn()},k)}async function Xs(){yn(),a(null),d(null),m(null),f(null),A(null),T([]),It(null),P([]),c([]),G([]),y(null),te([]),oe(null),he(!1),Pe(null),St(),He("idle"),ie("Signed out locally.")}async function Mt(u){u.preventDefault(),s&&await Ze("Update profile",async()=>{const S=await Yo(s,{displayName:Ut});d(S.user);const k=Zt();k&&xn({...k,email:S.user.email,displayName:S.user.displayName}),ie("Profile updated.")})}async function Be(u){u.preventDefault(),s&&await Ze("Create project",async()=>{const S=await Zo(s,{name:ct,slug:Dn(ct)});await Cs(s),Pe(null),ie(`Project "${S.project.name}" created. Select it before creating a workspace.`)})}async function Qs(u){u.preventDefault(),!(!s||!K)&&await Ze("Create workspace",async()=>{const S=await el(s,{projectId:K.id,name:b,slug:Dn(b)}),k=await aa(s,K.id);c(k.workspaces),ye(""),G([]),D(""),Pe(null),ie(`Workspace "${S.workspace.name}" created. Select it before creating a session.`)})}async function en(u){u.preventDefault(),!(!s||!ee||!Ce)&&await Ze("Create session",async()=>{const S=await tl(s,ee.id,{provider:be,title:U}),k=await ra(s,ee.id);G(k.sessions),D(""),Pe(null),ie(`Session "${S.session.title}" created. Select it before connecting.`)})}async function rs(u){s&&await Ze(`${u} sandbox`,async()=>{if(u==="start")m((await nl(s)).sandbox);else if(u==="stop")m((await al(s)).sandbox),oe(null),B(null),Nt(),St(),He("idle");else if(u==="restart")m((await rl(s)).sandbox),oe(null),B(null),Nt(),St(),He("idle");else{const S=await Ma(s);m(S.sandbox),ie(`Sandbox health is ${we(S.status.state)}.`)}})}async function Ts(u){if(st(u),!(!s||!Ce)){Qe(S=>({...S,harness:!0})),Xe(null);try{const[S,k]=await Promise.all([La(s,u),Da(s,u)]);dt(S),Ve(k)}catch(S){dt(null),Ve(null),Xe(S instanceof Error?S.message:"Harness module refresh failed.")}finally{Qe(S=>({...S,harness:!1}))}}}async function os(){!s||!o||await Ze("Inspect sandbox",async()=>{const u=await ll(s,o.id);f(u),ie("Sandbox detail loaded.")})}async function Lt(u="connecting",S=xe){return!s||!o||!Ce?null:Ze("Create route token",async()=>{const k={scopes:["worker:read","worker:write","session:prompt","provider:turn:create"]};K!=null&&K.id&&(k.projectId=K.id),_&&(k.workspaceId=_),S&&(k.sessionId=S);const X=await Ir(s,o.id,k);return oe(X),Zs(X),An(X,u),ie("Route token is available in memory."),X})}async function tn(){if(!s||!o||o.state!=="running"||!xe)return;He("reconnecting"),await Lt("reconnecting",xe)||He("idle")}function ls(u){I(null),D(u.id),oe(null),B(null),Nt(),St(),He("idle"),nt("summary"),De(!0)}function Is(u){ls(u),De(!0)}function Es(u,S){var k;S&&(I(null),(k=navigator.clipboard)==null||k.writeText(S),ie(`${u} copied.`))}function Rs(u,S){Je(u),Ge(S),I(null)}function Dt(){Je(null),Ge("")}async function is(u){if(u.preventDefault(),!s||!_e)return;const S=ft.trim();if(!S){Wt("Name is required.");return}const k=_e;await Ze(`Rename ${k.type}`,async()=>{if(k.type==="project"){const X=await Xo(s,k.id,{name:S,slug:Dn(S)});P(Oe=>Oe.map($e=>$e.id===X.project.id?X.project:$e))}else if(k.type==="workspace"){const X=await Oa(s,k.id,{name:S});c(Oe=>Oe.map($e=>$e.id===X.workspace.id?X.workspace:$e))}else{const X=await $a(s,k.id,{title:S});G(Oe=>Oe.map($e=>$e.id===X.session.id?X.session:$e))}Dt(),ie(`${we(k.type)} renamed.`)})}function sn(u){if(!u)return{title:"Delete item",description:"This item will be removed from the active control plane view."};if(u.type==="project"){const k=H.find(X=>X.id===u.id);return{title:`Delete project ${(k==null?void 0:k.name)??""}`.trim(),description:"The project will be archived and removed from the active project list. Its existing workspace records remain in the control plane database."}}if(u.type==="workspace"){const k=Y.find(X=>X.id===u.id);return{title:`Delete workspace ${(k==null?void 0:k.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 S=L.find(k=>k.id===u.id);return{title:`Delete session ${(S==null?void 0:S.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 Ps(){if(!s||!gt)return;const u=gt;await Ze(`Delete ${u.type}`,async()=>{if(u.type==="project"){const S=await Qo(s,u.id);P(k=>k.filter(X=>X.id!==S.project.id)),E===S.project.id&&(q(""),ye(""),D(""),c([]),G([]))}else if(u.type==="workspace"){const S=await Oa(s,u.id,{status:"deleted"});c(k=>k.filter(X=>X.id!==S.workspace.id)),_===S.workspace.id&&(ye(""),D(""),G([]))}else{const S=await $a(s,u.id,{status:"deleted"});G(k=>k.filter(X=>X.id!==S.session.id)),xe===S.session.id&&D("")}_e&&Ms(_e)===Ms(u)&&Dt(),Fe(null),oe(null),B(null),Nt(),St(),He("idle"),ie(`${we(u.type)} deleted.`)})}async function As(u){!s||!Ce||await Ze("Close session",async()=>{const S=await sl(s,u.id);G(k=>k.map(X=>X.id===S.session.id?S.session:X)),D(S.session.id),oe(null),B(null),Nt(),St(),He("idle"),ie("Session finalized and disconnected.")})}async function Us(u){!s||!Ce||await Ze("Resume session",async()=>{const S=await Tr(s,u.id);G(k=>k.map(X=>X.id===S.session.id?S.session:X)),D(S.session.id),await Lt("connecting",S.session.id),ie("Session resumed."),t(`/control-plane/sessions/${encodeURIComponent(S.session.id)}`)})}const Un=e.jsx(Oi,{title:En,subtitle:Rn,actions:e.jsxs(e.Fragment,{children:[o?e.jsx("span",{className:`control-status-pill ${Pt(o.state)}`,children:we(o.state)}):null,e.jsx(Me,{onClick:()=>void Cs(s),disabled:!s||ut==="Load control plane",children:"Refresh"}),e.jsx(Me,{onClick:()=>De(u=>!u),ariaLabel:ne?"Hide details inspector":"Show details inspector",children:"Inspector"}),e.jsxs("div",{className:"control-account-menu",children:[e.jsx("button",{type:"button",className:"control-avatar-button",onClick:()=>he(u=>!u),"aria-haspopup":"menu","aria-expanded":ce,"aria-label":"Open account menu",children:Ss}),ce?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:Ss}),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:Mt,className:"control-inline-form",children:[e.jsx(dn,{label:"Display name",value:Ut,onChange:xt}),e.jsx(Me,{type:"submit",disabled:!s||ut==="Update profile",children:"Save"})]}),e.jsxs("div",{className:"control-usage-grid compact",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Requests"}),e.jsx("strong",{children:(v==null?void 0:v.requestCount)??0})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Tokens"}),e.jsx("strong",{children:qs})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Total cost"}),e.jsxs("strong",{children:["$",ks.toFixed(2)]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Harness"}),e.jsx("strong",{children:(R==null?void 0:R.eventCount)??0})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Compute"}),e.jsx("strong",{children:Number((R==null?void 0:R.computeUnits)??0).toFixed(1)})]}),e.jsxs("div",{children:[e.jsx("span",{children:"LLM cost"}),e.jsxs("strong",{children:["$",Number((v==null?void 0:v.costUsd)??0).toFixed(2)]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Harness cost"}),e.jsxs("strong",{children:["$",Number((R==null?void 0:R.costUsd)??0).toFixed(2)]})]})]}),e.jsxs("details",{className:"control-account-disclosure",children:[e.jsx("summary",{children:"Account details"}),e.jsx("dl",{className:"control-detail-list compact",children:e.jsx(qe,{label:"Control plane API",value:Js})})]}),e.jsxs("details",{className:"control-account-disclosure",children:[e.jsx("summary",{children:"Usage history"}),e.jsx("div",{className:"control-usage-events compact",children:yt.usageEvents?e.jsx("p",{className:"control-empty",children:"Loading LLM usage..."}):C.length===0?e.jsx("p",{className:"control-empty",children:"No LLM usage events yet."}):C.slice(0,4).map(u=>e.jsxs("div",{children:[e.jsx("strong",{children:u.model}),e.jsxs("span",{children:[u.provider,", ",u.inputTokens+u.outputTokens," tokens, $",Number(u.costUsd).toFixed(2)]}),e.jsx("small",{children:u.occurredAt})]},u.id))}),e.jsx("div",{className:"control-usage-events compact",children:yt.usageEvents?e.jsx("p",{className:"control-empty",children:"Loading Harness usage..."}):V.length===0?e.jsx("p",{className:"control-empty",children:"No Harness usage events yet."}):V.slice(0,4).map(u=>e.jsxs("div",{children:[e.jsx("strong",{children:u.tool??u.module}),e.jsxs("span",{children:[u.module,", ",u.status,", $",Number(u.costUsd).toFixed(2)]}),e.jsx("small",{children:u.occurredAt})]},u.id))})]}),e.jsx(Me,{onClick:Xs,children:"Sign out"})]}):null]})]})}),On=e.jsxs(e.Fragment,{children:[Ft?e.jsx("div",{className:"control-alert danger",children:Ft}):null,se?e.jsx("div",{className:"control-alert success",children:se}):null,Fs?e.jsxs("div",{className:"control-alert warning",children:["LLM gateway unavailable: ",Fs]}):null,bs?e.jsxs("div",{className:"control-alert danger",children:["LLM quota exceeded: ",bs]}):null,Tt?e.jsxs("div",{className:"control-alert danger",children:["Account disabled: ",Tt]}):null,vt?e.jsxs("div",{className:"control-alert warning",children:["Session expired: ",vt]}):null,zt?e.jsxs("div",{className:"control-alert warning",children:["Admin access denied: ",zt]}):null,Qt==="reconnecting"?e.jsx("div",{className:"control-alert warning",children:"Reconnecting sandbox route."}):null,Qt==="connecting"?e.jsx("div",{className:"control-alert neutral",children:"Connecting sandbox route."}):null,je?e.jsxs("div",{className:"control-alert danger",children:["Sandbox offline: ",je]}):null,js?e.jsx("div",{className:`control-alert ${js.tone}`,children:js.text}):null]}),Os=sn(gt);return e.jsxs(e.Fragment,{children:[e.jsxs(Ai,{topBar:Un,alerts:On,sidebar:null,main:null,inspector:null,inspectorOpen:ne,children:[e.jsxs(Ui,{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:()=>Pe(wt),"aria-label":`Open create panel for ${ws.toLowerCase()}`,title:`Create ${ws.toLowerCase()}`,children:"+"})]}),Ne?e.jsxs("div",{className:"control-create-popover",children:[e.jsxs("div",{className:"control-panel-heading",children:[e.jsx("h2",{children:ss}),e.jsx("button",{type:"button",className:"control-icon-button quiet",onClick:()=>Pe(null),"aria-label":"Close create panel",children:"x"})]}),Ne==="project"?e.jsxs("form",{onSubmit:Be,className:"control-create-form",children:[e.jsx(dn,{label:"Project name",value:ct,onChange:Ct}),e.jsx(Me,{type:"submit",disabled:!Vt,children:"Create project"})]}):Ne==="workspace"?e.jsxs("form",{onSubmit:Qs,className:"control-create-form",children:[e.jsx(dn,{label:"Workspace name",value:b,onChange:w}),at?e.jsx("p",{className:"control-rule-note",children:at}):null,e.jsx(Me,{type:"submit",disabled:!$t,title:ts,children:"Create workspace"})]}):e.jsxs("form",{onSubmit:en,className:"control-create-form",children:[e.jsx(dn,{label:"Session title",value:U,onChange:Q}),e.jsxs("label",{className:"control-field",children:[e.jsx("span",{children:"Provider"}),e.jsxs("select",{value:be,onChange:u=>Le(u.currentTarget.value),disabled:!es,children:[e.jsx("option",{value:"codex",children:"Codex"}),e.jsx("option",{value:"claude",children:"Claude"}),e.jsx("option",{value:"opencode",children:"OpenCode"})]})]}),at?e.jsx("p",{className:"control-rule-note",children:at}):null,e.jsx(Me,{type:"submit",disabled:!es,title:jt,children:"Create session"})]})]}):null,e.jsxs("div",{className:"control-sidebar-body",children:[e.jsxs("section",{className:"control-sidebar-section",children:[e.jsxs("div",{className:"control-sidebar-section-title",children:[e.jsx("span",{children:"Workspace"}),e.jsx("strong",{children:(ee==null?void 0:ee.name)??(K==null?void 0:K.name)??"Not selected"})]}),e.jsxs("div",{className:"control-context-card",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Project"}),e.jsx("strong",{children:(K==null?void 0:K.name)??"Choose project"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Workspace"}),e.jsx("strong",{children:(ee==null?void 0:ee.name)??"Choose workspace"})]})]})]}),e.jsxs("section",{className:"control-sidebar-section",children:[e.jsxs("div",{className:"control-sidebar-section-title",children:[e.jsx("span",{children:"Sessions"}),e.jsx("strong",{children:L.length})]}),e.jsx("div",{className:"control-nav-list","aria-label":"Session filters",children:Vs.map((u,S)=>e.jsxs("button",{type:"button",className:`control-nav-row ${S===0?"selected":""}`,children:[e.jsx("span",{children:u.label}),e.jsx("strong",{children:u.value})]},u.label))})]}),e.jsxs("section",{className:"control-sidebar-section",children:[e.jsx("div",{className:"control-sidebar-section-title",children:e.jsx("span",{children:"System"})}),e.jsxs("div",{className:"control-nav-list","aria-label":"System navigation",children:[e.jsxs("button",{type:"button",className:"control-nav-row","aria-label":`Open sandbox details, ${we(o==null?void 0:o.state)}`,onClick:()=>{nt("summary"),De(!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:()=>he(!0),children:[e.jsx("span",{children:"Usage"}),e.jsxs("strong",{children:["$",ks.toFixed(2)]})]}),e.jsxs("button",{type:"button",className:"control-nav-row",onClick:()=>he(!0),children:[e.jsx("span",{children:"Settings"}),e.jsx("strong",{children:(n==null?void 0:n.plan)??"dev"})]})]})]})]}),e.jsx("div",{className:"control-explorer-tree",children:yt.projects?e.jsx("p",{className:"control-empty",children:"Loading projects..."}):H.length===0?e.jsx("p",{className:"control-empty",children:"No projects yet."}):H.map(u=>e.jsxs("div",{className:"control-tree-group",children:[Ms(_e)===`project:${u.id}`?e.jsx(Bn,{label:"Project name",value:ft,onChange:Ge,onCancel:Dt,onSubmit:is}):e.jsxs("div",{className:`control-tree-item ${E===u.id?"selected":""}`,children:[e.jsxs("button",{type:"button","aria-label":`Select project ${u.name}`,onClick:()=>{q(u.id),ye(""),G([]),D(""),oe(null),B(null),Nt(),St(),He("idle")},className:"control-tree-row project",children:[e.jsx("span",{className:"control-tree-caret",children:e.jsx(za,{open:E===u.id})}),e.jsx("span",{className:"control-tree-icon",children:e.jsx(Hi,{})}),e.jsx("strong",{children:u.name}),e.jsx("small",{children:we(u.status)})]}),e.jsx(_n,{label:`project ${u.name}`,onEdit:()=>Rs({type:"project",id:u.id},u.name),onDelete:()=>Fe({type:"project",id:u.id})})]}),E===u.id?e.jsx("div",{className:"control-tree-children",children:yt.workspaces?e.jsx("p",{className:"control-empty",children:"Loading workspaces..."}):Y.length===0?e.jsx("p",{className:"control-empty",children:"No workspaces in this project."}):Y.map(S=>e.jsxs("div",{className:"control-tree-group",children:[Ms(_e)===`workspace:${S.id}`?e.jsx(Bn,{label:"Workspace name",value:ft,onChange:Ge,onCancel:Dt,onSubmit:is}):e.jsxs("div",{className:`control-tree-item ${_===S.id?"selected":""}`,children:[e.jsxs("button",{type:"button","aria-label":`Select workspace ${S.name}`,onClick:()=>{ye(S.id),D(""),oe(null),B(null),Nt(),St(),He("idle")},className:"control-tree-row workspace",children:[e.jsx("span",{className:"control-tree-caret",children:e.jsx(za,{open:_===S.id})}),e.jsx("span",{className:"control-tree-icon",children:e.jsx(_i,{})}),e.jsx("strong",{children:S.name}),e.jsx("small",{children:Di(S)})]}),e.jsx(_n,{label:`workspace ${S.name}`,onEdit:()=>Rs({type:"workspace",id:S.id},S.name),onDelete:()=>Fe({type:"workspace",id:S.id})})]}),_===S.id?e.jsx("div",{className:"control-tree-children sessions",children:yt.sessions?e.jsx("p",{className:"control-empty",children:"Loading sessions..."}):L.length===0?e.jsx("p",{className:"control-empty",children:"No sessions for this workspace."}):L.map(k=>e.jsx("div",{className:"control-tree-group",children:Ms(_e)===`session:${k.id}`?e.jsx(Bn,{label:"Session title",value:ft,onChange:Ge,onCancel:Dt,onSubmit:is}):e.jsxs("div",{className:`control-tree-item ${xe===k.id?"selected":""}`,children:[e.jsxs("button",{type:"button","aria-label":`Open session ${k.title} from workspace browser`,onClick:()=>void ls(k),className:"control-tree-row session",children:[e.jsx("span",{className:"control-tree-caret"}),e.jsx("span",{className:"control-tree-icon",children:e.jsx(Bi,{})}),e.jsx("strong",{children:k.title}),e.jsxs("small",{children:[ln(k.provider)," / ",we(k.status),k.workerSessionId?"":" / Not started"]})]}),e.jsx(_n,{label:`session ${k.title}`,onEdit:()=>Rs({type:"session",id:k.id},k.title),onDelete:()=>Fe({type:"session",id:k.id})})]})},k.id))}):null]},S.id))}):null]},u.id))})]}),e.jsxs("main",{className:"control-main-column",children:[e.jsxs("section",{className:"control-workspace-hero","aria-label":"Current control plane context",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Current workspace"}),e.jsx("h2",{children:(ee==null?void 0:ee.name)??(K==null?void 0:K.name)??"Select a workspace"}),e.jsx("p",{children:ee?`${(K==null?void 0:K.name)??"Project"} · ${Ds(ee.sourceType)}`:"Pick a project and workspace before creating sessions."})]}),e.jsxs("div",{className:"control-workspace-hero-actions",children:[e.jsx("span",{className:`control-status-pill ${Pt((o==null?void 0:o.state)??"unknown")}`,children:we(o==null?void 0:o.state)}),e.jsx(Me,{onClick:()=>void rs("start"),disabled:Ae.start.disabled,title:Ae.start.title,ariaLabel:`Sandbox ${Ae.start.label}`,children:Ae.start.label}),e.jsx(Me,{onClick:()=>void rs("restart"),disabled:Ae.restart.disabled,title:Ae.restart.title,ariaLabel:"Sandbox restart",children:Ae.restart.label}),e.jsx(Me,{onClick:()=>void rs("health"),disabled:Ae.health.disabled,title:Ae.health.title,ariaLabel:"Sandbox health",children:Ae.health.label}),e.jsxs(Me,{onClick:()=>Pe(wt),disabled:wt==="workspace"?!$t:wt==="session"?!es:!Vt,title:wt==="workspace"?ts:wt==="session"?jt:void 0,children:["New ",ws]})]})]}),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:H.length})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Workspaces"}),e.jsx("strong",{children:Y.length})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Active sessions"}),e.jsx("strong",{children:et})]}),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:ee?`${L.length} in workspace`:"Select workspace"})]}),ee?e.jsxs(e.Fragment,{children:[jt?e.jsx("p",{className:"control-rule-note",children:jt}):null,yt.sessions?e.jsx("p",{className:"control-empty",children:"Loading sessions..."}):L.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:L.map(u=>e.jsxs("article",{role:"listitem",className:`control-session-row ${xe===u.id?"selected":""}`,children:[e.jsxs("button",{type:"button","aria-label":`Open session ${u.title} summary`,className:"control-session-row-main",onClick:()=>void ls(u),children:[e.jsx("strong",{children:u.title}),e.jsxs("span",{children:[ln(u.provider)," · ",on(u.lastActivityAt??u.updatedAt)]})]}),e.jsxs("div",{className:"control-session-row-state",children:[e.jsx(Ki,{status:u.status}),e.jsx("span",{children:Hn(u)})]}),e.jsxs("div",{className:"control-session-row-actions",children:[e.jsx(Me,{onClick:()=>void Us(u),disabled:!s||!Ce,title:Ce?void 0:"Start the sandbox before opening this session.",ariaLabel:`${u.workerSessionId?"Resume":"Start"} session ${u.title} from summary`,children:u.workerSessionId?"Resume":"Start"}),e.jsxs("div",{className:"control-row-menu",children:[e.jsx("button",{type:"button",className:"control-row-menu-trigger","aria-label":`More actions for session ${u.title}`,"aria-haspopup":"menu","aria-expanded":me===u.id,onClick:()=>I(S=>S===u.id?null:u.id),children:"..."}),me===u.id?e.jsxs("div",{className:"control-row-menu-popover",role:"menu",children:[e.jsx("button",{type:"button",role:"menuitem",onClick:()=>Is(u),children:"Show details"}),e.jsx("button",{type:"button",role:"menuitem",onClick:()=>Es("Session ID",u.id),children:"Copy session ID"}),u.sandboxId?e.jsx("button",{type:"button",role:"menuitem",onClick:()=>Es("Sandbox ID",u.sandboxId),children:"Copy sandbox ID"}):null,e.jsx("button",{type:"button",role:"menuitem",disabled:!s||!u.workerSessionId||!Ce,title:u.workerSessionId?void 0:"Session has not been started yet.",onClick:()=>{I(null),As(u)},children:"Close session"})]}):null]})]})]},u.id))}),e.jsx("div",{className:"control-action-row start",children:e.jsx(Me,{onClick:()=>Pe("session"),disabled:!es,title:jt,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:ae?"Selected session":ee?"Workspace context":K?"Project context":"Selection"}),e.jsx("span",{children:ae?we(ae.status):ee?Ds(ee.sourceType):K?we(K.status):"Root"})]}),ae?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:ae.title})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Provider"}),e.jsx("dd",{children:ln(ae.provider)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Status"}),e.jsx("dd",{children:e.jsx("span",{className:`control-status-pill compact ${Pt(ae.status)}`,children:we(ae.status)})})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Last activity"}),e.jsx("dd",{children:on(Tn)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Sandbox"}),e.jsx("dd",{children:Ce?"Ready":we(o==null?void 0:o.state)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Runtime"}),e.jsx("dd",{children:Hn(ae)})]})]}),e.jsxs("div",{className:"control-action-row start",children:[e.jsx(Me,{onClick:()=>void Us(ae),disabled:!s||!Ce,title:Ce?void 0:"Start the sandbox before opening this session.",ariaLabel:`${ae.workerSessionId?"Resume":"Start"} session ${ae.title} from detail`,children:ae.workerSessionId?"Resume":"Start sandbox session"}),e.jsx(Me,{onClick:()=>{nt("metadata"),De(!0)},children:"Details"})]})]}):ee?e.jsx(e.Fragment,{children:e.jsxs("dl",{className:"control-detail-list compact summary",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Workspace"}),e.jsx("dd",{children:ee.name})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Project"}),e.jsx("dd",{children:(K==null?void 0:K.name)??ee.projectId})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Source"}),e.jsx("dd",{children:Ds(ee.sourceType)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Sessions"}),e.jsx("dd",{children:L.length})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Active"}),e.jsx("dd",{children:et})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Not started"}),e.jsx("dd",{children:zs})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Sandbox"}),e.jsx("dd",{children:we(o==null?void 0:o.state)})]})]})}):K?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:K.name})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Status"}),e.jsx("dd",{children:we(K.status)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Workspaces"}),e.jsx("dd",{children:Y.length})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Path"}),e.jsx("dd",{children:ns})]})]}),e.jsx("div",{className:"control-action-row start",children:e.jsx(Me,{onClick:()=>Pe("workspace"),disabled:!$t,title:ts,children:"Create workspace"})})]}):e.jsx("p",{className:"control-empty",children:"Select a project to open the workspace hierarchy."})]})]}),ne?e.jsx("button",{type:"button",className:"control-inspector-scrim","aria-hidden":"true",tabIndex:-1,onClick:()=>De(!1)}):null,e.jsxs(Pi,{eyebrow:ae?"Session":ee?"Workspace":K?"Project":"Sandbox",hidden:!ne,onClose:()=>De(!1),children:[e.jsx("div",{className:"control-inspector-tabs",role:"tablist","aria-label":"Inspector sections",children:["summary","metadata","route","logs"].map(u=>e.jsx("button",{type:"button",role:"tab","aria-selected":bt===u,className:bt===u?"selected":"",onClick:()=>nt(u),children:u==="summary"?"Summary":u==="metadata"?"Metadata":u==="route"?"Route":"Logs"},u))}),bt==="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 ${Pt(o.state)}`,children:we(o.state)})})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Stage"}),e.jsx("dd",{children:Ks})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Health"}),e.jsx("dd",{children:In})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Last seen"}),e.jsx("dd",{children:on(Gs)})]})]}):e.jsx("p",{className:"control-empty",children:"Loading sandbox registry."})]}),e.jsxs("div",{className:"control-action-row",children:[e.jsx(Me,{onClick:()=>void rs("stop"),disabled:Ae.stop.disabled,title:Ae.stop.title,children:Ae.stop.label}),e.jsx(Me,{onClick:os,disabled:Ae.inspect.disabled,title:Ae.inspect.title,children:Ae.inspect.label})]}),o&&typeof o.startupProgress=="number"&&o.startupProgress>0&&o.startupProgress<100?e.jsxs("div",{className:"control-progress",children:[e.jsx("span",{children:Ks}),e.jsxs("span",{children:[o.startupProgress,"%"]}),e.jsx("div",{children:e.jsx("i",{style:{width:`${o.startupProgress}%`}})})]}):null,ae||ee||K?e.jsxs("div",{className:"control-inspector-section",children:[e.jsxs("div",{className:"control-panel-heading compact",children:[e.jsx("h2",{children:ae?"Session":ee?"Workspace":"Project"}),e.jsx("span",{children:ae?we(ae.status):ee?Ds(ee.sourceType):we(K==null?void 0:K.status)})]}),e.jsx("dl",{className:"control-detail-list compact summary",children:ae?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Title"}),e.jsx("dd",{children:ae.title})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Provider"}),e.jsx("dd",{children:ln(ae.provider)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Runtime"}),e.jsx("dd",{children:Hn(ae)})]})]}):ee?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Workspace"}),e.jsx("dd",{children:ee.name})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Sessions"}),e.jsx("dd",{children:L.length})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Active"}),e.jsx("dd",{children:et})]})]}):K?e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Project"}),e.jsx("dd",{children:K.name})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Workspaces"}),e.jsx("dd",{children:Y.length})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Status"}),e.jsx("dd",{children:we(K.status)})]})]}):null})]}):e.jsxs("div",{className:"control-inspector-empty",children:[e.jsx("strong",{children:"No object selected"}),e.jsx("span",{children:"Select a project, workspace, or session to inspect its metadata."})]}),e.jsxs("div",{className:"control-inspector-section",children:[e.jsxs("div",{className:"control-panel-heading compact",children:[e.jsx("h2",{children:"Harness"}),e.jsx("span",{className:`control-status-pill ${Ja(Jt)}`,children:we(Jt)})]}),Ce?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"control-action-row",children:e.jsx(Me,{onClick:()=>void Ys(s,ge),disabled:!s||yt.harness,children:yt.harness?"Checking...":"Refresh"})}),pt?e.jsxs("div",{className:"control-alert warning",children:["Harness unavailable: ",pt]}):null,e.jsxs("dl",{className:"control-detail-list compact summary",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Key"}),e.jsx("dd",{children:z!=null&&z.keyPresent?"Present":"Not present"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Chemistry"}),e.jsx("dd",{children:z!=null&&z.chemistryToolsEnabled?"Enabled":"Disabled"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Health"}),e.jsx("dd",{children:z!=null&&z.health?"OK":"Not available"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Module"}),e.jsx("dd",{children:rn[ge]})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Tools"}),e.jsx("dd",{children:Gt.length||"folder index"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Runs"}),e.jsx("dd",{children:ue.length||"history available"})]})]})]}):e.jsx("p",{className:"control-empty",children:"Start the sandbox to inspect Harness tools."})]})]}):null,bt==="metadata"?e.jsxs("div",{className:"control-inspector-tab-panel",role:"tabpanel",children:[ae?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(qe,{label:"Session ID",value:ae.id}),e.jsx(qe,{label:"Worker session",value:ae.workerSessionId}),e.jsx(qe,{label:"Workspace ID",value:ae.workspaceId}),e.jsx(qe,{label:"Sandbox ID",value:ae.sandboxId}),e.jsxs("div",{children:[e.jsx("dt",{children:"Created"}),e.jsx("dd",{children:ae.createdAt})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Updated"}),e.jsx("dd",{children:ae.updatedAt})]})]})]}):null,ee?e.jsxs("section",{className:"control-inspector-section",children:[e.jsx("div",{className:"control-panel-heading compact",children:e.jsx("h2",{children:"Workspace metadata"})}),e.jsxs("dl",{className:"control-detail-list",children:[e.jsx(qe,{label:"Workspace ID",value:ee.id}),e.jsx(qe,{label:"Project ID",value:ee.projectId}),e.jsx(qe,{label:"Path",value:ee.path}),e.jsxs("div",{children:[e.jsx("dt",{children:"Slug"}),e.jsx("dd",{children:ee.slug})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Created"}),e.jsx("dd",{children:ee.createdAt})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Updated"}),e.jsx("dd",{children:ee.updatedAt})]})]})]}):null,K?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(qe,{label:"Project ID",value:K.id}),e.jsxs("div",{children:[e.jsx("dt",{children:"Slug"}),e.jsx("dd",{children:K.slug})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Created"}),e.jsx("dd",{children:K.createdAt})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Updated"}),e.jsx("dd",{children:K.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(qe,{label:"Sandbox ID",value:o.id}),e.jsx(qe,{label:"Image",value:o.image}),e.jsx(qe,{label:"Worker ID",value:o.workerServiceName}),e.jsx(qe,{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,bt==="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(Me,{onClick:()=>void Lt("connecting",xe),disabled:!Ce||!ae,title:Ws,children:"Create route token"})]}),le?e.jsxs("dl",{className:"control-detail-list compact summary route-token",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Session"}),e.jsx("dd",{children:(ae==null?void 0:ae.title)??xe})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Connection"}),e.jsx("dd",{children:Va(Qt)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Token"}),e.jsxs("dd",{children:[on(le.expiresAt)," expiry"]})]})]}):e.jsx("p",{className:"control-empty",children:ae?`Selected session: ${ae.title}. Create a route token after the sandbox is running.`:"Select a session before creating a route token."})]}),le?e.jsxs("section",{className:"control-inspector-section",children:[e.jsx("div",{className:"control-panel-heading compact",children:e.jsx("h2",{children:"Route metadata"})}),e.jsxs("dl",{className:"control-detail-list",children:[e.jsx(qe,{label:"Router URL",value:le.routerBaseUrl}),e.jsx(qe,{label:"WebSocket URL",value:le.wsBaseUrl}),e.jsx(qe,{label:"Worker socket",value:F}),e.jsxs("div",{children:[e.jsx("dt",{children:"Connection"}),e.jsx("dd",{children:Va(Qt)})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Expires"}),e.jsx("dd",{children:le.expiresAt})]})]})]}):null]}):null,bt==="logs"?e.jsxs("div",{className:"control-inspector-tab-panel",role:"tabpanel",children:[e.jsxs("section",{className:"control-inspector-section",children:[e.jsxs("div",{className:"control-panel-heading compact",children:[e.jsx("h2",{children:"Harness details"}),e.jsx("span",{className:`control-status-pill ${Ja(Jt)}`,children:we(Jt)})]}),Ce?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"control-segment-row",role:"tablist","aria-label":"Harness modules",children:Ns.map(u=>e.jsx("button",{type:"button",role:"tab","aria-selected":ge===u,className:ge===u?"selected":"",onClick:()=>void Ts(u),disabled:yt.harness||!(z!=null&&z.enabled)||!z.keyPresent,children:rn[u]},u))}),e.jsxs("dl",{className:"control-detail-list",children:[e.jsx(qe,{label:"Base URL",value:z==null?void 0:z.baseUrl}),e.jsxs("div",{children:[e.jsx("dt",{children:"Enabled"}),e.jsx("dd",{children:z!=null&&z.enabled?"yes":"no"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Modules"}),e.jsx("dd",{children:Ns.map(u=>rn[u]).join(", ")})]})]}),e.jsxs("div",{className:"control-usage-events compact",children:[e.jsxs("div",{children:[e.jsxs("strong",{children:[rn[ge]," tools"]}),e.jsxs("small",{children:[Gt.length," advertised"]})]}),Gt.slice(0,5).map((u,S)=>e.jsxs("div",{children:[e.jsx("strong",{children:Ya(u,`tool-${S+1}`)}),e.jsx("span",{children:Za(u)||"tool"})]},`${ge}-tool-${S}`)),Gt.length===0&&Kt?e.jsx("div",{children:e.jsx("span",{children:Kt.slice(0,180)})}):null,Gt.length===0&&!Kt?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:[ue.length," reported"]})]}),ue.slice(0,4).map((u,S)=>e.jsxs("div",{children:[e.jsx("strong",{children:Ya(u,`run-${S+1}`)}),e.jsx("span",{children:Za(u)||"run"})]},`${ge}-run-${S}`)),ue.length===0&&as?e.jsx("div",{children:e.jsx("span",{children:as.slice(0,180)})}):null,ue.length===0&&!as?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(u=>e.jsxs("div",{children:[e.jsx("strong",{children:u.action}),e.jsx("small",{children:u.createdAt})]},u.id))})]}):e.jsxs("div",{className:"control-inspector-empty",children:[e.jsx("strong",{children:"No admin inspection loaded"}),e.jsx("span",{children:"Use Inspect from Summary to load sandbox runtime diagnostics."})]})]}):null]})]}),e.jsx(wn,{open:!!gt,title:Os.title,description:Os.description,confirmLabel:"Delete",busy:!!(ut!=null&&ut.startsWith("Delete ")),onCancel:()=>Fe(null),onConfirm:Ps})]})}const Zi="http://127.0.0.1:8790";function Xa({children:t}){const s=Xt(),[a,n]=r.useState(null);return r.useEffect(()=>{let d=!1;return Promise.resolve().then(()=>{d||n(Ri())}),()=>{d=!0}},[s.pathname]),a===null?e.jsx("div",{className:"grid min-h-[60vh] place-items-center text-sm text-[var(--theme-fg-muted)]",children:"Loading account session..."}):a?t:e.jsx(_s,{to:"/control-plane/login",replace:!0,state:{from:s}})}function Xi(t){return{baseUrl:t.baseUrl,token:t.token}}function Qi(){if(typeof window>"u")return null;const t=new URLSearchParams(window.location.search),s=t.get("control_plane_token"),a=t.get("control_plane_expires_at"),n=t.get("control_plane_base_url"),d=t.get("auth_error");return{token:s,expiresAt:a,baseUrl:n,error:d}}function ed(){var G;const t=it(),s=Xt(),a=Zt(),[n,d]=r.useState("login"),[o,m]=r.useState((a==null?void 0:a.baseUrl)??Zi),[h,f]=r.useState((a==null?void 0:a.email)??"dev@example.com"),[v,A]=r.useState((a==null?void 0:a.displayName)??"Developer"),[g,p]=r.useState(""),[C,T]=r.useState(!1),[R,y]=r.useState(null),[V,te]=r.useState(null),H=s.state,P=((G=H==null?void 0:H.from)==null?void 0:G.pathname)??"/control-plane",Y=r.useMemo(()=>{if(typeof window>"u")return;const E=new URL(window.location.href);return E.search="",E.toString()},[]);r.useEffect(()=>{const E=Qi();if(!E)return;if(E.error){te(`OAuth sign in failed: ${E.error}`);return}if(!E.token||!E.baseUrl)return;const q={baseUrl:E.baseUrl,token:E.token};E.expiresAt&&(q.expiresAt=E.expiresAt),xn(q),ha(Xi(q)).then(_=>{xn({...q,email:_.user.email,displayName:_.user.displayName}),t("/control-plane",{replace:!0})}).catch(_=>{yn(),te(_ instanceof Error?_.message:"Unable to finish OAuth sign in.")})},[t]);async function c(E){E.preventDefault(),T(!0),te(null),y(null);try{const q=n==="register"?await zo(o,{email:h,password:g,displayName:v||null}):await Vo(o,{email:h,password:g});xn({baseUrl:o,token:q.session.token,expiresAt:q.session.expiresAt,email:q.user.email,displayName:q.user.displayName}),y("Account session is ready."),t(P,{replace:!0})}catch(q){q instanceof re&&q.payload.code==="conflict"?te("An account already exists for this email. Use sign in instead."):te(q instanceof Error?q.message:"Unable to authenticate.")}finally{T(!1)}}function L(E){window.location.assign(qo(o,E,Y))}return e.jsx("div",{className:"control-auth-shell",children:e.jsxs("section",{className:"control-auth-panel","aria-label":"Control plane account login",children:[e.jsxs("div",{className:"control-auth-aside",children:[e.jsx("p",{className:"control-kicker",children:"Remote Codex"}),e.jsx("h1",{children:"Control plane sign in"}),e.jsx("p",{children:"Use a product account to manage sandboxes, workspaces, route tokens, and usage from the cloud control plane."}),e.jsxs("div",{className:"control-auth-checks","aria-label":"Login capabilities",children:[e.jsx("span",{children:"Google"}),e.jsx("span",{children:"GitHub"}),e.jsx("span",{children:"Email password"})]})]}),e.jsxs("form",{onSubmit:c,className:"control-auth-form",children:[e.jsxs("div",{className:"control-auth-tabs",role:"tablist","aria-label":"Authentication mode",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":n==="login",onClick:()=>d("login"),children:"Sign in"}),e.jsx("button",{type:"button",role:"tab","aria-selected":n==="register",onClick:()=>d("register"),children:"Create account"})]}),e.jsxs("label",{className:"control-field",children:[e.jsx("span",{children:"Control plane URL"}),e.jsx("input",{value:o,onChange:E=>m(E.currentTarget.value)})]}),e.jsxs("div",{className:"control-oauth-row",children:[e.jsx("button",{type:"button",onClick:()=>L("google"),children:"Continue with Google"}),e.jsx("button",{type:"button",onClick:()=>L("github"),children:"Continue with GitHub"})]}),e.jsx("div",{className:"control-auth-divider",children:e.jsx("span",{children:"Email"})}),n==="register"?e.jsxs("label",{className:"control-field",children:[e.jsx("span",{children:"Display name"}),e.jsx("input",{value:v,onChange:E=>A(E.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:E=>f(E.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:E=>p(E.currentTarget.value)})]}),V?e.jsx("p",{className:"control-auth-error",children:V}):null,R?e.jsx("p",{className:"control-auth-message",children:R}):null,e.jsx("button",{type:"submit",className:"control-primary-button",disabled:C,children:C?"Working...":n==="register"?"Create account":"Sign in"})]})]})})}function td(t){return t.sandboxMode??(t.approvalMode==="guarded"?"workspace-write":"danger-full-access")}function sd(t,s){const a=new Set(s.map(n=>n.id));return[...s,...t.filter(n=>!a.has(n.id))]}function Ht(t,s){const a=new Set(s.map(n=>n.id));return[...t.filter(n=>!a.has(n.id)),...s]}function nd(t,s){return!s||s.items.length===0?t:t.map(a=>{if(a.id!==s.turnId)return a;const n=s.items.filter(f=>f.kind==="agentMessage"&&f.createdAt);if(n.length===0)return a;const d=new Map(n.map(f=>[f.id,f])),o=new Set;let m=!1;const h=a.items.map(f=>{if(f.kind!=="agentMessage"||f.createdAt&&f.createdAt!==a.startedAt)return f;let v=d.get(f.id);return v||(v=n.find(A=>!o.has(A.id)&&A.text.trim().length>=8&&f.text.trim().includes(A.text.trim()))),!(v!=null&&v.createdAt)||v.createdAt===a.startedAt?f:(o.add(v.id),m=!0,{...f,createdAt:v.createdAt})});return m?{...a,items:h}:a})}function ad(t,s){return{...t,pendingRequests:[...t.pendingRequests.filter(a=>a.id!==s.id),s]}}function rd(t,s){const a=t.pendingRequests.filter(n=>n.id!==s);return a.length===t.pendingRequests.length?t:{...t,pendingRequests:a}}function ia(t,s,a){const n=s.filter(h=>!a.has(h.id)),d=t.filter(h=>!a.has(h.id));if(d.length===0)return n;const o=new Map(n.map(h=>[h.id,h]));return[...d.map(h=>o.get(h.id)??h),...n.filter(h=>!d.some(f=>f.id===h.id))].sort((h,f)=>h.createdAt.localeCompare(f.createdAt))}function od(t){if(!t||typeof t!="object")return!1;const s=t;return typeof s.id=="string"&&(s.kind==="requestUserInput"||s.kind==="planDecision")&&typeof s.title=="string"&&typeof s.createdAt=="string"&&Array.isArray(s.questions)}function qr(t,s){var o,m;if(!t||t.kind!==s.kind)return s;const a=h=>{let f=h;const v=typeof s.sequence=="number"&&Number.isFinite(s.sequence)?s.sequence:typeof t.sequence=="number"&&Number.isFinite(t.sequence)?t.sequence:null;v!==null&&f.sequence!==v&&(f={...f,sequence:v});const A=typeof s.transcriptOrder=="number"&&Number.isFinite(s.transcriptOrder)?s.transcriptOrder:typeof t.transcriptOrder=="number"&&Number.isFinite(t.transcriptOrder)?t.transcriptOrder:null;return A!==null&&f.transcriptOrder!==A&&(f={...f,transcriptOrder:A}),f};if(t.kind==="agentMessage"&&s.kind==="agentMessage")return a(t.text.length>s.text.length?{...s,text:t.text,sequence:s.sequence??t.sequence??null}:s);const n=((o=t.detailText)==null?void 0:o.trim())||t.text.trim(),d=((m=s.detailText)==null?void 0:m.trim())||s.text.trim();return a(n.length>d.length?t:s)}function ld(t,s,a){if(!t||s&&s.turnId!==t.turnId)return s;const n=a.find(g=>g.id===t.turnId),d=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(p=>p.includes(g.text.trim()));if(!s){const g=t.items.filter(p=>{const C=d.get(p.id);return C?C.kind!==p.kind||typeof p.sequence=="number"&&Number.isFinite(p.sequence)&&C.sequence!==p.sequence:!m(p)});return g.length===0?null:{...t,items:g}}const h=new Map(t.items.map(g=>[g.id,g])),f=new Map(s.items.map(g=>[g.id,g])),A=[...t.items.map(g=>g.id),...s.items.map(g=>g.id).filter(g=>!h.has(g))].map(g=>{const p=f.get(g),C=h.get(g);if(!p){const T=d.get(g);return!T&&C&&m(C)||T&&T.kind===(C==null?void 0:C.kind)&&!(C&&typeof C.sequence=="number"&&Number.isFinite(C.sequence)&&T.sequence!==C.sequence)?null:C??null}return qr(C,p)}).filter(g=>!!g);return A.length===0?null:{turnId:s.turnId,items:A,updatedAt:s.updatedAt.localeCompare(t.updatedAt)>=0?s.updatedAt:t.updatedAt}}function Ls(t,s){const a=t.filter(n=>n.id!==s.id);return[s,...a]}function id(t){return`${t.threadId}:${t.objective}:${t.createdAt}`}function dd(t,s){const a=Date.parse(t.updatedAt)||0,d=(Date.parse(s.updatedAt)||0)>=a?s:t,o=d===s?t:s;return{...d,localGoalId:d.localGoalId??o.localGoalId??null}}function zr(t){const s=new Map;for(const a of t){const n=id(a),d=s.get(n);s.set(n,d?dd(d,a):a)}return[...s.values()].sort((a,n)=>Date.parse(n.updatedAt)-Date.parse(a.updatedAt))}function cn(t,s){return zr([s,...t])}function cd(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 ud(t){const s=Math.max(0,Math.floor(t/60)),a=Math.floor(s/60),n=s%60;return a>0?`${a}h ${n}m`:`${s}m`}function Qa(t,s){if(!s)return null;const a=t.find(n=>n.model===s);return a?a.supportedReasoningEfforts.length>1:null}function md(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`client-${Date.now()}-${Math.random().toString(16).slice(2,10)}`}function Hs(t,s){return(t==null?void 0:t.items.some(a=>a.kind==="userMessage"&&a.text.trim()===s))??!1}function er(t){return t.replace(/\s*\[PHOTO\s+[^\]]+\]\s*/g," ").replace(/\s+/g," ").trim()}function gn(t,s){const a=er(s);return a?(t==null?void 0:t.items.some(n=>n.kind==="userMessage"&&er(n.text)===a))??!1:!1}function Fn(t){return(t==null?void 0:t.items.some(s=>s.kind==="userMessage"&&/\[PHOTO\s+\.\/\.temp\/threads\/[^\]]+\]/.test(s.text)))??!1}function hd(t,s){return t.find(a=>Hs(a,s))??(s.includes("[PHOTO ")?t.find(a=>gn(a,s))??null:null)}function pd(t,s,a,n){let d=!1;const o=t.map(m=>m.id!==s?m:(d=!0,{...m,tokenUsage:a,priceEstimate:n}));return d?o:t}const fd=3e3,xd=6e4,gd=5e3,bd=2147e6,vd=["worker:read","worker:write","session:prompt","provider:turn:create","provider:turn:interrupt"];function yd(t){if(!t)return"no activity yet";const s=Date.parse(t);if(!Number.isFinite(s))return t;const a=Date.now()-s,n=Math.abs(a),d=a>=0?"ago":"from now",o=6e4,m=60*o,h=24*m;return n<o?"just now":n<m?`${Math.round(n/o)}m ${d}`:n<h?`${Math.round(n/m)}h ${d}`:`${Math.round(n/h)}d ${d}`}function jd({title:t,children:s}){const[a,n]=r.useState(!1);return e.jsxs("section",{className:"control-metadata-disclosure",children:[e.jsxs("button",{type:"button","aria-expanded":a,onClick:()=>n(d=>!d),className:"control-metadata-trigger",children:[e.jsx("span",{children:t}),e.jsx("span",{children:a?"Hide":"Show"})]}),a?s:null]})}function Ue({label:t,value:s}){const a=s&&s.trim()?s:"not assigned";return e.jsxs("div",{children:[e.jsx("dt",{children:t}),e.jsxs("dd",{children:[e.jsx("span",{children:a}),s?e.jsx("button",{type:"button",className:"control-copy-button",onClick:()=>{var n;(n=navigator.clipboard)==null||n.writeText(s)},children:"Copy"}):null]})]})}function wd(t){if(!t||typeof t!="object")return null;const s=t,a=Array.isArray(s.content)?s.content.filter(n=>typeof n=="string"):typeof s.content=="string"?[s.content]:[];return a.length===0?null:{content:a.join(`
5
+ `),format:typeof s.format=="string"?s.format:"text",name:typeof s.name=="string"?s.name:null}}function Nd({selected:t,onClose:s}){const a=ca(),[n,d]=r.useState(t.kind==="artifact"?"preview":"logs"),[o,m]=r.useState(!0),h=t.kind==="artifact"?t.artifact:null,f=t.kind==="historyDetail"?t.detail:null,v=t.item,A=h?wd(h.payload):null,g=h?a.renderArtifact({artifact:h,expanded:o,onToggleExpanded:()=>m(C=>!C)}):null,p=[{id:"preview",label:"Preview"},{id:"source",label:"Source"},{id:"logs",label:"Logs"},{id:"metadata",label:"Metadata"}];return e.jsxs("aside",{className:"control-artifact-inspector","aria-label":"Thread inspector",children:[e.jsxs("header",{className:"control-artifact-inspector-header",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{children:(h==null?void 0:h.type)??v.kind}),e.jsx("h2",{children:(h==null?void 0:h.title)??(f==null?void 0:f.title)??v.text??"Timeline detail"})]}),e.jsx("button",{type:"button",onClick:s,"aria-label":"Close thread inspector",children:"x"})]}),e.jsx("div",{className:"control-artifact-tabs",role:"tablist","aria-label":"Thread details",children:p.map(C=>e.jsx("button",{type:"button",role:"tab","aria-selected":n===C.id,onClick:()=>d(C.id),children:C.label},C.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"?f?e.jsx("pre",{className:"control-artifact-source-raw",children:f.text}):A?e.jsxs("div",{className:"control-artifact-source",children:[e.jsxs("div",{children:[e.jsx("span",{children:A.format}),A.name?e.jsx("strong",{children:A.name}):null]}),e.jsx("pre",{children:A.content})]}):e.jsx("pre",{className:"control-artifact-source-raw",children:JSON.stringify(h==null?void 0:h.payload,null,2)}):null,n==="logs"?e.jsx("div",{className:"control-artifact-logs",children:f?e.jsx("pre",{children:f.text}):e.jsxs("dl",{className:"control-detail-list",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Timeline item"}),e.jsx("dd",{children:v.text||v.previewText||(h==null?void 0:h.summaryText)||"Artifact created"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Status"}),e.jsx("dd",{children:v.status??"completed"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Source turn"}),e.jsx("dd",{children:(h==null?void 0:h.sourceTurnId)??v.sourceTurnId??"not assigned"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Source item"}),e.jsx("dd",{children:(h==null?void 0:h.sourceItemId)??v.id})]})]})}):null,n==="metadata"?e.jsxs("dl",{className:"control-detail-list",children:[e.jsx(Ue,{label:"Timeline item id",value:v.id}),e.jsx(Ue,{label:"Timeline kind",value:v.kind}),h?e.jsxs(e.Fragment,{children:[e.jsx(Ue,{label:"Artifact id",value:h.id}),e.jsx(Ue,{label:"Plugin id",value:h.pluginId}),e.jsx(Ue,{label:"Artifact type",value:h.type}),e.jsx(Ue,{label:"Created",value:ps(h.createdAt)}),e.jsx(Ue,{label:"Source turn",value:h.sourceTurnId}),e.jsx(Ue,{label:"Source item",value:h.sourceItemId})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ue,{label:"Detail id",value:f==null?void 0:f.id}),e.jsx(Ue,{label:"Detail kind",value:f==null?void 0:f.kind})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Payload"}),e.jsx("dd",{children:e.jsx("pre",{children:JSON.stringify(h?h.payload:{item:v,detail:f},null,2)})})]})]}):null]})]})}const Sd=[],kd=[],Cd=[],Td={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 Id(){const t=Zt();return t?{baseUrl:t.baseUrl,token:t.token}:null}function Vr(t){switch(t){case"idle":case"running":case"interrupted":case"failed":case"not_loaded":case"system_error":return t;case"active":return"idle";default:return"not_loaded"}}function tr(t,s,a){const n=a==null?void 0:a.thread;return{id:t.id,workspaceId:s.id,provider:t.provider,providerSessionId:t.workerSessionId??(n==null?void 0:n.providerSessionId)??null,source:"supervisor",title:t.title||(n==null?void 0:n.title)||"Remote session",model:(n==null?void 0:n.model)??null,reasoningEffort:(n==null?void 0:n.reasoningEffort)??null,fastMode:(n==null?void 0:n.fastMode)??!1,collaborationMode:(n==null?void 0:n.collaborationMode)??"default",approvalMode:(n==null?void 0:n.approvalMode)??"guarded",sandboxMode:(n==null?void 0:n.sandboxMode)??null,status:(n==null?void 0:n.status)??Vr(t.status),summaryText:(n==null?void 0:n.summaryText)??null,lastError:(n==null?void 0:n.lastError)??null,activeTurnId:(n==null?void 0:n.activeTurnId)??null,isLoaded:!!(n!=null&&n.isLoaded),isPinned:!1,createdAt:t.createdAt,updatedAt:(n==null?void 0:n.updatedAt)??t.updatedAt,lastTurnStartedAt:(n==null?void 0:n.lastTurnStartedAt)??t.lastActivityAt,lastTurnCompletedAt:(n==null?void 0:n.lastTurnCompletedAt)??null,...n!=null&&n.contextUsage?{contextUsage:n.contextUsage}:{}}}function Ed(t,s,a){const n=new URL(`/api/sandboxes/${encodeURIComponent(t.sandboxId)}/api/threads/${encodeURIComponent(s)}/assets/image`,t.routerBaseUrl);return n.searchParams.set("path",a),n.toString()}const Rd={status:"not_created",connectionButtonDisabled:!0,connectionButtonLabel:"Remote shell unavailable",shellInputEnabled:!1,isConnecting:!1,isCommandRunning:!1,promptLabel:"Remote shell adapter not connected",isMobileShell:!1,hasShell:!1,busy:!1,loading:!1,error:"Remote sandbox shell routing is not connected yet."};function Wn(t){return t instanceof re&&t.statusCode===401&&t.payload.code==="invalid_route_token"}function sr(t){return t instanceof re&&(t.statusCode===404||t.statusCode===409)}function Jr(t,s){return Object.is(t,s)?!0:JSON.stringify(t)===JSON.stringify(s)}function qn(t,s){let a=t.length!==s.length||t.some((o,m)=>{var h;return o.id!==((h=s[m])==null?void 0:h.id)});const n=new Map(t.map(o=>[o.id,o])),d=s.map(o=>{const m=n.get(o.id);return m&&Jr(m,o)?m:(a=!0,o)});return a?d:t}function un(t,s){return Jr(t,s)?t:s}function Pd(t,s){if(!t)return s;const a=qn(t.turns,Ht(t.turns,s.turns)),n=qn(t.pendingRequests,ia(t.pendingRequests,s.pendingRequests,new Set)),d={...s,turns:a,pendingRequests:n,pendingSteers:qn(t.pendingSteers,s.pendingSteers)};return("answeredRequestNotes"in s||"answeredRequestNotes"in t)&&(d.answeredRequestNotes=un(t.answeredRequestNotes,s.answeredRequestNotes)??[]),("activityNotes"in s||"activityNotes"in t)&&(d.activityNotes=un(t.activityNotes,s.activityNotes)??[]),("livePlan"in s||"livePlan"in t)&&(d.livePlan=un(t.livePlan,s.livePlan)??null),("liveItems"in s||"liveItems"in t)&&(d.liveItems=un(t.liveItems,s.liveItems)??null),d}function Ad(){return e.jsx(Ud,{})}function Ud(){const{sessionId:t=""}=ur(),s=it(),a=Bt(),n=r.useMemo(Id,[]),[d,o]=r.useState(null),[m,h]=r.useState(null),[f,v]=r.useState(null),[A,g]=r.useState([]),[p,C]=r.useState(null),[T,R]=r.useState(null),[y,V]=r.useState(null),[te,H]=r.useState({prompt:"",attachments:[]}),[P,Y]=r.useState(!0),[c,L]=r.useState(!1),[G,E]=r.useState(null),[q,_]=r.useState(0),[ye,xe]=r.useState("chat"),[D,me]=r.useState(!0),[I,le]=r.useState(null),oe=r.useRef(!1),F=r.useRef(null),B=r.useRef(null),z=r.useCallback(se=>{V(ie=>{const ce=Pd(ie,se);return B.current=ce,ce})},[]),de=r.useCallback(async se=>{if(!n)return null;const ie=await Ir(n,se.sandbox.id,{projectId:se.project.id,workspaceId:se.workspace.id,sessionId:se.session.id,scopes:vd});return R(ie),ie},[n]),ge=r.useCallback(async()=>!d||!m||!f||!p||d.state!=="running"?null:de({sandbox:d,project:m,workspace:f,session:p}),[de,m,d,p,f]),st=r.useCallback(async()=>{if(!n)return s("/control-plane/login",{replace:!0}),null;Y(!0),E(null);try{const se=await ha(n);if(o(se.sandbox),se.sandbox.state!=="running")return C(null),R(null),V(null),B.current=null,E("Sandbox is not running. Start the sandbox from the control plane before opening chat."),null;const ie=await Cr(n);for(const ce of ie.projects){const he=await aa(n,ce.id);for(const Ne of he.workspaces){const Pe=await ra(n,Ne.id),ne=Pe.sessions.find(xt=>xt.id===t);if(!ne)continue;const De=await Tr(n,ne.id),bt=Pe.sessions.map(xt=>xt.id===De.session.id?De.session:xt),nt=await de({sandbox:se.sandbox,project:ce,workspace:Ne,session:De.session});if(!nt)return E("Unable to issue a router token for this session."),null;if(h(ce),v(Ne),g(bt),C(De.session),!De.session.workerSessionId)return V(null),B.current=null,E("Session resumed, but the worker did not return a thread id."),null;const Ut=await us(nt,De.session.workerSessionId);return z(Ut),_(xt=>xt+1),{session:De.session,token:nt,detail:Ut}}}return E("Session was not found in any project workspace."),null}catch(se){return se instanceof re&&se.payload.code==="unauthorized"?(yn(),s("/control-plane/login",{replace:!0}),null):(E(se instanceof Error?se.message:"Unable to open control-plane session."),null)}finally{Y(!1)}},[z,n,de,s,t]);r.useEffect(()=>{st()},[st]),r.useEffect(()=>{le(null)},[t]),r.useEffect(()=>{if(F.current&&(window.clearTimeout(F.current),F.current=null),!T)return;const se=Date.parse(T.expiresAt);if(!Number.isFinite(se))return;const ie=Math.max(gd,Math.min(bd,se-Date.now()-xd));return F.current=window.setTimeout(()=>{ge().catch(ce=>{E(ce instanceof Error?ce.message:"Unable to refresh router token.")})},ie),()=>{F.current&&(window.clearTimeout(F.current),F.current=null)}},[ge,T]);const ht=r.useCallback(async(se={})=>{if(!(!T||!(p!=null&&p.workerSessionId))){se.silent||E(null);try{z(await us(T,p.workerSessionId))}catch(ie){if(Wn(ie))try{const ce=await ge();if(ce&&p.workerSessionId){z(await us(ce,p.workerSessionId));return}}catch(ce){E(ce instanceof Error?ce.message:"Unable to refresh worker thread.");return}if(sr(ie)&&!oe.current){oe.current=!0;try{await st();return}finally{oe.current=!1}}E(ie instanceof Error?ie.message:"Unable to refresh worker thread.")}}},[z,st,ge,T,p==null?void 0:p.workerSessionId]);r.useEffect(()=>{if(!((y==null?void 0:y.thread.status)==="running"||!!(y!=null&&y.thread.activeTurnId)||c)||!T||!(p!=null&&p.workerSessionId))return;const ie=window.setInterval(()=>{ht({silent:!0})},fd);return()=>window.clearInterval(ie)},[y==null?void 0:y.thread.activeTurnId,y==null?void 0:y.thread.status,ht,T,c,p==null?void 0:p.workerSessionId]);async function dt(se){const ie=se.prompt.trim();if(!ie||!T||!(p!=null&&p.workerSessionId))return!1;L(!0),E(null);try{return await $n(T,p.workerSessionId,{prompt:ie}),H({prompt:"",attachments:[]}),await ht(),_(ce=>ce+1),!0}catch(ce){if(Wn(ce))try{const he=await ge();if(!he||!p.workerSessionId)throw ce;await $n(he,p.workerSessionId,{prompt:ie});const Ne=await us(he,p.workerSessionId);return z(Ne),H({prompt:"",attachments:[]}),_(Pe=>Pe+1),!0}catch(he){return E(he instanceof Error?he.message:"Unable to send prompt."),!1}if(sr(ce)&&!oe.current){oe.current=!0;try{const he=await st();if(!(he!=null&&he.session.workerSessionId))throw ce;await $n(he.token,he.session.workerSessionId,{prompt:ie});const Ne=await us(he.token,he.session.workerSessionId);return z(Ne),H({prompt:"",attachments:[]}),_(Pe=>Pe+1),!0}catch(he){return E(he instanceof Error?he.message:"Unable to send prompt."),!1}finally{oe.current=!1}}return E(ce instanceof Error?ce.message:"Unable to send prompt."),!1}finally{L(!1)}}async function kt(){var se,ie;if(!(!T||!(p!=null&&p.workerSessionId))){L(!0),E(null);try{const ce=((se=B.current)==null?void 0:se.thread.activeTurnId)??void 0,he=await Ha(T,p.workerSessionId,ce?{turnId:ce}:{});V(Ne=>Ne&&{...Ne,thread:he}),await ht({silent:!0})}catch(ce){if(Wn(ce))try{const he=await ge();if(!he||!p.workerSessionId)throw ce;const Ne=((ie=B.current)==null?void 0:ie.thread.activeTurnId)??void 0,Pe=await Ha(he,p.workerSessionId,Ne?{turnId:Ne}:{});V(ne=>ne&&{...ne,thread:Pe}),z(await us(he,p.workerSessionId));return}catch(he){E(he instanceof Error?he.message:"Unable to interrupt turn.");return}E(ce instanceof Error?ce.message:"Unable to interrupt turn.")}finally{L(!1)}}}const Ve=T?p!=null&&p.workerSessionId?void 0:"Reconnect this session before sending a prompt.":"Waiting for a router token...",pt=f?A.map(se=>tr(se,f,se.id===(p==null?void 0:p.id)?y:null)):[],Xe=p&&f?tr(p,f,y):null,ct=Xe&&pt.every(se=>se.id!==Xe.id)?[Xe,...pt]:pt,Ct=(y==null?void 0:y.thread.status)??Vr(p==null?void 0:p.status),b=fr(Ct),w=(y==null?void 0:y.thread.lastTurnStartedAt)??(y==null?void 0:y.thread.updatedAt)??(p==null?void 0:p.lastActivityAt)??(p==null?void 0:p.updatedAt)??null,U=(p==null?void 0:p.provider)??(y==null?void 0:y.thread.provider)??"codex",Q=(y==null?void 0:y.thread.model)??"default model",be=(T==null?void 0:T.expiresAt)??null,Le=e.jsxs("div",{className:"control-session-meta",children:[e.jsxs("dl",{className:"control-detail-list compact summary two",children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Status"}),e.jsx("dd",{children:b})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Provider"}),e.jsx("dd",{children:U})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Workspace"}),e.jsx("dd",{children:(f==null?void 0:f.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:Q})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Last activity"}),e.jsx("dd",{children:yd(w)})]})]}),e.jsx(jd,{title:"Diagnostics",children:e.jsxs("dl",{className:"control-detail-list",children:[e.jsx(Ue,{label:"Control session id",value:(p==null?void 0:p.id)??t}),e.jsx(Ue,{label:"Worker thread id",value:p==null?void 0:p.workerSessionId}),e.jsx(Ue,{label:"Workspace path",value:(f==null?void 0:f.path)??(y==null?void 0:y.workspace.absPath)}),e.jsx(Ue,{label:"Workspace id",value:f==null?void 0:f.id}),e.jsx(Ue,{label:"Project id",value:m==null?void 0:m.id}),e.jsx(Ue,{label:"Sandbox id",value:d==null?void 0:d.id}),e.jsx(Ue,{label:"Router URL",value:(T==null?void 0:T.routerBaseUrl)??(d==null?void 0:d.routerBaseUrl)}),e.jsx(Ue,{label:"Image",value:d==null?void 0:d.image}),e.jsx(Ue,{label:"Worker service",value:d==null?void 0:d.workerServiceName}),e.jsx(Ue,{label:"Session updated",value:ps((p==null?void 0:p.updatedAt)??null)}),e.jsx(Ue,{label:"Route token expires",value:ps(be)})]})})]}),_e=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 st(),disabled:P,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:P?"Reconnecting...":"Reconnect session"}),e.jsx("button",{type:"button",onClick:()=>void ht(),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"})]})}),Je=r.useCallback(se=>{le({kind:"artifact",...se})},[]),ft=r.useCallback(se=>{le({kind:"historyDetail",...se})},[]),Ge=r.useCallback(async se=>{if(!T||!(p!=null&&p.workerSessionId))throw new Error("Reconnect this session before loading item details.");return il(T,p.workerSessionId,se)},[T,p==null?void 0:p.workerSessionId]),gt=r.useMemo(()=>({scrollRequestKey:q,className:"thread-timeline-surface min-h-0 flex-1",onTailVisibilityChange:me,answeredRequestNotes:(y==null?void 0:y.answeredRequestNotes)??Sd,activityNotes:(y==null?void 0:y.activityNotes)??kd,pendingSteers:(y==null?void 0:y.pendingSteers)??Cd,onLoadHistoryItemDetail:Ge,onSelectArtifact:Je,onSelectHistoryItemDetail:ft}),[y==null?void 0:y.activityNotes,y==null?void 0:y.answeredRequestNotes,y==null?void 0:y.pendingSteers,Je,ft,Ge,q]),Fe=y?{busy:c,error:G,model:y.thread.model,reasoningEffort:y.thread.reasoningEffort,fastMode:y.thread.fastMode??!1,collaborationMode:y.thread.collaborationMode,contextUsage:y.thread.contextUsage,capabilities:Td,toolboxItems:[],followTail:D,threadConnected:y.thread.isLoaded,disabled:!!Ve,...Ve?{disabledPlaceholder:Ve}:{},draftPrompt:te.prompt,draftAttachments:te.attachments,onDraftChange:H,canInterrupt:!!y.thread.activeTurnId,onInterrupt:kt,shellControlState:Rd,onToggleView:()=>xe("shell"),onToggleFollow:()=>_(se=>se+1)}:null,ut=e.jsx("span",{className:"control-session-status-badge",children:b}),At=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:()=>xe("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"})]})}),Ft=r.useCallback(se=>T&&(p!=null&&p.workerSessionId)?Ed(T,p.workerSessionId,se):"",[T,p==null?void 0:p.workerSessionId]),Wt=r.useMemo(()=>({openThread:se=>{s(`/control-plane/sessions/${se}`)},getThreadHref:se=>`/control-plane/sessions/${se}`,getNewThreadHref:()=>"/control-plane",sendPrompt:dt,interrupt:kt,getImageAssetUrl:Ft,shell:null}),[Ft,s]);return e.jsxs("div",{className:"control-chat-workspace",children:[e.jsx(pr,{threads:ct,detail:y,status:null,loading:P,error:P?null:G,adapter:Wt,currentWorkspaceId:(f==null?void 0:f.id)??null,currentWorkspaceLabel:(f==null?void 0:f.name)??(y==null?void 0:y.workspace.label)??null,metaContent:Le,settingsContent:_e,surfaceActions:ut,appMenuButton:e.jsx(vo,{}),appNavigationMenu:e.jsx(bo,{currentPath:`/control-plane/sessions/${t}`,items:[{label:"Control Plane",href:"/control-plane"},{label:"Workspaces",href:"/workspaces"}],onNavigate:s}),onCloseAppNavigation:(a==null?void 0:a.closeNav)??(()=>{}),activeView:ye,timelineProps:gt,shellEffectiveTheme:(a==null?void 0:a.effectiveTheme)??"dark",shellThemeMode:(a==null?void 0:a.themeMode)??"system",...a!=null&&a.setThemeMode?{onShellThemeModeChange:a.setThemeMode}:{},shellUnavailableContent:At,shellDisconnectedContent:At,shellContent:At,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."}),...p?{currentThreadId:p.id}:{},...Fe?{composerProps:Fe}:{}}),I?e.jsx("div",{className:"control-artifact-inspector-overlay",children:e.jsx(Nd,{selected:I,onClose:()=>le(null)})}):null]})}function Od({onLogin:t}){const[s,a]=r.useState(""),[n,d]=r.useState(""),[o,m]=r.useState(null),[h,f]=r.useState(!1);async function v(A){A.preventDefault(),m(null),f(!0);try{await t({username:s,password:n})}catch(g){g instanceof re?m(g.payload.message):m("Unable to sign in.")}finally{f(!1)}}return e.jsx("main",{className:"flex min-h-screen items-center justify-center bg-[var(--app-bg)] px-4 py-8 text-[var(--app-fg)]",children:e.jsxs("section",{className:"w-full max-w-sm rounded-[1.35rem] border border-[var(--theme-border)] bg-[var(--theme-panel)] p-5 shadow-2xl shadow-[color-mix(in_oklch,var(--app-fg)_14%,transparent)] sm:p-6",children:[e.jsxs("div",{className:"mb-5",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-muted)]",children:"Supervisor Access"}),e.jsx("h1",{className:"mt-2 text-2xl font-semibold tracking-normal text-[var(--theme-fg)]",children:"Sign in"}),e.jsx("p",{className:"mt-2 text-sm leading-6 text-[var(--theme-muted)]",children:"Use the admin credentials configured on this Remote Codex server."})]}),e.jsxs("form",{onSubmit:v,className:"space-y-4",children:[e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm font-medium text-[var(--theme-fg-soft)]",children:"Username"}),e.jsx("input",{autoComplete:"username",autoFocus:!0,className:"mt-2 h-11 w-full rounded-xl border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 text-sm text-[var(--theme-fg)] outline-none transition focus:border-[var(--theme-accent-solid)] focus:ring-2 focus:ring-[var(--theme-accent-border)]",disabled:h,name:"username",onChange:A=>a(A.target.value),value:s})]}),e.jsxs("label",{className:"block",children:[e.jsx("span",{className:"text-sm font-medium text-[var(--theme-fg-soft)]",children:"Password"}),e.jsx("input",{autoComplete:"current-password",className:"mt-2 h-11 w-full rounded-xl border border-[var(--theme-border)] bg-[var(--theme-surface)] px-3 text-sm text-[var(--theme-fg)] outline-none transition focus:border-[var(--theme-accent-solid)] focus:ring-2 focus:ring-[var(--theme-accent-border)]",disabled:h,name:"password",onChange:A=>d(A.target.value),type:"password",value:n})]}),o&&e.jsx("p",{className:"rounded-xl border border-[var(--status-danger-border)] bg-[var(--status-danger-bg)] px-3 py-2 text-sm text-[var(--status-danger-fg)]",children:o}),e.jsx("button",{className:"h-11 w-full rounded-xl bg-[var(--theme-accent-solid)] px-4 text-sm font-semibold text-[var(--theme-accent-solid-fg)] transition hover:bg-[var(--theme-accent-solid-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--theme-accent-border)] disabled:cursor-not-allowed disabled:opacity-60",disabled:h||!s.trim()||!n,type:"submit",children:h?"Signing in...":"Sign in"})]})]})})}function zn(t,s){return t instanceof re?t.payload.message:t instanceof Error?t.message:s}function $d(){var E;const[t,s]=r.useState(null),[a,n]=r.useState(""),[d,o]=r.useState(""),[m,h]=r.useState(""),[f,v]=r.useState(""),[A,g]=r.useState(!0),[p,C]=r.useState(!1),[T,R]=r.useState(!1),[y,V]=r.useState(null),[te,H]=r.useState(null),[P,Y]=r.useState(!1);async function c(){var q;g(!0),H(null);try{xs();const _=await Bs();s(_),n(((q=_.user)==null?void 0:q.username)??"")}catch(_){H(zn(_,"Unable to load account."))}finally{g(!1)}}r.useEffect(()=>{c()},[]);async function L(q){q.preventDefault(),C(!0),H(null),V(null);try{const _=await pl({username:a});s(ye=>ye!=null&&ye.authenticated?{...ye,user:_}:ye),n(_.username),V("Account updated.")}catch(_){H(zn(_,"Unable to update account."))}finally{C(!1)}}async function G(q){q.preventDefault(),R(!0),H(null),V(null);try{if(m!==f){H("New passwords do not match.");return}await fl({currentPassword:d,newPassword:m}),o(""),h(""),v(""),V("Password changed.")}catch(_){H(zn(_,"Unable to change password."))}finally{R(!1)}}return e.jsx("main",{className:"min-h-screen bg-[var(--app-bg)] px-4 py-6 text-[var(--app-fg)] sm:px-6",children:e.jsxs("div",{className:"mx-auto w-full max-w-4xl space-y-5 pr-12 sm:pr-0",children:[e.jsxs("header",{className:"border-b border-[var(--theme-border)] pb-5",children:[e.jsx(Rt,{className:"text-sm text-[var(--theme-accent-strong)]",to:"/workspaces",children:"Back to workspaces"}),e.jsx("p",{className:"mt-4 text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-fg-muted)]",children:"Relay Account"}),e.jsx("h1",{className:"mt-2 text-2xl font-semibold text-[var(--theme-fg)]",children:"Account settings"})]}),A?e.jsx("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4 text-sm text-[var(--theme-fg-muted)]",children:"Loading account..."}):t!=null&&t.authenticated?e.jsxs(e.Fragment,{children:[te?e.jsx(nr,{tone:"danger",children:te}):null,y?e.jsx(nr,{tone:"success",children:y}):null,e.jsxs("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:"Profile"}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"Username changes apply to future shares and login."})]}),e.jsxs("form",{className:"space-y-4",onSubmit:L,children:[e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Email",e.jsx("input",{className:"relay-input mt-2 w-full",disabled:!0,readOnly:!0,value:((E=t.user)==null?void 0:E.email)??""})]}),e.jsxs("div",{className:"flex flex-col gap-2 sm:flex-row sm:items-end",children:[e.jsxs("label",{className:"block flex-1 text-sm text-[var(--theme-fg-soft)]",children:["Username",e.jsx("input",{className:"relay-input mt-2 w-full",onChange:q=>n(q.target.value),value:a})]}),e.jsxs("button",{className:"relay-button-primary inline-flex h-10 items-center justify-center gap-2",disabled:p||!a.trim(),type:"submit",children:[e.jsx(lt.Save,{className:"h-4 w-4"}),"Save"]})]}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-2",onClick:()=>Y(!0),type:"button",children:[P?e.jsx(lt.CheckCircle2,{className:"h-4 w-4"}):e.jsx(lt.MailCheck,{className:"h-4 w-4"}),P?"Verification queued":"Verify email"]})]})]}),e.jsxs("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:"Password"}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"Use at least 8 characters."})]}),e.jsxs("form",{className:"grid gap-4 sm:grid-cols-3",onSubmit:G,children:[e.jsx(Vn,{label:"Current password",value:d,onChange:o}),e.jsx(Vn,{label:"New password",value:m,onChange:h}),e.jsx(Vn,{label:"Confirm password",value:f,onChange:v}),e.jsxs("button",{className:"relay-button-primary inline-flex h-10 items-center justify-center gap-2 sm:col-span-3 sm:w-fit",disabled:T||!d||m.length<8||!f,type:"submit",children:[e.jsx(lt.Save,{className:"h-4 w-4"}),"Change password"]})]})]})]}):e.jsx("section",{className:"rounded-lg border border-[var(--status-danger-border)] bg-[var(--status-danger-bg)] p-4 text-sm text-[var(--status-danger-fg)]",children:"Relay login is required."})]})})}function Vn({label:t,value:s,onChange:a}){return e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:[t,e.jsx("input",{autoComplete:"new-password",className:"relay-input mt-2 w-full",onChange:n=>a(n.target.value),type:"password",value:s})]})}function nr({tone:t,children:s}){return e.jsx("div",{className:`rounded-lg border px-3 py-2 text-sm ${t==="danger"?"border-[var(--status-danger-border)] bg-[var(--status-danger-bg)] text-[var(--status-danger-fg)]":"border-[var(--status-success-border)] bg-[var(--status-success-bg)] text-[var(--status-success-fg)]"}`,children:s})}function Jn(t){return t instanceof re?t.payload.message:t instanceof Error?t.message:"Unable to update relay admin state."}function Md(){const[t,s]=r.useState(null),[a,n]=r.useState(!0),[d,o]=r.useState(null),[m,h]=r.useState(null);async function f(){n(!0),o(null);try{xs(),s(await bl())}catch(g){o(Jn(g))}finally{n(!1)}}r.useEffect(()=>{f()},[]);async function v(g){h("registration"),o(null);try{const p=await vl(g);s(C=>C&&{...C,registrationEnabled:p.registrationEnabled})}catch(p){o(Jn(p))}finally{h(null)}}async function A(g,p){h(g),o(null);try{const C=await yl(g,p);s(T=>T&&{...T,users:T.users.map(R=>R.id===C.id?C:R)})}catch(C){o(Jn(C))}finally{h(null)}}return e.jsxs("main",{className:"min-h-screen bg-[var(--app-bg)] px-4 py-6 text-[var(--app-fg)] sm:px-6",children:[e.jsx(ga,{}),e.jsxs("div",{className:"mx-auto flex w-full max-w-6xl flex-col gap-5",children:[e.jsxs("header",{className:"flex flex-col gap-3 border-b border-[var(--theme-border)] pb-5 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-fg-muted)]",children:"Relay Admin"}),e.jsx("h1",{className:"mt-2 text-2xl font-semibold text-[var(--theme-fg)]",children:"Users and devices"}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"Manage relay accounts, registration, and connected devices."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Rt,{className:"relay-button-secondary",to:"/relay-portal",children:"Portal"}),e.jsx("button",{className:"relay-button-secondary",onClick:()=>void f(),type:"button",children:"Refresh"})]})]}),a?e.jsx("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4 text-sm text-[var(--theme-fg-muted)]",children:"Loading relay admin..."}):d?e.jsx("section",{className:"rounded-lg border border-[var(--status-danger-border)] bg-[var(--status-danger-bg)] p-4 text-sm text-[var(--status-danger-fg)]",children:d}):t?e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:"Registration"}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"New users can create relay accounts without email verification."})]}),e.jsx("button",{className:"relay-button-primary",disabled:m==="registration",onClick:()=>void v(!t.registrationEnabled),type:"button",children:t.registrationEnabled?"Disable":"Enable"})]})}),e.jsxs("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:"Users"}),e.jsx("div",{className:"mt-4 overflow-x-auto",children:e.jsxs("table",{className:"w-full min-w-[44rem] border-collapse text-left text-sm",children:[e.jsx("thead",{className:"text-xs uppercase tracking-[0.16em] text-[var(--theme-fg-muted)]",children:e.jsxs("tr",{children:[e.jsx("th",{className:"border-b border-[var(--theme-border)] py-2 pr-3",children:"User"}),e.jsx("th",{className:"border-b border-[var(--theme-border)] py-2 pr-3",children:"Email"}),e.jsx("th",{className:"border-b border-[var(--theme-border)] py-2 pr-3",children:"Role"}),e.jsx("th",{className:"border-b border-[var(--theme-border)] py-2 pr-3",children:"Status"}),e.jsx("th",{className:"border-b border-[var(--theme-border)] py-2 pr-3",children:"Actions"})]})}),e.jsx("tbody",{children:t.users.map(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 A(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 Gn(t,s){return t instanceof re?t.payload.message:t instanceof Error?t.message:s}function Ld(){const t=it(),[s,a]=r.useState(null),[n,d]=r.useState(""),[o,m]=r.useState(null),[h,f]=r.useState(null),[v,A]=r.useState(!0),[g,p]=r.useState(null),[C,T]=r.useState(null);async function R(){A(!0),T(null);try{xs(),a(await Rr())}catch(P){T(Gn(P,"Unable to load devices."))}finally{A(!1)}}r.useEffect(()=>{R()},[]);async function y(P){P.preventDefault(),p("create"),T(null);try{const Y=await Pr({name:n});m(Y),d(""),await R()}catch(Y){T(Gn(Y,"Unable to create device."))}finally{p(null)}}async function V(P){p(P.id),T(null);try{await Ar(P.id),(o==null?void 0:o.device.id)===P.id&&m(null),await R()}catch(Y){T(Gn(Y,"Unable to delete device."))}finally{p(null)}}function te(P){bn(P.id),vn(null),t("/workspaces")}async function H(P){var c;const Y=P.token;if(!Y){T("This device token is not available. Create a new device token for devices created before token storage was enabled.");return}try{await((c=navigator.clipboard)==null?void 0:c.writeText(Gr(Y))),f(P.id),window.setTimeout(()=>{f(L=>L===P.id?null:L)},1600)}catch{}}return e.jsx("main",{className:"min-h-screen bg-[var(--app-bg)] px-4 py-6 text-[var(--app-fg)] sm:px-6",children:e.jsxs("div",{className:"mx-auto w-full max-w-6xl space-y-5 pr-12 sm:pr-0",children:[e.jsxs("header",{className:"flex flex-col gap-3 border-b border-[var(--theme-border)] pb-5 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{children:[e.jsx(Rt,{className:"text-sm text-[var(--theme-accent-strong)]",to:"/workspaces",children:"Back to workspaces"}),e.jsx("p",{className:"mt-4 text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-fg-muted)]",children:"Relay Devices"}),e.jsx("h1",{className:"mt-2 text-2xl font-semibold text-[var(--theme-fg)]",children:"Device management"})]}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-2",onClick:()=>void R(),type:"button",children:[e.jsx(lt.RefreshCcw,{className:"h-4 w-4"}),"Refresh"]})]}),C?e.jsx(_d,{tone:"danger",children:C}):null,o?e.jsx(Hd,{result:o}):null,e.jsxs("section",{className:"grid gap-4 lg:grid-cols-[minmax(20rem,0.8fr)_minmax(0,1.2fr)]",children:[e.jsxs("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsxs("div",{className:"mb-4 flex items-start gap-3",children:[e.jsx("span",{className:"inline-flex h-9 w-9 items-center justify-center rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] text-[var(--theme-fg)]",children:e.jsx(lt.Plus,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:"Add device"}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"Create a token for one private supervisor."})]})]}),e.jsxs("form",{className:"space-y-3",onSubmit:y,children:[e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Device name",e.jsx("input",{className:"relay-input mt-2 w-full",onChange:P=>d(P.target.value),placeholder:"MacBook Pro",value:n})]}),e.jsxs("button",{className:"relay-button-primary inline-flex h-10 w-full items-center justify-center gap-2",disabled:g==="create"||!n.trim(),type:"submit",children:[e.jsx(lt.MonitorSmartphone,{className:"h-4 w-4"}),"Create device token"]})]})]}),e.jsxs("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:"Devices"}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"Connect to an online device before opening workspaces."})]}),e.jsx("span",{className:"rounded-full border border-[var(--theme-border)] px-2 py-0.5 text-xs text-[var(--theme-fg-muted)]",children:(s==null?void 0:s.devices.length)??0})]}),v?e.jsx("p",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-4 text-sm text-[var(--theme-fg-muted)]",children:"Loading devices..."}):s!=null&&s.devices.length?e.jsx("div",{className:"space-y-3",children:s.devices.map(P=>e.jsx(Dd,{busy:g===P.id,copiedSetup:h===P.id,device:P,onConnect:()=>te(P),onCopySetup:()=>void H(P),onDelete:()=>void V(P),setupTokenAvailable:!!P.token},P.id))}):e.jsx("div",{className:"rounded-lg border border-dashed border-[var(--theme-border)] bg-[var(--theme-surface)] p-5 text-sm text-[var(--theme-fg-muted)]",children:"No devices yet. Create a token, then start `remote-codex relay-supervisor` on your private machine."})]})]})]})})}function Dd({device:t,busy:s,copiedSetup:a,onConnect:n,onCopySetup:d,onDelete:o,setupTokenAvailable:m}){return e.jsxs("article",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-3",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[e.jsx("span",{className:`h-2.5 w-2.5 rounded-full ${t.connected?"bg-[var(--status-success-fg)]":"bg-[var(--theme-fg-muted)]"}`}),e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:t.name})]}),e.jsx("p",{className:"mt-1 font-mono text-xs text-[var(--theme-fg-muted)]",children:t.tokenPreview}),e.jsx("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:t.connected?`Online since ${or(t.connectedAt)}`:`Offline. Last heartbeat: ${or(t.lastHeartbeatAt)}`})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-2",onClick:d,title:m?"Copy relay supervisor setup command":"Device token is not available. Create a new device token for devices created before token storage was enabled.",disabled:!m,type:"button",children:[e.jsx(lt.Copy,{className:"h-4 w-4"}),a?"Copied":"Copy setup"]}),e.jsxs("button",{className:"relay-button-primary inline-flex items-center gap-2",disabled:!t.connected,onClick:n,type:"button",children:[e.jsx(lt.Plug,{className:"h-4 w-4"}),"Connect"]}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-2",disabled:s,onClick:o,type:"button",children:[e.jsx(lt.Trash2,{className:"h-4 w-4"}),"Delete"]})]})]}),m?null:e.jsx("p",{className:"mt-3 rounded-md border border-[var(--theme-border)] bg-[var(--theme-panel)] px-3 py-2 text-xs text-[var(--theme-fg-muted)]",children:"Token not available for this device. Create a new device token to copy a ready-to-run setup command."})]})}function Hd({result:t}){const s=Gr(t.token);return e.jsxs("section",{className:"rounded-lg border border-[var(--theme-accent-border)] bg-[var(--theme-accent-soft)] p-4",children:[e.jsxs("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:["Token created for ",t.device.name]}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:"Store this token now. It will not be shown again."}),e.jsx(ar,{label:"Device token",value:t.token}),e.jsx(ar,{label:"Supervisor command",value:s})]})}function ar({label:t,value:s}){async function a(){var n;try{await((n=navigator.clipboard)==null?void 0:n.writeText(s))}catch{}}return e.jsxs("div",{className:"mt-3",children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between gap-2",children:[e.jsx("p",{className:"text-xs font-medium uppercase tracking-[0.14em] text-[var(--theme-fg-muted)]",children:t}),e.jsxs("button",{className:"relay-button-secondary inline-flex items-center gap-1 px-2 py-1 text-xs",onClick:()=>void a(),type:"button",children:[e.jsx(lt.Copy,{className:"h-3.5 w-3.5"}),"Copy"]})]}),e.jsx("code",{className:"block break-all rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] px-3 py-2 font-mono text-xs text-[var(--theme-fg)]",children:s})]})}function _d({tone:t,children:s}){return e.jsx("div",{className:"rounded-lg border border-[var(--status-danger-border)] bg-[var(--status-danger-bg)] px-3 py-2 text-sm text-[var(--status-danger-fg)]",children:s})}function Gr(t){const s=Bd();return[`REMOTE_CODEX_RELAY_SERVER_URL=${rr(s)} \\`,`REMOTE_CODEX_RELAY_AGENT_TOKEN=${rr(t)} \\`,"remote-codex relay-supervisor"].join(`
6
+ `)}function rr(t){return/^[A-Za-z0-9_./:@%+=,~-]+$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}function Bd(){return typeof window>"u"?"wss://relay.example.com":window.location.origin.replace(/^https:\/\//,"wss://").replace(/^http:\/\//,"ws://")}function or(t){return t?new Date(t).toLocaleString():"never"}function kn(t,s){return t instanceof re?t.payload.message:t instanceof Error?t.message:s}function Kr(){var P,Y;const t=it(),[s,a]=r.useState(null),[n,d]=r.useState(null),[o,m]=r.useState(!0),[h,f]=r.useState(null),[v,A]=r.useState(null);async function g(){m(!0),f(null);try{xs();const c=await Bs();a(c),c.authenticated?d(await Rr()):d(null)}catch(c){f(kn(c,"Unable to load relay portal."))}finally{m(!1)}}r.useEffect(()=>{g()},[]);async function p(){A(null),await g()}async function C(c){const L=await Pr({name:c});A(L),await g()}async function T(c){await Ar(c),await g()}async function R(c){await xl(c),await g()}async function y(c){await gl(c),await g()}async function V(){await Er(),a(await Bs()),d(null),A(null)}function te(c){bn(c),vn(null),t("/workspaces")}function H(c,L){bn(c),vn(L),t(`/threads/${encodeURIComponent(L)}`)}return o?e.jsx(Kn,{children:"Checking relay session..."}):s!=null&&s.authenticated?e.jsx(Kn,{children:e.jsxs("div",{className:"mx-auto flex w-full max-w-6xl flex-col gap-5",children:[e.jsxs("header",{className:"flex flex-col gap-3 border-b border-[var(--theme-border)] pb-5 sm:flex-row sm:items-end sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-fg-muted)]",children:"Relay Portal"}),e.jsx("h1",{className:"mt-2 text-2xl font-semibold text-[var(--theme-fg)]",children:(P=s.user)==null?void 0:P.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:[((Y=s.user)==null?void 0:Y.role)==="admin"?e.jsx(Rt,{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 V(),type:"button",children:"Sign out"})]})]}),h?e.jsx(da,{tone:"danger",children:h}):null,v?e.jsxs(da,{tone:"accent",children:["Device token for ",v.device.name,". Store it on the device as REMOTE_CODEX_RELAY_AGENT_TOKEN. It will not be shown again.",e.jsx("code",{className:"mt-2 block break-all rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] px-3 py-2 font-mono text-xs",children:v.token}),e.jsx("code",{className:"mt-2 block break-all rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] px-3 py-2 font-mono text-xs",children:zd(v.token)})]}):null,e.jsxs("section",{className:"grid gap-4 lg:grid-cols-[minmax(0,1.2fr)_minmax(20rem,0.8fr)]",children:[e.jsxs(Yn,{title:"Devices",description:"Owned devices and sessions shared with you.",children:[e.jsx(Wd,{onCreate:C}),e.jsx("div",{className:"mt-4 divide-y divide-[var(--theme-border)] rounded-lg border border-[var(--theme-border)]",children:n!=null&&n.devices.length?n.devices.map(c=>e.jsxs("div",{className:"flex flex-col gap-3 p-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`h-2.5 w-2.5 rounded-full ${c.connected?"bg-emerald-500":"bg-[var(--theme-fg-muted)]"}`}),e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:c.name})]}),e.jsx("p",{className:"mt-1 font-mono text-xs text-[var(--theme-fg-muted)]",children:c.tokenPreview}),e.jsx("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:c.connected?`Online. Last heartbeat: ${lr(c.lastHeartbeatAt??c.connectedAt)}`:`Offline. Last online: ${lr(c.lastHeartbeatAt??c.connectedAt)}`})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("button",{className:"relay-button-primary",disabled:!c.connected,onClick:()=>te(c.id),type:"button",children:"Open"}),e.jsx("button",{className:"relay-button-secondary",onClick:()=>void T(c.id),type:"button",children:"Delete"})]})]},c.id)):e.jsx("p",{className:"p-3 text-sm text-[var(--theme-fg-muted)]",children:"No devices yet."})}),e.jsxs("div",{className:"mt-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("h3",{className:"text-sm font-semibold text-[var(--theme-fg)]",children:"Shared"}),e.jsx("span",{className:"rounded-full border border-[var(--theme-border)] px-2 py-0.5 text-[11px] text-[var(--theme-fg-muted)]",children:(n==null?void 0:n.sharedWithMe.length)??0})]}),e.jsx("div",{className:"mt-3 space-y-3",children:n!=null&&n.sharedWithMe.length?n.sharedWithMe.map(c=>e.jsx("article",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-3",children:e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate text-sm font-medium text-[var(--theme-fg)]",children:c.label||c.threadId}),e.jsxs("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:[c.ownerUsername," / ",c.deviceName]})]}),e.jsx("button",{className:"relay-button-primary",onClick:()=>H(c.deviceId,c.threadId),type:"button",children:"Continue"})]})},c.id)):e.jsx("p",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-3 text-sm text-[var(--theme-fg-muted)]",children:"No shared sessions."})})]})]}),e.jsx(Yn,{title:"Invite",description:"Share a single thread with another relay user.",children:e.jsx(qd,{devices:(n==null?void 0:n.devices)??[],onShare:R})})]}),e.jsx("section",{children:e.jsx(Yn,{title:"Shared By Me",description:"Active invitations you created.",children:e.jsx("div",{className:"space-y-3",children:n!=null&&n.sharedByMe.length?n.sharedByMe.map(c=>e.jsxs("article",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-surface)] p-3",children:[e.jsx("p",{className:"text-sm font-medium text-[var(--theme-fg)]",children:c.label||c.threadId}),e.jsxs("p",{className:"mt-1 text-xs text-[var(--theme-fg-muted)]",children:["Shared with ",c.targetUsername," on ",c.deviceName]}),e.jsx("button",{className:"relay-button-secondary mt-3",onClick:()=>void y(c.id),type:"button",children:"Revoke"})]},c.id)):e.jsx("p",{className:"text-sm text-[var(--theme-fg-muted)]",children:"No active shares."})})})})]})}):e.jsx(Kn,{children:e.jsx(Fd,{registrationEnabled:(s==null?void 0:s.registrationEnabled)??!0,initialError:h,onAuthenticated:p})})}function Fd({registrationEnabled:t,initialError:s,onAuthenticated:a}){const[n,d]=r.useState("login"),[o,m]=r.useState(""),[h,f]=r.useState(""),[v,A]=r.useState(""),[g,p]=r.useState(""),[C,T]=r.useState(""),[R,y]=r.useState(s),[V,te]=r.useState(!1);async function H(P){P.preventDefault(),te(!0),y(null);try{n==="login"?await ml({identifier:o,password:g}):await hl({email:h,username:v,password:g,registrationPassword:C}),await a()}catch(Y){y(kn(Y,"Unable to authenticate with relay."))}finally{te(!1)}}return e.jsxs("section",{className:"w-full max-w-sm rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-5 shadow-xl shadow-black/10",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-fg-muted)]",children:"Relay Access"}),e.jsx("h1",{className:"mt-2 text-2xl font-semibold text-[var(--theme-fg)]",children:n==="login"?"Sign in":"Create account"}),e.jsxs("form",{className:"mt-5 space-y-4",onSubmit:H,children:[n==="login"?e.jsx(_t,{autoComplete:"username",label:"Email or username",onChange:m,value:o}):e.jsxs(e.Fragment,{children:[e.jsx(_t,{autoComplete:"email",label:"Email",onChange:f,value:h}),e.jsx(_t,{autoComplete:"username",label:"Username",onChange:A,value:v}),e.jsx(_t,{autoComplete:"one-time-code",label:"Registration password",onChange:T,type:"password",value:C})]}),e.jsx(_t,{autoComplete:n==="login"?"current-password":"new-password",label:"Password",onChange:p,type:"password",value:g}),R?e.jsx(da,{tone:"danger",children:R}):null,e.jsx("button",{className:"relay-button-primary h-11 w-full",disabled:V,type:"submit",children:V?"Working...":n==="login"?"Sign in":"Register"})]}),e.jsx("button",{className:"mt-4 text-sm text-[var(--theme-accent-strong)] disabled:text-[var(--theme-fg-muted)]",disabled:n==="login"?!t:!1,onClick:()=>d(n==="login"?"register":"login"),type:"button",children:n==="login"?t?"Create relay account":"Registration is disabled":"Use an existing account"})]})}function Wd({onCreate:t}){const[s,a]=r.useState(""),[n,d]=r.useState(!1),[o,m]=r.useState(null);async function h(f){f.preventDefault(),d(!0),m(null);try{await t(s),a("")}catch(v){m(kn(v,"Unable to create device."))}finally{d(!1)}}return e.jsxs("form",{className:"flex flex-col gap-2 sm:flex-row",onSubmit:h,children:[e.jsx("input",{className:"relay-input min-w-0 flex-1",onChange:f=>a(f.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 qd({devices:t,onShare:s}){const a=r.useMemo(()=>{var y;return((y=t[0])==null?void 0:y.id)??""},[t]),[n,d]=r.useState(a),[o,m]=r.useState(""),[h,f]=r.useState(""),[v,A]=r.useState(""),[g,p]=r.useState(!1),[C,T]=r.useState(null);r.useEffect(()=>{!n&&a&&d(a)},[n,a]);async function R(y){y.preventDefault(),p(!0),T(null);try{await s({targetUsername:o,deviceId:n,threadId:h,...v.trim()?{label:v}:{}}),m(""),f(""),A(""),T("Invitation created.")}catch(V){T(kn(V,"Unable to create invitation."))}finally{p(!1)}}return e.jsxs("form",{className:"space-y-3",onSubmit:R,children:[e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:["Device",e.jsx("select",{className:"relay-input mt-2 w-full",onChange:y=>d(y.target.value),value:n,children:t.map(y=>e.jsx("option",{value:y.id,children:y.name},y.id))})]}),e.jsx(_t,{label:"Username",onChange:m,value:o}),e.jsx(_t,{label:"Thread ID",onChange:f,value:h}),e.jsx(_t,{label:"Label",onChange:A,value:v}),C?e.jsx("p",{className:"text-sm text-[var(--theme-fg-muted)]",children:C}):null,e.jsx("button",{className:"relay-button-primary",disabled:g||!n||!o.trim()||!h.trim(),type:"submit",children:"Invite"})]})}function Kn({children:t}){return e.jsxs("main",{className:"min-h-screen bg-[var(--app-bg)] px-4 py-6 text-[var(--app-fg)] sm:px-6",children:[e.jsx(ga,{}),e.jsx("div",{className:"flex min-h-[calc(100vh-3rem)] items-center justify-center",children:t})]})}function Yn({title:t,description:s,children:a}){return e.jsxs("section",{className:"rounded-lg border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("h2",{className:"text-base font-semibold text-[var(--theme-fg)]",children:t}),e.jsx("p",{className:"mt-1 text-sm text-[var(--theme-fg-muted)]",children:s})]}),a]})}function _t({label:t,value:s,onChange:a,type:n="text",autoComplete:d}){return e.jsxs("label",{className:"block text-sm text-[var(--theme-fg-soft)]",children:[t,e.jsx("input",{autoComplete:d,className:"relay-input mt-2 w-full",onChange:o=>a(o.target.value),type:n,value:s})]})}function da({tone:t,children:s}){return e.jsx("div",{className:`rounded-lg border px-3 py-2 text-sm ${t==="danger"?"border-[var(--status-danger-border)] bg-[var(--status-danger-bg)] text-[var(--status-danger-fg)]":"border-[var(--theme-accent-border)] bg-[var(--theme-accent-soft)] text-[var(--theme-fg)]"}`,children:s})}function zd(t){return`REMOTE_CODEX_RELAY_SERVER_URL=${Vd()} REMOTE_CODEX_RELAY_AGENT_TOKEN=${t} remote-codex relay-supervisor`}function Vd(){return typeof window>"u"?"wss://relay.example.com":window.location.origin.replace(/^https:\/\//,"wss://").replace(/^http:\/\//,"ws://")}function lr(t){return t??"never"}const ir=3,Jd=10,Gd=1e3,Kd=2e3,Zn=5500,Yd=3e3,Xn=0,ms=1,mn=3,Zd=["read-only","workspace-write","danger-full-access"],Xd=[],Qd=[],ec=[],tc={workspace:!0,toolUsage:!1,guide:!1,threadGraph:!1,extensions:!1,defaultTab:"workspace"};function sc(){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 nc(){return e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-4 w-4 fill-none stroke-current",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M4.25 2.25h5.2l2.3 2.3v9.2h-7.5a2 2 0 0 1-2-2v-7.5a2 2 0 0 1 2-2Z"}),e.jsx("path",{d:"M9.25 2.5v2.25h2.25"}),e.jsx("path",{d:"M7 6.75v4"}),e.jsx("path",{d:"m5.45 9.35 1.55 1.55 1.55-1.55"})]})}function hn({status:t}){return e.jsxs("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-4.5 w-4.5 fill-none stroke-current",strokeWidth:"1.4",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M2.5 6.75A8.22 8.22 0 0 1 8 4.5c2.14 0 4.1.8 5.5 2.25"}),e.jsx("path",{d:"M4.75 9a4.95 4.95 0 0 1 6.5 0"}),e.jsx("path",{d:"M6.9 11.3a1.9 1.9 0 0 1 2.2 0"}),t==="connected"?e.jsx("path",{d:"m6.7 13.2.9.9 1.7-2"}):t==="offline"?e.jsx("path",{d:"M3 3l10 10"}):t==="detached"?null:e.jsxs(e.Fragment,{children:[e.jsx("path",{d:"M11.8 11.1a2.2 2.2 0 0 1-1.8 2.7"}),e.jsx("path",{d:"m10.7 11.35 1.3-.55-.55-1.3"})]})]})}function ac(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 rc(){var Ea;const{id:t=""}=ur(),s=it(),a=Bt(),n=ca(),d=r.useRef(""),o=r.useRef(null),m=r.useRef(null),h=r.useRef(null),f=r.useRef(!1),v=r.useRef(null),A=r.useRef(null),g=r.useRef(typeof navigator>"u"?!0:navigator.onLine),p=r.useRef(!1),C=r.useRef(null),T=r.useRef(null),R=r.useRef(0),y=r.useRef(0),V=r.useRef(null),te=r.useRef(null),H=r.useRef(null),P=r.useRef(null),Y=r.useRef(new Set),[c,L]=r.useState(null),[G,E]=r.useState([]),[q,_]=r.useState([]),[ye,xe]=r.useState(null),[D,me]=r.useState(null),[I,le]=r.useState(null),[oe,F]=r.useState(""),[B,z]=r.useState(null),[de,ge]=r.useState(null),st=r.useRef(null),[ht,dt]=r.useState(!0),[kt,Ve]=r.useState(0),[pt,Xe]=r.useState(!0),[ct,Ct]=r.useState(!1),[b,w]=r.useState(!1),[U,Q]=r.useState("chat"),be=n.getThreadPanels().some(l=>l.kind==="terminal");r.useEffect(()=>{st.current=de},[de]);const Le=r.useMemo(()=>({fetchState:zl,createShell:Gl,terminateShell:Kl,updateShell:Yl,connectSocket:gi}),[]),_e=r.useCallback(l=>`/threads/${l}`,[]),Je=r.useCallback(l=>{s(`/threads/${l}`)},[s]),ft=r.useCallback(l=>l?`/threads/new?workspaceId=${encodeURIComponent(l)}`:"/threads/new",[]),Ge=r.useCallback(({threadId:l,path:i})=>`/api/threads/${l}/assets/image?path=${encodeURIComponent(i)}`,[]),[gt,Fe]=r.useState({prompt:"",attachments:[]}),[ut,At]=r.useState(!1),[Ft,Wt]=r.useState(0),[se,ie]=r.useState(0),[ce,he]=r.useState(0),[Ne,Pe]=r.useState(!1),[ne,De]=r.useState(null),[bt,nt]=r.useState(!1),[Ut,xt]=r.useState(!1),[Fs,gs]=r.useState(!1),[bs,vs]=r.useState(null),[Tt,qt]=r.useState("idle"),[vt,ys]=r.useState({status:g.current?"checking":"offline",browserOnline:g.current,healthOk:!1,socketOpen:!1,lastHealthyAt:null}),[je,Ke]=r.useState(null),[zt,It]=r.useState([]),[yt,Qe]=r.useState({status:"idle",data:null,error:null}),[Qt,He]=r.useState({status:"idle",data:null,error:null}),[Ot,Te]=r.useState({status:"idle",data:null,error:null}),[Vt,Ce]=r.useState({status:"idle",data:null,error:null}),[Ae,Ye]=r.useState({status:"idle",data:null,error:null}),[K,ee]=r.useState(!1),[ae,$t]=r.useState(!1),[es,js]=r.useState(()=>new Set),[ts,jt]=r.useState(!1),[Ws,wt]=r.useState(!1),[ws,ss]=r.useState({status:"idle",data:null,error:null}),[at,ns]=r.useState(null),[Jt,Ns]=r.useState(!1),[Gt,ue]=r.useState(null),Kt=((Ea=I==null?void 0:I.hostConfigFiles.find(l=>{var i;return(i=l.roles)==null?void 0:i.includes("mcp")}))==null?void 0:Ea.name)??null,as=r.useCallback(()=>{const l=d.current;d.current="",o.current=null,l&&r.startTransition(()=>{F(i=>i+l)})},[]),Ss=r.useCallback(l=>{d.current+=l,o.current===null&&(o.current=window.requestAnimationFrame(()=>{as()}))},[as]),qs=r.useCallback((l,i)=>{ge(x=>{const N=(x==null?void 0:x.turnId)===l?x.items:[],$=N.findIndex(Se=>Se.id===i.id),Z=qr(N[$],i),fe=$>=0?N.map((Se,Ie)=>Ie===$?Z:Se):[...N,Z];return{turnId:l,items:fe,updatedAt:new Date().toISOString()}})},[]),ks=r.useCallback((l,i,x,N,$)=>{ge(Z=>{const fe=(Z==null?void 0:Z.turnId)===l?Z.items:[],Se=fe.find(We=>We.id===i),Ie=(Se==null?void 0:Se.kind)==="agentMessage"?{...Se,text:`${Se.text}${x}`,sequence:N??Se.sequence??null}:{id:i,createdAt:$??new Date().toISOString(),kind:"agentMessage",text:x,sequence:N},W=fe.findIndex(We=>We.id===i),tt=W>=0?fe.map((We,pe)=>pe===W?Ie:We):[...fe,Ie];return{turnId:l,items:tt,updatedAt:new Date().toISOString()}})},[]),et=r.useCallback(()=>{d.current="",o.current!==null&&(window.cancelAnimationFrame(o.current),o.current=null)},[]);r.useEffect(()=>{Qe({status:"idle",data:null,error:null}),He({status:"idle",data:null,error:null}),Te({status:"idle",data:null,error:null}),Ce({status:"idle",data:null,error:null}),Ye({status:"idle",data:null,error:null}),jt(!1),ss({status:"idle",data:null,error:null})},[t]);const zs=r.useCallback(async()=>{if(t){ss(l=>({status:"loading",data:l.data,error:null}));try{const l=await Fl(t);ss({status:"ready",data:l,error:null})}catch(l){const i=l instanceof re?l.payload.message:"Unable to load export turns.";ss(x=>({status:"failed",data:x.data,error:i}))}}},[t]);async function Cn(l){if(t){ue(null),wt(!0);try{const{blob:i,filename:x}=await ql(t,l),N=URL.createObjectURL(i),$=document.createElement("a");$.href=N,$.download=x,document.body.append($),$.click(),$.remove(),window.setTimeout(()=>URL.revokeObjectURL(N),3e4),jt(!1)}catch(i){const x=i instanceof re?i.payload.message:"Unable to export transcript.";ue(x)}finally{wt(!1)}}}async function Vs(){if(t){Ye(l=>{var i;return{status:"loading",data:l.data??((i=H.current)==null?void 0:i.goal)??null,error:null}});try{const l=await ti(t);Ye({status:"ready",data:l.goal,error:null}),L(i=>i&&(l.goal?{...i,goal:l.goal,goalHistory:cn(i.goalHistory??[],l.goal)}:{...i,goal:l.goal}))}catch(l){Ye(i=>({status:"failed",data:i.data,error:l instanceof re?l.payload.message:"Unable to load goal."}))}}}async function Js(l){if(t){Ye(i=>{var x;return{status:"loading",data:i.data??((x=H.current)==null?void 0:x.goal)??null,error:null}});try{const i=await si(t,l);Ye({status:"ready",data:i.goal,error:null}),L(x=>x&&(i.goal?{...x,goal:i.goal,goalHistory:cn(x.goalHistory??[],i.goal)}:{...x,goal:i.goal}))}catch(i){throw Ye(x=>({status:"failed",data:x.data,error:i instanceof re?i.payload.message:"Unable to update goal."})),i}}}async function Tn(){if(t){Ye(l=>{var i;return{status:"loading",data:l.data??((i=H.current)==null?void 0:i.goal)??null,error:null}});try{const l=await ni(t);Ye({status:"ready",data:null,error:null}),L(i=>i&&(l.goalHistory?{...i,goal:null,goalHistory:l.goalHistory}:{...i,goal:null}))}catch(l){throw Ye(i=>({status:"failed",data:i.data,error:l instanceof re?l.payload.message:"Unable to clear goal."})),l}}}async function Gs(l){$t(!0);try{await Js({status:l})}finally{$t(!1)}}async function Ks(){$t(!0);try{await Tn()}finally{$t(!1)}}async function In(){if(t){Qe(l=>({status:"loading",data:l.data,error:null}));try{const l=await ri(t);Qe({status:"ready",data:l,error:null})}catch(l){Qe(i=>({status:"failed",data:i.data,error:l instanceof re?l.payload.message:"Unable to load skills."}))}}}async function En(){if(t){He(l=>({status:"loading",data:l.data,error:null}));try{const l=await oi(t);He({status:"ready",data:l,error:null})}catch(l){He(i=>({status:"failed",data:i.data,error:l instanceof re?l.payload.message:"Unable to load MCP servers."}))}}}async function Rn(){if(t){Te(l=>({status:"loading",data:l.data,error:null}));try{const l=await li(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 Ze(l){if(t){Te(i=>({status:"loading",data:i.data,error:null}));try{const i=await ii(t,l);Te({status:"ready",data:i,error:null})}catch(i){throw Te(x=>({status:"failed",data:x.data,error:i instanceof re?i.payload.message:"Unable to create hook."})),i}}}async function Cs(l){if(t){Te(i=>({status:"loading",data:i.data,error:null}));try{const i=await di(t,l);Te({status:"ready",data:i,error:null})}catch(i){throw Te(x=>({status:"failed",data:x.data,error:i instanceof re?i.payload.message:"Unable to update hook."})),i}}}async function Ys(l){if(t){Te(i=>({status:"loading",data:i.data,error:null}));try{const i=await ci(t,l);Te({status:"ready",data:i,error:null})}catch(i){throw Te(x=>({status:"failed",data:x.data,error:i instanceof re?i.payload.message:"Unable to trust hook."})),i}}}async function Nt(l){if(t){Te(i=>({status:"loading",data:i.data,error:null}));try{const i=await ui(t,l);Te({status:"ready",data:i,error:null})}catch(i){throw Te(x=>({status:"failed",data:x.data,error:i instanceof re?i.payload.message:"Unable to untrust hook."})),i}}}async function St(){if(t){Ce(l=>({status:"loading",data:l.data,error:null}));try{const l=await ai(t);Ce({status:"ready",data:l,error:null})}catch(l){Ce(i=>({status:"failed",data:i.data,error:l instanceof re?l.payload.message:"Unable to load turns for forking."}))}}}async function Pn(){if(!t)return;const l=await qa(t,{mode:"latest"});E(i=>Ls(i,l.thread.thread)),s(`/threads/${l.thread.thread.id}`)}async function An(l){if(!t)return;const i=await qa(t,{mode:"turn",turnId:l});E(x=>Ls(x,i.thread.thread)),s(`/threads/${i.thread.thread.id}`)}const Zs=r.useCallback(l=>{const i=P.current,x=i&&Object.keys(i).length>0?{...l,thread:{...l.thread,...i}}:l,N={...x,turns:nd(x.turns,st.current)},$=H.current;H.current=N,z(N.livePlan??null);const Z=$?Ht($.turns,N.turns):N.turns;ge(W=>ld(W,N.liveItems??null,Z)),Ye(W=>W.status==="idle"?W:{...W,data:N.goal??null});const fe=N.thread.activeTurnId===null&&N.thread.status!=="running";L(W=>W&&!N.goalHistory?{...N,turns:Ht(W.turns,N.turns),pendingRequests:ia(W.pendingRequests,N.pendingRequests,Y.current),...W.goalHistory?{goalHistory:W.goalHistory}:{}}:W?{...N,turns:Ht(W.turns,N.turns),pendingRequests:ia(W.pendingRequests,N.pendingRequests,Y.current)}:N),E(W=>Ls(W,N.thread));const Se=new Map(N.turns.map(W=>[W.id,W])),Ie=new Set((N.pendingSteers??[]).map(W=>W.clientRequestId).filter(W=>!!W));It(W=>W.filter(tt=>{if(Ie.has(tt.clientRequestId))return!1;const We=Se.get(tt.turnId);return!(!We||Hs(We,tt.prompt)||N.thread.activeTurnId!==tt.turnId&&We.status!=="inProgress")})),Ke(W=>{if(!W)return W;const tt=W.serverTurnId??W.id,We=N.turns.some(J=>J.id===tt),pe=Se.get(tt)??null,j=hd(N.turns,W.prompt),M=!!j;if(j&&!W.serverTurnId)return{...W,id:j.id,serverTurnId:j.id,status:W.status==="failed"?W.status:j.status==="inProgress"?"inProgress":W.status};if(pe&&W.serverTurnId)return Hs(pe,W.prompt)||W.prompt.includes("[PHOTO ")&&(gn(pe,W.prompt)||Fn(pe))?pe.status==="inProgress"?{...W,id:pe.id,serverTurnId:pe.id,status:W.status==="failed"?W.status:"inProgress"}:null:{...W,id:pe.id,serverTurnId:pe.id,status:W.status==="failed"?W.status:"inProgress"};if(!W.serverTurnId&&W.prompt.includes("[PHOTO ")&&N.thread.activeTurnId&&N.thread.status==="running"){const J=Se.get(N.thread.activeTurnId);if(J&&Fn(J))return{...W,id:J.id,serverTurnId:J.id,status:W.status==="failed"?W.status:"inProgress"}}return We||fe&&M?null:W}),(fe||te.current&&N.turns.some(W=>W.id===te.current))&&(te.current=null,et(),F(""),z(null),ge(null))},[et]);r.useEffect(()=>{H.current=c},[c]);const Xs=r.useCallback(async({seedThread:l}={})=>{var fe;const i=y.current+1;y.current=i;const x=(l==null?void 0:l.provider)??((fe=H.current)==null?void 0:fe.thread.provider)??"codex",[N,$,Z]=await Promise.allSettled([Mr(),Ur(x),oa(x)]);y.current===i&&(N.status==="fulfilled"?E(l?Ls(N.value,l):N.value):l&&E(Se=>Ls(Se,l)),$.status==="fulfilled"&&(V.current=x,xe($.value.status),me($.value.capabilities),le($.value.managementSchema)),Z.status==="fulfilled"&&(V.current=x,_(Z.value)))},[]),Mt=r.useCallback(async({showLoading:l=!0,clearError:i=!0,reportError:x=!0,limit:N=ir}={})=>{const $=R.current+1;R.current=$,l&&Xe(!0),i&&ue(null);try{const Z=await Ba(t,{limit:N});if(R.current!==$)return;Zs(Z),V.current!==Z.thread.provider&&Xs({seedThread:Z.thread})}catch(Z){if(R.current!==$||!x)return;ue(Z instanceof Error?Z.message:"Unable to load thread detail.")}finally{R.current===$&&Xe(!1)}},[Zs,t,Xs]),Be=r.useCallback(()=>{var Se;const l=((Se=m.current)==null?void 0:Se.readyState)??mn,i=l===ms,x=g.current,N=Date.now(),$=v.current!==null&&N-Date.parse(v.current)<=Zn,Z=A.current!==null&&N-A.current<=Zn;let fe;x?i&&Z?fe="connected":l===Xn||h.current!==null||$||Z||f.current?fe="reconnecting":fe="checking":fe="offline",ys(Ie=>Ie.status===fe&&Ie.browserOnline===x&&Ie.healthOk===$&&Ie.socketOpen===i&&Ie.lastHealthyAt===v.current?Ie:{status:fe,browserOnline:x,healthOk:$,socketOpen:i,lastHealthyAt:v.current})},[]);r.useEffect(()=>{R.current+=1,y.current+=1,L(null),Fe({prompt:"",attachments:[]}),Ct(!1),qt("idle"),Ke(null),It([]),ge(null),P.current=null,te.current=null,Y.current=new Set,v.current=null,A.current=null,p.current=!1,g.current=typeof navigator>"u"?!0:navigator.onLine,ys({status:g.current?"checking":"offline",browserOnline:g.current,healthOk:!1,socketOpen:!1,lastHealthyAt:null})},[t]),r.useEffect(()=>{if(Tt==="idle")return;const l=window.setTimeout(()=>{qt("idle")},Tt==="copied"?1200:1600);return()=>{window.clearTimeout(l)}},[Tt]),r.useEffect(()=>{if(typeof document>"u")return;const{documentElement:l,body:i}=document;return l.classList.add("thread-detail-scroll-locked"),i.classList.add("thread-detail-scroll-locked"),()=>{l.classList.remove("thread-detail-scroll-locked"),i.classList.remove("thread-detail-scroll-locked")}},[]),r.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const l=window.matchMedia("(max-width: 639px)"),i=()=>At(l.matches);return i(),l.addEventListener("change",i),()=>{l.removeEventListener("change",i)}},[]),r.useEffect(()=>{var i,x;if(typeof window>"u")return;const l=()=>{const N=window.visualViewport,$=N?Math.max(0,Math.round(window.innerHeight-N.height-N.offsetTop)):0;he($),document.documentElement.style.setProperty("--thread-detail-keyboard-inset",`${$}px`)};return l(),(i=window.visualViewport)==null||i.addEventListener("resize",l),(x=window.visualViewport)==null||x.addEventListener("scroll",l),window.addEventListener("resize",l),()=>{var N,$;(N=window.visualViewport)==null||N.removeEventListener("resize",l),($=window.visualViewport)==null||$.removeEventListener("scroll",l),window.removeEventListener("resize",l),document.documentElement.style.removeProperty("--thread-detail-keyboard-inset")}},[]),r.useEffect(()=>{if(typeof document>"u")return;const l=()=>{const i=document.activeElement,x=T.current,N=x==null?void 0:x.querySelector('[aria-label="Prompt"]');Pe(!!(i&&N&&(i===N||N.contains(i))))};return l(),document.addEventListener("focusin",l),document.addEventListener("focusout",l),()=>{document.removeEventListener("focusin",l),document.removeEventListener("focusout",l)}},[U,c==null?void 0:c.thread.id,ut]),r.useEffect(()=>{const l=T.current;if(!l||typeof ResizeObserver>"u")return;const i=l.querySelector("form")??l,x=()=>{Wt(Math.max(l.getBoundingClientRect().height,i.getBoundingClientRect().height))};x();const N=new ResizeObserver(()=>{x()});return N.observe(i),()=>{N.disconnect()}},[U,ut]),r.useEffect(()=>{var N,$;const l=T.current;if(!l||!ut||U!=="chat"){ie(0);return}const i=()=>{const Z=l.getBoundingClientRect();ie(Math.max(0,Math.ceil(window.innerHeight-Z.top)))};i(),window.addEventListener("resize",i),(N=window.visualViewport)==null||N.addEventListener("resize",i),($=window.visualViewport)==null||$.addEventListener("scroll",i);let x=null;return typeof ResizeObserver<"u"&&(x=new ResizeObserver(i),x.observe(l)),()=>{var Z,fe;window.removeEventListener("resize",i),(Z=window.visualViewport)==null||Z.removeEventListener("resize",i),(fe=window.visualViewport)==null||fe.removeEventListener("scroll",i),x==null||x.disconnect()}},[U,c==null?void 0:c.thread.id,ut,ce,Ne]),r.useEffect(()=>{Mt({showLoading:!0,limit:ir})},[Mt]),r.useEffect(()=>{let l=!1,i=null;const x=()=>{Mt({showLoading:!1,clearError:!1,reportError:!1})},N=()=>{h.current!==null&&(window.clearTimeout(h.current),h.current=null)},$=()=>{l||!g.current||h.current!==null||(h.current=window.setTimeout(()=>{h.current=null,!l&&Ie()},Gd),Be())},Z=()=>{const j=m.current;if(m.current=null,j)try{j.close()}catch{}},fe=j=>{if(j.threadId===t){if(j.type==="thread.output.delta"&&typeof j.payload.delta=="string"){const M=typeof j.payload.turnId=="string"?j.payload.turnId:null,J=typeof j.payload.itemId=="string"?j.payload.itemId:null,Ee=typeof j.payload.sequence=="number"&&Number.isFinite(j.payload.sequence)?j.payload.sequence:null;M&&J?ks(M,J,j.payload.delta,Ee,j.payload.createdAt??j.timestamp):Ss(j.payload.delta),M&&Ke(ve=>ve&&(ve.serverTurnId===null||ve.serverTurnId===M)?{...ve,serverTurnId:M,id:M,status:ve.status==="failed"?ve.status:"inProgress",tokenUsage:ve.tokenUsage}:ve)}if(j.type==="thread.context.updated"){const M=j.payload.contextUsage&&typeof j.payload.contextUsage=="object"?j.payload.contextUsage:null;if(M){const J=M;L(Ee=>Ee&&{...Ee,thread:{...Ee.thread,contextUsage:J}}),E(Ee=>Ee.map(ve=>ve.id===t?{...ve,contextUsage:J}:ve))}}if(j.type==="thread.turn.token.updated"&&typeof j.payload.turnId=="string"&&j.payload.tokenUsage&&typeof j.payload.tokenUsage=="object"){const M=j.payload.turnId,J=j.payload.tokenUsage,Ee=j.payload.priceEstimate&&typeof j.payload.priceEstimate=="object"?j.payload.priceEstimate:null;L(ve=>{if(!ve)return ve;const rt=pd(ve.turns,M,J,Ee);return rt===ve.turns?ve:{...ve,turns:rt}}),Ke(ve=>ve&&(ve.serverTurnId===M||ve.id===M)?{...ve,tokenUsage:J,priceEstimate:Ee}:ve)}if(j.type==="thread.turn.started"||j.type==="thread.turn.completed"||j.type==="thread.turn.failed"||j.type==="thread.updated"||j.type==="thread.goal.updated"||j.type==="thread.goal.cleared"||j.type==="thread.request.created"||j.type==="thread.request.resolved"){if(j.type==="thread.goal.updated"){const M=j.payload.goal&&typeof j.payload.goal=="object"?j.payload.goal:null,J=Array.isArray(j.payload.goalHistory)?j.payload.goalHistory:null;Ye({status:"ready",data:M,error:null}),L(Ee=>Ee&&(J?{...Ee,goal:M,goalHistory:J}:M?{...Ee,goal:M,goalHistory:cn(Ee.goalHistory??[],M)}:{...Ee,goal:M}))}if(j.type==="thread.goal.cleared"){const M=Array.isArray(j.payload.goalHistory)?j.payload.goalHistory:null;Ye({status:"ready",data:null,error:null}),L(J=>J&&(M?{...J,goal:null,goalHistory:M}:{...J,goal:null}))}if(x(),j.type==="thread.turn.started"){et(),F(""),ge(null),te.current=null;const M=typeof j.payload.turnId=="string"?j.payload.turnId:null;M&&Ke(J=>J&&{...J,serverTurnId:M,id:M,status:J.status==="failed"?J.status:"inProgress",error:null,tokenUsage:J.tokenUsage})}if(j.type==="thread.turn.completed"||j.type==="thread.turn.failed"){et(),F("");const M=typeof j.payload.turnId=="string"?j.payload.turnId:null;M&&(te.current=M,j.type==="thread.turn.failed"&&Ke(J=>J&&(J.serverTurnId===M||J.id===M)?{...J,status:"failed",error:typeof j.payload.error=="string"?j.payload.error:"Unable to complete the turn.",tokenUsage:J.tokenUsage}:J))}}if(j.type==="thread.request.created"&&od(j.payload.request)&&(Y.current.delete(j.payload.request.id),L(M=>M&&ad(M,j.payload.request))),j.type==="thread.request.resolved"&&typeof j.payload.requestId=="string"){const M=j.payload.requestId;Y.current.add(M),L(J=>J&&rd(J,M))}if((j.type==="thread.item.started"||j.type==="thread.item.completed")&&j.payload.item&&typeof j.payload.item=="object"&&typeof j.payload.turnId=="string"){const M=j.payload.turnId,J=j.payload.item;typeof J.id=="string"&&typeof J.text=="string"&&qs(M,J)}j.type==="thread.plan.updated"&&Array.isArray(j.payload.plan)&&z({turnId:String(j.payload.turnId??""),explanation:typeof j.payload.explanation=="string"?j.payload.explanation:null,plan:j.payload.plan})}},Se=()=>{const j=m.current;if(!(!j||j.readyState!==ms))try{j.send(JSON.stringify({type:"supervisor.ping",timestamp:new Date().toISOString()}))}catch{p.current=!0,Z(),$(),Be()}},Ie=()=>{var J;if(l||!g.current){Be();return}const j=((J=m.current)==null?void 0:J.readyState)??mn;if(j===Xn||j===ms){Be();return}const M=Hr(fe);m.current=M,Be(),M.addEventListener("message",Ee=>{if(m.current===M)try{const ve=JSON.parse(Ee.data);(ve.type==="supervisor.connected"||ve.type==="supervisor.pong")&&(A.current=Date.now(),Be())}catch{}}),M.addEventListener("open",()=>{m.current===M&&(p.current=!0,x(),Se(),Be())}),M.addEventListener("close",()=>{m.current===M&&(m.current=null),p.current=!0,$(),Be()}),M.addEventListener("error",()=>{m.current===M&&(m.current=null),p.current=!0,$(),Be()})},W=async()=>{var j;if(!(l||!g.current||f.current)){f.current=!0,Be();try{await Rl();const M=p.current;v.current=new Date().toISOString(),M&&(p.current=!1,x()),(((j=m.current)==null?void 0:j.readyState)??mn)!==ms&&Ie()}catch{v.current=null,p.current=!0,$()}finally{f.current=!1,Be()}}},tt=()=>{g.current=!0,p.current=!0,Be(),Ie(),W()},We=()=>{g.current=!1,v.current=null,A.current=null,p.current=!0,N(),Z(),Be()},pe=()=>{var J;if(l||!g.current){Be();return}const j=((J=m.current)==null?void 0:J.readyState)??mn,M=A.current===null?null:Date.now()-A.current;j===ms&&M!==null&&M>Zn?(p.current=!0,Z(),$()):j===ms?Se():j!==Xn&&Ie(),W(),Be()};return window.addEventListener("online",tt),window.addEventListener("offline",We),Ie(),W(),i=window.setInterval(pe,Kd),()=>{l=!0,window.removeEventListener("online",tt),window.removeEventListener("offline",We),N(),i!==null&&window.clearInterval(i),et(),Z()}},[ks,et,t,Mt,Ss,Be,qs]),r.useEffect(()=>{if(!((c==null?void 0:c.thread.activeTurnId)!==null||(c==null?void 0:c.thread.status)==="running"||je!==null||zt.length>0||oe.length>0||B!==null||de!==null))return;const i=window.setInterval(()=>{Mt({showLoading:!1,clearError:!1,reportError:!1})},Yd);return()=>{window.clearInterval(i)}},[c==null?void 0:c.thread.activeTurnId,c==null?void 0:c.thread.status,oe.length,de,B,Mt,zt.length,je]);const Qs=r.useCallback(async()=>{var l;if(!(!c||c.turns.length===0||ct)){Ct(!0),ue(null);try{const i=(l=c.turns[0])==null?void 0:l.id,x=await Ba(t,{limit:Jd,...i?{beforeTurnId:i}:{}});L(N=>N?{...x,turns:sd(N.turns,x.turns)}:x),E(N=>N.map($=>$.id===x.thread.id?x.thread:$))}catch(i){ue(i instanceof Error?i.message:"Unable to load earlier turns.")}finally{Ct(!1)}}},[c,t,ct]);async function en(l){var W,tt,We;if(U==="shell"){if((c==null?void 0:c.thread.isLoaded)===!1)return await Ts({attachShell:!0}),!1;let pe=!1;if((ne==null?void 0:ne.shellInputEnabled)!==!0&&((ne==null?void 0:ne.loading)===!1&&(ne==null?void 0:ne.isConnecting)!==!0&&(ne==null?void 0:ne.status)!=="creating"&&(ne==null?void 0:ne.status)!=="workspace_missing"&&(await((W=C.current)==null?void 0:W.toggleConnection()),pe=!0),(ne==null?void 0:ne.isConnecting)===!0))return ue("Connecting to the shell. Try again after it attaches."),!1;if(((tt=C.current)==null?void 0:tt.sendCommand(l.prompt))??!1)ue(null);else return ue(pe?"Shell is still attaching. Try again after it connects.":"Connect the shell before sending commands."),!1;return!0}w(!0),ue(null),Ve(pe=>pe+1);const i=H.current,x=i?{...i.thread,...P.current??{}}:null,N=(x==null?void 0:x.model)??null,$=(x==null?void 0:x.reasoningEffort)??null,Z=md(),fe=`optimistic-${Date.now()}`,Se=`optimistic-steer-${Z}`,Ie=new Date().toISOString();try{let pe=H.current;if(pe&&!pe.thread.isLoaded){const Re={...pe.thread,...P.current??{}},mt=await Fa(t,{...pe.thread.model?{model:pe.thread.model}:{},...pe.thread.sandboxMode?{sandboxMode:pe.thread.sandboxMode}:{}}),ot={...mt,thread:{...mt.thread,model:Re.model??mt.thread.model,reasoningEffort:Re.reasoningEffort??mt.thread.reasoningEffort,collaborationMode:Re.collaborationMode??mt.thread.collaborationMode,sandboxMode:Re.sandboxMode??mt.thread.sandboxMode??null}};pe=ot,H.current=ot,L(an=>an?{...ot,turns:Ht(an.turns,ot.turns)}:ot),E(an=>an.map(Ra=>Ra.id===ot.thread.id?ot.thread:Ra))}const j=pe?{...pe.thread,...P.current??{}}:null,M=(j==null?void 0:j.status)==="running"?j.activeTurnId:null,J=U==="chat"&&!!M;J&&M?It(Re=>[...Re,{id:Se,clientRequestId:Z,turnId:M,prompt:l.prompt,createdAt:Ie,status:"steering"}]):(et(),F(""),Ke({id:fe,serverTurnId:null,startedAt:Ie,status:"sending",error:null,prompt:l.prompt,model:N,reasoningEffort:$,reasoningEffortAvailable:Qa(q,N),tokenUsage:null,priceEstimate:null}));const Ee={prompt:l.prompt,clientRequestId:Z,...j!=null&&j.model?{model:j.model}:{},...j!=null&&j.reasoningEffort?{reasoningEffort:j.reasoningEffort}:{},...j!=null&&j.collaborationMode?{collaborationMode:j.collaborationMode}:{},...j!=null&&j.sandboxMode?{sandboxMode:j.sandboxMode}:{},...(We=l.attachments)!=null&&We.length?{attachments:l.attachments}:{}},ve=await Xl(t,Ee),rt=P.current&&Object.keys(P.current).length>0?{...ve,...P.current}:ve;L(Re=>Re&&{...Re,thread:rt}),E(Re=>Re.map(mt=>mt.id===rt.id?rt:mt)),J&&M?rt.activeTurnId!==null&&rt.activeTurnId!==M&&rt.lastTurnStartedAt!==(j==null?void 0:j.lastTurnStartedAt)?(et(),F(""),z(null),It(mt=>mt.filter(ot=>ot.id!==Se)),Ke({id:fe,serverTurnId:rt.activeTurnId,startedAt:rt.lastTurnStartedAt??Ie,status:"inProgress",error:null,prompt:l.prompt,model:N,reasoningEffort:$,reasoningEffortAvailable:Qa(q,N),tokenUsage:null,priceEstimate:null})):It(mt=>mt.map(ot=>ot.id===Se?{...ot,turnId:rt.activeTurnId??ot.turnId,status:"accepted"}:ot)):(Ke(Re=>Re&&Re.id===fe?{...Re,id:rt.activeTurnId??Re.id,serverTurnId:rt.activeTurnId??Re.serverTurnId,status:"inProgress",error:null,tokenUsage:Re.tokenUsage,priceEstimate:Re.priceEstimate}:Re),z(null)),Fe({prompt:"",attachments:[]})}catch(pe){const j=pe instanceof re?pe.payload.message:pe instanceof Error?pe.message:"Unable to send prompt.";pe instanceof re?ue(pe.payload.message):ue(j),It(M=>M.filter(J=>J.clientRequestId!==Z)),Ke(M=>M&&M.id===fe?{...M,status:"failed",error:j}:M)}finally{w(!1)}}async function rs(){const l=c==null?void 0:c.thread.providerSessionId;if(l)try{await navigator.clipboard.writeText(l),qt("copied")}catch{qt("failed")}}async function Ts(l){if(c){w(!0),ue(null),et(),F("");try{if(c.thread.isLoaded){const x=await Zl(t);L(N=>N?{...x,turns:Ht(N.turns,x.turns)}:x),De(null),E(N=>N.map($=>$.id===x.thread.id?x.thread:$)),nt(!1);return}const i=await Fa(t,{...c.thread.model?{model:c.thread.model}:{},...c.thread.sandboxMode?{sandboxMode:c.thread.sandboxMode}:{}});L(x=>x?{...i,turns:Ht(x.turns,i.turns)}:i),E(x=>x.map(N=>N.id===i.thread.id?i.thread:N)),l!=null&&l.attachShell&&U==="shell"&&nt(!0)}catch(i){ue(i instanceof Error?i.message:"Unable to change connection state.")}finally{w(!1)}}}async function os(){var l;if(U==="shell"){const i=((l=C.current)==null?void 0:l.sendControl("ctrl_c"))??!1;ue(i?null:"Connect the shell before sending Ctrl-C.");return}w(!0),ue(null);try{const i=c!=null&&c.thread.activeTurnId?await Wa(t,{turnId:c.thread.activeTurnId}):await Wa(t);L(x=>x&&{...x,thread:i}),E(x=>x.map(N=>N.id===i.id?i:N)),et(),F("")}catch(i){ue(i instanceof Error?i.message:"Unable to interrupt turn.")}finally{w(!1)}}async function Lt(l){if(!c)return;const i=c,x={...P.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}:{}},N={...c.thread,...x};xt(!0),P.current=x,H.current={...c,thread:N},L($=>$&&{...$,thread:N}),E($=>$.map(Z=>Z.id===N.id?{...Z,...N}:Z));try{const $=await Ql(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}:{}});P.current=null,H.current=i?{...i,thread:$}:null,L(Z=>Z&&{...Z,thread:$}),E(Z=>Z.map(fe=>fe.id===$.id?$:fe))}catch($){P.current=null,H.current=i,L(i),E(Z=>Z.map(fe=>fe.id===i.thread.id?i.thread:fe)),ue($ instanceof Error?$.message:"Unable to update thread settings.")}finally{xt(!1)}}const tn=r.useCallback(async(l,i)=>{vs(l),ue(null);try{const x=await mi(t,l,i);L(N=>N?{...x,turns:Ht(N.turns,x.turns)}:x),z(x.livePlan??null),ge(x.liveItems??null)}catch(x){ue(x instanceof Error?x.message:"Unable to answer this request.")}finally{vs(null)}},[t]),ls=r.useCallback(l=>Ll(t,l),[t]);async function Is(){if(c){gs(!0),ue(null);try{const l=await ei(t);L(i=>i&&{...i,thread:l}),E(i=>i.map(x=>x.id===l.id?l:x))}catch(l){ue(l instanceof Error?l.message:"Unable to compact this thread context.")}finally{gs(!1)}}}async function Es(l,i){try{const x=await Lr(l,{title:i});E(N=>N.map($=>$.id===x.id?{...$,title:x.title,updatedAt:x.updatedAt}:$)),L(N=>N&&N.thread.id===x.id?{...N,thread:{...N.thread,title:x.title,updatedAt:x.updatedAt}}:N)}catch(x){throw ue(x instanceof Error?x.message:"Unable to rename thread."),x}}async function Rs(){if(at){Ns(!0),ue(null);try{await Dr(at.id),E(i=>i.filter(x=>x.id!==at.id));const l=at.id===(c==null?void 0:c.thread.id);if(ns(null),l){const i=G.find(x=>x.id!==at.id&&x.workspaceId===(c==null?void 0:c.thread.workspaceId))??G.find(x=>x.id!==at.id);s(i?`/threads/${i.id}`:"/threads")}}catch(l){ue(l instanceof Error?l.message:"Unable to delete thread.")}finally{Ns(!1)}}}function Dt(){Q(l=>l==="chat"?(c!=null&&c.thread.isLoaded&&nt(!0),"shell"):"chat")}async function is(){var i;const l=await((i=C.current)==null?void 0:i.copyLastCommandOutput());ue(l?null:"Unable to copy the last shell command output.")}function sn(l){var x,N;const i=l==="clear"?((x=C.current)==null?void 0:x.sendCommand("clear"))??!1:((N=C.current)==null?void 0:N.sendControl(l))??!1;ue(i?null:"Connect the shell before sending control input.")}r.useEffect(()=>{if(!(!bt||U!=="shell"||!C.current||(c==null?void 0:c.thread.isLoaded)===!1||(ne==null?void 0:ne.loading)!==!1)){if((ne==null?void 0:ne.status)==="attached"){nt(!1);return}nt(!1),C.current.toggleConnection()}},[U,c==null?void 0:c.thread.isLoaded,bt,ne==null?void 0:ne.loading,ne==null?void 0:ne.status]),r.useEffect(()=>{if(U!=="shell")return;const l=window.requestAnimationFrame(()=>{var i;(i=C.current)==null||i.refreshLayout({syncBackendSize:!1})});return()=>{window.cancelAnimationFrame(l)}},[U]);const Ps=c&&c.workspacePathStatus==="missing"?"Restore this workspace path on the current machine before continuing.":null,As=ut&&U==="chat",Us=As&&Ne?ce:0,Un=Math.max(Ft,144),On=Math.max(se,Un+Us),Os=As?On+12:0,nn=c?e.jsxs("dl",{className:"space-y-4 text-sm",children:[e.jsxs("div",{className:"relative pr-9",children:[e.jsx("dt",{className:"text-[var(--theme-fg-muted)]",children:"Session ID"}),e.jsx("dd",{className:"mt-1 break-all text-[var(--theme-fg)]",children:c.thread.providerSessionId??"Unavailable"}),c.thread.providerSessionId&&e.jsx("button",{type:"button","aria-label":"Copy session ID",title:Tt==="copied"?"Copied":Tt==="failed"?"Copy failed":"Copy session ID",onClick:()=>void rs(),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 ${Tt==="copied"?"ui-status-info":Tt==="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(sc,{})})})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[var(--theme-fg-muted)]",children:"Source"}),e.jsx("dd",{className:"mt-1 text-[var(--theme-fg)]",children:c.thread.source==="local_codex_import"?`Imported local ${c.thread.provider} session`:`${c.thread.provider} supervisor thread`})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[var(--theme-fg-muted)]",children:"Status"}),e.jsx("dd",{className:"mt-1 text-[var(--theme-fg)]",children:fr(c.thread.status)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[var(--theme-fg-muted)]",children:"Created"}),e.jsx("dd",{className:"mt-1 text-[var(--theme-fg)]",children:ps(c.thread.createdAt)})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[var(--theme-fg-muted)]",children:"Workspace"}),e.jsx("dd",{className:"mt-1 break-words text-[var(--theme-fg)]",children:c.workspace.absPath})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[var(--theme-fg-muted)]",children:"Workspace path"}),e.jsx("dd",{className:"mt-1 text-[var(--theme-fg)]",children:c.workspacePathStatus==="present"?"Present":"Missing on this machine"})]}),e.jsxs("div",{children:[e.jsx("dt",{className:"text-[var(--theme-fg-muted)]",children:"Active turn"}),e.jsx("dd",{className:"mt-1 text-[var(--theme-fg)]",children:c.thread.activeTurnId??"None"})]})]}):null,u=c&&(D!=null&&D.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:Zd.map(l=>{const i=td(c.thread)===l;return e.jsx("button",{type:"button",disabled:Ut,onClick:()=>void Lt({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,S=(je==null?void 0:je.serverTurnId)??null,k=je&&c?c.turns.find(l=>(Hs(l,je.prompt)||je.prompt.includes("[PHOTO ")&&(gn(l,je.prompt)||Fn(l)))&&(S&&l.id===S||l.id===je.id||Hs(l,je.prompt)||je.prompt.includes("[PHOTO ")&&gn(l,je.prompt)))??null:null,X=r.useMemo(()=>je&&!k?{id:je.id,startedAt:je.startedAt,status:je.status,error:je.error,model:je.model,reasoningEffort:je.reasoningEffort,reasoningEffortAvailable:je.reasoningEffortAvailable,tokenUsage:je.tokenUsage,priceEstimate:je.priceEstimate,items:[{id:`${je.id}-user-message`,kind:"userMessage",text:je.prompt}]}:null,[k,je]),Oe=(c==null?void 0:c.thread.isLoaded)??!1,$e=Oe?vt.status==="connected"?"ui-action-success shadow-lg shadow-stone-950/20":vt.status==="reconnecting"?"thread-live-connection-reconnecting ui-status-success shadow-lg shadow-stone-950/20":vt.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",Yt=ac(Oe,vt),ds=[Yt,Oe?null:"Tap to connect this thread",vt.lastHealthyAt?`Last healthy ${ps(vt.lastHealthyAt)}`:null].filter(Boolean).join(" · "),so=Oe?e.jsx("div",{role:"status","aria-live":"polite","aria-label":Yt,title:ds,className:`inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition ${$e}`,children:e.jsx(hn,{status:vt.status})}):e.jsx("button",{type:"button",onClick:()=>void Ts(),disabled:b||!c,"aria-label":b?"Connecting thread":"Connect thread",title:b?"Connecting thread":ds,className:`inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full transition ${$e}`,children:e.jsx(hn,{status:"detached"})}),no=Oe?e.jsx("div",{title:ds,className:`hidden lg:inline-flex h-9 w-9 items-center justify-center rounded-full transition ${$e}`,children:e.jsx(hn,{status:vt.status})}):e.jsx("button",{type:"button",onClick:()=>void Ts(),disabled:b||!c,title:b?"Connecting thread":ds,className:`hidden lg:inline-flex h-9 w-9 items-center justify-center rounded-full transition ${$e}`,children:e.jsx(hn,{status:"detached"})}),va=Ae.data??(c==null?void 0:c.goal)??null,ya=(c==null?void 0:c.goalHistory)??[],ja=va?cn(ya,va):zr(ya),wa=(D==null?void 0:D.controls.goals)??!1,ao=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"})]}),ro=K&&wa?e.jsxs("div",{className:"host-dialog w-96 max-w-[calc(100vw-1.5rem)] rounded-3xl border p-3 text-left shadow-2xl shadow-black/20 backdrop-blur-xl",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"host-page-title text-sm font-semibold",children:"Goal monitor"}),e.jsx("p",{className:"host-muted text-xs",children:"Current thread only"})]}),e.jsx("button",{type:"button",onClick:()=>ee(!1),className:"host-secondary-button rounded-full border px-2.5 py-1 text-xs transition",children:"Close"})]}),Ae.error?e.jsx("p",{className:"host-error mt-3 rounded-2xl border px-3 py-2 text-xs",children:Ae.error}):null,e.jsx("div",{className:"mt-3 max-h-[28rem] space-y-2 overflow-auto pr-1",children:ja.length===0?e.jsx("p",{className:"host-empty-state rounded-2xl border px-3 py-3 text-sm",children:"No goals in this thread yet."}):ja.map(l=>{const i=`${l.threadId}:${l.objective}:${l.createdAt}`,x=es.has(i),N=["active","paused","budgetLimited"].includes(l.status);return e.jsxs("div",{className:`rounded-2xl border px-3 py-3 ${N?"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:()=>js($=>{const Z=new Set($);return Z.has(i)?Z.delete(i):Z.add(i),Z}),className:"min-w-0 flex-1 text-left",children:e.jsx("p",{className:`text-sm font-medium leading-5 ${x?"":"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:ud(l.timeUsedSeconds)}),e.jsx("span",{children:cd(l)}),e.jsxs("span",{title:ps(l.updatedAt),children:["Updated ",new Date(l.updatedAt).toLocaleTimeString()]})]}),N?e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx("button",{type:"button",disabled:ae||l.status==="active",onClick:()=>void Gs("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:ae||l.status==="paused",onClick:()=>void Gs("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:ae,onClick:()=>void Ks(),className:"rounded-full border border-[var(--status-danger-border)] px-3 py-1.5 text-xs text-[var(--status-danger-fg)] transition hover:bg-[var(--status-danger-bg)] disabled:cursor-not-allowed disabled:opacity-50",children:"Terminate"})]}):null]},i)})})]}):null,Na=wa?e.jsx("button",{type:"button","aria-label":"Open goal monitor",title:"Open goal monitor",onClick:()=>{ee(l=>!l),Vs()},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:ao}):null,Sa=e.jsx("button",{type:"button","aria-label":"Export transcript",title:"Export transcript",onClick:()=>jt(!0),disabled:!c,className:"host-icon-button inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-full border shadow-lg shadow-black/10 transition disabled:cursor-not-allowed disabled:opacity-50 lg:h-9 lg:w-9",children:e.jsx(nc,{})}),oo=e.jsxs("div",{className:"relative flex items-center justify-end gap-1.5",children:[Sa,Na,so]}),lo=e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[Sa,Na,no]}),io=r.useMemo(()=>({livePlan:B,liveItems:de,respondingRequestId:bs,onRespondToRequest:tn,scrollRequestKey:kt,bottomSpacer:Os,className:"thread-timeline-surface min-h-0 flex-1",onTailVisibilityChange:dt,loadingEarlier:ct,onLoadEarlier:Qs,onOpenThread:Je,answeredRequestNotes:(c==null?void 0:c.answeredRequestNotes)??Xd,activityNotes:(c==null?void 0:c.activityNotes)??Qd,pendingSteers:(c==null?void 0:c.pendingSteers)??ec,optimisticSteers:zt,optimisticTurn:X}),[c==null?void 0:c.answeredRequestNotes,c==null?void 0:c.activityNotes,c==null?void 0:c.pendingSteers,Qs,tn,de,B,ct,Je,zt,bs,kt,Os,X]),ka=c?{busy:U==="chat"?b:!1,settingsBusy:Ut,error:null,model:c.thread.model,reasoningEffort:c.thread.reasoningEffort,fastMode:c.thread.fastMode??!1,collaborationMode:c.thread.collaborationMode,modelOptions:q,contextUsage:c.thread.contextUsage,capabilities:D,toolboxItems:(I==null?void 0:I.toolboxItems)??[],hookCommandTemplates:(I==null?void 0:I.hookCommandTemplates)??[],mcpConfigFormat:(I==null?void 0:I.mcpConfigFormat)??"none",followTail:ht,threadConnected:c.thread.isLoaded,shellAvailable:be,disabled:!!Ps,...Ps?{disabledPlaceholder:Ps}:{},shellControlState:ne,draftPrompt:gt.prompt,draftAttachments:gt.attachments,onDraftChange:Fe,canInterrupt:!!c.thread.activeTurnId,onInterrupt:os,onCompact:Is,onOpenForkTurns:St,onForkLatest:Pn,onForkTurn:An,onOpenSkills:In,onOpenMcp:En,onOpenHooks:Rn,onCreateHook:Ze,onUpdateHook:Cs,onTrustHook:Ys,onUntrustHook:Nt,goalState:Ae,onOpenGoal:Vs,onUpdateGoal:Js,...Kt?{onReadProviderConfig:()=>Or(c.thread.provider,Kt),onWriteProviderConfig:l=>$r(c.thread.provider,Kt,{content:l})}:{},onToggleFollow:()=>Ve(l=>l+1),onUpdateSettings:Lt,onToggleView:Dt,onShellCopy:is,onShellControl:sn,compactBusy:Fs,skillsState:yt,mcpState:Qt,hooksState:Ot,forkTurnOptionsState:Vt}:null,Ca=c?{busy:b,settingsBusy:!1,error:c.thread.isLoaded?(ne==null?void 0:ne.error)??null:null,followTail:!1,capabilities:D,toolboxItems:(I==null?void 0:I.toolboxItems)??[],hookCommandTemplates:(I==null?void 0:I.hookCommandTemplates)??[],mcpConfigFormat:(I==null?void 0:I.mcpConfigFormat)??"none",threadConnected:c.thread.isLoaded,shellAvailable:be,shellControlState:ne,canInterrupt:!!(c.thread.isLoaded&&(ne!=null&&ne.isCommandRunning)),onInterrupt:os,onToggleView:Dt,onShellCopy:is,onShellControl:sn}:null,Ta=r.useCallback(l=>c?Ge({threadId:c.thread.id,path:l}):"",[c==null?void 0:c.thread.id,Ge]),Ia=r.useMemo(()=>{const l=(c==null?void 0:c.workspace.id)??null;return l?{listTree:()=>Pl(l),readFile:i=>Al(l,{path:i.path,...i.offset!==void 0?{offset:i.offset}:{},...i.limit!==void 0?{limit:i.limit}:{}}),getRawFileUrl:i=>Ul(l,{path:i.path}),uploadFile:i=>$l(l,{file:i.file}),writeFile:async i=>{await Ml(l,{path:i.path,content:i.content})},downloadNode:async i=>{ue(null);try{const x=await Ol(l,{path:i.path}),N=URL.createObjectURL(x.blob),$=document.createElement("a");$.href=N,$.download=x.filename,document.body.append($),$.click(),$.remove(),URL.revokeObjectURL(N)}catch(x){ue(x instanceof re?x.payload.message:x instanceof Error?x.message:"Workspace download failed.")}}}:null},[c==null?void 0:c.workspace.id]),co=r.useMemo(()=>({openThread:Je,getThreadHref:_e,getNewThreadHref:ft,renameThread:Es,deleteThread:ns,sendPrompt:en,interrupt:os,compact:Is,updateSettings:Lt,loadHistoryItemDetail:ls,getImageAssetUrl:Ta,workspace:Ia,shell:Le}),[Ta,ft,_e,Is,os,ls,en,Es,Lt,Le,Je,Ia]),uo=c!=null&&c.thread.workspaceId?`/threads?workspaceId=${encodeURIComponent(c.thread.workspaceId)}`:"/workspaces",mo=e.jsxs(e.Fragment,{children:[e.jsx(yo,{open:ts,busy:Ws,turnsState:ws,onCancel:()=>{Ws||jt(!1)},onLoadTurns:zs,onExport:Cn}),e.jsx(wn,{open:at!==null,title:"Delete Thread",description:at?`Delete ${$o(at.title)} from supervisor. The backend session id will no longer appear in this workspace list.`:"",confirmLabel:"Delete Thread",busy:Jt,onCancel:()=>{Jt||ns(null)},onConfirm:()=>void Rs()})]});return e.jsx(pr,{threads:G,detail:c,status:ye,loading:pt,error:pt?null:Gt,plugins:n,adapter:co,metaContent:nn,settingsContent:u,globalSettingsContent:e.jsx(xa,{embedded:!0}),mobileHeaderAction:oo,workspaceReturnHref:uo,onCloseAppNavigation:(a==null?void 0:a.closeNav)??(()=>{}),surfaceActions:lo,floatingPanel:ro,workspaceFeatures:tc,activeView:U,liveOutput:oe,timelineProps:io,timelineComponent:wo,useFloatingMobileComposer:As,floatingMobileComposerBottomOffset:Us,composerHostRef:T,shellPanelRef:C,shellPanelComponent:jo,shellEffectiveTheme:(a==null?void 0:a.effectiveTheme)??"dark",shellThemeMode:(a==null?void 0:a.themeMode)??"system",...a!=null&&a.setThemeMode?{onShellThemeModeChange:a.setThemeMode}:{},onShellStateChange:De,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:mo,...ka?{composerProps:ka}:{},...Ca?{shellComposerProps:Ca}:{}})}function oc(){const t=it(),[s,a]=r.useState(""),[n,d]=r.useState(Et),[o,m]=r.useState([]),[h,f]=r.useState(!0),[v,A]=r.useState(!1),[g,p]=r.useState(null);r.useEffect(()=>{let R=!1;return f(!0),pa().then(y=>{var te,H;if(R)return;m(y);const V=((te=y.find(P=>P.isDefault&&P.enabled))==null?void 0:te.provider)??((H=y.find(P=>P.enabled))==null?void 0:H.provider)??Et;d(V)}).catch(()=>{R||m([])}).finally(()=>{R||f(!1)}),()=>{R=!0}},[]);const C=r.useMemo(()=>o.length>0?o:[{provider:Et,displayName:Pa[Et].displayName,enabled:!0}],[o]);async function T(R){R.preventDefault();const y=s.trim();if(!y){p("Session ID is required.");return}A(!0),p(null);try{const V=await Jl({sessionId:y,provider:n});t(`/threads/${V.thread.id}`)}catch(V){V instanceof re?p(V.payload.message):p(V instanceof Error?V.message:"Unable to import session.")}finally{A(!1)}}return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("p",{className:"host-page-eyebrow text-xs uppercase tracking-[0.3em]",children:"Import Session"}),e.jsx("h2",{className:"host-page-title mt-2 text-3xl font-semibold",children:"Bring in a local backend session"}),e.jsx("p",{className:"host-page-description mt-3 max-w-3xl text-sm leading-6",children:"Select the backend and paste a session ID from this machine. Supervisor will recover the workspace path, reuse an existing workspace when possible, or create one with the last folder name as the default label."}),e.jsx("p",{className:"host-muted mt-2 max-w-3xl text-sm leading-6",children:"Imported history appears immediately, but sending a new prompt still requires a manual Resume / Connect."})]}),e.jsxs("form",{onSubmit:T,className:"host-panel space-y-5 rounded-3xl border p-6",children:[e.jsxs("div",{children:[e.jsx("label",{htmlFor:"backend-provider",className:"host-form-label text-sm font-medium",children:"Backend"}),e.jsx("select",{id:"backend-provider",value:n,onChange:R=>d(R.target.value),disabled:v||h,className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition",children:C.map(R=>e.jsxs("option",{value:R.provider,children:[R.displayName||Pa[R.provider].displayName,R.enabled?"":" (not ready)"]},R.provider))})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"session-id",className:"host-form-label text-sm font-medium",children:"Session ID"}),e.jsx("input",{id:"session-id",value:s,onChange:R=>a(R.target.value),placeholder:"019d6fb7-7033-7a30-a2c7-74d0919e87d4",className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition"})]}),g&&e.jsx("div",{className:"host-error rounded-2xl border px-4 py-3 text-sm",children:g}),e.jsx("div",{className:"flex flex-wrap items-center gap-3",children:e.jsx("button",{type:"submit",disabled:v,className:"ui-action-primary rounded-full px-5 py-3 font-medium transition disabled:cursor-not-allowed",children:v?"Importing...":"Import Session"})})]})]})}function jn(t){return t.enabled&&t.capabilities.sessions.resume&&t.capabilities.turns.start}function lc(t,s){var n;const a=t.find(d=>d.provider===s);return a&&jn(a)?a.provider:((n=t.find(jn))==null?void 0:n.provider)??Et}function ic(){const t=it(),s=Bt(),[a]=mr(),[n,d]=r.useState([]),[o,m]=r.useState([]),[h,f]=r.useState([]),[v,A]=r.useState((s==null?void 0:s.defaultBackend)??Et),[g,p]=r.useState(""),[C,T]=r.useState(""),R=a.get("title"),[y,V]=r.useState(()=>R??""),[te,H]=r.useState("yolo"),[P,Y]=r.useState(!0),[c,L]=r.useState(!1),[G,E]=r.useState(null),q=a.get("workspaceId"),_=(s==null?void 0:s.defaultBackend)??Et;r.useEffect(()=>{let D=!1;return Promise.all([fa(),pa()]).then(async([me,I])=>{var B,z,de;if(D)return;const le=lc(I,_);A(le),m(I);const oe=await oa(le);if(D)return;d(me),f(oe);const F=me.some(ge=>ge.id===q)?q:((B=me[0])==null?void 0:B.id)??"";p(F),T(((z=oe.find(ge=>ge.isDefault))==null?void 0:z.model)??((de=oe[0])==null?void 0:de.model)??"")}).catch(me=>{D||E(me instanceof Error?me.message:"Unable to load creation form data.")}).finally(()=>{D||Y(!1)}),()=>{D=!0}},[_,q]),r.useEffect(()=>{if(!v)return;let D=!1;return f([]),T(""),E(null),oa(v).then(me=>{var I,le;D||(f(me),T(((I=me.find(oe=>oe.isDefault))==null?void 0:I.model)??((le=me[0])==null?void 0:le.model)??""))}).catch(me=>{D||(f([]),T(""),E(me instanceof Error?me.message:"Unable to load backend models."))}),()=>{D=!0}},[v]);function ye(){if(window.history.length>1){t(-1);return}if(q){t(`/threads?workspaceId=${encodeURIComponent(q)}`);return}t("/workspaces")}async function xe(D){D.preventDefault(),L(!0),E(null);try{const me=await Vl(y.trim()?{workspaceId:g,provider:v,model:C,approvalMode:te,title:y.trim()}:{workspaceId:g,provider:v,model:C,approvalMode:te});t(`/threads/${me.id}`)}catch(me){me instanceof re?E(me.payload.message):E(me instanceof Error?me.message:"Unable to create thread.")}finally{L(!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."})]}),P?e.jsx("div",{className:"host-empty-state rounded-3xl border px-6 py-12 text-center",children:"Loading creation form..."}):e.jsxs("form",{onSubmit:xe,className:"host-panel space-y-5 rounded-3xl border p-6",children:[e.jsxs("div",{children:[e.jsx("label",{className:"host-form-label text-sm font-medium",htmlFor:"thread-backend",children:"Backend"}),e.jsx("select",{id:"thread-backend",value:v,onChange:D=>{const me=D.target.value;A(me)},className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition",children:o.map(D=>e.jsxs("option",{value:D.provider,disabled:!jn(D),children:[D.displayName,jn(D)?"":" (not available)"]},D.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:D=>p(D.target.value),className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition",children:n.map(D=>e.jsxs("option",{value:D.id,children:[D.label," · ",D.absPath]},D.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:C,onChange:D=>T(D.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(D=>e.jsxs("option",{value:D.model,children:[D.displayName," · ",D.model]},D.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:D=>V(D.target.value),placeholder:"Optional. Falls back to first prompt.",className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"host-form-label text-sm font-medium",htmlFor:"thread-approval-mode",children:"Approval mode"}),e.jsxs("select",{id:"thread-approval-mode",value:te,onChange:D=>H(D.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"})]})]}),G&&e.jsx("div",{className:"host-error rounded-2xl border px-4 py-3 text-sm",children:G}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx("button",{type:"submit",disabled:c||!g||!C,className:"ui-action-primary rounded-full px-5 py-3 font-medium transition disabled:cursor-not-allowed",children:c?"Creating...":"Create Thread"}),e.jsx("button",{type:"button",onClick:ye,disabled:c,className:"host-secondary-button rounded-full border px-5 py-3 font-medium transition disabled:cursor-not-allowed disabled:opacity-60",children:"Cancel"})]})]})]})}function dc(t){return t?`/threads/new?workspaceId=${encodeURIComponent(t)}`:"/threads/new"}function cc({getThreadHref:t,onOpenThread:s,getNewThreadHref:a,renderThreadLink:n,onCloseAppNavigation:d,...o}){const m=it(),h=Bt(),f=d??(h==null?void 0:h.closeNav),v=o.effectiveTheme??(h==null?void 0:h.effectiveTheme),A=o.themeMode??(h==null?void 0:h.themeMode),g=o.onThemeModeChange??(h==null?void 0:h.setThemeMode);return e.jsx(No,{...o,workspaceReturnHref:o.workspaceReturnHref??"/workspaces",globalSettingsContent:o.globalSettingsContent??e.jsx(xa,{embedded:!0}),...v?{effectiveTheme:v}:{},...A?{themeMode:A}:{},...g?{onThemeModeChange:g}:{},getThreadHref:t??(p=>`/threads/${p}`),onOpenThread:s??(p=>m(`/threads/${p}`)),getNewThreadHref:a??dc,renderThreadLink:n??(({thread:p,children:C,className:T,onClick:R})=>e.jsx(Rt,{to:`/threads/${p.id}`,className:T,onClick:R,children:C})),...f?{onCloseAppNavigation:f}:{}})}function Yr({open:t,title:s,label:a,value:n,busy:d=!1,onChange:o,onCancel:m,onSubmit:h}){if(r.useEffect(()=>{if(!t)return;function v(A){A.key==="Escape"&&!d&&m()}return window.addEventListener("keydown",v),()=>{window.removeEventListener("keydown",v)}},[d,m,t]),!t)return null;function f(v){v.preventDefault(),h()}return ho.createPortal(e.jsxs("div",{className:"fixed inset-0 z-[95] flex items-center justify-center p-4 sm:p-6",children:[e.jsx("button",{type:"button","aria-label":"Close rename dialog",onClick:m,disabled:d,className:"ui-overlay-scrim absolute inset-0 backdrop-blur-sm disabled:cursor-not-allowed"}),e.jsxs("form",{role:"dialog","aria-modal":"true","aria-label":s,onSubmit:f,className:"host-dialog relative z-[1] w-full max-w-md rounded-[1.6rem] border p-5 shadow-2xl shadow-black/20 sm:p-6",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"host-page-title text-sm font-medium",children:s}),e.jsx("p",{className:"host-muted mt-1 text-sm",children:"Changes are saved only after confirmation."})]}),e.jsx("button",{type:"button","aria-label":"Close dialog",onClick:m,disabled:d,className:"host-icon-button inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-full border transition disabled:cursor-not-allowed disabled:opacity-60",children:e.jsx("svg",{"aria-hidden":"true",viewBox:"0 0 16 16",className:"h-4 w-4 fill-current",children:e.jsx("path",{d:"M3.22 2.47 8 7.25l4.78-4.78 1.06 1.06L9.06 8.31l4.78 4.78-1.06 1.06L8 9.37l-4.78 4.78-1.06-1.06 4.78-4.78-4.78-4.78 1.06-1.06Z"})})})]}),e.jsxs("div",{className:"mt-5",children:[e.jsx("label",{htmlFor:"rename-dialog-input",className:"host-form-label text-sm font-medium",children:a}),e.jsx("input",{id:"rename-dialog-input","aria-label":a,autoFocus:!0,value:n,onChange:v=>o(v.target.value),className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition"})]}),e.jsxs("div",{className:"mt-5 flex items-center justify-end gap-2",children:[e.jsx("button",{type:"button",onClick:m,disabled:d,className:"host-secondary-button rounded-full border px-4 py-2 text-sm font-medium transition disabled:cursor-not-allowed disabled:opacity-60",children:"Cancel"}),e.jsx("button",{type:"submit",disabled:d||!n.trim(),className:"ui-action-success rounded-full px-4 py-2 text-sm font-medium transition disabled:cursor-not-allowed",children:"Save"})]})]})]}),document.body)}function uc(){const[t]=mr(),s=it(),a=Bt(),n=t.get("workspaceId"),[d,o]=r.useState([]),[m,h]=r.useState([]),[f,v]=r.useState(null),[A,g]=r.useState(!0),[p,C]=r.useState(null),[T,R]=r.useState(null),[y,V]=r.useState(""),[te,H]=r.useState(null),[P,Y]=r.useState(null),[c,L]=r.useState(!1),G=(a==null?void 0:a.defaultBackend)??Et,E=r.useCallback(async()=>{g(!0),C(null);try{const[F,B,z]=await Promise.all([Ur(G).then(de=>de.status),Mr(),fa()]);v(F),o(B),h(z)}catch(F){C(F instanceof Error?F.message:"Unable to load threads.")}finally{g(!1)}},[G]);r.useEffect(()=>{if(n===null)return;E();const F=Hr(B=>{o(z=>z.map(de=>de.id===B.threadId?{...de,status:B.type==="thread.updated"&&typeof B.payload.status=="string"?B.payload.status:de.status,lastError:(B.type==="thread.turn.failed"||B.type==="thread.turn.completed")&&typeof B.payload.error=="string"?B.payload.error:de.lastError,title:B.type==="thread.updated"&&typeof B.payload.title=="string"?B.payload.title:de.title}:de))});return()=>{F.close()}},[E,n]);const q=Object.fromEntries(m.map(F=>[F.id,F.label])),_=m.find(F=>F.id===n)??null,ye=r.useMemo(()=>n?d.filter(F=>F.workspaceId===n):[],[n,d]),xe=ye.filter(F=>F.status==="running").length,D=n?`/threads/new?workspaceId=${encodeURIComponent(n)}`:"/threads/new";if(n===null)return e.jsx(_s,{to:"/workspaces",replace:!0});function me(){switch(f==null?void 0:f.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 I(F,B){try{const z=await Lr(F,{title:B});o(de=>de.map(ge=>ge.id===z.id?{...ge,title:z.title,updatedAt:z.updatedAt}:ge))}catch(z){throw C(z instanceof Error?z.message:"Unable to rename thread."),z}}async function le(){if(!T)return;const F=y.trim();if(F){H(T);try{await I(T,F),R(null),V("")}finally{H(null)}}}async function oe(){if(P){L(!0);try{await Dr(P.id),o(F=>F.filter(B=>B.id!==P.id)),Y(null)}catch(F){C(F instanceof Error?F.message:"Unable to delete thread.")}finally{L(!1)}}}return e.jsx(cc,{threads:d,workspaceLabels:q,status:f,loading:A,error:p,viewportConstrained:n!==null,showMobileAppMenu:!0,showMobileThreadNavToggle:!1,showMobileNewThreadShortcut:!1,currentWorkspaceId:n,currentWorkspaceLabel:(_==null?void 0:_.label)??null,onRenameThread:I,onDeleteThread:Y,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:_?`${_.label} threads`:"All threads",children:_?_.label:"All Threads"}),e.jsx(Rt,{to:D,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 ${me()}`}),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:(f==null?void 0:f.lastError)??((f==null?void 0:f.state)==="ready"?"Ready":(f==null?void 0:f.state)??"Checking")})]})]})}),!A&&!p&&ye.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:[ye.length," total"]}),xe>0&&e.jsxs("span",{className:"host-muted text-xs",children:["· ",xe," running"]})]}),e.jsx("div",{className:"mt-3 min-h-0 flex-1",children:e.jsx(So,{threads:ye,currentWorkspaceId:n,workspaceLabels:q,onOpenThread:F=>s(`/threads/${F}`),onBeginRenameThread:F=>{R(F.id),V(F.title)},onDeleteThread:F=>Y(F),scrollable:!0,maxHeightClassName:"max-h-full",showDeleteButton:!0,showSessionCopyButton:!0})})]}),!A&&!p&&ye.length===0&&e.jsx("div",{className:"host-muted border-t border-[var(--theme-border)] px-4 py-6 text-sm sm:px-6",children:"No threads available in this workspace."})]}),e.jsx(Yr,{open:T!==null,title:"Rename Thread",label:"Thread Title",value:y,busy:te!==null,onChange:V,onCancel:()=>{R(null),V("")},onSubmit:()=>void le()}),e.jsx(wn,{open:P!==null,title:"Delete Thread",description:P?`Delete ${Ao(P.title)} from supervisor. The backend session id will no longer appear in this workspace list.`:"",confirmLabel:"Delete Thread",busy:c,onCancel:()=>{c||Y(null)},onConfirm:()=>void oe()})]})})}function dr(t){const s=t.trim(),a=s.replace(/[\\/]+$/,"");if(!a)return"";if(Zr(s)){const d=(a.split(/[?#]/)[0]??a).split(/[/:]/).filter(Boolean).at(-1)??"";return d.endsWith(".git")?d.slice(0,-4):d}return a.split(/[\\/]/).filter(Boolean).at(-1)??""}function Zr(t){const s=t.trim();return/^https?:\/\/.+/i.test(s)||/^ssh:\/\/.+/i.test(s)||/^git@[^:]+:.+/.test(s)}function mc({initialPath:t="",initialLabel:s="",submitLabel:a="Save Workspace",error:n,busy:d=!1,onSubmit:o}){const m=dr(t),[h,f]=r.useState(t),[v,A]=r.useState(s||m),[g,p]=r.useState(null),C=r.useRef(m);r.useEffect(()=>{const R=dr(h);A(y=>!y.trim()||y===C.current?R:y),C.current=R},[h]);async function T(R){R.preventDefault();const y=h.trim();if(!y){p("Workspace path or Git URL is required.");return}p(null);const V=v.trim(),te=Zr(y)?"gitUrl":"absPath";await o(V?{[te]:y,label:V}:{[te]: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:R=>f(R.target.value),placeholder:"/Users/name/project or https://github.com/owner/repo.git",className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition"}),e.jsx("p",{className:"host-muted mt-2 text-xs",children:"Absolute paths register local directories. Git URLs clone into the configured dev home."})]}),e.jsxs("div",{children:[e.jsx("label",{htmlFor:"workspace-label",className:"host-form-label text-sm font-medium",children:"Display label"}),e.jsx("input",{id:"workspace-label",name:"label",value:v,onChange:R=>A(R.target.value),placeholder:"Optional override",className:"host-form-control mt-2 w-full rounded-2xl border px-4 py-3 outline-none transition"}),e.jsx("p",{className:"host-muted mt-2 text-xs",children:"Defaults to the last folder name. You can override it."})]}),(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:d,className:"ui-action-primary rounded-full px-5 py-3 font-medium transition disabled:cursor-not-allowed",children:d?"Saving...":a})]})}function hc(){const t=it(),[s,a]=r.useState(null),[n,d]=r.useState(!1);async function o(m){d(!0),a(null);try{const h=await hi(m);t(`/threads?workspaceId=${encodeURIComponent(h.id)}`)}catch(h){h instanceof re?a(h.payload.message):a(h instanceof Error?h.message:"Unable to create workspace.")}finally{d(!1)}}return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("p",{className:"host-page-eyebrow text-xs uppercase tracking-[0.3em]",children:"Add Workspace"}),e.jsx("h2",{className:"host-page-title mt-2 text-3xl font-semibold",children:"Create a workspace"}),e.jsx("p",{className:"host-page-description mt-3 max-w-2xl text-sm leading-6",children:"Register an existing local directory, create one missing child directory under dev home, or clone a Git repository into dev home."})]}),e.jsx(mc,{busy:n,error:s,submitLabel:"Create Workspace",onSubmit:o})]})}function cr(t){return Date.parse(t.lastOpenedAt??t.createdAt)}function pc(t,s){return t.isFavorite!==s.isFavorite?t.isFavorite?-1:1:cr(s)-cr(t)}function fc(t){return t?new Date(t).toLocaleString():"Never opened"}function xc(t,s=28){return t.length<=s?t:`...${t.slice(-(s-3))}`}function gc({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 bc(){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 vc(){const t=it(),[s,a]=r.useState([]),[n,d]=r.useState(!0),[o,m]=r.useState(null),[h,f]=r.useState(null),[v,A]=r.useState(null),[g,p]=r.useState(null),[C,T]=r.useState(""),[R,y]=r.useState(null),[V,te]=r.useState(null),[H,P]=r.useState(null),[Y,c]=r.useState(!1);async function L(){d(!0),A(null);try{a(await fa())}catch(I){A(I instanceof Error?I.message:"Unable to load workspaces.")}finally{d(!1)}}r.useEffect(()=>{L(),dl().then(I=>{m(I),f(null)}).catch(I=>{f(I instanceof Error?I.message:"Unable to load supervisor config.")})},[]);async function G(I){const le={...I,isFavorite:!I.isFavorite};a(oe=>oe.map(F=>F.id===I.id?le:F));try{const oe=await xi(I.id,{isFavorite:!I.isFavorite});a(F=>F.map(B=>B.id===oe.id?oe:B))}catch(oe){a(F=>F.map(B=>B.id===I.id?I:B)),A(oe instanceof Error?oe.message:"Unable to update workspace.")}}async function E(I){const le=C.trim();if(le){y(I);try{const oe=await pi(I,{label:le});a(F=>F.map(B=>B.id===oe.id?oe:B)),p(null),T("")}catch(oe){A(oe instanceof Error?oe.message:"Unable to rename workspace.")}finally{y(null)}}}function q(I){p(I.id),T(I.label)}function _(){p(null),T("")}function ye(I){t(`/threads?workspaceId=${encodeURIComponent(I)}`)}async function xe(){if(H){c(!0);try{await fi(H.id),a(I=>I.filter(le=>le.id!==H.id)),P(null)}catch(I){A(I instanceof Error?I.message:"Unable to delete workspace.")}finally{c(!1)}}}function D(I,le){(I.key==="Enter"||I.key===" ")&&(I.preventDefault(),ye(le))}const me=r.useMemo(()=>[...s].sort(pc),[s]);return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"host-topbar sticky top-[env(safe-area-inset-top)] z-20 -mx-4 border-b px-2.5 py-2 backdrop-blur sm:mx-0 sm:rounded-[1.4rem] sm:border sm:px-4",children:e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 sm:gap-2",children:[e.jsx(Fr,{}),e.jsx(Rt,{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(Rt,{to:"/workspaces/new",className:"ui-action-primary inline-flex h-8 shrink-0 items-center rounded-full px-2.5 text-[11px] font-medium uppercase tracking-[0.14em] transition sm:px-3 sm:text-xs sm:tracking-[0.18em]",children:"Create"}),e.jsx("div",{className:"min-w-0 flex-1 text-right",children:e.jsx("p",{className:"host-page-eyebrow truncate text-[11px] uppercase tracking-[0.24em]",children:"Workspaces"})})]}),e.jsx(Wr,{className:"absolute left-0 top-[calc(100%+0.5rem)] z-30 w-[min(22rem,calc(100vw-1rem))]"})]})}),e.jsxs("div",{className:"grid gap-4 xl:grid-cols-[minmax(0,1fr)_20rem]",children:[e.jsxs("section",{className:"min-w-0 space-y-4",children:[n&&e.jsx("div",{className:"host-empty-state rounded-[1.6rem] border px-6 py-12 text-center",children:"Loading workspace registry..."}),v&&e.jsx("div",{className:"host-error rounded-[1.4rem] border px-4 py-4",children:v}),!n&&!v&&s.length===0&&e.jsxs("div",{className:"host-empty-state rounded-[1.6rem] border border-dashed px-6 py-12 text-center",children:[e.jsx("p",{className:"host-page-title text-lg font-medium",children:"No workspaces yet"}),e.jsx("p",{className:"host-muted mt-2 text-sm",children:"Add a local directory inside the configured workspace root to start building the registry."})]}),!n&&me.length>0&&e.jsx("div",{className:"space-y-2 overflow-x-hidden",children:me.map(I=>e.jsxs("article",{role:"link",tabIndex:0,onClick:()=>ye(I.id),onKeyDown:le=>D(le,I.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 ${I.label}`,title:"Delete workspace",onClick:le=>{le.stopPropagation(),P(I)},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(bc,{})}),e.jsx("button",{type:"button","aria-label":I.isFavorite?`Unpin workspace ${I.label}`:`Pin workspace ${I.label}`,title:I.isFavorite?"Unpin workspace":"Pin workspace",onClick:le=>{le.stopPropagation(),G(I)},className:`inline-flex h-7 w-7 items-center justify-center rounded-full border transition ${I.isFavorite?"host-warning-pill":"host-icon-button"}`,children:e.jsx(gc,{active:I.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:I.label,children:I.label}),e.jsx("button",{type:"button",onClick:le=>{le.stopPropagation(),q(I)},"aria-label":`Rename workspace ${I.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":I.absPath,title:I.absPath,onClick:le=>{le.stopPropagation(),te(I.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:xc(I.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: ",fc(I.lastOpenedAt)]})})]})})]},I.id))})]}),e.jsx(yc,{config:o,error:h,workspaceCount:s.length})]}),e.jsx(Yr,{open:g!==null,title:"Rename Workspace",label:"Workspace Label",value:C,busy:R!==null,onChange:T,onCancel:_,onSubmit:()=>g?E(g):void 0}),e.jsx(ko,{open:V!==null,title:"Workspace Path",text:V??"",onClose:()=>te(null)}),e.jsx(wn,{open:H!==null,title:"Delete Workspace",description:H?`Delete ${H.label} from supervisor. This also removes its threads and local supervisor metadata.`:"",confirmLabel:"Delete Workspace",busy:Y,onCancel:()=>{Y||P(null)},onConfirm:()=>void xe()})]})}function yc({config:t,error:s,workspaceCount:a}){return e.jsxs("aside",{className:"space-y-3 xl:sticky xl:top-[calc(env(safe-area-inset-top)+4.25rem)] xl:self-start",children:[e.jsxs("section",{className:"rounded-[1.2rem] border border-[var(--theme-border)] bg-[var(--theme-panel)] p-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.18em] text-[var(--theme-fg-muted)]",children:"Supervisor"}),e.jsxs("dl",{className:"mt-4 space-y-3",children:[e.jsx(pn,{label:"Workspace root",value:(t==null?void 0:t.workspaceRoot)??"Loading..."}),e.jsx(pn,{label:"Environment",value:t?`${t.environment} · ${t.host}:${t.port}`:s??"Loading..."}),e.jsx(pn,{label:"Version",value:t?`${t.appName} ${t.appVersion}`:"Loading..."}),e.jsx(pn,{label:"Workspaces",value:String(a)})]})]}),s?e.jsx("section",{className:"rounded-[1.2rem] border border-[var(--status-warning-border)] bg-[var(--status-warning-bg)] p-4 text-sm text-[var(--status-warning-fg)]",children:"Runtime metadata is unavailable. Workspace actions may still work if a relay device is connected."}):null]})}function pn({label:t,value:s}){return e.jsxs("div",{children:[e.jsx("dt",{className:"text-[11px] font-medium uppercase tracking-[0.14em] text-[var(--theme-fg-muted)]",children:t}),e.jsx("dd",{className:"mt-1 break-words font-mono text-xs leading-5 text-[var(--theme-fg)]",children:s})]})}const Xr="remote-codex-theme-mode",Qr="remote-codex-default-backend",eo="remote-codex-auto-collapse-completed-turns";function to(){return!1}function jc(){return to()?e.jsx(_s,{to:"/control-plane",replace:!0}):e.jsx(_s,{to:"/workspaces",replace:!0})}function wc({children:t}){const s=Xt(),a=s.pathname.startsWith("/control-plane")||s.pathname==="/"&&to(),n=r.useMemo(()=>a?{}:{fetchPlugins:Dl,importPlugin:Hl,updatePlugin:_l,deletePlugin:Bl},[a]);return e.jsx(Co,{adapter:n,children:t})}function Nc(){if(typeof window>"u")return"system";const t=window.localStorage.getItem(Xr);return t==="light"||t==="dark"||t==="system"?t:"system"}function Sc(){if(typeof window>"u")return Et;const t=window.localStorage.getItem(Qr);return Ro(t)??Et}function kc(){return typeof window>"u"?!0:window.localStorage.getItem(eo)!=="false"}function Cc(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function Tc({themeMode:t,setThemeMode:s,effectiveTheme:a}){const[n,d]=r.useState(!1),[o,m]=r.useState(!1),[h,f]=r.useState(Sc),[v,A]=r.useState(kc),g=Xt(),p=/^\/threads\/[^/]+$/.test(g.pathname),C=/^\/control-plane\/sessions\/[^/]+$/.test(g.pathname),T=g.pathname==="/threads",R=p||C||T,y=T||p||C,V=p||C,te=g.pathname==="/workspaces",H=g.pathname.startsWith("/control-plane"),P=te||T||H;r.useEffect(()=>{d(!1)},[g.pathname,g.search]);function Y(G){f(G),window.localStorage.setItem(Qr,G)}function c(G){A(G),window.localStorage.setItem(eo,G?"true":"false")}const L={navOpen:n,openNav:()=>d(!0),toggleNav:()=>d(G=>!G),closeNav:()=>d(!1),settingsOpen:o,openSettings:()=>{d(!1),m(!0)},closeSettings:()=>m(!1),themeMode:t,setThemeMode:s,effectiveTheme:a,defaultBackend:h,setDefaultBackend:Y,autoCollapseCompletedTurns:v,setAutoCollapseCompletedTurns:c};return e.jsxs(To.Provider,{value:L,children:[e.jsxs("div",{className:`bg-[var(--app-bg)] text-[var(--app-fg)] ${R?"fixed inset-0 overflow-hidden overscroll-none":"min-h-screen"}`,children:[te?e.jsx(ga,{}):null,!P&&!V&&e.jsxs("div",{className:"fixed left-4 top-4 z-50",children:[e.jsx(Fr,{}),e.jsx(Wr,{className:"mt-3 w-[min(22rem,calc(100vw-2rem))]"})]}),e.jsx("main",{className:`mx-auto w-full ${y?"max-w-none":"max-w-[1600px]"} ${R?"absolute inset-0 pb-0 sm:pb-4":"pb-4"} ${y?p||C?"pt-0":T?"pt-[env(safe-area-inset-top)] sm:pt-4":"pt-[calc(env(safe-area-inset-top)+4rem)] sm:pt-4":te||H?"pt-[env(safe-area-inset-top)] sm:pt-4":"pt-4"} ${R?p||C?"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 ${R?p||C?"h-full min-h-0 overflow-hidden overscroll-none":"h-full overflow-hidden overscroll-none":""}`,children:e.jsx(fo,{})})})]}),e.jsx(xa,{})]})}function Ic({children:t}){const[s,a]=r.useState({status:"checking"});async function n(m){try{const h=await cl();if(m!=null&&m())return;a(!h.authRequired||h.authenticated?{status:"authenticated"}:{status:"loginRequired",session:h,error:null})}catch(h){if(m!=null&&m())return;if(h instanceof re&&h.statusCode===401){a({status:"loginRequired",session:{authenticated:!1,username:null,expiresAt:null,mode:"server",authRequired:!0},error:null});return}a({status:"unavailable",error:h instanceof Error?h.message:"Unable to check supervisor access."})}}r.useEffect(()=>{let m=!1;return n(()=>m),()=>{m=!0}},[]);async function d(m){await ul(m),a({status:"authenticated"})}function o(){a({status:"checking"}),n()}return s.status==="checking"?e.jsx("main",{className:"flex min-h-screen items-center justify-center bg-[var(--app-bg)] px-4 text-sm text-[var(--theme-muted)]",children:"Checking supervisor access..."}):s.status==="unavailable"?e.jsx("main",{className:"flex min-h-screen items-center justify-center bg-[var(--app-bg)] px-4 text-[var(--app-fg)]",children:e.jsxs("section",{className:"w-full max-w-md rounded-[1.35rem] border border-[var(--theme-border)] bg-[var(--theme-panel)] p-5 shadow-2xl shadow-[color-mix(in_oklch,var(--app-fg)_14%,transparent)] sm:p-6",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.22em] text-[var(--theme-muted)]",children:"Supervisor Access"}),e.jsx("h1",{className:"mt-2 text-2xl font-semibold tracking-normal text-[var(--theme-fg)]",children:"Unable to reach supervisor"}),e.jsx("p",{className:"mt-3 text-sm leading-6 text-[var(--theme-muted)]",children:s.error}),e.jsx("button",{className:"mt-5 h-11 rounded-xl bg-[var(--theme-accent-solid)] px-4 text-sm font-semibold text-[var(--theme-accent-solid-fg)] transition hover:bg-[var(--theme-accent-solid-hover)] focus:outline-none focus:ring-2 focus:ring-[var(--theme-accent-border)]",onClick:o,type:"button",children:"Retry"})]})}):s.status==="loginRequired"?e.jsxs(e.Fragment,{children:[s.error&&e.jsx("div",{className:"fixed left-1/2 top-4 z-50 w-[min(28rem,calc(100vw-2rem))] -translate-x-1/2 rounded-xl border border-[var(--status-warning-border)] bg-[var(--status-warning-bg)] px-3 py-2 text-sm text-[var(--status-warning-fg)]",children:s.error}),e.jsx(Od,{onLogin:d})]}):t}function Ec({children:t}){const[s,a]=r.useState({status:"checking"});return r.useEffect(()=>{let n=!1;return Bs().then(d=>{n||a(d.authenticated?{status:"authenticated",session:d}:{status:"loginRequired"})}).catch(()=>{n||a({status:"loginRequired"})}),()=>{n=!0}},[]),s.status==="checking"?e.jsx("main",{className:"flex min-h-screen items-center justify-center bg-[var(--app-bg)] px-4 text-sm text-[var(--theme-muted)]",children:"Checking relay access..."}):s.status==="loginRequired"?e.jsx(Kr,{}):t}function Rc({children:t}){return Xt().pathname.startsWith("/control-plane")?t:na()?e.jsx(Ec,{children:t}):e.jsx(Ic,{children:t})}function Pc({themeMode:t,setThemeMode:s,effectiveTheme:a}){return e.jsxs(hr,{children:[e.jsx(ze,{path:"/",element:e.jsx(_s,{to:"/workspaces",replace:!0})}),e.jsxs(ze,{element:e.jsx(Tc,{themeMode:t,setThemeMode:s,effectiveTheme:a}),children:[e.jsx(ze,{path:"/workspaces",element:e.jsx(vc,{})}),e.jsx(ze,{path:"/workspaces/new",element:e.jsx(hc,{})}),e.jsx(ze,{path:"/relay-account",element:e.jsx($d,{})}),e.jsx(ze,{path:"/relay-devices",element:e.jsx(Ld,{})}),e.jsx(ze,{path:"/control-plane/login",element:e.jsx(ed,{})}),e.jsx(ze,{path:"/control-plane",element:e.jsx(Xa,{children:e.jsx(Yi,{})})}),e.jsx(ze,{path:"/control-plane/sessions/:sessionId",element:e.jsx(Xa,{children:e.jsx(Ad,{})})}),e.jsx(ze,{path:"/threads",element:e.jsx(uc,{})}),e.jsx(ze,{path:"/threads/import",element:e.jsx(oc,{})}),e.jsx(ze,{path:"/threads/new",element:e.jsx(ic,{})}),e.jsx(ze,{path:"/threads/:id",element:e.jsx(rc,{})})]})]})}function Ac(){const[t,s]=r.useState(()=>Nc()),[a,n]=r.useState(()=>Cc()),d=t==="system"?a:t;return r.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const o=window.matchMedia("(prefers-color-scheme: dark)"),m=()=>{n(o.matches?"dark":"light")};return m(),typeof o.addEventListener=="function"?o.addEventListener("change",m):o.addListener(m),()=>{typeof o.removeEventListener=="function"?o.removeEventListener("change",m):o.removeListener(m)}},[]),r.useEffect(()=>{typeof window>"u"||window.localStorage.setItem(Xr,t)},[t]),r.useEffect(()=>{const o=document.documentElement;o.dataset.themeMode=t,o.dataset.themeEffective=d,o.style.colorScheme=d},[d,t]),e.jsx("div",{className:"theme-shell theme-scrollbar",children:e.jsx(po,{children:e.jsx(wc,{children:e.jsxs(hr,{children:[e.jsx(ze,{path:"/",element:e.jsx(jc,{})}),e.jsx(ze,{path:"/relay-portal",element:e.jsx(Kr,{})}),e.jsx(ze,{path:"/relay-admin",element:e.jsx(Md,{})}),e.jsx(ze,{path:"/*",element:e.jsx(Rc,{children:e.jsx(Pc,{themeMode:t,setThemeMode:s,effectiveTheme:d})})})]})})})})}xo.createRoot(document.getElementById("root")).render(e.jsx(go.StrictMode,{children:e.jsx(Ac,{})}));