remote-codex 0.11.19 → 0.11.21

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